Skip to content
Merged
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
20 changes: 10 additions & 10 deletions packages/cre-sdk-examples/src/workflows/http-fetch/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
consensusMedianAggregation,
cre,
type NodeRuntime,
type HTTPSendRequester,
Runner,
type Runtime,
} from '@chainlink/cre-sdk'
Expand All @@ -14,21 +14,21 @@ const configSchema = z.object({

type Config = z.infer<typeof configSchema>

const fetchMathResult = async (nodeRuntime: NodeRuntime<Config>) => {
const httpCapability = new cre.capabilities.HTTPClient()
const response = httpCapability
.sendRequest(nodeRuntime, {
url: nodeRuntime.config.apiUrl,
})
.result()
const fetchMathResult = async (sendRequester: HTTPSendRequester, config: Config) => {
const response = await sendRequester.sendRequest({ url: config.apiUrl }).result()
return Number.parseFloat(Buffer.from(response.body).toString('utf-8').trim())
}

const onCronTrigger = async (runtime: Runtime<Config>) => {
return await runtime.runInNodeMode(fetchMathResult, consensusMedianAggregation())()
const httpCapability = new cre.capabilities.HTTPClient()
return await httpCapability.sendRequest(
runtime,
fetchMathResult,
consensusMedianAggregation(),
)(runtime.config)
}

const initWorkflow = (config: Config) => {
const initWorkflow = (config: Config) => {
const cron = new cre.capabilities.CronCapability()
return [cre.handler(cron.trigger({ schedule: config.schedule }), onCronTrigger)]
}
Expand Down
18 changes: 11 additions & 7 deletions packages/cre-sdk-examples/src/workflows/on-chain-write/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
consensusMedianAggregation,
cre,
getNetwork,
type HTTPSendRequester,
hexToBase64,
type NodeRuntime,
Runner,
type Runtime,
} from '@chainlink/cre-sdk'
Expand Down Expand Up @@ -34,19 +34,23 @@ type Result = {
TxHash: string
}

async function fetchMathResult(nodeRuntime: NodeRuntime<Config>): Promise<number> {
const httpCapability = new cre.capabilities.HTTPClient()
const response = httpCapability
.sendRequest(nodeRuntime, {
url: nodeRuntime.config.apiUrl,
async function fetchMathResult(sendRequester: HTTPSendRequester, config: Config) {
const response = await sendRequester
.sendRequest({
url: config.apiUrl,
})
.result()
return Number.parseFloat(Buffer.from(response.body).toString('utf-8').trim())
}

const onCronTrigger = async (runtime: Runtime<Config>): Promise<Result> => {
// Step 1: Fetch offchain data using consensus (from Part 2)
const offchainValue = await runtime.runInNodeMode(fetchMathResult, consensusMedianAggregation())()
const httpCapability = new cre.capabilities.HTTPClient()
const offchainValue = await httpCapability.sendRequest(
runtime,
fetchMathResult,
consensusMedianAggregation(),
)(runtime.config)

runtime.log('Successfully fetched offchain value')

Expand Down
17 changes: 9 additions & 8 deletions packages/cre-sdk-examples/src/workflows/on-chain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
consensusMedianAggregation,
cre,
getNetwork,
type HTTPSendRequester,
hexToBase64,
type NodeRuntime,
Runner,
Expand All @@ -26,19 +27,19 @@ const configSchema = z.object({

type Config = z.infer<typeof configSchema>

async function fetchMathResult(nodeRuntime: NodeRuntime<Config>): Promise<number> {
const httpCapability = new cre.capabilities.HTTPClient()
const response = httpCapability
.sendRequest(nodeRuntime, {
url: nodeRuntime.config.apiUrl,
})
.result()
const fetchMathResult = async (sendRequester: HTTPSendRequester, config: Config) => {
const response = await sendRequester.sendRequest({ url: config.apiUrl }).result()
return Number.parseFloat(Buffer.from(response.body).toString('utf-8').trim())
}

const onCronTrigger = async (runtime: Runtime<Config>): Promise<bigint> => {
// Step 1: Fetch offchain data using consensus (from Part 2)
const offchainValue = await runtime.runInNodeMode(fetchMathResult, consensusMedianAggregation())()
const httpCapability = new cre.capabilities.HTTPClient()
const offchainValue = await httpCapability.sendRequest(
runtime,
fetchMathResult,
consensusMedianAggregation(),
)(runtime.config)

runtime.log(`Successfully fetched offchain value: ${offchainValue}`)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import {
type WriteReportRequestJson,
WriteReportRequestSchema,
} from '@cre/generated/capabilities/blockchain/evm/v1alpha/client_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'
import { type Trigger } from '@cre/sdk/utils/triggers/trigger-interface'

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
type TriggerEvent,
TriggerEventSchema,
} from '@cre/generated/capabilities/internal/actionandtrigger/v1/action_and_trigger_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'
import { type Trigger } from '@cre/sdk/utils/triggers/trigger-interface'

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
type Outputs,
OutputsSchema,
} from '@cre/generated/capabilities/internal/basicaction/v1/basic_action_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'

/**
* BasicAction Capability
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
type Outputs,
OutputsSchema,
} from '@cre/generated/capabilities/internal/basictrigger/v1/basic_trigger_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'
import { type Trigger } from '@cre/sdk/utils/triggers/trigger-interface'

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
SimpleConsensusInputsSchema,
} from '@cre/generated/sdk/v1alpha/sdk_pb'
import { type Value, ValueSchema } from '@cre/generated/values/v1/values_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'

/**
* Consensus Capability
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@ import {
type NodeOutputs,
NodeOutputsSchema,
} from '@cre/generated/capabilities/internal/nodeaction/v1/node_action_pb'
import { type NodeRuntime } from '@cre/sdk/runtime'
import type { NodeRuntime, Runtime } from '@cre/sdk/runtime'
import type { ConsensusAggregation, PrimitiveTypes, UnwrapOptions } from '@cre/sdk/utils'

export class PerformActioner {
constructor(
private readonly runtime: NodeRuntime<any>,
private readonly client: BasicActionCapability,
) {}
performAction(input: NodeInputs | NodeInputsJson): { result: () => NodeOutputs } {
return this.client.performAction(this.runtime, input)
}
}

/**
* BasicAction Capability
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@ import {
type Response,
ResponseSchema,
} from '@cre/generated/capabilities/networking/http/v1alpha/client_pb'
import { type NodeRuntime } from '@cre/sdk/runtime'
import type { NodeRuntime, Runtime } from '@cre/sdk/runtime'
import type { ConsensusAggregation, PrimitiveTypes, UnwrapOptions } from '@cre/sdk/utils'

export class SendRequester {
constructor(
private readonly runtime: NodeRuntime<any>,
private readonly client: ClientCapability,
) {}
sendRequest(input: Request | RequestJson): { result: () => Response } {
return this.client.sendRequest(this.runtime, input)
}
}

/**
* Client Capability
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
type Payload,
PayloadSchema,
} from '@cre/generated/capabilities/networking/http/v1alpha/trigger_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'
import { type Trigger } from '@cre/sdk/utils/triggers/trigger-interface'

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
type Payload,
PayloadSchema,
} from '@cre/generated/capabilities/scheduler/cron/v1/trigger_pb'
import { type Runtime } from '@cre/sdk/runtime'
import type { Runtime } from '@cre/sdk/runtime'
import { type Trigger } from '@cre/sdk/utils/triggers/trigger-interface'

/**
Expand Down
32 changes: 29 additions & 3 deletions packages/cre-sdk/src/generator/generate-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
method as methodOption,
} from '@cre/generated/tools/generator/v1alpha/cre_metadata_pb'
import { generateActionMethod } from './generate-action'
import { generateActionSugarClass } from './generate-sugar'
import { generateTriggerClass, generateTriggerMethod } from './generate-trigger'
import { getImportPathForFile, lowerCaseFirstLetter } from './utils'

Expand Down Expand Up @@ -45,8 +46,16 @@ export function generateSdk(file: GenFile, outputDir: string) {
// Generate imports - collect all unique types first
const typeImports = new Map<string, Set<string>>()

var hasTriggers = false
var hasActions = false
// Process each method to collect types
service.methods.forEach((method) => {
if (method.methodKind === 'server_streaming') {
hasTriggers = true
} else {
hasActions = true
}

// Handle input type
const inputFile = method.input.file
const inputPath =
Expand Down Expand Up @@ -79,8 +88,6 @@ export function generateSdk(file: GenFile, outputDir: string) {
outputPathTypes.add(`type ${method.output.name}`)
})

const hasTriggers = service.methods.some((m) => m.methodKind === 'server_streaming')
const hasActions = service.methods.some((m) => m.methodKind !== 'server_streaming')
const modePrefix = capOption.mode === Mode.NODE ? 'Node' : ''

// Build import statements
Expand All @@ -99,7 +106,11 @@ export function generateSdk(file: GenFile, outputDir: string) {

// TODO???
if (hasActions || true) {
imports.add(`import { type ${modePrefix}Runtime } from "@cre/sdk/runtime"`)
if (modePrefix !== '') {
imports.add(`import type { Runtime, ${modePrefix}Runtime } from "@cre/sdk/runtime"`)
} else {
imports.add(`import type { Runtime } from "@cre/sdk/runtime"`)
}
}

// Generate deduplicated type imports
Expand All @@ -125,6 +136,20 @@ export function generateSdk(file: GenFile, outputDir: string) {
return !methodMeta?.mapToUntypedApi
})

const sugarClasses = serviceMethods
.map((method) => {
const methodName = lowerCaseFirstLetter(method.name)
return generateActionSugarClass(method, methodName, capabilityClassName, modePrefix)
})
.filter((method) => method !== '')
.join('\n')

if (sugarClasses.length > 0) {
imports.add(
'import type { ConsensusAggregation, PrimitiveTypes, UnwrapOptions } from "@cre/sdk/utils"',
)
}

// Generate methods
const methods = serviceMethods
.map((method) => {
Expand Down Expand Up @@ -195,6 +220,7 @@ ${Object.entries(defaults)

// Generate the complete file
const output = `${Array.from(imports).join('\n')}
${sugarClasses}
${classComment}
export class ${capabilityClassName} {
/** The capability ID for this service */
Expand Down
17 changes: 17 additions & 0 deletions packages/cre-sdk/src/generator/generate-sugar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { DescMethod } from '@bufbuild/protobuf'
export function generateActionSugarClass(
method: DescMethod,
methodName: string,
capabilityClassName: string,
modePrefix: string,
): string {
const sugarClassName = `${methodName.charAt(0).toUpperCase() + methodName.slice(1)}er`
if (modePrefix !== 'Node') return ''
return `
export class ${sugarClassName} {
constructor(private readonly runtime: NodeRuntime<any>, private readonly client: ${capabilityClassName}) {}
${methodName}(input: ${method.input.name} | ${method.input.name}Json): {result: () =>${method.output.name}} {
return this.client.${methodName}(this.runtime, input)
}
}`
}
6 changes: 5 additions & 1 deletion packages/cre-sdk/src/sdk/cre/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
*/

import { ClientCapability as EVMClient } from '@cre/generated-sdk/capabilities/blockchain/evm/v1alpha/client_sdk_gen'
import { ClientCapability as HTTPClient } from '@cre/generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen'
import {
ClientCapability as HTTPClient,
type SendRequester as HTTPSendRequester,
} from '@cre/generated-sdk/capabilities/networking/http/v1alpha/client_sdk_gen'
import { HTTPCapability } from '@cre/generated-sdk/capabilities/networking/http/v1alpha/http_sdk_gen'
import { CronCapability } from '@cre/generated-sdk/capabilities/scheduler/cron/v1/cron_sdk_gen'
import { prepareRuntime } from '@cre/sdk/utils/prepare-runtime'
Expand All @@ -13,6 +16,7 @@ export type { Log as EVMLog } from '@cre/generated/capabilities/blockchain/evm/v
export type { Payload as HTTPPayload } from '@cre/generated/capabilities/networking/http/v1alpha/trigger_pb'
export type { Payload as CronPayload } from '@cre/generated/capabilities/scheduler/cron/v1/trigger_pb'
export type { NodeRuntime, Runtime } from '@cre/sdk/runtime'
export type { HTTPSendRequester }

prepareRuntime()

Expand Down