@elizaos/plugin-tee 0.1.7-alpha.2 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,53 @@
1
+ import {
2
+ secp256k1
3
+ } from "./chunk-4L6P6TY5.js";
4
+ import {
5
+ BaseError,
6
+ BytesSizeMismatchError,
7
+ FeeCapTooHighError,
8
+ Hash,
9
+ InvalidAddressError,
10
+ InvalidChainIdError,
11
+ InvalidLegacyVError,
12
+ InvalidSerializableTransactionError,
13
+ InvalidStorageKeySizeError,
14
+ TipAboveFeeCapError,
15
+ aexists,
16
+ aoutput,
17
+ bytesRegex,
18
+ bytesToHex,
19
+ checksumAddress,
20
+ concat,
21
+ concatHex,
22
+ createCursor,
23
+ createView,
24
+ encodeAbiParameters,
25
+ hexToBigInt,
26
+ hexToBytes,
27
+ hexToNumber,
28
+ integerRegex,
29
+ isAddress,
30
+ isHex,
31
+ keccak256,
32
+ maxUint256,
33
+ numberToHex,
34
+ rotr,
35
+ size,
36
+ slice,
37
+ stringToHex,
38
+ stringify,
39
+ toBytes,
40
+ toBytes2,
41
+ toHex,
42
+ trim,
43
+ wrapConstructor
44
+ } from "./chunk-KSHJJL6X.js";
45
+ import "./chunk-PR4QN5HX.js";
46
+
1
47
  // src/providers/remoteAttestationProvider.ts
48
+ import {
49
+ elizaLogger
50
+ } from "@elizaos/core";
2
51
  import { TappdClient } from "@phala/dstack-sdk";
3
52
 
4
53
  // src/types/tee.ts
