@chainlink/cre-sdk 1.16.0 → 1.17.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +2 -62
  2. package/dist/generated/capabilities/blockchain/aptos/v1alpha/client_pb.d.ts +1035 -0
  3. package/dist/generated/capabilities/blockchain/aptos/v1alpha/client_pb.js +290 -0
  4. package/dist/generated/capabilities/blockchain/solana/v1alpha/client_pb.d.ts +2885 -15
  5. package/dist/generated/capabilities/blockchain/solana/v1alpha/client_pb.js +459 -7
  6. package/dist/generated/capabilities/networking/http/v1alpha/client_pb.js +1 -1
  7. package/dist/generated/sdk/v1alpha/sdk_pb.d.ts +505 -0
  8. package/dist/generated/sdk/v1alpha/sdk_pb.js +121 -15
  9. package/dist/generated/tools/generator/v1alpha/cre_metadata_pb.d.ts +30 -1
  10. package/dist/generated/tools/generator/v1alpha/cre_metadata_pb.js +20 -2
  11. package/dist/generated/workflows/v2/cre_info_pb.d.ts +123 -0
  12. package/dist/generated/workflows/v2/cre_info_pb.js +17 -0
  13. package/dist/generated/workflows/v2/workflow_key_pb.d.ts +55 -0
  14. package/dist/generated/workflows/v2/workflow_key_pb.js +17 -0
  15. package/dist/generated/workflows/v2/workflow_user_metric_pb.d.ts +118 -0
  16. package/dist/generated/workflows/v2/workflow_user_metric_pb.js +41 -0
  17. package/dist/generated-sdk/capabilities/blockchain/aptos/v1alpha/client_sdk_gen.d.ts +63 -0
  18. package/dist/generated-sdk/capabilities/blockchain/aptos/v1alpha/client_sdk_gen.js +247 -0
  19. package/dist/generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen.d.ts +13 -0
  20. package/dist/generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen.js +94 -0
  21. package/dist/generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen.d.ts +69 -2
  22. package/dist/generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen.js +403 -1
  23. package/dist/generated-sdk/capabilities/internal/consensus/v1alpha/consensus_sdk_gen.d.ts +5 -1
  24. package/dist/generated-sdk/capabilities/internal/consensus/v1alpha/consensus_sdk_gen.js +22 -0
  25. package/dist/generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen.d.ts +4 -0
  26. package/dist/generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen.js +12 -0
  27. package/dist/generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen.d.ts +11 -1
  28. package/dist/generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen.js +12 -0
  29. package/dist/generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen.d.ts +2 -0
  30. package/dist/generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen.js +2 -0
  31. package/dist/generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen.d.ts +2 -0
  32. package/dist/generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen.js +2 -0
  33. package/dist/sdk/cre/index.d.ts +30 -15
  34. package/dist/sdk/cre/index.js +29 -14
  35. package/dist/sdk/impl/runtime-impl.d.ts +28 -1
  36. package/dist/sdk/impl/runtime-impl.js +52 -1
  37. package/dist/sdk/runtime.d.ts +23 -1
  38. package/dist/sdk/tee-constraints.d.ts +68 -0
  39. package/dist/sdk/tee-constraints.js +59 -0
  40. package/dist/sdk/test/evm-contract-mock.js +58 -60
  41. package/dist/sdk/test/generated/capabilities/blockchain/aptos/v1alpha/aptos_mock_gen.d.ts +25 -0
  42. package/dist/sdk/test/generated/capabilities/blockchain/aptos/v1alpha/aptos_mock_gen.js +111 -0
  43. package/dist/sdk/test/generated/capabilities/blockchain/solana/v1alpha/solana_mock_gen.d.ts +19 -1
  44. package/dist/sdk/test/generated/capabilities/blockchain/solana/v1alpha/solana_mock_gen.js +141 -1
  45. package/dist/sdk/test/generated/index.d.ts +1 -0
  46. package/dist/sdk/test/generated/index.js +1 -0
  47. package/dist/sdk/test/index.d.ts +0 -1
  48. package/dist/sdk/test/index.js +0 -1
  49. package/dist/sdk/testutils/index.d.ts +1 -1
  50. package/dist/sdk/testutils/index.js +1 -1
  51. package/dist/sdk/testutils/test-runtime.d.ts +17 -4
  52. package/dist/sdk/testutils/test-runtime.js +31 -5
  53. package/dist/sdk/testutils/test-writer.d.ts +7 -1
  54. package/dist/sdk/testutils/test-writer.js +13 -1
  55. package/dist/sdk/types/global.d.ts +8 -0
  56. package/dist/sdk/utils/capabilities/blockchain/{evm/evm-helpers.d.ts → blockchain-helpers.d.ts} +6 -7
  57. package/dist/sdk/utils/capabilities/blockchain/{evm/evm-helpers.js → blockchain-helpers.js} +8 -6
  58. package/dist/sdk/utils/hex-utils.d.ts +0 -6
  59. package/dist/sdk/utils/hex-utils.js +0 -8
  60. package/dist/sdk/utils/index.d.ts +1 -3
  61. package/dist/sdk/utils/index.js +1 -2
  62. package/dist/sdk/wasm/host-bindings.d.ts +4 -0
  63. package/dist/sdk/wasm/host-bindings.js +4 -0
  64. package/dist/sdk/wasm/runner.d.ts +10 -4
  65. package/dist/sdk/wasm/runner.js +86 -13
  66. package/dist/sdk/wasm/runtime.d.ts +4 -1
  67. package/dist/sdk/wasm/runtime.js +9 -1
  68. package/dist/sdk/workflow.d.ts +16 -7
  69. package/dist/sdk/workflow.js +10 -2
  70. package/dist/workflows/standard_tests/restrictions/test.ts +41 -0
  71. package/dist/workflows/standard_tests/tee_runtime/test.ts +29 -0
  72. package/package.json +3 -6
  73. package/scripts/src/generate-sdks.ts +6 -0
  74. package/dist/sdk/test/contract-mock-core.d.ts +0 -16
  75. package/dist/sdk/test/contract-mock-core.js +0 -21
  76. package/dist/sdk/test/solana-contract-mock.d.ts +0 -54
  77. package/dist/sdk/test/solana-contract-mock.js +0 -63
  78. package/dist/sdk/utils/capabilities/blockchain/report-helpers.d.ts +0 -19
  79. package/dist/sdk/utils/capabilities/blockchain/report-helpers.js +0 -16
  80. package/dist/sdk/utils/capabilities/blockchain/solana/solana-helpers.d.ts +0 -101
  81. package/dist/sdk/utils/capabilities/blockchain/solana/solana-helpers.js +0 -100
