### Expected Output of Bun Install Source: https://docs.chain.link/cre/getting-started/part-1-project-setup-ts Shows the typical output when running `bun install`, including the CRE SDK setup process and installed packages. Note that user-specific cache paths and versions may vary. ```bash bun install v1.2.23 (cf136713) $ bunx cre-setup [cre-sdk-javy-plugin] Detected platform: darwin, arch: arm64 [cre-sdk-javy-plugin] Using cached binary: /Users//.cache/javy/v5.0.4/darwin-arm64/javy ✅ CRE TS SDK is ready to use. + @types/bun@1.2.21 + @chainlink/cre-sdk@1.0.0 30 packages installed [4.71s] ``` -------------------------------- ### Example: Simulate Specific HTTP Workflow Source: https://docs.chain.link/cre/llms-full-go.txt An example command to simulate the 'my-http-workflow' targeting 'staging-settings'. ```bash cre workflow simulate my-http-workflow --target staging-settings ``` -------------------------------- ### Install Dependencies with Bun Source: https://docs.chain.link/cre-templates/custom-data-feed Install project dependencies using Bun. Ensure Bun is installed before running. ```bash bun install --cwd ./my-workflow ``` -------------------------------- ### Configuration for Storage Contract Read Example Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/generating-bindings-ts JSON configuration file for the Storage contract read example, specifying schedule, contract address, and chain selector. ```json { "schedule": "*/30 * * * * *", "storageAddress": "0xa17CF997C28FF154eDBae1422e6a50BeF23927F4", "chainSelector": "16015286601757825753" } ``` -------------------------------- ### Example Output: Access Request Submitted Source: https://docs.chain.link/cre/reference/cli/account This is an example of the output when deployment access is not yet enabled for your organization and an access request is submitted via the CLI. ```bash ! Deployment access is not yet enabled for your organization. Request deployment access? Yes Briefly describe your use case What are you building with CRE? > I'm working on a prediction market and I need to deploy my workflow! (or whatever you're building) ✓ Access request submitted successfully! Our team will review your request and get back to you via email shortly. ``` -------------------------------- ### Complete EVM Log Trigger Workflow Example Source: https://docs.chain.link/cre/reference/sdk/triggers/evm-log-trigger-ts A full example demonstrating how to initialize and run an EVM log trigger workflow. It includes setting up the network, EVM client, and the handler for the log trigger. ```typescript import { EVMClient, handler, bytesToHex, getNetwork, Runner, hexToBase64, type Runtime, type EVMLog, } from "@chainlink/cre-sdk" type Config = { chainSelectorName: string contractAddress: string } const onLogTrigger = (runtime: Runtime, log: EVMLog): string => { const topics = log.topics if (topics.length < 2) { throw new Error("Log missing required topics") } runtime.log(`Processing log from ${bytesToHex(log.address)}`) runtime.log(`Event signature: ${bytesToHex(topics[0])}`) // Decode the log data based on your event ABI // For this example, we just log the raw data runtime.log(`Data length: ${log.data.length} bytes`) return "Log processed" } const initWorkflow = (config: Config) => { const network = getNetwork({ chainFamily: "evm", chainSelectorName: config.chainSelectorName, }) if (!network) { throw new Error(`Network not found: ${config.chainSelectorName}`) } const evmClient = new EVMClient(network.chainSelector.selector) return [ handler( evmClient.logTrigger({ addresses: [hexToBase64(config.contractAddress)], }), onLogTrigger ), ] } export async function main() { const runner = await Runner.newRunner() await runner.run(initWorkflow) } ``` -------------------------------- ### Complete Cron Trigger Workflow Example Source: https://docs.chain.link/cre/reference/sdk/triggers/cron-trigger-ts A full example demonstrating how to initialize and run a workflow with a Cron Trigger, including configuration and callback. ```typescript import { CronCapability, handler, Runner, type Runtime, type CronPayload } from "@chainlink/cre-sdk" type Config = { schedule: string } const onCronTrigger = (runtime: Runtime, payload: CronPayload): string => { runtime.log("Cron workflow triggered!") return "Success" } const initWorkflow = (config: Config) => { const cron = new CronCapability() return [handler(cron.trigger({ schedule: config.schedule }), onCronTrigger)] } export async function main() { const runner = await Runner.newRunner() await runner.run(initWorkflow) } ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.chain.link/cre-templates/tokenized-asset-servicing Install project dependencies using npm. This is a prerequisite for deploying smart contracts. ```bash npm install ``` -------------------------------- ### Install Plugin Package Source: https://docs.chain.link/cre/guides/operations/custom-rust-plugins-ts Install a prebuilt plugin package from npm like any other dependency. ```bash bun add @acme/my-cre-plugin ``` -------------------------------- ### Example HTTP POST Request for Workflow Trigger Source: https://docs.chain.link/cre/guides/workflow/using-triggers/http-trigger/local-testing-tool An example demonstrating how to send a POST request to trigger a workflow with specific input data. ```bash curl -X POST "http://localhost:2000/trigger?workflowID=" \ -H "Content-Type: application/json" \ -d '{ "input": { "userId": "user_456", "action": "purchase", "amount": 250 } }' ``` -------------------------------- ### Install Workflow Dependencies Source: https://docs.chain.link/cre/getting-started/part-1-project-setup-ts Installs all necessary dependencies for the workflow, including the CRE SDK. The postinstall script automatically runs `bunx cre-setup` to prepare WebAssembly compilation tools. ```bash bun install ``` -------------------------------- ### Tenant Context Configuration Example Source: https://docs.chain.link/cre/reference/cli/authentication Illustrative example of the `context.yaml` file structure, showing tenant-specific configurations like vault gateway URLs and registry details. This file is generated by the CLI based on platform data. ```yaml PRODUCTION: tenant_id: "" default_don_family: zone-a vault_gateway_url: https://01.gateway.zone-a.cre.chain.link registries: - id: onchain:ethereum-mainnet label: ethereum-mainnet (0x1234...abcd) type: on-chain chain_selector: "" address: "0x0000000000000000000000000000000000000000" secrets_auth_flows: - browser - owner-key-signing - id: private label: Private (Chainlink-hosted) type: off-chain secrets_auth_flows: - browser ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://docs.chain.link/cre-templates/x402-price-alerts Clone the x402-cre-price-alerts repository and install all project dependencies using npm workspaces. ```bash git clone https://github.com/smartcontractkit/x402-cre-price-alerts.git cd x402-cre-alerts npm install ``` -------------------------------- ### Sync Dependencies with Go Get Source: https://docs.chain.link/cre/llms-full-go.txt Use these `go get` commands to add the necessary CRE SDK packages to your Go module. Ensure you are using the specified versions for compatibility. ```bash go get github.com/smartcontractkit/cre-sdk-go/capabilities/networking/http@v1.0.0-beta.0 go get github.com/smartcontractkit/cre-sdk-go/capabilities/scheduler/cron@v1.0.0-beta.0 go get github.com/smartcontractkit/cre-sdk-go@v1.0.0 ``` -------------------------------- ### Example Deployment Output Source: https://docs.chain.link/cre/guides/operations/deploying-to-private-registry-go This output shows a successful deployment to a private registry, including compilation, artifact upload, and registration details. Note the absence of a transaction hash and gas cost. ```text Deploying Workflow: my-workflow-staging Registry: private Target: staging-settings Owner Address: (derived) Compiling workflow... ✓ Workflow compiled successfully Binary hash: Config hash: Workflow hash: Uploading files... ✔ Loaded binary from: ./binary.wasm.br.b64 ✔ Uploaded binary to: https://storage.cre.chain.link/artifacts//binary.wasm ✔ Loaded config from: ./config.staging.json ✔ Uploaded config to: https://storage.cre.chain.link/artifacts//config Registering workflow in private registry (workflowID: )... ✓ Workflow registered in private registry Details: Registry: private Workflow Name: my-workflow Workflow ID: Status: Active Binary URL: https://storage.cre.chain.link/artifacts//binary.wasm Config URL: https://storage.cre.chain.link/artifacts//config Owner: ``` -------------------------------- ### Initialize New CRE Project Source: https://docs.chain.link/cre/reference/cli/project-setup-go Use this command to start a new Chainlink CRE project or add a workflow to an existing one. Interactive mode guides you through setup, while non-interactive mode is suitable for CI/CD. ```bash cre init [flags] ``` ```bash # Interactive setup cre init ``` -------------------------------- ### Prompting AI Agent with CRE Skill Source: https://docs.chain.link/cre/getting-started/build-with-ai-go Example of how to prompt an AI agent, explicitly referencing the installed Chainlink CRE skill for guidance. This ensures the agent utilizes the skill's domain-specific knowledge. ```shell Use the /chainlink-cre-skill skill and [describe what you want to build] ``` -------------------------------- ### Example Handler (Go) Source: https://docs.chain.link/cre/index Illustrates the trigger-and-callback pattern in Go for defining workflow logic. ```go package main import ( "context" "github.com/smartcontractkit/chainlink-common/pkg/capabilities/øracles" "github.com/smartcontractkit/chainlink-common/pkg/loop" "github.com/smartcontractkit/chainlink-common/pkg/services/chainlink" "github.com/smartcontractkit/chainlink-common/pkg/types" "github.com/smartcontractkit/chainlink-common/pkg/types/core" "github.com/smartcontractkit/chainlink-common/pkg/types/evm" "github.com/smartcontractkit/chainlink-common/pkg/utils/errors" "github.com/smartcontractkit/chainlink-common/pkg/utils/mailbox" "github.com/smartcontractkit/chainlink-common/pkg/utils/probes" "github.com/smartcontractkit/chainlink-common/pkg/utils/slices" "github.com/smartcontractkit/chainlink-common/pkg/utils/timeouts" ) // ExampleHandler demonstrates a basic workflow handler. func ExampleHandler(ctx context.Context, env loop.Environment) (types.Service, error) { // Initialize the capability registry registry, err := env.Registry() // Assuming env provides access to the registry if err != nil { return nil, errors.Wrap(err, "failed to get registry") } // Example: Get an Oracle capability oracleCap, err := registry.Get(ctx, "oracle", "evm") if err != nil { return nil, errors.Wrap(err, "failed to get oracle capability") } // Example: Get a secrets capability secretsCap, err := registry.Get(ctx, "secrets", "kvstore") if err != nil { return nil, errors.Wrap(err, "failed to get secrets capability") } // Define the callback function callback := func(ctx context.Context, _ any) (any, error) { // Inside the callback, use SDK clients to invoke capabilities // Example: Invoke the oracle capability oracleClient, ok := oracleCap.(evm.Oracle) if !ok { return nil, errors.New("failed to cast oracle capability to evm.Oracle") } // Example: Invoke the secrets capability secretsClient, ok := secretsCap.(øracles.Secrets) if !ok { return nil, errors.New("failed to cast secrets capability to øracles.Secrets") } // Perform business logic using clients... // For example, fetch data using the oracle client // result, err := oracleClient.FetchData(ctx, "some_data_feed") // if err != nil { // return nil, err // } // Example: Access secrets // secretValue, err := secretsClient.Get(ctx, "my_secret_key") // if err != nil { // return nil, err // } // Return the result of the callback execution return "Callback executed successfully", nil } // Define a trigger (e.g., cron trigger) // This is a placeholder; actual trigger implementation would be here // trigger := cron.NewTrigger(env, "* * * * *", callback) // In a real scenario, you would register triggers and callbacks with the DON // For demonstration, we'll just return a dummy service // Example: Create a dummy service that does nothing but satisfies the interface ssvc := &struct { chainlink.Service }{ Service: probes.NewService(), } return ssvc, nil } ``` -------------------------------- ### Generated Storage Contract Binding Method Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/onchain-read-go Example of a generated Go binding method for a smart contract's 'get' function. This method handles ABI encoding and EVM client interaction, returning a promise for the contract call response. ```go func (c Storage) Get(runtime cre.Runtime, blockNumber *big.Int) cre.Promise[*evm.CallContractReply] { // This method handles ABI encoding, calling the evm.Client, // and returns a promise for the response. } ``` -------------------------------- ### Low-level sendRequest Example Source: https://docs.chain.link/cre/reference/sdk/http-client-ts Demonstrates how to use the low-level `sendRequest` method for making HTTP GET requests. This requires manual wrapping in `runtime.runInNodeMode()` and includes error handling for non-200 status codes. It parses the JSON response to extract a 'price' field. ```typescript import { HTTPClient, consensusMedianAggregation, type Runtime, type NodeRuntime } from "@chainlink/cre-sdk" // Low-level usage with manual node mode const fetchPrice = (nodeRuntime: NodeRuntime): number => { const httpClient = new HTTPClient() const response = httpClient .sendRequest(nodeRuntime, { url: nodeRuntime.config.apiUrl, method: "GET", }) .result() if (response.statusCode !== 200) { throw new Error(`HTTP request failed with status: ${response.statusCode}`) } const responseText = new TextDecoder().decode(response.body) const data = JSON.parse(responseText) return data.price } // In your workflow const workflow = (runtime: Runtime) => { const price = runtime.runInNodeMode(fetchPrice, consensusMedianAggregation())().result() runtime.log(`Aggregated price: ${price}`) return price } ``` -------------------------------- ### Initialize Go Project Non-Interactively Source: https://docs.chain.link/cre/reference/cli/project-setup-go Use this command to set up a new Go project without interactive prompts. Ensure you provide all necessary flags, including RPC URLs for required networks. ```bash cre init \ --non-interactive \ --project-name my-cre-project \ --workflow-name my-workflow \ --template hello-world-go \ --deployment-registry private \ --rpc-url sepolia=https://sepolia.infura.io/v3/YOUR_KEY ``` -------------------------------- ### Verify CRE CLI Installation on Windows Source: https://docs.chain.link/cre/getting-started/cli-installation/windows After installation, run this command in a new PowerShell window to confirm the CRE CLI is installed and check its version. ```powershell cre version ``` -------------------------------- ### Go Build with Build Tags Source: https://docs.chain.link/cre/guides/operations/custom-build Example of customizing the Go build command in the Makefile to include build tags. ```makefile .PHONY: build build: GOOS=wasip1 GOARCH=wasm CGO_ENABLED=0 go build -tags mytag -o wasm/workflow.wasm -trimpath -ldflags="-buildid= -w -s" . ``` -------------------------------- ### Install CRE CLI Automatically Source: https://docs.chain.link/cre/getting-started/cli-installation/macos-linux Use this command to automatically download and install the CRE CLI. It detects your OS and architecture, verifies the binary, and installs it to $HOME/.cre. ```bash curl -sSL https://app.chain.link/cre/install.sh | bash ``` -------------------------------- ### Cron Trigger Examples Source: https://docs.chain.link/cre/llms-full-go.txt Examples of cron expressions for various scheduling needs. ```text */30 * * * * * ``` ```text 0 * * * * * ``` ```text 0 0 * * * * ``` ```text */5 8 * * 1-5 ``` -------------------------------- ### Complete EVM On-Chain Read Workflow in Go Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/onchain-read-go This example shows a full, runnable workflow that triggers on a cron schedule and reads a value from the Storage contract. It includes setting up the EVM client, instantiating the contract, and awaiting the result of a contract method call. ```go package main import ( "contracts/evm/src/generated/storage" // Generated Storage binding "fmt" "log/slog" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/smartcontractkit/cre-sdk-go/capabilities/blockchain/evm" "github.com/smartcontractkit/cre-sdk-go/capabilities/scheduler/cron" "github.com/smartcontractkit/cre-sdk-go/cre" "github.com/smartcontractkit/cre-sdk-go/cre/wasm" ) type Config struct { ContractAddress string `json:"contractAddress"` ChainSelector uint64 `json:"chainSelector"` } type MyResult struct { StoredValue *big.Int } func onCronTrigger(config *Config, runtime cre.Runtime, trigger *cron.Payload) (*MyResult, error) { logger := runtime.Logger() // Create EVM client evmClient := &evm.Client{ ChainSelector: config.ChainSelector, } // Create contract instance contractAddress := common.HexToAddress(config.ContractAddress) storageContract, err := storage.NewStorage(evmClient, contractAddress, nil) if err != nil { return nil, fmt.Errorf("failed to create contract instance: %w", err) } // Call contract method - it returns the decoded type directly storedValue, err := storageContract.Get(runtime, big.NewInt(-3)).Await() if err != nil { return nil, fmt.Errorf("failed to read storage value: %w", err) } logger.Info("Successfully read storage value", "value", storedValue.String()) return &MyResult{StoredValue: storedValue}, nil } func InitWorkflow(config *Config, logger *slog.Logger, secretsProvider cre.SecretsProvider) (cre.Workflow[*Config], error) { return cre.Workflow[*Config]{ cre.Handler( cron.Trigger(&cron.Config{Schedule: "*/10 * * * * *"}), onCronTrigger, ), }, nil } func main() { wasm.NewRunner(cre.ParseJSON[Config]).Run(InitWorkflow) } ``` -------------------------------- ### Initialize Workflow with Event Trigger in Go Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/generating-bindings-go Demonstrates how to initialize a workflow in Go, create a contract binding instance, and set up a trigger for the `UserAdded` event using the generated bindings. Ensure the project name is correctly replaced. ```go import ( "log/slog" "/contracts/evm/src/generated/user_directory" // Replace "" with your project's module name "github.com/smartcontractkit/cre-sdk-go/capabilities/blockchain/evm" "github.com/smartcontractkit/cre-sdk-go/cre" ) // In InitWorkflow, create an instance of the contract binding and use it // to generate a trigger for the "UserAdded" event. func InitWorkflow(config *Config, logger *slog.Logger, secretsProvider cre.SecretsProvider) (cre.Workflow[*Config], error) { // ... userDirectory, err := user_directory.NewUserDirectory(evmClient, contractAddress, nil) if err != nil { /* ... */ } // Use the generated helper to create a trigger for the UserAdded event. // Set confidence to evm.ConfidenceLevel_CONFIDENCE_LEVEL_FINALIZED to only trigger on finalized blocks. // The last argument (filters) is nil to listen for all UserAdded events. userAddedTrigger, err := userDirectory.LogTriggerUserAddedLog(chainSelector, evm.ConfidenceLevel_CONFIDENCE_LEVEL_FINALIZED, nil) if err != nil { /* ... */ } return cre.Workflow[*Config]{ cre.Handler( userAddedTrigger, onUserAdded, ), }, nil } ``` -------------------------------- ### Timezone-Aware Cron Trigger Examples Source: https://docs.chain.link/cre/llms-full-go.txt Examples of cron expressions with specified IANA timezones. ```text TZ=America/New_York 0 0 * * * ``` ```text TZ=Asia/Tokyo 0 20 * * 0 ``` ```text TZ=Europe/London 0 9 * * 1-5 ``` -------------------------------- ### Complete EVM Workflow Example Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/onchain-write/using-write-report-helpers A runnable Go workflow function demonstrating the end-to-end pattern for updating reserves using the EVM client and write report helpers. Includes contract interaction and transaction awaiting. ```go package main import ( "contracts/evm/src/generated/reserve_manager" "fmt" "log/slog" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/smartcontractkit/cre-sdk-go/capabilities/blockchain/evm" "github.com/smartcontractkit/cre-sdk-go/cre" ) type EvmConfig struct { ConsumerAddress string `json:"consumerAddress"` ChainSelector uint64 `json:"chainSelector"` } type Config struct { // Add other config fields from your workflow here } func updateReserves(config *Config, runtime cre.Runtime, evmConfig EvmConfig, totalSupply *big.Int, totalReserveScaled *big.Int) error { logger := runtime.Logger() logger.Info("Updating reserves", "totalSupply", totalSupply, "totalReserveScaled", totalReserveScaled) // Create EVM client with chain selector evmClient := &evm.Client{ ChainSelector: evmConfig.ChainSelector, } // Create contract binding contractAddress := common.HexToAddress(evmConfig.ConsumerAddress) reserveManager, err := reserve_manager.NewReserveManager(evmClient, contractAddress, nil) if err != nil { return fmt.Errorf("failed to create reserve manager: %w", err) } logger.Info("Writing report", "totalSupply", totalSupply, "totalReserveScaled", totalReserveScaled) // Call the write method writePromise := reserveManager.WriteReportFromUpdateReserves(runtime, reserve_manager.UpdateReserves{ TotalMinted: totalSupply, TotalReserve: totalReserveScaled, }, nil) logger.Info("Waiting for write report response") // Await the transaction resp, err := writePromise.Await() if err != nil { logger.Error("WriteReport await failed", "error", err, "errorType", fmt.Sprintf("%T", err)) return fmt.Errorf("failed to write report: %w", err) } logger.Info("Write report transaction succeeded", "txHash", common.BytesToHash(resp.TxHash).Hex()) return nil } // NOTE: This is a placeholder. You would need a full workflow with InitWorkflow, // a trigger, and a callback that calls this `updateReserves` function. func main() { // wasm.NewRunner(cre.ParseJSON[Config]).Run(InitWorkflow) } ``` -------------------------------- ### Create EVM Client Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/onchain-write/submitting-reports-onchain Initializes an EVM client with the necessary chain selector. Ensure you have the correct chain selector for your target network. ```go import "github.com/smartcontractkit/cre-sdk-go/capabilities/blockchain/evm" evMClient := &evm.Client{ ChainSelector: config.ChainSelector, // e.g., 16015286601757825753 for Sepolia } ``` -------------------------------- ### HTTP Trigger Simulation Example (TypeScript) Source: https://docs.chain.link/cre/guides/workflow/using-triggers/http-trigger/testing-in-simulation Example TypeScript code for simulating an HTTP trigger in a workflow. ```ts import functions = require("chainlink-functions-sdk") // This is an example of a workflow that processes HTTP requests. // It is intended to be used with the Chainlink Functions. // The workflow is triggered by an HTTP request and processes a purchase. functions.http("my-http-workflow", async (context, request) => { // Get the configuration from the context const config = functions.getConfig(context.config) // Get the minimum amount from the configuration const minimumAmount = config.getNumber("minimumAmount") // Parse the request payload const payload = JSON.parse(request.body) // Validate the amount against the minimum amount if (payload.amount < minimumAmount) { return functions.errorResponse( `Amount ${payload.amount} below minimum ${minimumAmount}`, 400, ) } // Process the purchase console.log(`Processing purchase for user ${payload.userId}`) console.log(`Processing amount: ${payload.amount}`) // Return a success response return functions.okResponse("Successfully processed purchase") }) ``` -------------------------------- ### HTTP Trigger Simulation Example (Go) Source: https://docs.chain.link/cre/guides/workflow/using-triggers/http-trigger/testing-in-simulation Example Go code for simulating an HTTP trigger in a workflow. ```go package main import ( "fmt" "github.com/chainlink/go-functions-sdk/core" "github.com/chainlink/go-functions-sdk/core/functions" ) // This is an example of a workflow that processes HTTP requests. // It is intended to be used with the Chainlink Functions. // The workflow is triggered by an HTTP request and processes a purchase. func main() { core.RegisterHTTPTrigger( "my-http-workflow", functions.NewHTTPTrigger( func(ctx functions.HTTPTriggerExecutionContext, req functions.HTTPRequest) (functions.HTTPResponse, error) { // Get the configuration from the context config, err := functions.GetConfig(ctx.Config) if err != nil { return functions.NewHTTPError(500, "Failed to get config: %v", err) } // Get the minimum amount from the configuration minimumAmount := config.GetInt("minimumAmount") // Parse the request payload var payload struct { UserId string `json:"userId"` Action string `json:"action"` Amount int `json:"amount"` } if err := functions.ParseJSON(req.Body, &payload); err != nil { return functions.NewHTTPError(400, "Failed to parse request body: %v", err) } // Validate the amount against the minimum amount if payload.Amount < minimumAmount { return functions.NewHTTPError(400, "Amount %d below minimum %d", payload.Amount, minimumAmount) } // Process the purchase fmt.Printf("Processing purchase for user %s\n", payload.UserId) fmt.Printf("Processing amount: %d\n", payload.Amount) // Return a success response return functions.NewHTTPResponse(200, "Successfully processed purchase") }, ), ) } ``` -------------------------------- ### Complete Workflow for Generating Reports from Structs Source: https://docs.chain.link/cre/guides/workflow/using-evm-client/onchain-write/generating-reports-structs This example shows a full workflow, including struct definition, encoding, and report generation. It requires WASM build tags and specific imports. ```go //go:build wasip1 package main import ( "fmt" "log/slog" "math/big" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/smartcontractkit/cre-sdk-go/capabilities/scheduler/cron" "github.com/smartcontractkit/cre-sdk-go/cre" "github.com/smartcontractkit/cre-sdk-go/cre/wasm" ) type Config struct { Schedule string `json:"schedule"` } // Go struct matching Solidity struct type PaymentData struct { Recipient common.Address Amount *big.Int Nonce *big.Int } type MyResult struct { EncodedHex string } func InitWorkflow(config *Config, logger *slog.Logger, secretsProvider cre.SecretsProvider) (cre.Workflow[*Config], error) { return cre.Workflow[*Config]{ cre.Handler(cron.Trigger(&cron.Config{Schedule: config.Schedule}), onCronTrigger), }, nil } func onCronTrigger(config *Config, runtime cre.Runtime, trigger *cron.Payload) (*MyResult, error) { logger := runtime.Logger() // Step 1: Create struct instance paymentData := PaymentData{ Recipient: common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"), Amount: big.NewInt(1000000000000000000), // 1 ETH Nonce: big.NewInt(42), } logger.Info("Created payment data", "recipient", paymentData.Recipient.Hex(), "amount", paymentData.Amount.String()) // Step 2: Create tuple type matching Solidity struct tupleType, err := abi.NewType( "tuple", "", []abi.ArgumentMarshaling{ {Name: "recipient", Type: "address"}, {Name: "amount", Type: "uint256"}, {Name: "nonce", Type: "uint256"}, }, ) if err != nil { return nil, fmt.Errorf("failed to create tuple type: %w", err) } // Step 3: Encode the struct args := abi.Arguments{{Name: "paymentData", Type: tupleType}} encodedStruct, err := args.Pack(paymentData) if err != nil { return nil, fmt.Errorf("failed to encode struct: %w", err) } logger.Info("Encoded struct", "hex", fmt.Sprintf("0x%%x", encodedStruct)) // Step 4: Generate report reportPromise := runtime.GenerateReport(&cre.ReportRequest{ EncodedPayload: encodedStruct, EncoderName: "evm", SigningAlgo: "ecdsa", HashingAlgo: "keccak256", }) report, err := reportPromise.Await() if err != nil { return nil, fmt.Errorf("failed to generate report: %w", err) } logger.Info("Report generated successfully") // At this point, you would typically submit the report: // - To the blockchain: see "Submitting Reports Onchain" guide // - Via HTTP: see "Submitting Reports via HTTP" guide // For this example, we'll just return the encoded data for verification _ = report // Report is ready to use return &MyResult{ EncodedHex: fmt.Sprintf("0x%%x", encodedStruct), }, nil } func main() { wasm.NewRunner(cre.ParseJSON[Config]).Run(InitWorkflow) } ``` -------------------------------- ### Configure Environment Variables for Local Testing Source: https://docs.chain.link/cre/guides/workflow/using-triggers/http-trigger/local-testing-tool Create a .env file to store your private key and the appropriate gateway URL for your deployment. Ensure your private key is kept secure and not committed to version control. ```bash PRIVATE_KEY=0xYourPrivateKeyHere GATEWAY_URL=https://01.gateway.zone-a.cre.chain.link ``` -------------------------------- ### Error Response Example Source: https://docs.chain.link/cre/guides/workflow/using-triggers/http-trigger/triggering-deployed-workflows This is an example of a JSON-RPC error response returned by the gateway when a workflow execution request fails. ```json { "jsonrpc": "2.0", "id": "req-123", "method": "", "error": { "code": -32600, "message": "Auth failure: signer '0x...' is not authorized for workflow '0x...'. Ensure that the signer is registered in the workflow definition" } } ``` -------------------------------- ### Install Workflow Dependencies Source: https://docs.chain.link/cre/templates/running-demo-workflow-ts Installs TypeScript dependencies for a specific workflow using Bun. Ensure you are in the project root directory. ```bash bun install --cwd ./demo/custom-data-feed ``` -------------------------------- ### Example JSON Payload Source: https://docs.chain.link/cre/guides/workflow/using-http-client/post-request-ts This is an example of a JSON payload that might be sent in an HTTP request. It shows a simple structure with a message and a value. ```json { "message": "Hello there!", "value": 77 } ``` -------------------------------- ### Example Output of Manual Linking Process Source: https://docs.chain.link/cre/llms-full-ts.txt This output shows the interactive prompts and transaction details during the manual key linking process, including address, label, contract information, and estimated cost. ```bash Linking web3 key to your CRE organization Target : production-settings ✔ Using Address : Provide a label for your owner address: Checking existing registrations... ✓ No existing link found for this address Starting linking: owner=, label= Contract address validation passed Transaction details: Chain Name: ethereum-mainnet To: 0x4Ac54353FA4Fa961AfcC5ec4B118596d3305E7e5 # Workflow Registry contract address Function: LinkOwner ... Estimated Cost: Gas Price: 0.12450327 gwei Total Cost: 0.00001606 ETH ? Do you want to execute this transaction?: ▸ Yes No ```