Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/config/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,10 @@ export const SIDEBAR: Partial<Record<Sections, SectionEntry[]>> = {
url: "cre/reference/sdk/consensus",
highlightAsCurrent: ["cre/reference/sdk/consensus-ts", "cre/reference/sdk/consensus-go"],
},
{
title: "Type Conversions",
url: "cre/reference/sdk/type-conversions-ts",
},
],
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ The [Confidential HTTP](/cre/capabilities/confidential-http-ts) Client lets you

{/* prettier-ignore */}
<Aside type="note" title="Runtime types vs JSON types">
Each core type has a corresponding `Json` variant (e.g., `ConfidentialHTTPRequest` and `ConfidentialHTTPRequestJson`). The `Json` variant is the plain JSON-serializable form of the protobuf message. Both forms are accepted wherever a type is required.
Each core type has a corresponding `Json` variant (e.g., `ConfidentialHTTPRequest` and `ConfidentialHTTPRequestJson`). The `Json` variant is the plain JSON-serializable form of the protobuf message. Both forms are accepted wherever a type is required. See [Type Conversions](/cre/reference/sdk/type-conversions-ts) for a full reference on how protobuf types map to TypeScript.
</Aside>

### `ConfidentialHTTPRequest` / `ConfidentialHTTPRequestJson`
Expand Down
67 changes: 67 additions & 0 deletions src/content/cre/reference/sdk/core-go.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,70 @@ func onTrigger(config *Config, runtime cre.Runtime, ...) (string, error) {
//...
}
```

## `runtime.GetSecret()`

Retrieves a secret from the Vault DON. Secrets are key-value pairs stored securely and made available to your workflow at runtime. The `GetSecret` method is available on the `Runtime` interface through the embedded `SecretsProvider`.

**Signature:**

```go
runtime.GetSecret(req *SecretRequest) Promise[*Secret]
```

### `SecretRequest`

| Field | Type | Required | Description |
| ----------- | -------- | -------- | ----------------------------------------- |
| `Id` | `string` | Yes | The identifier of the secret to retrieve. |
| `Namespace` | `string` | Yes | The namespace the secret belongs to. |

### `Secret`

The value returned when the promise resolves.

| Field | Type | Description |
| ----------- | -------- | -------------------------------- |
| `Id` | `string` | The secret identifier. |
| `Namespace` | `string` | The secret namespace. |
| `Owner` | `string` | The address of the secret owner. |
| `Value` | `string` | The secret value. |

### `SecretsProvider` interface

The `SecretsProvider` interface is embedded in `Runtime`, which means `GetSecret` is available directly on the runtime object. It is also passed as a parameter to [`InitWorkflow`](#initworkflow), allowing you to access secrets during workflow initialization.

```go
type SecretsProvider interface {
GetSecret(req *SecretRequest) Promise[*Secret]
}
```

### Example

```go
import "github.com/smartcontractkit/cre-sdk-go/cre"

func onTrigger(config *Config, runtime cre.Runtime, ...) (string, error) {
secretPromise := runtime.GetSecret(&cre.SecretRequest{
Id: "my-api-key",
Namespace: "default",
})

secret, err := secretPromise.Await()
if err != nil {
return "", fmt.Errorf("failed to get secret: %w", err)
}

logger := runtime.Logger()
logger.Info("Secret retrieved", "owner", secret.Owner)

// Use secret.Value in your workflow logic
return "done", nil
}
```

<Aside type="note" title="Secrets guide">
For a complete walkthrough on creating, storing, and using secrets, see the [Secrets
guide](/cre/guides/workflow/secrets).
</Aside>
116 changes: 115 additions & 1 deletion src/content/cre/reference/sdk/core-ts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -389,12 +389,64 @@ runtime.runInNodeMode<TArgs extends unknown[], TOutput>(

- `fn`: A function that receives a `NodeRuntime` and executes on each individual node
- `consensusAggregation`: An aggregation function (e.g., `consensusMedianAggregation<bigint>()`)
- `unwrapOptions`: Optional configuration for how to unwrap complex return types
- `unwrapOptions`: Optional configuration for how to deserialize the consensus result. See [`UnwrapOptions`](#unwrapoptions) below.

**Returns:**

A function that, when called with any additional arguments, returns an object with a `.result()` method.

### `UnwrapOptions`

When `runInNodeMode` returns a non-primitive type, the SDK needs to know how to deserialize the consensus result back into a typed object. The `unwrapOptions` parameter tells the SDK which deserialization strategy to use.

{/* prettier-ignore */}
<Aside type="note" title="When do you need this?">
Primitives (`string`, `number`, `bigint`, `boolean`) and simple flat objects usually don't need `unwrapOptions`. You only need it when `runInNodeMode` returns a complex object type and the SDK can't infer the shape automatically.
</Aside>

**Type definition:**

```typescript
type UnwrapOptions<T> = { instance: T } | { schema: StandardSchemaV1<T> } | { factory: () => T }
```

**Variants:**

| Variant | When to use | Example |
| ----------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------ |
| `{ instance: value }` | Primitive types (`string`, `number`, `bigint`, `boolean`) | `{ instance: 0n }` |
| `{ schema: validator }` | Objects with a Zod or Standard Schema validator | `{ schema: myZodSchema }` |
| `{ factory: () => T }` | Objects without a schema — provide a factory that returns a default instance | `{ factory: () => ({ price: 0n, source: "" }) }` |

**Example with `schema` (most common for complex types):**

```typescript
import { HTTPClient, consensusMedianAggregation, type Runtime, type NodeRuntime } from "@chainlink/cre-sdk"
import { z } from "zod"