@@ -1,31 +1,35 @@
1
1
  /**
2
2
  * Public API for the CRE SDK.
3
3
  */
4
- import { ClientCapability as EVMClient } from '../../generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen';
5
- import { ClientCapability as SolanaClient } from '../../generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen';
6
- import { ClientCapability as ConfidentialHTTPClient } from '../../generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen';
7
- import { ClientCapability as HTTPClient } from '../../generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen';
8
- import { HTTPCapability } from '../../generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen';
9
- import { CronCapability } from '../../generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen';
4
+ import { ClientCapability as AptosClient, ClientRestrictor as AptosRestrictor, } from '../../generated-sdk/capabilities/blockchain/aptos/v1alpha/client_sdk_gen';
5
+ import { ClientCapability as EVMClient, ClientRestrictor as EVMRestrictor, } from '../../generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen';
6
+ import { ClientCapability as SolanaClient, ClientRestrictor as SolanaRestrictor, } from '../../generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen';
7
+ import { ClientCapability as ConfidentialHTTPClient, ClientRestrictor as ConfidentialHTTPRestrictor, } from '../../generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen';
8
+ import { ClientCapability as HTTPClient, ClientRestrictor as HTTPClientRestrictor, } from '../../generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen';
9
+ import { HTTPCapability, HTTPRestrictor, } from '../../generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen';
10
+ import { CronCapability, CronRestrictor, } from '../../generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen';
10
11
  import { prepareRuntime } from '../utils/prepare-runtime';
11
- import { handler } from '../workflow';
12
+ import { handler, handlerInTee } from '../workflow';
12
13
  /**
13
14
  * Public exports for the CRE SDK.
14
15
  */
15
16
  export { TxStatus, } from '../../generated/capabilities/blockchain/evm/v1alpha/client_pb';
16
17
  export { ReceiverContractExecutionStatus as SolanaReceiverContractExecutionStatus, TxStatus as SolanaTxStatus, } from '../../generated/capabilities/blockchain/solana/v1alpha/client_pb';
18
+ export { TeeType } from '../../generated/sdk/v1alpha/sdk_pb';
19
+ // Aptos Capability
20
+ export { ClientCapability as AptosClient, ClientRestrictor as AptosRestrictor, } from '../../generated-sdk/capabilities/blockchain/aptos/v1alpha/client_sdk_gen';
17
21
  // EVM Capability
18
- export { ClientCapability as EVMClient, } from '../../generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen';
22
+ export { ClientCapability as EVMClient, ClientRestrictor as EVMRestrictor, } from '../../generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen';
19
23
  // Solana Capability
20
- export { ClientCapability as SolanaClient, } from '../../generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen';
24
+ export { ClientCapability as SolanaClient, ClientRestrictor as SolanaRestrictor, } from '../../generated-sdk/capabilities/blockchain/solana/v1alpha/client_sdk_gen';
21
25
  // Confidential HTTP Capability
22
- export { ClientCapability as ConfidentialHTTPClient } from '../../generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen';
26
+ export { ClientCapability as ConfidentialHTTPClient, ClientRestrictor as ConfidentialHTTPRestrictor, } from '../../generated-sdk/capabilities/networking/confidentialhttp/v1alpha/client_sdk_gen';
23
27
  // HTTP Capability
24
- export { ClientCapability as HTTPClient, } from '../../generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen';
25
- export { HTTPCapability } from '../../generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen';
28
+ export { ClientCapability as HTTPClient, ClientRestrictor as HTTPClientRestrictor, } from '../../generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen';
29
+ export { HTTPCapability, HTTPRestrictor, } from '../../generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen';
26
30
  // CRON Capability