@@ -18,19 +67,19 @@ var RemoteAttestationProvider = class {
18
67
  switch (teeMode) {
19
68
  case "LOCAL" /* LOCAL */:
20
69
  endpoint = "http://localhost:8090";
21
- console.log(
70
+ elizaLogger.log(
22
71
  "TEE: Connecting to local simulator at localhost:8090"
23
72
  );
24
73
  break;
25
74
  case "DOCKER" /* DOCKER */:
26
75
  endpoint = "http://host.docker.internal:8090";
27
- console.log(
76
+ elizaLogger.log(
28
77
  "TEE: Connecting to simulator via Docker at host.docker.internal:8090"
29
78
  );
30
79
  break;
31
80
  case "PRODUCTION" /* PRODUCTION */:
32
81
  endpoint = void 0;
33
- console.log(
82
+ elizaLogger.log(
34
83
  "TEE: Running in production mode without simulator"
35
84
  );
36
85
  break;
@@ -41,12 +90,12 @@ var RemoteAttestationProvider = class {
41
90
  }
42
91
  this.client = endpoint ? new TappdClient(endpoint) : new TappdClient();
43
92
  }
44
- async generateAttestation(reportData) {
93
+ async generateAttestation(reportData, hashAlgorithm) {
45
94
  try {
46
- console.log("Generating attestation for: ", reportData);
47
- const tdxQuote = await this.client.tdxQuote(reportData);
95
+ elizaLogger.log("Generating attestation for: ", reportData);
96
+ const tdxQuote = await this.client.tdxQuote(reportData, hashAlgorithm);
48
97
  const rtmrs = tdxQuote.replayRtmrs();
49
- console.log(
98
+ elizaLogger.log(
50
99
  `rtmr0: ${rtmrs[0]}
51
100
  rtmr1: ${rtmrs[1]}
52
101
  rtmr2: ${rtmrs[2]}
@@ -56,7 +105,7 @@ rtmr3: ${rtmrs[3]}f`
56
105
  quote: tdxQuote.quote,
57
106
  timestamp: Date.now()
58
107
  };
59
- console.log("Remote attestation quote: ", quote);
108
+ elizaLogger.log("Remote attestation quote: ", quote);
60
109
  return quote;
61
110
  } catch (error) {
62
111
  console.error("Error generating remote attestation:", error);
@@ -72,8 +121,8 @@ var remoteAttestationProvider = {
72
121
  const provider = new RemoteAttestationProvider(teeMode);
73
122
  const agentId = runtime.agentId;
74
123
  try {
75
- console.log("Generating attestation for: ", agentId);
76
- const attestation = await provider.generateAttestation(agentId);
124
+ elizaLogger.log("Generating attestation for: ", agentId);
125
+ const attestation = await provider.generateAttestation(agentId, "raw");
77
126
  return `Your Agent's remote attestation is: ${JSON.stringify(attestation)}`;
78
127
  } catch (error) {
79
128
  console.error("Error in remote attestation provider:", error);
@@ -85,11 +134,1219 @@ var remoteAttestationProvider = {
85
134
  };
86
135
 
87
136
  // src/providers/deriveKeyProvider.ts
137
+ import {
138
+ elizaLogger as elizaLogger2
139
+ } from "@elizaos/core";
88
140
  import { Keypair } from "@solana/web3.js";
89
141
  import crypto from "crypto";
90
142
  import { TappdClient as TappdClient2 } from "@phala/dstack-sdk";
91
- import { privateKeyToAccount } from "viem/accounts";
92
- import { keccak256 } from "viem";
143
+
144
+ // ../../node_modules/viem/node_modules/@noble/hashes/esm/_md.js
145
+ function setBigUint64(view, byteOffset, value, isLE) {
146
+ if (typeof view.setBigUint64 === "function")
147
+ return view.setBigUint64(byteOffset, value, isLE);
148
+ const _32n = BigInt(32);
149
+ const _u32_max = BigInt(4294967295);
150
+ const wh = Number(value >> _32n & _u32_max);
151
+ const wl = Number(value & _u32_max);
152
+ const h = isLE ? 4 : 0;
153
+ const l = isLE ? 0 : 4;
154
+ view.setUint32(byteOffset + h, wh, isLE);
155
+ view.setUint32(byteOffset + l, wl, isLE);
156
+ }
157
+ var Chi = (a, b, c) => a & b ^ ~a & c;
158
+ var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
159
+ var HashMD = class extends Hash {
160
+ constructor(blockLen, outputLen, padOffset, isLE) {
161
+ super();
162
+ this.blockLen = blockLen;
163
+ this.outputLen = outputLen;
164
+ this.padOffset = padOffset;
165
+ this.isLE = isLE;
166
+ this.finished = false;
167
+ this.length = 0;
168
+ this.pos = 0;
169
+ this.destroyed = false;
170
+ this.buffer = new Uint8Array(blockLen);
171
+ this.view = createView(this.buffer);
172
+ }
173
+ update(data) {
174
+ aexists(this);
175
+ const { view, buffer, blockLen } = this;
176
+ data = toBytes(data);
177
+ const len = data.length;
178
+ for (let pos = 0; pos < len; ) {
179
+ const take = Math.min(blockLen - this.pos, len - pos);
180
+ if (take === blockLen) {
181
+ const dataView = createView(data);
182
+ for (; blockLen <= len - pos; pos += blockLen)
183
+ this.process(dataView, pos);
184
+ continue;
185
+ }
186
+ buffer.set(data.subarray(pos, pos + take), this.pos);
187
+ this.pos += take;
188
+ pos += take;
189
+ if (this.pos === blockLen) {
190
+ this.process(view, 0);
191
+ this.pos = 0;
192
+ }
193
+ }
194
+ this.length += data.length;
195
+ this.roundClean();
196
+ return this;
197
+ }
198
+ digestInto(out) {
199
+ aexists(this);
200
+ aoutput(out, this);
201
+ this.finished = true;
202
+ const { buffer, view, blockLen, isLE } = this;
203
+ let { pos } = this;
204
+ buffer[pos++] = 128;
205
+ this.buffer.subarray(pos).fill(0);
206
+ if (this.padOffset > blockLen - pos) {
207
+ this.process(view, 0);
208
+ pos = 0;
209
+ }
210
+ for (let i = pos; i < blockLen; i++)
211
+ buffer[i] = 0;
212
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
213
+ this.process(view, 0);
214
+ const oview = createView(out);
215
+ const len = this.outputLen;
216
+ if (len % 4)
217
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
218
+ const outLen = len / 4;
219
+ const state = this.get();
220
+ if (outLen > state.length)
221
+ throw new Error("_sha2: outputLen bigger than state");
222
+ for (let i = 0; i < outLen; i++)
223
+ oview.setUint32(4 * i, state[i], isLE);
224
+ }
225
+ digest() {
226
+ const { buffer, outputLen } = this;
227
+ this.digestInto(buffer);
228
+ const res = buffer.slice(0, outputLen);
229
+ this.destroy();
230
+ return res;
231
+ }
232
+ _cloneInto(to) {
233
+ to || (to = new this.constructor());
234
+ to.set(...this.get());
235
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
236
+ to.length = length;
237
+ to.pos = pos;
238
+ to.finished = finished;
239
+ to.destroyed = destroyed;
240
+ if (length % blockLen)
241
+ to.buffer.set(buffer);
242
+ return to;
243
+ }
244
+ };
245
+
246
+ // ../../node_modules/viem/node_modules/@noble/hashes/esm/sha256.js
247
+ var SHA256_K = /* @__PURE__ */ new Uint32Array([
248
+ 1116352408,
249
+ 1899447441,
250
+ 3049323471,
251
+ 3921009573,
252
+ 961987163,
253
+ 1508970993,
254
+ 2453635748,
255
+ 2870763221,
256
+ 3624381080,
257
+ 310598401,
258
+ 607225278,
259
+ 1426881987,
260
+ 1925078388,
261
+ 2162078206,
262
+ 2614888103,
263
+ 3248222580,
264
+ 3835390401,
265
+ 4022224774,
266
+ 264347078,
267
+ 604807628,
268
+ 770255983,
269
+ 1249150122,
270
+ 1555081692,
271
+ 1996064986,
272
+ 2554220882,
273
+ 2821834349,
274
+ 2952996808,
275
+ 3210313671,
276
+ 3336571891,
277
+ 3584528711,
278
+ 113926993,
279
+ 338241895,
280
+ 666307205,
281
+ 773529912,
282
+ 1294757372,
283
+ 1396182291,
284
+ 1695183700,
285
+ 1986661051,
286
+ 2177026350,
287
+ 2456956037,
288
+ 2730485921,
289
+ 2820302411,
290
+ 3259730800,
291
+ 3345764771,
292
+ 3516065817,
293
+ 3600352804,
294
+ 4094571909,
295
+ 275423344,
296
+ 430227734,
297
+ 506948616,
298
+ 659060556,
299
+ 883997877,
300
+ 958139571,
301
+ 1322822218,
302
+ 1537002063,
303
+ 1747873779,
304
+ 1955562222,
305
+ 2024104815,
306
+ 2227730452,
307
+ 2361852424,
308
+ 2428436474,
309
+ 2756734187,
310
+ 3204031479,
311
+ 3329325298
312
+ ]);
313
+ var SHA256_IV = /* @__PURE__ */ new Uint32Array([
314
+ 1779033703,
315
+ 3144134277,
316
+ 1013904242,
317
+ 2773480762,
318
+ 1359893119,
319
+ 2600822924,
320
+ 528734635,
321
+ 1541459225
322
+ ]);
323
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
324
+ var SHA256 = class extends HashMD {
325
+ constructor() {
326
+ super(64, 32, 8, false);
327
+ this.A = SHA256_IV[0] | 0;
328
+ this.B = SHA256_IV[1] | 0;
329
+ this.C = SHA256_IV[2] | 0;
330
+ this.D = SHA256_IV[3] | 0;
331
+ this.E = SHA256_IV[4] | 0;
332
+ this.F = SHA256_IV[5] | 0;
333
+ this.G = SHA256_IV[6] | 0;
334
+ this.H = SHA256_IV[7] | 0;
335
+ }
336
+ get() {
337
+ const { A, B, C, D, E, F, G, H } = this;
338
+ return [A, B, C, D, E, F, G, H];
339
+ }
340
+ // prettier-ignore
341
+ set(A, B, C, D, E, F, G, H) {
342
+ this.A = A | 0;
343
+ this.B = B | 0;
344
+ this.C = C | 0;
345
+ this.D = D | 0;
346
+ this.E = E | 0;
347
+ this.F = F | 0;
348
+ this.G = G | 0;
349
+ this.H = H | 0;
350
+ }
351
+ process(view, offset) {
352
+ for (let i = 0; i < 16; i++, offset += 4)
353
+ SHA256_W[i] = view.getUint32(offset, false);
354
+ for (let i = 16; i < 64; i++) {
355
+ const W15 = SHA256_W[i - 15];
356
+ const W2 = SHA256_W[i - 2];
357
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
358
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
359
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
360
+ }
361
+ let { A, B, C, D, E, F, G, H } = this;
362
+ for (let i = 0; i < 64; i++) {
363
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
364
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
365
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
366
+ const T2 = sigma0 + Maj(A, B, C) | 0;
367
+ H = G;
368
+ G = F;
369
+ F = E;
370
+ E = D + T1 | 0;
371
+ D = C;
372
+ C = B;
373
+ B = A;
374
+ A = T1 + T2 | 0;
375
+ }
376
+ A = A + this.A | 0;
377
+ B = B + this.B | 0;
378
+ C = C + this.C | 0;
379
+ D = D + this.D | 0;
380
+ E = E + this.E | 0;
381
+ F = F + this.F | 0;
382
+ G = G + this.G | 0;
383
+ H = H + this.H | 0;
384
+ this.set(A, B, C, D, E, F, G, H);
385
+ }
386
+ roundClean() {
387
+ SHA256_W.fill(0);
388
+ }
389
+ destroy() {
390
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
391
+ this.buffer.fill(0);
392
+ }
393
+ };
394
+ var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
395
+
396
+ // ../../node_modules/viem/_esm/accounts/toAccount.js
397
+ function toAccount(source) {
398
+ if (typeof source === "string") {
399
+ if (!isAddress(source, { strict: false }))
400
+ throw new InvalidAddressError({ address: source });
401
+ return {
402
+ address: source,
403
+ type: "json-rpc"
404
+ };
405
+ }
406
+ if (!isAddress(source.address, { strict: false }))
407
+ throw new InvalidAddressError({ address: source.address });
408
+ return {
409
+ address: source.address,
410
+ nonceManager: source.nonceManager,
411
+ sign: source.sign,
412
+ experimental_signAuthorization: source.experimental_signAuthorization,
413
+ signMessage: source.signMessage,
414
+ signTransaction: source.signTransaction,
415
+ signTypedData: source.signTypedData,
416
+ source: "custom",
417
+ type: "local"
418
+ };
419
+ }
420
+
421
+ // ../../node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
422
+ function publicKeyToAddress(publicKey) {
423
+ const address = keccak256(`0x${publicKey.substring(4)}`).substring(26);
424
+ return checksumAddress(`0x${address}`);
425
+ }
426
+
427
+ // ../../node_modules/viem/_esm/utils/signature/serializeSignature.js
428
+ function serializeSignature({ r, s, to = "hex", v, yParity }) {
429
+ const yParity_ = (() => {
430
+ if (yParity === 0 || yParity === 1)
431
+ return yParity;
432
+ if (v && (v === 27n || v === 28n || v >= 35n))
433
+ return v % 2n === 0n ? 1 : 0;
434
+ throw new Error("Invalid `v` or `yParity` value");
435
+ })();
436
+ const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`;
437
+ if (to === "hex")
438
+ return signature;
439
+ return hexToBytes(signature);
440
+ }
441
+
442
+ // ../../node_modules/viem/_esm/accounts/utils/sign.js
443
+ var extraEntropy = false;
444
+ async function sign({ hash, privateKey, to = "object" }) {
445
+ const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), { lowS: true, extraEntropy });
446
+ const signature = {
447
+ r: numberToHex(r, { size: 32 }),
448
+ s: numberToHex(s, { size: 32 }),
449
+ v: recovery ? 28n : 27n,
450
+ yParity: recovery
451
+ };
452
+ return (() => {
453
+ if (to === "bytes" || to === "hex")
454
+ return serializeSignature({ ...signature, to });
455
+ return signature;
456
+ })();
457
+ }
458
+
459
+ // ../../node_modules/viem/_esm/utils/encoding/toRlp.js
460
+ function toRlp(bytes, to = "hex") {
461
+ const encodable = getEncodable(bytes);
462
+ const cursor = createCursor(new Uint8Array(encodable.length));
463
+ encodable.encode(cursor);
464
+ if (to === "hex")
465
+ return bytesToHex(cursor.bytes);
466
+ return cursor.bytes;
467
+ }
468
+ function getEncodable(bytes) {
469
+ if (Array.isArray(bytes))
470
+ return getEncodableList(bytes.map((x) => getEncodable(x)));
471
+ return getEncodableBytes(bytes);
472
+ }
473
+ function getEncodableList(list) {
474
+ const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
475
+ const sizeOfBodyLength = getSizeOfLength(bodyLength);
476
+ const length = (() => {
477
+ if (bodyLength <= 55)
478
+ return 1 + bodyLength;
479
+ return 1 + sizeOfBodyLength + bodyLength;
480
+ })();
481
+ return {
482
+ length,
483
+ encode(cursor) {
484
+ if (bodyLength <= 55) {
485
+ cursor.pushByte(192 + bodyLength);
486
+ } else {
487
+ cursor.pushByte(192 + 55 + sizeOfBodyLength);
488
+ if (sizeOfBodyLength === 1)
489
+ cursor.pushUint8(bodyLength);
490
+ else if (sizeOfBodyLength === 2)
491
+ cursor.pushUint16(bodyLength);
492
+ else if (sizeOfBodyLength === 3)
493
+ cursor.pushUint24(bodyLength);
494
+ else
495
+ cursor.pushUint32(bodyLength);
496
+ }
497
+ for (const { encode } of list) {
498
+ encode(cursor);
499
+ }
500
+ }
501
+ };
502
+ }
503
+ function getEncodableBytes(bytesOrHex) {
504
+ const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex;
505
+ const sizeOfBytesLength = getSizeOfLength(bytes.length);
506
+ const length = (() => {
507
+ if (bytes.length === 1 && bytes[0] < 128)
508
+ return 1;
509
+ if (bytes.length <= 55)
510
+ return 1 + bytes.length;
511
+ return 1 + sizeOfBytesLength + bytes.length;
512
+ })();
513
+ return {
514
+ length,
515
+ encode(cursor) {
516
+ if (bytes.length === 1 && bytes[0] < 128) {
517
+ cursor.pushBytes(bytes);
518
+ } else if (bytes.length <= 55) {
519
+ cursor.pushByte(128 + bytes.length);
520
+ cursor.pushBytes(bytes);
521
+ } else {
522
+ cursor.pushByte(128 + 55 + sizeOfBytesLength);
523
+ if (sizeOfBytesLength === 1)
524
+ cursor.pushUint8(bytes.length);
525
+ else if (sizeOfBytesLength === 2)
526
+ cursor.pushUint16(bytes.length);
527
+ else if (sizeOfBytesLength === 3)
528
+ cursor.pushUint24(bytes.length);
529
+ else
530
+ cursor.pushUint32(bytes.length);
531
+ cursor.pushBytes(bytes);
532
+ }
533
+ }
534
+ };
535
+ }
536
+ function getSizeOfLength(length) {
537
+ if (length < 2 ** 8)
538
+ return 1;
539
+ if (length < 2 ** 16)
540
+ return 2;
541
+ if (length < 2 ** 24)
542
+ return 3;
543
+ if (length < 2 ** 32)
544
+ return 4;
545
+ throw new BaseError("Length is too large.");
546
+ }
547
+
548
+ // ../../node_modules/viem/_esm/experimental/eip7702/utils/hashAuthorization.js
549
+ function hashAuthorization(parameters) {
550
+ const { chainId, contractAddress, nonce, to } = parameters;
551
+ const hash = keccak256(concatHex([
552
+ "0x05",
553
+ toRlp([
554
+ chainId ? numberToHex(chainId) : "0x",
555
+ contractAddress,
556
+ nonce ? numberToHex(nonce) : "0x"
557
+ ])
558
+ ]));
559
+ if (to === "bytes")
560
+ return hexToBytes(hash);
561
+ return hash;
562
+ }
563
+
564
+ // ../../node_modules/viem/_esm/accounts/utils/signAuthorization.js
565
+ async function experimental_signAuthorization(parameters) {
566
+ const { contractAddress, chainId, nonce, privateKey, to = "object" } = parameters;
567
+ const signature = await sign({
568
+ hash: hashAuthorization({ contractAddress, chainId, nonce }),
569
+ privateKey,
570
+ to
571
+ });
572
+ if (to === "object")
573
+ return {
574
+ contractAddress,
575
+ chainId,
576
+ nonce,
577
+ ...signature
578
+ };
579
+ return signature;
580
+ }
581
+
582
+ // ../../node_modules/viem/_esm/constants/strings.js
583
+ var presignMessagePrefix = "Ethereum Signed Message:\n";
584
+
585
+ // ../../node_modules/viem/_esm/utils/signature/toPrefixedMessage.js
586
+ function toPrefixedMessage(message_) {
587
+ const message = (() => {
588
+ if (typeof message_ === "string")
589
+ return stringToHex(message_);
590
+ if (typeof message_.raw === "string")
591
+ return message_.raw;
592
+ return bytesToHex(message_.raw);
593
+ })();
594
+ const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`);
595
+ return concat([prefix, message]);
596
+ }
597
+
598
+ // ../../node_modules/viem/_esm/utils/signature/hashMessage.js
599
+ function hashMessage(message, to_) {
600
+ return keccak256(toPrefixedMessage(message), to_);
601
+ }
602
+
603
+ // ../../node_modules/viem/_esm/accounts/utils/signMessage.js
604
+ async function signMessage({ message, privateKey }) {
605
+ return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
606
+ }
607
+
608
+ // ../../node_modules/viem/_esm/utils/blob/blobsToCommitments.js
609
+ function blobsToCommitments(parameters) {
610
+ const { kzg } = parameters;
611
+ const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
612
+ const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
613
+ const commitments = [];
614
+ for (const blob of blobs)
615
+ commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
616
+ return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x));
617
+ }
618
+
619
+ // ../../node_modules/viem/_esm/utils/blob/blobsToProofs.js
620
+ function blobsToProofs(parameters) {
621
+ const { kzg } = parameters;
622
+ const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
623
+ const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
624
+ const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments;
625
+ const proofs = [];
626
+ for (let i = 0; i < blobs.length; i++) {
627
+ const blob = blobs[i];
628
+ const commitment = commitments[i];
629
+ proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
630
+ }
631
+ return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x));
632
+ }
633
+
634
+ // ../../node_modules/viem/_esm/utils/hash/sha256.js
635
+ function sha2562(value, to_) {
636
+ const to = to_ || "hex";
637
+ const bytes = sha256(isHex(value, { strict: false }) ? toBytes2(value) : value);
638
+ if (to === "bytes")
639
+ return bytes;
640
+ return toHex(bytes);
641
+ }
642
+
643
+ // ../../node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
644
+ function commitmentToVersionedHash(parameters) {
645
+ const { commitment, version = 1 } = parameters;
646
+ const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
647
+ const versionedHash = sha2562(commitment, "bytes");
648
+ versionedHash.set([version], 0);
649
+ return to === "bytes" ? versionedHash : bytesToHex(versionedHash);
650
+ }
651
+
652
+ // ../../node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
653
+ function commitmentsToVersionedHashes(parameters) {
654
+ const { commitments, version } = parameters;
655
+ const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
656
+ const hashes = [];
657
+ for (const commitment of commitments) {
658
+ hashes.push(commitmentToVersionedHash({
659
+ commitment,
660
+ to,
661
+ version
662
+ }));
663
+ }
664
+ return hashes;
665
+ }
666
+
667
+ // ../../node_modules/viem/_esm/constants/blob.js
668
+ var blobsPerTransaction = 6;
669
+ var bytesPerFieldElement = 32;
670
+ var fieldElementsPerBlob = 4096;
671
+ var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
672
+ var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
673
+ 1 - // zero byte (0x00) appended to each field element.
674
+ 1 * fieldElementsPerBlob * blobsPerTransaction;
675
+
676
+ // ../../node_modules/viem/_esm/constants/kzg.js
677
+ var versionedHashVersionKzg = 1;
678
+
679
+ // ../../node_modules/viem/_esm/errors/blob.js
680
+ var BlobSizeTooLargeError = class extends BaseError {
681
+ constructor({ maxSize, size: size2 }) {
682
+ super("Blob size is too large.", {
683
+ metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`],
684
+ name: "BlobSizeTooLargeError"
685
+ });
686
+ }
687
+ };
688
+ var EmptyBlobError = class extends BaseError {
689
+ constructor() {
690
+ super("Blob data must not be empty.", { name: "EmptyBlobError" });
691
+ }
692
+ };
693
+ var InvalidVersionedHashSizeError = class extends BaseError {
694
+ constructor({ hash, size: size2 }) {
695
+ super(`Versioned hash "${hash}" size is invalid.`, {
696
+ metaMessages: ["Expected: 32", `Received: ${size2}`],
697
+ name: "InvalidVersionedHashSizeError"
698
+ });
699
+ }
700
+ };
701
+ var InvalidVersionedHashVersionError = class extends BaseError {
702
+ constructor({ hash, version }) {
703
+ super(`Versioned hash "${hash}" version is invalid.`, {
704
+ metaMessages: [
705
+ `Expected: ${versionedHashVersionKzg}`,
706
+ `Received: ${version}`
707
+ ],
708
+ name: "InvalidVersionedHashVersionError"
709
+ });
710
+ }
711
+ };
712
+
713
+ // ../../node_modules/viem/_esm/utils/blob/toBlobs.js
714
+ function toBlobs(parameters) {
715
+ const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
716
+ const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data;
717
+ const size_ = size(data);
718
+ if (!size_)
719
+ throw new EmptyBlobError();
720
+ if (size_ > maxBytesPerTransaction)
721
+ throw new BlobSizeTooLargeError({
722
+ maxSize: maxBytesPerTransaction,
723
+ size: size_
724
+ });
725
+ const blobs = [];
726
+ let active = true;
727
+ let position = 0;
728
+ while (active) {
729
+ const blob = createCursor(new Uint8Array(bytesPerBlob));
730
+ let size2 = 0;
731
+ while (size2 < fieldElementsPerBlob) {
732
+ const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
733
+ blob.pushByte(0);
734
+ blob.pushBytes(bytes);
735
+ if (bytes.length < 31) {
736
+ blob.pushByte(128);
737
+ active = false;
738
+ break;
739
+ }
740
+ size2++;
741
+ position += 31;
742
+ }
743
+ blobs.push(blob);
744
+ }
745
+ return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes));
746
+ }
747
+
748
+ // ../../node_modules/viem/_esm/utils/blob/toBlobSidecars.js
749
+ function toBlobSidecars(parameters) {
750
+ const { data, kzg, to } = parameters;
751
+ const blobs = parameters.blobs ?? toBlobs({ data, to });
752
+ const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
753
+ const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
754
+ const sidecars = [];
755
+ for (let i = 0; i < blobs.length; i++)
756
+ sidecars.push({
757
+ blob: blobs[i],
758
+ commitment: commitments[i],
759
+ proof: proofs[i]
760
+ });
761
+ return sidecars;
762
+ }
763
+
764
+ // ../../node_modules/viem/_esm/experimental/eip7702/utils/serializeAuthorizationList.js
765
+ function serializeAuthorizationList(authorizationList) {
766
+ if (!authorizationList || authorizationList.length === 0)
767
+ return [];
768
+ const serializedAuthorizationList = [];
769
+ for (const authorization of authorizationList) {
770
+ const { contractAddress, chainId, nonce, ...signature } = authorization;
771
+ serializedAuthorizationList.push([
772
+ chainId ? toHex(chainId) : "0x",
773
+ contractAddress,
774
+ nonce ? toHex(nonce) : "0x",
775
+ ...toYParitySignatureArray({}, signature)
776
+ ]);
777
+ }
778
+ return serializedAuthorizationList;
779
+ }
780
+
781
+ // ../../node_modules/viem/_esm/utils/transaction/assertTransaction.js
782
+ function assertTransactionEIP7702(transaction) {
783
+ const { authorizationList } = transaction;
784
+ if (authorizationList) {
785
+ for (const authorization of authorizationList) {
786
+ const { contractAddress, chainId } = authorization;
787
+ if (!isAddress(contractAddress))
788
+ throw new InvalidAddressError({ address: contractAddress });
789
+ if (chainId < 0)
790
+ throw new InvalidChainIdError({ chainId });
791
+ }
792
+ }
793
+ assertTransactionEIP1559(transaction);
794
+ }
795
+ function assertTransactionEIP4844(transaction) {
796
+ const { blobVersionedHashes } = transaction;
797
+ if (blobVersionedHashes) {
798
+ if (blobVersionedHashes.length === 0)
799
+ throw new EmptyBlobError();
800
+ for (const hash of blobVersionedHashes) {
801
+ const size_ = size(hash);
802
+ const version = hexToNumber(slice(hash, 0, 1));
803
+ if (size_ !== 32)
804
+ throw new InvalidVersionedHashSizeError({ hash, size: size_ });
805
+ if (version !== versionedHashVersionKzg)
806
+ throw new InvalidVersionedHashVersionError({
807
+ hash,
808
+ version
809
+ });
810
+ }
811
+ }
812
+ assertTransactionEIP1559(transaction);
813
+ }
814
+ function assertTransactionEIP1559(transaction) {
815
+ const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
816
+ if (chainId <= 0)
817
+ throw new InvalidChainIdError({ chainId });
818
+ if (to && !isAddress(to))
819
+ throw new InvalidAddressError({ address: to });
820
+ if (maxFeePerGas && maxFeePerGas > maxUint256)
821
+ throw new FeeCapTooHighError({ maxFeePerGas });
822
+ if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
823
+ throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
824
+ }
825
+ function assertTransactionEIP2930(transaction) {
826
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
827
+ if (chainId <= 0)
828
+ throw new InvalidChainIdError({ chainId });
829
+ if (to && !isAddress(to))
830
+ throw new InvalidAddressError({ address: to });
831
+ if (maxPriorityFeePerGas || maxFeePerGas)
832
+ throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
833
+ if (gasPrice && gasPrice > maxUint256)
834
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
835
+ }
836
+ function assertTransactionLegacy(transaction) {
837
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
838
+ if (to && !isAddress(to))
839
+ throw new InvalidAddressError({ address: to });
840
+ if (typeof chainId !== "undefined" && chainId <= 0)
841
+ throw new InvalidChainIdError({ chainId });
842
+ if (maxPriorityFeePerGas || maxFeePerGas)
843
+ throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
844
+ if (gasPrice && gasPrice > maxUint256)
845
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
846
+ }
847
+
848
+ // ../../node_modules/viem/_esm/utils/transaction/getTransactionType.js
849
+ function getTransactionType(transaction) {
850
+ if (transaction.type)
851
+ return transaction.type;
852
+ if (typeof transaction.authorizationList !== "undefined")
853
+ return "eip7702";
854
+ if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
855
+ return "eip4844";
856
+ if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
857
+ return "eip1559";
858
+ }
859
+ if (typeof transaction.gasPrice !== "undefined") {
860
+ if (typeof transaction.accessList !== "undefined")
861
+ return "eip2930";
862
+ return "legacy";
863
+ }
864
+ throw new InvalidSerializableTransactionError({ transaction });
865
+ }
866
+
867
+ // ../../node_modules/viem/_esm/utils/transaction/serializeAccessList.js
868
+ function serializeAccessList(accessList) {
869
+ if (!accessList || accessList.length === 0)
870
+ return [];
871
+ const serializedAccessList = [];
872
+ for (let i = 0; i < accessList.length; i++) {
873
+ const { address, storageKeys } = accessList[i];
874
+ for (let j = 0; j < storageKeys.length; j++) {
875
+ if (storageKeys[j].length - 2 !== 64) {
876
+ throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
877
+ }
878
+ }
879
+ if (!isAddress(address, { strict: false })) {
880
+ throw new InvalidAddressError({ address });
881
+ }
882
+ serializedAccessList.push([address, storageKeys]);
883
+ }
884
+ return serializedAccessList;
885
+ }
886
+
887
+ // ../../node_modules/viem/_esm/utils/transaction/serializeTransaction.js
888
+ function serializeTransaction(transaction, signature) {
889
+ const type = getTransactionType(transaction);
890
+ if (type === "eip1559")
891
+ return serializeTransactionEIP1559(transaction, signature);
892
+ if (type === "eip2930")
893
+ return serializeTransactionEIP2930(transaction, signature);
894
+ if (type === "eip4844")
895
+ return serializeTransactionEIP4844(transaction, signature);
896
+ if (type === "eip7702")
897
+ return serializeTransactionEIP7702(transaction, signature);
898
+ return serializeTransactionLegacy(transaction, signature);
899
+ }
900
+ function serializeTransactionEIP7702(transaction, signature) {
901
+ const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
902
+ assertTransactionEIP7702(transaction);
903
+ const serializedAccessList = serializeAccessList(accessList);
904
+ const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
905
+ return concatHex([
906
+ "0x04",
907
+ toRlp([
908
+ toHex(chainId),
909
+ nonce ? toHex(nonce) : "0x",
910
+ maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
911
+ maxFeePerGas ? toHex(maxFeePerGas) : "0x",
912
+ gas ? toHex(gas) : "0x",
913
+ to ?? "0x",
914
+ value ? toHex(value) : "0x",
915
+ data ?? "0x",
916
+ serializedAccessList,
917
+ serializedAuthorizationList,
918
+ ...toYParitySignatureArray(transaction, signature)
919
+ ])
920
+ ]);
921
+ }
922
+ function serializeTransactionEIP4844(transaction, signature) {
923
+ const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
924
+ assertTransactionEIP4844(transaction);
925
+ let blobVersionedHashes = transaction.blobVersionedHashes;
926
+ let sidecars = transaction.sidecars;
927
+ if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
928
+ const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x));
929
+ const kzg = transaction.kzg;
930
+ const commitments2 = blobsToCommitments({
931
+ blobs: blobs2,
932
+ kzg
933
+ });
934
+ if (typeof blobVersionedHashes === "undefined")
935
+ blobVersionedHashes = commitmentsToVersionedHashes({
936
+ commitments: commitments2
937
+ });
938
+ if (typeof sidecars === "undefined") {
939
+ const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
940
+ sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
941
+ }
942
+ }
943
+ const serializedAccessList = serializeAccessList(accessList);
944
+ const serializedTransaction = [
945
+ toHex(chainId),
946
+ nonce ? toHex(nonce) : "0x",
947
+ maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
948
+ maxFeePerGas ? toHex(maxFeePerGas) : "0x",
949
+ gas ? toHex(gas) : "0x",
950
+ to ?? "0x",
951
+ value ? toHex(value) : "0x",
952
+ data ?? "0x",
953
+ serializedAccessList,
954
+ maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x",
955
+ blobVersionedHashes ?? [],
956
+ ...toYParitySignatureArray(transaction, signature)
957
+ ];
958
+ const blobs = [];
959
+ const commitments = [];
960
+ const proofs = [];
961
+ if (sidecars)
962
+ for (let i = 0; i < sidecars.length; i++) {
963
+ const { blob, commitment, proof } = sidecars[i];
964
+ blobs.push(blob);
965
+ commitments.push(commitment);
966
+ proofs.push(proof);
967
+ }
968
+ return concatHex([
969
+ "0x03",
970
+ sidecars ? (
971
+ // If sidecars are enabled, envelope turns into a "wrapper":
972
+ toRlp([serializedTransaction, blobs, commitments, proofs])
973
+ ) : (
974
+ // If sidecars are disabled, standard envelope is used:
975
+ toRlp(serializedTransaction)
976
+ )
977
+ ]);
978
+ }
979
+ function serializeTransactionEIP1559(transaction, signature) {
980
+ const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
981
+ assertTransactionEIP1559(transaction);
982
+ const serializedAccessList = serializeAccessList(accessList);
983
+ const serializedTransaction = [
984
+ toHex(chainId),
985
+ nonce ? toHex(nonce) : "0x",
986
+ maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x",
987
+ maxFeePerGas ? toHex(maxFeePerGas) : "0x",
988
+ gas ? toHex(gas) : "0x",
989
+ to ?? "0x",
990
+ value ? toHex(value) : "0x",
991
+ data ?? "0x",
992
+ serializedAccessList,
993
+ ...toYParitySignatureArray(transaction, signature)
994
+ ];
995
+ return concatHex([
996
+ "0x02",
997
+ toRlp(serializedTransaction)
998
+ ]);
999
+ }
1000
+ function serializeTransactionEIP2930(transaction, signature) {
1001
+ const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
1002
+ assertTransactionEIP2930(transaction);
1003
+ const serializedAccessList = serializeAccessList(accessList);
1004
+ const serializedTransaction = [
1005
+ toHex(chainId),
1006
+ nonce ? toHex(nonce) : "0x",
1007
+ gasPrice ? toHex(gasPrice) : "0x",
1008
+ gas ? toHex(gas) : "0x",
1009
+ to ?? "0x",
1010
+ value ? toHex(value) : "0x",
1011
+ data ?? "0x",
1012
+ serializedAccessList,
1013
+ ...toYParitySignatureArray(transaction, signature)
1014
+ ];
1015
+ return concatHex([
1016
+ "0x01",
1017
+ toRlp(serializedTransaction)
1018
+ ]);
1019
+ }
1020
+ function serializeTransactionLegacy(transaction, signature) {
1021
+ const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
1022
+ assertTransactionLegacy(transaction);
1023
+ let serializedTransaction = [
1024
+ nonce ? toHex(nonce) : "0x",
1025
+ gasPrice ? toHex(gasPrice) : "0x",
1026
+ gas ? toHex(gas) : "0x",
1027
+ to ?? "0x",
1028
+ value ? toHex(value) : "0x",
1029
+ data ?? "0x"
1030
+ ];
1031
+ if (signature) {
1032
+ const v = (() => {
1033
+ if (signature.v >= 35n) {
1034
+ const inferredChainId = (signature.v - 35n) / 2n;
1035
+ if (inferredChainId > 0)
1036
+ return signature.v;
1037
+ return 27n + (signature.v === 35n ? 0n : 1n);
1038
+ }
1039
+ if (chainId > 0)
1040
+ return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);
1041
+ const v2 = 27n + (signature.v === 27n ? 0n : 1n);
1042
+ if (signature.v !== v2)
1043
+ throw new InvalidLegacyVError({ v: signature.v });
1044
+ return v2;
1045
+ })();
1046
+ const r = trim(signature.r);
1047
+ const s = trim(signature.s);
1048
+ serializedTransaction = [
1049
+ ...serializedTransaction,
1050
+ toHex(v),
1051
+ r === "0x00" ? "0x" : r,
1052
+ s === "0x00" ? "0x" : s
1053
+ ];
1054
+ } else if (chainId > 0) {
1055
+ serializedTransaction = [
1056
+ ...serializedTransaction,
1057
+ toHex(chainId),
1058
+ "0x",
1059
+ "0x"
1060
+ ];
1061
+ }
1062
+ return toRlp(serializedTransaction);
1063
+ }
1064
+ function toYParitySignatureArray(transaction, signature_) {
1065
+ const signature = signature_ ?? transaction;
1066
+ const { v, yParity } = signature;
1067
+ if (typeof signature.r === "undefined")
1068
+ return [];
1069
+ if (typeof signature.s === "undefined")
1070
+ return [];
1071
+ if (typeof v === "undefined" && typeof yParity === "undefined")
1072
+ return [];
1073
+ const r = trim(signature.r);
1074
+ const s = trim(signature.s);
1075
+ const yParity_ = (() => {
1076
+ if (typeof yParity === "number")
1077
+ return yParity ? toHex(1) : "0x";
1078
+ if (v === 0n)
1079
+ return "0x";
1080
+ if (v === 1n)
1081
+ return toHex(1);
1082
+ return v === 27n ? "0x" : toHex(1);
1083
+ })();
1084
+ return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s];
1085
+ }
1086
+
1087
+ // ../../node_modules/viem/_esm/accounts/utils/signTransaction.js
1088
+ async function signTransaction(parameters) {
1089
+ const { privateKey, transaction, serializer = serializeTransaction } = parameters;
1090
+ const signableTransaction = (() => {
1091
+ if (transaction.type === "eip4844")
1092
+ return {
1093
+ ...transaction,
1094
+ sidecars: false
1095
+ };
1096
+ return transaction;
1097
+ })();
1098
+ const signature = await sign({
1099
+ hash: keccak256(serializer(signableTransaction)),
1100
+ privateKey
1101
+ });
1102
+ return serializer(transaction, signature);
1103
+ }
1104
+
1105
+ // ../../node_modules/viem/_esm/errors/typedData.js
1106
+ var InvalidDomainError = class extends BaseError {
1107
+ constructor({ domain }) {
1108
+ super(`Invalid domain "${stringify(domain)}".`, {
1109
+ metaMessages: ["Must be a valid EIP-712 domain."]
1110
+ });
1111
+ }
1112
+ };
1113
+ var InvalidPrimaryTypeError = class extends BaseError {
1114
+ constructor({ primaryType, types }) {
1115
+ super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
1116
+ docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
1117
+ metaMessages: ["Check that the primary type is a key in `types`."]
1118
+ });
1119
+ }
1120
+ };
1121
+ var InvalidStructTypeError = class extends BaseError {
1122
+ constructor({ type }) {
1123
+ super(`Struct type "${type}" is invalid.`, {
1124
+ metaMessages: ["Struct type must not be a Solidity type."],
1125
+ name: "InvalidStructTypeError"
1126
+ });
1127
+ }
1128
+ };
1129
+
1130
+ // ../../node_modules/viem/_esm/utils/typedData.js
1131
+ function validateTypedData(parameters) {
1132
+ const { domain, message, primaryType, types } = parameters;
1133
+ const validateData = (struct, data) => {
1134
+ for (const param of struct) {
1135
+ const { name, type } = param;
1136
+ const value = data[name];
1137
+ const integerMatch = type.match(integerRegex);
1138
+ if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
1139
+ const [_type, base, size_] = integerMatch;
1140
+ numberToHex(value, {
1141
+ signed: base === "int",
1142
+ size: Number.parseInt(size_) / 8
1143
+ });
1144
+ }
1145
+ if (type === "address" && typeof value === "string" && !isAddress(value))
1146
+ throw new InvalidAddressError({ address: value });
1147
+ const bytesMatch = type.match(bytesRegex);
1148
+ if (bytesMatch) {
1149
+ const [_type, size_] = bytesMatch;
1150
+ if (size_ && size(value) !== Number.parseInt(size_))
1151
+ throw new BytesSizeMismatchError({
1152
+ expectedSize: Number.parseInt(size_),
1153
+ givenSize: size(value)
1154
+ });
1155
+ }
1156
+ const struct2 = types[type];
1157
+ if (struct2) {
1158
+ validateReference(type);
1159
+ validateData(struct2, value);
1160
+ }
1161
+ }
1162
+ };
1163
+ if (types.EIP712Domain && domain) {
1164
+ if (typeof domain !== "object")
1165
+ throw new InvalidDomainError({ domain });
1166
+ validateData(types.EIP712Domain, domain);
1167
+ }
1168
+ if (primaryType !== "EIP712Domain") {
1169
+ if (types[primaryType])
1170
+ validateData(types[primaryType], message);
1171
+ else
1172
+ throw new InvalidPrimaryTypeError({ primaryType, types });
1173
+ }
1174
+ }
1175
+ function getTypesForEIP712Domain({ domain }) {
1176
+ return [
1177
+ typeof domain?.name === "string" && { name: "name", type: "string" },
1178
+ domain?.version && { name: "version", type: "string" },
1179
+ typeof domain?.chainId === "number" && {
1180
+ name: "chainId",
1181
+ type: "uint256"
1182
+ },
1183
+ domain?.verifyingContract && {
1184
+ name: "verifyingContract",
1185
+ type: "address"
1186
+ },
1187
+ domain?.salt && { name: "salt", type: "bytes32" }
1188
+ ].filter(Boolean);
1189
+ }
1190
+ function validateReference(type) {
1191
+ if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
1192
+ throw new InvalidStructTypeError({ type });
1193
+ }
1194
+
1195
+ // ../../node_modules/viem/_esm/utils/signature/hashTypedData.js
1196
+ function hashTypedData(parameters) {
1197
+ const { domain = {}, message, primaryType } = parameters;
1198
+ const types = {
1199
+ EIP712Domain: getTypesForEIP712Domain({ domain }),
1200
+ ...parameters.types
1201
+ };
1202
+ validateTypedData({
1203
+ domain,
1204
+ message,
1205
+ primaryType,
1206
+ types
1207
+ });
1208
+ const parts = ["0x1901"];
1209
+ if (domain)
1210
+ parts.push(hashDomain({
1211
+ domain,
1212
+ types
1213
+ }));
1214
+ if (primaryType !== "EIP712Domain")
1215
+ parts.push(hashStruct({
1216
+ data: message,
1217
+ primaryType,
1218
+ types
1219
+ }));
1220
+ return keccak256(concat(parts));
1221
+ }
1222
+ function hashDomain({ domain, types }) {
1223
+ return hashStruct({
1224
+ data: domain,
1225
+ primaryType: "EIP712Domain",
1226
+ types
1227
+ });
1228
+ }
1229
+ function hashStruct({ data, primaryType, types }) {
1230
+ const encoded = encodeData({
1231
+ data,
1232
+ primaryType,
1233
+ types
1234
+ });
1235
+ return keccak256(encoded);
1236
+ }
1237
+ function encodeData({ data, primaryType, types }) {
1238
+ const encodedTypes = [{ type: "bytes32" }];
1239
+ const encodedValues = [hashType({ primaryType, types })];
1240
+ for (const field of types[primaryType]) {
1241
+ const [type, value] = encodeField({
1242
+ types,
1243
+ name: field.name,
1244
+ type: field.type,
1245
+ value: data[field.name]
1246
+ });
1247
+ encodedTypes.push(type);
1248
+ encodedValues.push(value);
1249
+ }
1250
+ return encodeAbiParameters(encodedTypes, encodedValues);
1251
+ }
1252
+ function hashType({ primaryType, types }) {
1253
+ const encodedHashType = toHex(encodeType({ primaryType, types }));
1254
+ return keccak256(encodedHashType);
1255
+ }
1256
+ function encodeType({ primaryType, types }) {
1257
+ let result = "";
1258
+ const unsortedDeps = findTypeDependencies({ primaryType, types });
1259
+ unsortedDeps.delete(primaryType);
1260
+ const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
1261
+ for (const type of deps) {
1262
+ result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
1263
+ }
1264
+ return result;
1265
+ }
1266
+ function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
1267
+ const match = primaryType_.match(/^\w*/u);
1268
+ const primaryType = match?.[0];
1269
+ if (results.has(primaryType) || types[primaryType] === void 0) {
1270
+ return results;
1271
+ }
1272
+ results.add(primaryType);
1273
+ for (const field of types[primaryType]) {
1274
+ findTypeDependencies({ primaryType: field.type, types }, results);
1275
+ }
1276
+ return results;
1277
+ }
1278
+ function encodeField({ types, name, type, value }) {
1279
+ if (types[type] !== void 0) {
1280
+ return [
1281
+ { type: "bytes32" },
1282
+ keccak256(encodeData({ data: value, primaryType: type, types }))
1283
+ ];
1284
+ }
1285
+ if (type === "bytes") {
1286
+ const prepend = value.length % 2 ? "0" : "";
1287
+ value = `0x${prepend + value.slice(2)}`;
1288
+ return [{ type: "bytes32" }, keccak256(value)];
1289
+ }
1290
+ if (type === "string")
1291
+ return [{ type: "bytes32" }, keccak256(toHex(value))];
1292
+ if (type.lastIndexOf("]") === type.length - 1) {
1293
+ const parsedType = type.slice(0, type.lastIndexOf("["));
1294
+ const typeValuePairs = value.map((item) => encodeField({
1295
+ name,
1296
+ type: parsedType,
1297
+ types,
1298
+ value: item
1299
+ }));
1300
+ return [
1301
+ { type: "bytes32" },
1302
+ keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
1303
+ ];
1304
+ }
1305
+ return [{ type }, value];
1306
+ }
1307
+
1308
+ // ../../node_modules/viem/_esm/accounts/utils/signTypedData.js
1309
+ async function signTypedData(parameters) {
1310
+ const { privateKey, ...typedData } = parameters;
1311
+ return await sign({
1312
+ hash: hashTypedData(typedData),
1313
+ privateKey,
1314
+ to: "hex"
1315
+ });
1316
+ }
1317
+
1318
+ // ../../node_modules/viem/_esm/accounts/privateKeyToAccount.js
1319
+ function privateKeyToAccount(privateKey, options = {}) {
1320
+ const { nonceManager } = options;
1321
+ const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
1322
+ const address = publicKeyToAddress(publicKey);
1323
+ const account = toAccount({
1324
+ address,
1325
+ nonceManager,
1326
+ async sign({ hash }) {
1327
+ return sign({ hash, privateKey, to: "hex" });
1328
+ },
1329
+ async experimental_signAuthorization(authorization) {
1330
+ return experimental_signAuthorization({ ...authorization, privateKey });
1331
+ },
1332
+ async signMessage({ message }) {
1333
+ return signMessage({ message, privateKey });
1334
+ },
1335
+ async signTransaction(transaction, { serializer } = {}) {
1336
+ return signTransaction({ privateKey, transaction, serializer });
1337
+ },
1338
+ async signTypedData(typedData) {
1339
+ return signTypedData({ ...typedData, privateKey });
1340
+ }
1341
+ });
1342
+ return {
1343
+ ...account,
1344
+ publicKey,
1345
+ source: "privateKey"
1346
+ };
1347
+ }
1348
+
1349
+ // src/providers/deriveKeyProvider.ts
93
1350
  var DeriveKeyProvider = class {
94
1351
  client;
95
1352
  raProvider;
@@ -98,19 +1355,19 @@ var DeriveKeyProvider = class {
98
1355
  switch (teeMode) {
99
1356
  case "LOCAL" /* LOCAL */:
100
1357
  endpoint = "http://localhost:8090";
101
- console.log(
1358
+ elizaLogger2.log(
102
1359
  "TEE: Connecting to local simulator at localhost:8090"
103
1360
  );
104
1361
  break;
105
1362
  case "DOCKER" /* DOCKER */:
106
1363
  endpoint = "http://host.docker.internal:8090";
107
- console.log(
1364
+ elizaLogger2.log(
108
1365
  "TEE: Connecting to simulator via Docker at host.docker.internal:8090"
109
1366
  );
110
1367
  break;
111
1368
  case "PRODUCTION" /* PRODUCTION */:
112
1369
  endpoint = void 0;
113
- console.log(
1370
+ elizaLogger2.log(
114
1371
  "TEE: Running in production mode without simulator"
115
1372
  );
116
1373
  break;
@@ -128,35 +1385,37 @@ var DeriveKeyProvider = class {
128
1385
  publicKey
129
1386
  };
130
1387
  const reportdata = JSON.stringify(deriveKeyData);
131
- console.log("Generating Remote Attestation Quote for Derive Key...");
1388
+ elizaLogger2.log(
1389
+ "Generating Remote Attestation Quote for Derive Key..."
1390
+ );
132
1391
  const quote = await this.raProvider.generateAttestation(reportdata);
133
- console.log("Remote Attestation Quote generated successfully!");
1392
+ elizaLogger2.log("Remote Attestation Quote generated successfully!");
134
1393
  return quote;
135
1394
  }
136
1395
  async rawDeriveKey(path, subject) {
137
1396
  try {
138
1397
  if (!path || !subject) {
139
- console.error(
1398
+ elizaLogger2.error(
140
1399
  "Path and Subject are required for key derivation"
141
1400
  );
142
1401
  }
143
- console.log("Deriving Raw Key in TEE...");
1402
+ elizaLogger2.log("Deriving Raw Key in TEE...");
144
1403
  const derivedKey = await this.client.deriveKey(path, subject);
145
- console.log("Raw Key Derived Successfully!");
1404
+ elizaLogger2.log("Raw Key Derived Successfully!");
146
1405
  return derivedKey;
147
1406
  } catch (error) {
148
- console.error("Error deriving raw key:", error);
1407
+ elizaLogger2.error("Error deriving raw key:", error);
149
1408
  throw error;
150
1409
  }
151
1410
  }
152
1411
  async deriveEd25519Keypair(path, subject, agentId) {
153
1412
  try {
154
1413
  if (!path || !subject) {
155
- console.error(
1414
+ elizaLogger2.error(
156
1415
  "Path and Subject are required for key derivation"
157
1416
  );
158
1417
  }
159
- console.log("Deriving Key in TEE...");
1418
+ elizaLogger2.log("Deriving Key in TEE...");
160
1419
  const derivedKey = await this.client.deriveKey(path, subject);
161
1420
  const uint8ArrayDerivedKey = derivedKey.asUint8Array();
162
1421
  const hash = crypto.createHash("sha256");
@@ -168,21 +1427,21 @@ var DeriveKeyProvider = class {
168
1427
  agentId,
169
1428
  keypair.publicKey.toBase58()
170
1429
  );
171
- console.log("Key Derived Successfully!");
1430
+ elizaLogger2.log("Key Derived Successfully!");
172
1431
  return { keypair, attestation };
173
1432
  } catch (error) {
174
- console.error("Error deriving key:", error);
1433
+ elizaLogger2.error("Error deriving key:", error);
175
1434
  throw error;
176
1435
  }
177
1436
  }
178
1437
  async deriveEcdsaKeypair(path, subject, agentId) {
179
1438
  try {
180
1439
  if (!path || !subject) {
181
- console.error(
1440
+ elizaLogger2.error(
182
1441
  "Path and Subject are required for key derivation"
183
1442
  );
184
1443
  }
185
- console.log("Deriving ECDSA Key in TEE...");
1444
+ elizaLogger2.log("Deriving ECDSA Key in TEE...");
186
1445
  const deriveKeyResponse = await this.client.deriveKey(path, subject);
187
1446
  const hex = keccak256(deriveKeyResponse.asUint8Array());
188
1447
  const keypair = privateKeyToAccount(hex);
@@ -190,10 +1449,10 @@ var DeriveKeyProvider = class {
190
1449
  agentId,
191
1450
  keypair.address
192
1451
  );
193
- console.log("ECDSA Key Derived Successfully!");
1452
+ elizaLogger2.log("ECDSA Key Derived Successfully!");
194
1453
  return { keypair, attestation };
195
1454
  } catch (error) {
196
- console.error("Error deriving ecdsa key:", error);
1455
+ elizaLogger2.error("Error deriving ecdsa key:", error);
197
1456
  throw error;
198
1457
  }
199
1458
  }
@@ -205,7 +1464,7 @@ var deriveKeyProvider = {
205
1464
  const agentId = runtime.agentId;
206
1465
  try {
207
1466
  if (!runtime.getSetting("WALLET_SECRET_SALT")) {
208
- console.error(
1467
+ elizaLogger2.error(
209
1468
  "Wallet secret salt is not configured in settings"
210
1469
  );
211
1470
  return "";
@@ -227,22 +1486,101 @@ var deriveKeyProvider = {
227
1486
  evm: evmKeypair.keypair.address
228
1487
  });
229
1488
  } catch (error) {
230
- console.error("Error creating PublicKey:", error);
1489
+ elizaLogger2.error("Error creating PublicKey:", error);
231
1490
  return "";
232
1491
  }
233
1492
  } catch (error) {
234
- console.error("Error in derive key provider:", error.message);
1493
+ elizaLogger2.error("Error in derive key provider:", error.message);
235
1494
  return `Failed to fetch derive key information: ${error instanceof Error ? error.message : "Unknown error"}`;
236
1495
  }
237
1496
  }
238
1497
  };
239
1498
 
1499
+ // src/actions/remoteAttestation.ts
1500
+ import { fetch } from "undici";
1501
+ function hexToUint8Array(hex) {
1502
+ hex = hex.trim();
1503
+ if (!hex) {
1504
+ throw new Error("Invalid hex string");
1505
+ }
1506
+ if (hex.startsWith("0x")) {
1507
+ hex = hex.substring(2);
1508
+ }
1509
+ if (hex.length % 2 !== 0) {
1510
+ throw new Error("Invalid hex string");
1511
+ }
1512
+ const array = new Uint8Array(hex.length / 2);
1513
+ for (let i = 0; i < hex.length; i += 2) {
1514
+ const byte = parseInt(hex.slice(i, i + 2), 16);
1515
+ if (isNaN(byte)) {
1516
+ throw new Error("Invalid hex string");
1517
+ }
1518
+ array[i / 2] = byte;
1519
+ }
1520
+ return array;
1521
+ }
1522
+ async function uploadUint8Array(data) {
1523
+ const blob = new Blob([data], { type: "application/octet-stream" });
1524
+ const formData = new FormData();
1525
+ formData.append("file", blob, "quote.bin");
1526
+ return await fetch("https://proof.t16z.com/api/upload", {
1527
+ method: "POST",
1528
+ body: formData
1529
+ });
1530
+ }
1531
+ var remoteAttestationAction = {
1532
+ name: "REMOTE_ATTESTATION",
1533
+ similes: ["REMOTE_ATTESTATION", "TEE_REMOTE_ATTESTATION", "TEE_ATTESTATION"],
1534
+ description: "Generate a remote attestation to prove that the agent is running in a TEE",
1535
+ handler: async (runtime, _message, _state, _options, callback) => {
1536
+ try {
1537
+ const agentId = runtime.agentId;
1538
+ const teeMode = runtime.getSetting("TEE_MODE");
1539
+ const provider = new RemoteAttestationProvider(teeMode);
1540
+ const attestation = await provider.generateAttestation(agentId, "raw");
1541
+ const attestationData = hexToUint8Array(attestation.quote);
1542
+ const response = await uploadUint8Array(attestationData);
1543
+ const data = await response.json();
1544
+ callback({
1545
+ text: `Here's my \u{1F9FE} RA Quote \u{1FAE1}
1546
+ https://proof.t16z.com/reports/${data.checksum}`,
1547
+ action: "NONE"
1548
+ });
1549
+ return true;
1550
+ } catch (error) {
1551
+ console.error("Failed to fetch remote attestation: ", error);
1552
+ return false;
1553
+ }
1554
+ },
1555
+ validate: async (_runtime) => {
1556
+ return true;
1557
+ },
1558
+ examples: [
1559
+ [
1560
+ {
1561
+ user: "{{user1}}",
1562
+ content: {
1563
+ text: "If you are running in a TEE, generate a remote attestation"
1564
+ }
1565
+ },
1566
+ {
1567
+ user: "{{user2}}",
1568
+ content: {
1569
+ text: "Of course, one second...",
1570
+ action: "REMOTE_ATTESTATION"
1571
+ }
1572
+ }
1573
+ ]
1574
+ ]
1575
+ };
1576
+
240
1577
  // src/index.ts
241
1578
  var teePlugin = {
242
1579
  name: "tee",
243
1580
  description: "TEE plugin with actions to generate remote attestations and derive keys",
244
1581
  actions: [
245
1582
  /* custom actions */
1583
+ remoteAttestationAction
246
1584
  ],
247
1585
  evaluators: [
248
1586
  /* custom evaluators */