const priceResultSchema = z.object({
price: z.bigint(),
source: z.string(),
})

type PriceResult = z.infer<typeof priceResultSchema>

const fetchPrice = (nodeRuntime: NodeRuntime<Config>): PriceResult => {
const httpClient = new HTTPClient()
// ... fetch and parse price ...
return { price: 42000n, source: "api.example.com" }
}

const onTrigger = (runtime: Runtime<Config>): string => {
const price = runtime
.runInNodeMode(fetchPrice, consensusMedianAggregation<PriceResult>(), { schema: priceResultSchema })()
.result()

runtime.log(`Price: ${price.price} from ${price.source}`)
return "done"
}
```

**Example:**

This example uses `runInNodeMode` to fetch data from an API on each node, and then uses the DON-level `Runtime` to write the aggregated result onchain.
Expand Down Expand Up @@ -437,3 +489,65 @@ const onTrigger = (runtime: Runtime<Config>, ...): string => {
The pattern `runInNodeMode(fn, aggregation)()` requires calling the returned function immediately with `()` before
calling `.result()`. This is because `runInNodeMode` returns a function that can accept additional arguments.
</Aside>

## `runtime.getSecret()`

Retrieves a secret from the Vault DON. Secrets are key-value pairs stored securely and made available to your workflow at runtime.

**Signature:**

```typescript
runtime.getSecret(
req: SecretRequest | SecretRequestJson
): { result: () => Secret }
```

### `SecretRequest` / `SecretRequestJson`

| Field | Type | Required | Description |
| ----------- | -------- | -------- | ----------------------------------------- |
| `id` | `string` | Yes | The identifier of the secret to retrieve. |
| `namespace` | `string` | Yes | The namespace the secret belongs to. |

### `Secret`

The object returned by `.result()`.

| Field | Type | Description |
| ----------- | -------- | -------------------------------- |
| `id` | `string` | The secret identifier. |
| `namespace` | `string` | The secret namespace. |
| `owner` | `string` | The address of the secret owner. |
| `value` | `string` | The secret value. |

### Using secrets in `initWorkflow`

To use `runtime.getSecret()`, your `initWorkflow` function must accept a `SecretsProvider` as its second parameter. This wires secret access into the runtime.

```typescript
import { handler, type Runtime, type SecretsProvider } from "@chainlink/cre-sdk"

const initWorkflow = (config: Config, secretsProvider: SecretsProvider) => {
return [handler(triggerInstance, onTrigger)]
}
```

### Example

```typescript
import { type Runtime } from "@chainlink/cre-sdk"

const onTrigger = (runtime: Runtime<Config>): string => {
const secret = runtime.getSecret({ id: "my-api-key", namespace: "default" }).result()

runtime.log(`Secret owner: ${secret.owner}`)

// Use secret.value in your workflow logic
return "done"
}
```

{/* prettier-ignore */}
<Aside type="note" title="Secrets guide">
For a complete walkthrough on creating, storing, and using secrets, see the [Secrets guide](/cre/guides/workflow/secrets).
</Aside>
117 changes: 117 additions & 0 deletions src/content/cre/reference/sdk/evm-client-ts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,123 @@ See [Custom Block Depths](/cre/guides/workflow/using-evm-client/onchain-read-ts#

---

### `hexToBytes()`

Converts a `0x`-prefixed hex string to a `Uint8Array`.

**Signature:**

```typescript
function hexToBytes(hex: Hex): Uint8Array
```

**Usage:**

```typescript
import { hexToBytes } from "@chainlink/cre-sdk"