27
- export { CronCapability } from '../../generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen';
28
- export { handler } from '../workflow';
31
+ export { CronCapability, CronRestrictor, } from '../../generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen';
32
+ export { handler, handlerInTee, NITRO_REGIONS, REGIONS } from '../workflow';
29
33
  prepareRuntime();
30
34
  export const cre = {
31
35
  capabilities: {
@@ -34,7 +38,18 @@ export const cre = {
34
38
  ConfidentialHTTPClient,
35
39
  HTTPClient,
36
40
  EVMClient,
41
+ AptosClient,
37
42
  SolanaClient,
38
43
  },
44
+ restrictors: {
45
+ CronRestrictor,
46
+ HTTPRestrictor,
47
+ ConfidentialHTTPRestrictor,
48
+ HTTPClientRestrictor,
49
+ EVMRestrictor,
50
+ SolanaRestrictor,
51
+ AptosRestrictor,
52
+ },
39
53
  handler,
54
+ handlerInTee,
40
55
  };
@@ -1,6 +1,6 @@
1
1
  import { type Message } from '@bufbuild/protobuf';
2
2
  import { type AwaitCapabilitiesRequest, type AwaitCapabilitiesResponse, type AwaitSecretsRequest, type AwaitSecretsResponse, type CapabilityRequest, type GetSecretsRequest, Mode, type Secret, type SecretRequest, type SecretRequestJson } from '../../generated/sdk/v1alpha/sdk_pb';
3
- import type { BaseRuntime, CallCapabilityParams, NodeRuntime, ReportRequest, ReportRequestJson, Runtime } from '..';
3
+ import type { BaseRuntime, CallCapabilityParams, NodeRuntime, ReportRequest, ReportRequestJson, Runtime, TeeRuntime } from '..';
4
4
  import type { Report } from '../report';
5
5
  import { type ConsensusAggregation, type PrimitiveTypes, type UnwrapOptions } from '../utils';
6
6
  /**
@@ -44,7 +44,10 @@ export declare class BaseRuntimeImpl<C> implements BaseRuntime<C> {
44
44
  now(): Date;
45
45
  sleep(ms: number): void;
46
46
  log(message: string): void;
47
+ emitMetric(name: string, value: number, type: MetricType, labels?: Record<string, string>): boolean;
47
48
  }
49
+ /** Ergonomic union for {@link BaseRuntimeImpl.emitMetric}. */
50
+ export type MetricType = 'counter' | 'gauge';
48
51
  /**
49
52
  * It is used when a BFT guarantee cannot be provided automatically (e.g. calling a standard API).
50
53
  * You tell each node to perform a task on its own.
@@ -94,6 +97,25 @@ export declare class RuntimeImpl<C> extends BaseRuntimeImpl<C> implements Runtim
94
97
  result: () => Report;
95
98
  };
96
99
  }
100
+ export declare class TeeRuntimeImpl<C> implements TeeRuntime<C> {
101
+ config: C;
102
+ nextCallId: number;
103
+ private readonly runtime;
104
+ constructor(config: C, nextCallId: number, helpers: RuntimeHelpers, maxResponseSize: bigint);
105
+ getSecret(request: SecretRequest | SecretRequestJson): {
106
+ result: () => Secret;
107
+ };
108
+ now(): Date;
109
+ log(message: string): void;
110
+ emitMetric(name: string, value: number, type: MetricType, labels?: Record<string, string>): boolean;
111
+ callCapability<I extends Message, O extends Message>({ capabilityId, method, payload, inputSchema, outputSchema, }: CallCapabilityParams<I, O>): {
112
+ result: () => O;
113
+ };
114
+ reportFromDon(input: ReportRequest | ReportRequestJson): {
115
+ result: () => Report;
116
+ };
117
+ usingTheDons(): Runtime<C>;
118
+ }
97
119
  /**
98
120
  * Interface to the WASM host environment.
99
121
  * Provides low-level access to capabilities, secrets, and utilities.
@@ -115,4 +137,9 @@ export interface RuntimeHelpers {
115
137
  sleep(ms: number): void;
116
138
  /** Logs a message to the host environment. */
117
139
  log(message: string): void;
140
+ /**
141
+ * Emits a user metric to the host. Payload is a protobuf-encoded
142
+ * `workflows.v2.WorkflowUserMetric`. Returns false if the host rejected it.
143
+ */
144
+ emitMetric(payload: Uint8Array): boolean;
118
145
  }
@@ -1,7 +1,8 @@
1
- import { create } from '@bufbuild/protobuf';
1
+ import { create, toBinary } from '@bufbuild/protobuf';
2
2
  import { anyPack, anyUnpack } from '@bufbuild/protobuf/wkt';
3
3
  import { deserializeErrorFromString } from '../../capabilities/errors';
4
4
  import { AwaitCapabilitiesRequestSchema, AwaitSecretsRequestSchema, CapabilityRequestSchema, GetSecretsRequestSchema, Mode, SecretRequestSchema, SimpleConsensusInputsSchema, } from '../../generated/sdk/v1alpha/sdk_pb';
5
+ import { UserMetricType, WorkflowUserMetricSchema, } from '../../generated/workflows/v2/workflow_user_metric_pb';
5
6
  import { ConsensusCapability } from '../../generated-sdk/capabilities/internal/consensus/v1alpha/consensus_sdk_gen';
6
7
  import { Value, } from '../utils';
7
8
  import { CapabilityRuntimeError, DonModeError, NodeModeError, SecretsError } from '../errors';
@@ -139,7 +140,20 @@ export class BaseRuntimeImpl {
139
140
  log(message) {
140
141
  this.helpers.log(message);
141
142
  }
143
+ emitMetric(name, value, type, labels) {
144
+ const metric = create(WorkflowUserMetricSchema, {
145
+ name,
146
+ value,
147
+ type: METRIC_TYPE_TO_PROTO[type],
148
+ labels: labels ?? {},
149
+ });
150
+ return this.helpers.emitMetric(toBinary(WorkflowUserMetricSchema, metric));
151
+ }
142
152
  }
153
+ const METRIC_TYPE_TO_PROTO = {
154
+ counter: UserMetricType.COUNTER,
155
+ gauge: UserMetricType.GAUGE,
156
+ };
143
157
  /**
144
158
  * It is used when a BFT guarantee cannot be provided automatically (e.g. calling a standard API).
145
159
  * You tell each node to perform a task on its own.
@@ -321,6 +335,43 @@ export class RuntimeImpl extends BaseRuntimeImpl {
321
335
  };
322
336
  }
323
337
  }
338
+ export class TeeRuntimeImpl {
339
+ config;
340
+ nextCallId;
341
+ runtime;
342
+ constructor(config, nextCallId, helpers, maxResponseSize) {
343
+ this.config = config;
344
+ this.nextCallId = nextCallId;
345
+ this.runtime = new RuntimeImpl(config, nextCallId, helpers, maxResponseSize);
346
+ }
347
+ getSecret(request) {
348
+ return this.runtime.getSecret(request);
349
+ }
350
+ now() {
351
+ return this.runtime.now();
352
+ }
353
+ log(message) {
354
+ this.runtime.log(message);
355
+ }
356
+ emitMetric(name, value, type, labels) {
357
+ return this.runtime.emitMetric(name, value, type, labels);
358
+ }
359
+ callCapability({ capabilityId, method, payload, inputSchema, outputSchema, }) {
360
+ return this.runtime.callCapability({
361
+ capabilityId,
362
+ method,
363
+ payload,
364
+ inputSchema,
365
+ outputSchema,
366
+ });
367
+ }
368
+ reportFromDon(input) {
369
+ return this.runtime.report(input);
370
+ }
371
+ usingTheDons() {
372
+ return this.runtime;
373
+ }
374
+ }
324
375
  function clearIgnoredFields(value, descriptor) {
325
376
  if (!descriptor || !value) {
326
377
  return;
@@ -1,10 +1,11 @@
1
1
  import type { Message } from '@bufbuild/protobuf';
2
2
  import type { GenMessage } from '@bufbuild/protobuf/codegenv2';
3
3
  import type { ReportRequest, ReportRequestJson } from '../generated/sdk/v1alpha/sdk_pb';
4
+ import type { MetricType } from './impl/runtime-impl';
4
5
  import type { Report } from './report';
5
6
  import type { ConsensusAggregation, PrimitiveTypes, UnwrapOptions } from './utils';
6
7
  import type { SecretsProvider } from '.';
7
- export type { ReportRequest, ReportRequestJson };
8
+ export type { ReportRequest, ReportRequestJson, MetricType };
8
9
  export type CallCapabilityParams<I extends Message, O extends Message> = {
9
10
  capabilityId: string;
10
11
  method: string;
@@ -23,6 +24,7 @@ export interface BaseRuntime<C> {
23
24
  };
24
25
  now(): Date;
25
26
  log(message: string): void;
27
+ emitMetric(name: string, value: number, type: MetricType, labels?: Record<string, string>): boolean;
26
28
  }
27
29
  /**
28
30
  * Runtime for Node mode execution.
@@ -30,6 +32,26 @@ export interface BaseRuntime<C> {
30
32
  export interface NodeRuntime<C> extends BaseRuntime<C> {
31
33
  readonly _isNodeRuntime: true;
32
34
  }
35
+ /**
36
+ * Runtime for Tee mode execution.
37
+ */
38
+ export interface TeeRuntime<C> extends BaseRuntime<C>, SecretsProvider {
39
+ /**
40
+ * Generates a report from the DON.
41
+ * Data requestsed throught this method will be routed outside of the TEE.
42
+ *
43
+ * @param input - Report request to generate a report from the DON
44
+ * @returns Report generated from the DON
45
+ */
46
+ reportFromDon(input: ReportRequest | ReportRequestJson): {
47
+ result: () => Report;
48
+ };
49
+ /**
50
+ * Returns the runtime that makes requests to the CRE DONs.
51
+ * Requests made through this runtime will therefore be routed outside of the TEE
52
+ */
53
+ usingTheDons(): Runtime<C>;
54
+ }
33
55
  /**
34
56
  * Runtime for DON mode execution.
35
57
  */