const bytes = hexToBytes("0xabcdef")
// → Uint8Array [171, 205, 239]
```

---

### `base64ToHex()`

Converts a base64-encoded string to a `0x`-prefixed hex string. This is useful for converting protobuf `bytes` fields (which are base64-encoded in JSON form) back to hex for use with viem or other EVM libraries.

**Signature:**

```typescript
function base64ToHex(base64: string): Hex
```

**Usage:**

```typescript
import { base64ToHex } from "@chainlink/cre-sdk"

const hex = base64ToHex("q83v")
// → "0xabcdef"
```

---

### `bigintToBytes()`

Converts a native JavaScript `bigint` to a big-endian `Uint8Array`. This is useful when you need to encode a `bigint` as raw bytes for protobuf fields or ABI encoding.

**Signature:**

```typescript
function bigintToBytes(n: bigint): Uint8Array
```

**Usage:**

```typescript
import { bigintToBytes } from "@chainlink/cre-sdk"

const bytes = bigintToBytes(256n)
// → Uint8Array [1, 0]
```

---

### `bytesToBigint()`

Converts a big-endian `Uint8Array` to a native JavaScript `bigint`. This is the inverse of `bigintToBytes()`.

**Signature:**

```typescript
function bytesToBigint(bytes: Uint8Array): bigint
```

**Usage:**

```typescript
import { bytesToBigint } from "@chainlink/cre-sdk"

const value = bytesToBigint(new Uint8Array([1, 0]))
// → 256n
```

---

### `bigintToProtoBigInt()`

Converts a native `bigint`, `number`, or `string` to the protobuf `BigIntJson` format used by SDK methods. The [`blockNumber()`](#blocknumber) function is a convenience alias for this function.

**Signature:**

```typescript
function bigintToProtoBigInt(n: number | bigint | string): BigIntJson
```

**Returns:**

A `BigIntJson` object with `absVal` (base64-encoded big-endian bytes) and `sign` (`"1"`, `"0"`, or `"-1"`).

**Usage:**

```typescript
import { bigintToProtoBigInt } from "@chainlink/cre-sdk"

const protoBigInt = bigintToProtoBigInt(12345678n)
// → { absVal: "ALxhTg==", sign: "1" }

const negative = bigintToProtoBigInt(-42n)
// → { absVal: "Kg==", sign: "-1" }

const zero = bigintToProtoBigInt(0n)
// → { absVal: "", sign: "0" }
```

See [Type Conversions](/cre/reference/sdk/type-conversions-ts#protobigint) for more details on the `ProtoBigInt` format.

---

### `prepareReportRequest()`

Prepares a report request with default EVM encoding parameters for use with `runtime.report()`. This helper simplifies report generation by automatically setting the standard encoding configuration (`evm`, `ecdsa`, `keccak256`) required for EVM-based workflows.
Expand Down
1 change: 1 addition & 0 deletions src/content/cre/reference/sdk/overview-ts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ The SDK Reference is broken down into several pages, each corresponding to a cor
- **[HTTP Client](/cre/reference/sdk/http-client-ts)**: Provides a reference for the `HTTPClient`, used for making offchain API requests from individual nodes.
- **[Confidential HTTP Client](/cre/reference/sdk/confidential-http-client-ts)**: Provides a reference for the `ConfidentialHTTPClient`, used for privacy-preserving API requests with enclave execution and optional response encryption.
- **[Consensus & Aggregation](/cre/reference/sdk/consensus-ts)**: Describes how to use aggregators like `consensusMedianAggregation` and `ConsensusAggregationByFields` with `runtime.runInNodeMode()` to process and consolidate data from multiple nodes.
- **[Type Conversions](/cre/reference/sdk/type-conversions-ts)**: Explains the dual `Type` / `TypeJson` system, protobuf-to-TypeScript type mappings, and the `ProtoBigInt` format used for block numbers, balances, and gas values.

## Package Structure

Expand Down
Loading
Loading