@@ -0,0 +1,68 @@
1
+ import type { Requirements } from '../generated/sdk/v1alpha/sdk_pb';
2
+ import { z } from 'zod';
3
+ export declare const REGIONS: readonly ["us-west-2"];
4
+ export declare const NITRO_REGIONS: readonly ["us-west-2"];
5
+ declare const regionSchema: z.ZodEnum<["us-west-2"]>;
6
+ declare const nitroRegionSchema: z.ZodEnum<["us-west-2"]>;
7
+ declare const nitroBindingSchema: z.ZodObject<{
8
+ tee: z.ZodLiteral<"nitro">;
9
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
10
+ }, "strict", z.ZodTypeAny, {
11
+ tee: "nitro";
12
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
13
+ }, {
14
+ tee: "nitro";
15
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
16
+ }>;
17
+ declare const teeBindingSchema: z.ZodDiscriminatedUnion<"tee", [z.ZodObject<{
18
+ tee: z.ZodLiteral<"nitro">;
19
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
20
+ }, "strict", z.ZodTypeAny, {
21
+ tee: "nitro";
22
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
23
+ }, {
24
+ tee: "nitro";
25
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
26
+ }>]>;
27
+ declare const oneOfTeesSchema: z.ZodArray<z.ZodDiscriminatedUnion<"tee", [z.ZodObject<{
28
+ tee: z.ZodLiteral<"nitro">;
29
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
30
+ }, "strict", z.ZodTypeAny, {
31
+ tee: "nitro";
32
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
33
+ }, {
34
+ tee: "nitro";
35
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
36
+ }>]>, "atleastone">;
37
+ declare const anyTeeConstraintSchema: z.ZodObject<{
38
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
39
+ }, "strict", z.ZodTypeAny, {
40
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
41
+ }, {
42
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
43
+ }>;
44
+ export declare const teeConstraintSchema: z.ZodUnion<[z.ZodArray<z.ZodDiscriminatedUnion<"tee", [z.ZodObject<{
45
+ tee: z.ZodLiteral<"nitro">;
46
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
47
+ }, "strict", z.ZodTypeAny, {
48
+ tee: "nitro";
49
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
50
+ }, {
51
+ tee: "nitro";
52
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
53
+ }>]>, "atleastone">, z.ZodObject<{
54
+ regions: z.ZodOptional<z.ZodArray<z.ZodEnum<["us-west-2"]>, "atleastone">>;
55
+ }, "strict", z.ZodTypeAny, {
56
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
57
+ }, {
58
+ regions?: ["us-west-2", ..."us-west-2"[]] | undefined;
59
+ }>]>;
60
+ export type Region = z.infer<typeof regionSchema>;
61
+ export type NitroRegion = z.infer<typeof nitroRegionSchema>;
62
+ export type NitroBinding = z.infer<typeof nitroBindingSchema>;
63
+ export type TeeBinding = z.infer<typeof teeBindingSchema>;
64
+ export type OneOfTees = z.infer<typeof oneOfTeesSchema>;
65
+ export type AnyTeeConstraint = z.infer<typeof anyTeeConstraintSchema>;
66
+ export type TeeConstraint = z.infer<typeof teeConstraintSchema>;
67
+ export declare function buildTeeRequirements(input: TeeConstraint): Requirements;
68
+ export {};
@@ -0,0 +1,59 @@
1
+ import { create } from '@bufbuild/protobuf';
2
+ import { RegionsSchema, RequirementsSchema, TeeSchema, TeeType, TeeTypesAndRegionsSchema, } from '../generated/sdk/v1alpha/sdk_pb';
3
+ import { z } from 'zod';
4
+ // --- Region schemas (source of truth) ---
5
+ export const REGIONS = ['us-west-2'];
6
+ export const NITRO_REGIONS = ['us-west-2'];
7
+ const regionSchema = z.enum(REGIONS, {
8
+ message: `unknown region; expected one of: ${REGIONS.join(', ')}`,
9
+ });
10
+ const nitroRegionSchema = z.enum(NITRO_REGIONS, {
11
+ message: `aws nitro does not support this region; expected one of: ${NITRO_REGIONS.join(', ')}`,
12
+ });
13
+ // --- TeeConstraint schemas (types inferred from these) ---
14
+ const nitroBindingSchema = z
15
+ .object({
16
+ tee: z.literal('nitro'),
17
+ regions: z.array(nitroRegionSchema).nonempty().optional(),
18
+ })
19
+ .strict();
20
+ const teeBindingSchema = z.discriminatedUnion('tee', [nitroBindingSchema]);
21
+ const oneOfTeesSchema = z.array(teeBindingSchema).nonempty();
22
+ const anyTeeConstraintSchema = z
23
+ .object({
24
+ regions: z.array(regionSchema).nonempty().optional(),
25
+ })
26
+ .strict();
27
+ export const teeConstraintSchema = z.union([oneOfTeesSchema, anyTeeConstraintSchema]);
28
+ // --- Conversion to protobuf Requirements ---
29
+ export function buildTeeRequirements(input) {
30
+ const parsed = teeConstraintSchema.parse(input);
31
+ if (Array.isArray(parsed)) {
32
+ const teeTypes = parsed.map((binding) => ({
33
+ type: teeTypeFromBinding(binding),
34
+ regions: binding.regions ?? [],
35
+ }));
36
+ return create(RequirementsSchema, {
37
+ tee: create(TeeSchema, {
38
+ item: {
39
+ case: 'teeTypesAndRegions',
40
+ value: create(TeeTypesAndRegionsSchema, { teeTypeAndRegions: teeTypes }),
41
+ },
42
+ }),
43
+ });
44
+ }
45
+ return create(RequirementsSchema, {
46
+ tee: create(TeeSchema, {
47
+ item: {
48
+ case: 'anyRegions',
49
+ value: create(RegionsSchema, { regions: parsed.regions ?? [] }),
50
+ },
51
+ }),
52
+ });
53
+ }
54
+ function teeTypeFromBinding(binding) {
55
+ switch (binding.tee) {
56
+ case 'nitro':
57
+ return TeeType.AWS_NITRO;
58
+ }
59
+ }
@@ -1,5 +1,4 @@
1
1
  import { decodeFunctionData, encodeFunctionResult, } from 'viem';
2
- import { chainContractHandler } from './contract-mock-core';
3
2
  function bytesToHexAddress(bytes) {
4
3
  return `0x${Array.from(bytes)
5
4
  .map((b) => b.toString(16).padStart(2, '0'))
@@ -50,67 +49,66 @@ export function addContractMock(evmMock, options) {
50
49
  const mock = {};
51
50
  const normalizedAddress = options.address.toLowerCase();
52
51
  const previousCallContract = evmMock.callContract;
53
- evmMock.callContract = chainContractHandler({
54
- previous: previousCallContract,
55
- matches: (req) => {
56
- const toBytes = req.call?.to;
57
- return !!toBytes && bytesToHexAddress(toBytes) === normalizedAddress;
58
- },
59
- noMatchError: (req) => `addContractMock: no mock registered for address ${req.call?.to ? bytesToHexAddress(req.call.to) : '(empty)'}`,
60
- handle: (req) => {
61
- const dataBytes = req.call?.data;
62
- if (!dataBytes || dataBytes.length < 4) {
63
- throw new Error('addContractMock: call data too short (need at least 4 bytes for selector)');
64
- }
65
- const callDataHex = bytesToHex(dataBytes);
66
- let decoded;
67
- try {
68
- decoded = decodeFunctionData({
69
- abi: options.abi,
70
- data: callDataHex,
71
- });
72
- }
73
- catch (e) {
74
- if (previousCallContract)
75
- return previousCallContract(req);
76
- throw new Error(`addContractMock: failed to decode function data for ${options.address}: ${e instanceof Error ? e.message : e}`);
77
- }
78
- const handler = mock[decoded.functionName];
79
- if (typeof handler !== 'function') {
80
- throw new Error(`addContractMock: no handler set for ${decoded.functionName} on ${options.address}`);
81
- }
82
- const result = handler(...(decoded.args ?? []));
83
- const encoded = encodeFunctionResult({
52
+ evmMock.callContract = (req) => {
53
+ const toBytes = req.call?.to;
54
+ if (!toBytes || bytesToHexAddress(toBytes) !== normalizedAddress) {
55
+ if (previousCallContract)
56
+ return previousCallContract(req);
57
+ throw new Error(`addContractMock: no mock registered for address ${toBytes ? bytesToHexAddress(toBytes) : '(empty)'}`);
58
+ }
59
+ const dataBytes = req.call?.data;
60
+ if (!dataBytes || dataBytes.length < 4) {
61
+ throw new Error('addContractMock: call data too short (need at least 4 bytes for selector)');
62
+ }
63
+ const callDataHex = bytesToHex(dataBytes);
64
+ let decoded;
65
+ try {
66
+ decoded = decodeFunctionData({
84
67
  abi: options.abi,
85
- functionName: decoded.functionName,
86
- result: result,
68
+ data: callDataHex,
87
69
  });
88
- return {
89
- data: hexToUint8Array(encoded),
90
- };
91
- },
92
- });
70
+ }
71
+ catch (e) {
72
+ if (previousCallContract)
73
+ return previousCallContract(req);
74
+ throw new Error(`addContractMock: failed to decode function data for ${options.address}: ${e instanceof Error ? e.message : e}`);
75
+ }
76
+ const handler = mock[decoded.functionName];
77
+ if (typeof handler !== 'function') {
78
+ throw new Error(`addContractMock: no handler set for ${decoded.functionName} on ${options.address}`);
79
+ }
80
+ const result = handler(...(decoded.args ?? []));
81
+ const encoded = encodeFunctionResult({
82
+ abi: options.abi,
83
+ functionName: decoded.functionName,
84
+ result: result,
85
+ });
86
+ return {
87
+ data: hexToUint8Array(encoded),
88
+ };
89
+ };
93
90
  const previousWriteReport = evmMock.writeReport;
94
- evmMock.writeReport = chainContractHandler({
95
- previous: previousWriteReport,
96
- matches: (req) => !!req.receiver && bytesToHexAddress(req.receiver) === normalizedAddress,
97
- noMatchError: (req) => `addContractMock: no writeReport mock registered for receiver ${req.receiver ? bytesToHexAddress(req.receiver) : '(empty)'}`,
98
- handle: (req) => {
99
- if (typeof mock.writeReport !== 'function') {
100
- throw new Error(`addContractMock: no writeReport handler set for ${options.address}`);
101
- }
102
- if (!req.report) {
103
- throw new Error(`addContractMock: writeReport called without report for ${options.address}`);
104
- }
105
- if (!req.gasConfig) {
106
- throw new Error(`addContractMock: writeReport called without gasConfig for ${options.address}`);
107
- }
108
- return mock.writeReport({
109
- receiver: req.receiver,
110
- report: req.report,
111
- gasConfig: req.gasConfig,
112
- });
113
- },
114
- });
91
+ evmMock.writeReport = (req) => {
92
+ const receiverBytes = req.receiver;
93
+ if (!receiverBytes || bytesToHexAddress(receiverBytes) !== normalizedAddress) {
94
+ if (previousWriteReport)
95
+ return previousWriteReport(req);
96
+ throw new Error(`addContractMock: no writeReport mock registered for receiver ${receiverBytes ? bytesToHexAddress(receiverBytes) : '(empty)'}`);
97
+ }
98
+ if (typeof mock.writeReport !== 'function') {
99
+ throw new Error(`addContractMock: no writeReport handler set for ${options.address}`);
100
+ }
101
+ if (!req.report) {
102
+ throw new Error(`addContractMock: writeReport called without report for ${options.address}`);
103
+ }
104
+ if (!req.gasConfig) {
105
+ throw new Error(`addContractMock: writeReport called without gasConfig for ${options.address}`);
106
+ }
107
+ return mock.writeReport({
108
+ receiver: req.receiver,
109
+ report: req.report,
110
+ gasConfig: req.gasConfig,
111
+ });
112
+ };
115
113
  return mock;
116
114
  }
@@ -0,0 +1,25 @@
1
+ import { type AccountAPTBalanceReply, type AccountAPTBalanceReplyJson, type AccountAPTBalanceRequest, type AccountTransactionsReply, type AccountTransactionsReplyJson, type AccountTransactionsRequest, type TransactionByHashReply, type TransactionByHashReplyJson, type TransactionByHashRequest, type ViewReply, type ViewReplyJson, type ViewRequest, type WriteReportReply, type WriteReportReplyJson, type WriteReportRequest } from '../../../../../../../generated/capabilities/blockchain/aptos/v1alpha/client_pb';
2
+ /**
3
+ * Mock for ClientCapability. Use testInstance() to obtain an instance; do not construct directly.
4
+ * Set per-method properties (e.g. performAction) to define return values. If a method is invoked without a handler set, an error is thrown.
5
+ */
6
+ export declare class AptosMock {
7
+ static readonly CAPABILITY_ID = "aptos@1.0.0";
8
+ /** Set to define the return value for AccountAPTBalance. May return a plain object (AccountAPTBalanceReplyJson) or the message type. */
9
+ accountAPTBalance?: (input: AccountAPTBalanceRequest) => AccountAPTBalanceReply | AccountAPTBalanceReplyJson;
10
+ /** Set to define the return value for View. May return a plain object (ViewReplyJson) or the message type. */
11
+ view?: (input: ViewRequest) => ViewReply | ViewReplyJson;
12
+ /** Set to define the return value for TransactionByHash. May return a plain object (TransactionByHashReplyJson) or the message type. */
13
+ transactionByHash?: (input: TransactionByHashRequest) => TransactionByHashReply | TransactionByHashReplyJson;
14
+ /** Set to define the return value for AccountTransactions. May return a plain object (AccountTransactionsReplyJson) or the message type. */
15
+ accountTransactions?: (input: AccountTransactionsRequest) => AccountTransactionsReply | AccountTransactionsReplyJson;
16
+ /** Set to define the return value for WriteReport. May return a plain object (WriteReportReplyJson) or the message type. */
17
+ writeReport?: (input: WriteReportRequest) => WriteReportReply | WriteReportReplyJson;
18
+ private constructor();
19
+ /**
20
+ * Returns the mock instance for this capability and the specified tags.
21
+ * Multiple calls with the same tag values return the same instance.
22
+ * Must be called within the test framework's test() method.
23
+ */
24
+ static testInstance(chainSelector: bigint): AptosMock;
25
+ }
@@ -0,0 +1,111 @@
1
+ import { fromJson } from '@bufbuild/protobuf';
2
+ import { anyPack, anyUnpack } from '@bufbuild/protobuf/wkt';
3
+ import { AccountAPTBalanceReplySchema, AccountAPTBalanceRequestSchema, AccountTransactionsReplySchema, AccountTransactionsRequestSchema, TransactionByHashReplySchema, TransactionByHashRequestSchema, ViewReplySchema, ViewRequestSchema, WriteReportReplySchema, WriteReportRequestSchema, } from '../../../../../../../generated/capabilities/blockchain/aptos/v1alpha/client_pb';
4
+ import { __getTestMockInstance, __setTestMockInstance, registerTestCapability, } from '../../../../../../testutils/test-runtime';
5
+ /**
6
+ * Mock for ClientCapability. Use testInstance() to obtain an instance; do not construct directly.
7
+ * Set per-method properties (e.g. performAction) to define return values. If a method is invoked without a handler set, an error is thrown.
8
+ */
9
+ export class AptosMock {
10
+ static CAPABILITY_ID = 'aptos@1.0.0';
11
+ /** Set to define the return value for AccountAPTBalance. May return a plain object (AccountAPTBalanceReplyJson) or the message type. */
12
+ accountAPTBalance;
13
+ /** Set to define the return value for View. May return a plain object (ViewReplyJson) or the message type. */
14
+ view;
15
+ /** Set to define the return value for TransactionByHash. May return a plain object (TransactionByHashReplyJson) or the message type. */
16
+ transactionByHash;
17
+ /** Set to define the return value for AccountTransactions. May return a plain object (AccountTransactionsReplyJson) or the message type. */
18
+ accountTransactions;
19
+ /** Set to define the return value for WriteReport. May return a plain object (WriteReportReplyJson) or the message type. */
20
+ writeReport;
21
+ constructor(chainSelector) {
22
+ const self = this;
23
+ const qualifiedId = `aptos:ChainSelector:${chainSelector}@1.0.0`;
24
+ try {
25
+ registerTestCapability(qualifiedId, (req) => {
26
+ switch (req.method) {
27
+ case 'AccountAPTBalance': {
28
+ const input = anyUnpack(req.payload, AccountAPTBalanceRequestSchema);
29
+ const handler = self.accountAPTBalance;
30
+ if (typeof handler !== 'function')
31
+ throw new Error("AccountAPTBalance: no implementation provided; set the mock's accountAPTBalance property to define the return value.");
32
+ const raw = handler(input);
33
+ const output = raw && typeof raw.$typeName === 'string'
34
+ ? raw
35
+ : fromJson(AccountAPTBalanceReplySchema, raw);
36
+ return {
37
+ response: { case: 'payload', value: anyPack(AccountAPTBalanceReplySchema, output) },
38
+ };
39
+ }
40
+ case 'View': {
41
+ const input = anyUnpack(req.payload, ViewRequestSchema);
42
+ const handler = self.view;
43
+ if (typeof handler !== 'function')
44
+ throw new Error("View: no implementation provided; set the mock's view property to define the return value.");
45
+ const raw = handler(input);
46
+ const output = raw && typeof raw.$typeName === 'string'
47
+ ? raw
48
+ : fromJson(ViewReplySchema, raw);
49
+ return { response: { case: 'payload', value: anyPack(ViewReplySchema, output) } };
50
+ }
51
+ case 'TransactionByHash': {
52
+ const input = anyUnpack(req.payload, TransactionByHashRequestSchema);
53
+ const handler = self.transactionByHash;
54
+ if (typeof handler !== 'function')
55
+ throw new Error("TransactionByHash: no implementation provided; set the mock's transactionByHash property to define the return value.");
56
+ const raw = handler(input);
57
+ const output = raw && typeof raw.$typeName === 'string'
58
+ ? raw
59
+ : fromJson(TransactionByHashReplySchema, raw);
60
+ return {
61
+ response: { case: 'payload', value: anyPack(TransactionByHashReplySchema, output) },
62
+ };
63
+ }
64
+ case 'AccountTransactions': {
65
+ const input = anyUnpack(req.payload, AccountTransactionsRequestSchema);
66
+ const handler = self.accountTransactions;
67
+ if (typeof handler !== 'function')
68
+ throw new Error("AccountTransactions: no implementation provided; set the mock's accountTransactions property to define the return value.");
69
+ const raw = handler(input);
70
+ const output = raw && typeof raw.$typeName === 'string'
71
+ ? raw
72
+ : fromJson(AccountTransactionsReplySchema, raw);
73
+ return {
74
+ response: { case: 'payload', value: anyPack(AccountTransactionsReplySchema, output) },
75
+ };
76
+ }
77
+ case 'WriteReport': {
78
+ const input = anyUnpack(req.payload, WriteReportRequestSchema);
79
+ const handler = self.writeReport;
80
+ if (typeof handler !== 'function')
81
+ throw new Error("WriteReport: no implementation provided; set the mock's writeReport property to define the return value.");
82
+ const raw = handler(input);
83
+ const output = raw && typeof raw.$typeName === 'string'
84
+ ? raw
85
+ : fromJson(WriteReportReplySchema, raw);
86
+ return { response: { case: 'payload', value: anyPack(WriteReportReplySchema, output) } };
87
+ }
88
+ default:
89
+ return { response: { case: 'error', value: `unknown method ${req.method}` } };
90
+ }
91
+ });
92
+ }
93
+ catch {
94
+ throw new Error("Capability mocks must be used within the CRE test framework's test() method.");
95
+ }
96
+ }
97
+ /**
98
+ * Returns the mock instance for this capability and the specified tags.
99
+ * Multiple calls with the same tag values return the same instance.
100
+ * Must be called within the test framework's test() method.
101
+ */
102
+ static testInstance(chainSelector) {
103
+ const qualifiedId = `aptos:ChainSelector:${chainSelector}@1.0.0`;
104
+ let instance = __getTestMockInstance(qualifiedId);
105
+ if (!instance) {
106
+ instance = new AptosMock(chainSelector);
107
+ __setTestMockInstance(qualifiedId, instance);
108
+ }
109
+ return instance;
110
+ }
111
+ }