crec

package module
v0.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 12 Imported by: 0

README ΒΆ

Chainlink

CRE Connect SDK

Build the next generation of verifiable applications with secure, blockchain-agnostic event processing and transaction execution β€” powered by the Chainlink Runtime Environment and Verifiable Network.

What problem does CRE Connect SDK solve?

Building reliable blockchain applications requires handling:

Event Verification Challenges:

  • Ensuring events from the blockchain are authentic and haven't been tampered with
  • Decoding complex event data from various smart contracts
  • Managing multiple signature verification schemes for trust

Transaction Execution Complexities:

  • Batching multiple transactions atomically without gas estimation headaches
  • Supporting various signature algorithms beyond traditional ECDSA
  • Abstracting away account management while maintaining security

How CRE Connect SDK solves it

CRE Connect SDK is a client library for the Chainlink Runtime Environment (CRE), designed to facilitate the development of applications that interact with onchain data and services.

  • Receiving verifiable events from the blockchain with high assurance of authenticity
  • Sending operations to the blockchain using account abstraction with gas sponsorship

Key Features

  • πŸ” Cryptographically Secure: Multi-signature verification ensures event authenticity
  • β›½ Account Abstraction: Batch transactions, gas sponsorship, and multiple signature support
  • πŸ› οΈ Developer-Friendly: Rich helper services for common blockchain operations
  • 🧱 Modular Design: Use individual components or combine them for complex use cases

Quick Start

Prerequisites
  • Go 1.24 or higher - Check with go version
  • Basic Go and blockchain knowledge
Installation
go get github.com/smartcontractkit/crec-sdk
Initialize the Client
import "github.com/smartcontractkit/crec-sdk"

client, err := crec.NewClient(
    "https://api.crec.chainlink.com",
    "your-api-key",
)

Event verification is enabled by default using the production DON public keys. See Event Verification Keys for details.

The unified client provides access to all sub-clients:

client.Channels   // Channel CRUD operations
client.Events     // Event polling and verification
client.Transact   // Operation signing and sending
client.Watchers   // Watcher CRUD operations
Using Individual Sub-Clients

If you only need a subset of the SDK's functionality, create individual sub-clients using NewAPIClient:

import (
    "github.com/smartcontractkit/crec-sdk"
    "github.com/smartcontractkit/crec-sdk/channels"
    "github.com/smartcontractkit/crec-sdk/watchers"
)

// Create an authenticated API client
api, err := crec.NewAPIClient(
    "https://api.crec.chainlink.com",
    "your-api-key",
)

// Create only the sub-clients you need
channelsClient, _ := channels.NewClient(&channels.Options{APIClient: api})
watchersClient, _ := watchers.NewClient(&watchers.Options{
    APIClient:    api,
    PollInterval: 5 * time.Second,
})

Core Workflows

πŸ” Receiving and Verifying Events
graph LR
    A[Smart Contract Event] --> B(DON Consensus) --> C(Event Signing) --> D{CREC API} --> E[SDK: Events Client] --> F[Verify Signatures] --> G[Your Logic]

Poll and verify events:

// Poll events from a channel
events, hasMore, _ := client.Events.Poll(ctx, channelID, nil)

for _, event := range events {
    // CRITICAL: Always verify before processing
    verified, _ := client.Events.Verify(&event)
    if verified {
        var decoded map[string]interface{}
        client.Events.Decode(&event, &decoded)
        processEvent(decoded)
    }
}
⚑ Sending Signed Operations (Gas-less)
graph LR
    A[Build Operation] --> B[Sign] --> C[SDK: Transact Client] --> D{CREC API} --> E[Pays Gas & Relays] --> F[Smart Account Executes]

Build and execute an operation:

import (
    "github.com/smartcontractkit/crec-sdk/transact/signer/local"
    "github.com/smartcontractkit/crec-sdk/transact/types"
)

// Build the operation
operation := &types.Operation{
    ID:      big.NewInt(time.Now().Unix()),
    Account: accountAddress,
    Transactions: []types.Transaction{
        {To: target, Value: big.NewInt(0), Data: calldata},
    },
}

// Create signer and execute
signer := local.NewSigner(privateKey)
result, _ := client.Transact.ExecuteOperation(ctx, channelID, signer, operation, chainSelector)

Documentation

API Reference

For complete API documentation, use Go's built-in documentation tools:

go doc github.com/smartcontractkit/crec-sdk
go doc github.com/smartcontractkit/crec-sdk/events
go doc github.com/smartcontractkit/crec-sdk/transact
go doc github.com/smartcontractkit/crec-sdk/channels
go doc github.com/smartcontractkit/crec-sdk/watchers

Or run a local documentation server:

go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite -http :8080
# Navigate to http://localhost:8080/github.com/smartcontractkit/crec-sdk
Complete Example

See the crec-example-payment-processor repository for a full working application.

Extensions

Protocol-specific helpers for common Chainlink systems:

Event Verification Keys (Mainnet)

The SDK includes built-in mainnet DON public keys for event verification. No configuration is required β€” verification is enabled by default.

Default Configuration
  • Keys: All Zone A workflow nodes (10 keys)
  • Required Signatures: 3 (configurable)

DON Keys Reference

ethereum-mainnet
zone-a
Node Operator Public Key
chainlayer-wf-zone-a-1 0xff9b062fccb2f042311343048b9518068370f837
clp-cre-wf-zone-a-0 0xe55fcaf921e76c6bbcf9415bba12b1236f07b0c3
dextrac-wf-zone-a-3 0x4d6cfd44f94408a39fb1af94a53c107a730ba161
fiews-wf-zone-a-2 0xde5cd1dd4300a0b4854f8223add60d20e1dfe21b
inotel-wf-zone-a-4 0xf3baa9a99b5ad64f50779f449bac83baac8bfdb6
linkforest-wf-zone-a-5 0xd7f22fb5382ff477d2ff5c702cab0ef8abf18233
linkpool-wf-zone-a-0 0xcdf20f8ffd41b02c680988b20e68735cc8c1ca17
linkriver-wf-zone-a-6 0x4d7d71c7e584cfa1f5c06275e5d283b9d3176924
piertwo-wf-zone-a-7 0x1a89c98e75983ec384ad8e83eaf7d0176eeaf155
simplyvc-wf-zone-a-8 0x4f99b550623e77b807df7cbed9c79d55e1163b48
Customizing Verification

Override the defaults if you need custom keys or signature requirements:

// Use custom keys and signature threshold
client, err := crec.NewClient(
    "https://api.crec.chainlink.com",
    "your-api-key",
    crec.WithEventVerification(5, []string{  // Require 5 signatures
        "0xff9b062fccb2f042311343048b9518068370f837",
        "0xe55fcaf921e76c6bbcf9415bba12b1236f07b0c3",
        // ... custom key list ...
    }),
)

// Or disable verification entirely
client, err := crec.NewClient(
    "https://api.crec.chainlink.com",
    "your-api-key",
    crec.WithoutEventVerification(),
)

Note: Keys rarely change. When they do, update the SDK to get the latest defaults.

Glossary

Term Description
CREC CRE Connect - decentralized network providing cryptographic proof of event authenticity
DON Decentralized Oracle Network - independent nodes that reach consensus and sign events
Verifiable Event Blockchain event with cryptographic signatures from DON members
Account Abstraction Transaction model with atomic execution, gas sponsorship, and flexible signing
Operation Bundle of transactions executed atomically by a smart account
EIP-712 Ethereum standard for typed data signing, used for operation signatures
CCIP Cross-Chain Interoperability Protocol for cross-chain transfers

Documentation ΒΆ

Overview ΒΆ

Package crec provides a unified SDK for interacting with the CREC system.

The SDK follows a resource-oriented design with sub-clients for each domain:

client, err := crec.NewClient("https://api.crec.example.com", "your-api-key")
if err != nil {
    log.Fatal(err)
}

// Create a channel
channel, err := client.Channels.Create(ctx, channels.CreateInput{Name: "my-channel"})

// Sign and send an operation
op, err := client.Transact.ExecuteOperation(ctx, signer, operation, chainSelector)

// Poll for events
events, hasMore, err := client.Events.Poll(ctx, channelID, params)

Package crec provides a unified SDK for interacting with the CREC system.

Overview ΒΆ

The CREC SDK follows a resource-oriented design with a single top-level Client that provides access to sub-clients for each domain:

Use Client.ListNetworks to list available networks (GET /networks); no separate sub-client.

Getting Started ΒΆ

Create a new client with your API credentials:

import "github.com/smartcontractkit/crec-sdk"

client, err := crec.NewClient(
    "https://api.crec.example.com",
    "your-api-key",
)
if err != nil {
    log.Fatal(err)
}

Working with Channels ΒΆ

Channels are logical groupings for organizing watchers, events, and operations:

// Create a channel
channel, err := client.Channels.Create(ctx, channels.CreateInput{
    Name: "my-channel",
})

// List channels
channels, hasMore, err := client.Channels.List(ctx, channels.ListInput{})

// Delete a channel
err = client.Channels.Delete(ctx, channelID)

Working with Watchers ΒΆ

Watchers monitor blockchain events on specific smart contracts:

// Create a watcher with a known service
watcher, err := client.Watchers.CreateWithService(ctx, channelID, watchers.CreateWithServiceInput{
    ChainSelector: "16015286601757825753",
    Address:       "0x...",
    Service:       "dvp",
    Events:        []string{"SettlementProposed"},
})

// Wait for watcher to become active
watcher, err = client.Watchers.WaitForActive(ctx, channelID, watcher.WatcherId, 30*time.Second)

Working with Events ΒΆ

Poll for events from a channel:

// Poll events
events, hasMore, err := client.Events.Poll(ctx, channelID, &apiClient.GetChannelsChannelIdEventsParams{
    Limit: ptr(100),
})

// Verify an event's authenticity (requires crec.WithOrgID or use VerifyWithOrgID for multi-org)
valid, err := client.Events.Verify(&event)

Signing and Sending Operations ΒΆ

The Transact client provides full operation lifecycle management:

// Create an operation from transactions
operation := &types.Operation{
    ID:           big.NewInt(time.Now().Unix()),
    Account:      executorAccount,
    Transactions: []types.Transaction{...},
}

// Sign and send in one step
result, err := client.Transact.ExecuteOperation(ctx, channelID, signer, operation, chainSelector)

// Or manually: sign, then send
hash, signature, err := client.Transact.SignOperation(ctx, operation, signer, chainSelector)
result, err := client.Transact.SendSignedOperation(ctx, channelID, operation, signature, chainSelector)

Configuration Options ΒΆ

Use functional options to customize the client:

client, err := crec.NewClient(
    baseURL,
    apiKey,
    crec.WithLogger(logger),
    crec.WithHTTPClient(customHTTPClient),
    crec.WithOrgID("my-org-id"),
    crec.WithEventVerification(2, []string{"0xSigner1", "0xSigner2", "0xSigner3"}),
    crec.WithWatcherPolling(5*time.Second, 10*time.Second),
)

Using Individual Sub-Clients ΒΆ

If you only need a subset of the SDK's functionality, you can create individual sub-clients without instantiating the full Client. Use NewAPIClient to create an authenticated API client, then pass it to the sub-client you need:

import (
    "github.com/smartcontractkit/crec-sdk"
    "github.com/smartcontractkit/crec-sdk/channels"
    "github.com/smartcontractkit/crec-sdk/watchers"
)

// Create an authenticated API client
api, err := crec.NewAPIClient("https://api.crec.example.com", "your-api-key")
if err != nil {
    log.Fatal(err)
}

// Create only the sub-clients you need
channelsClient, err := channels.NewClient(&channels.Options{APIClient: api})
watchersClient, err := watchers.NewClient(&watchers.Options{APIClient: api})

This approach is useful when:

  • You want to minimize dependencies in a specific package
  • You're building a focused service that only uses one domain
  • You need fine-grained control over sub-client configuration

Error Handling ΒΆ

All errors are wrapped with context and can be inspected using errors.Is:

if errors.Is(err, channels.ErrChannelNotFound) {
    // Handle 404
}

if errors.Is(err, transact.ErrOperationNotFound) {
    // Handle operation not found
}

Index ΒΆ

Constants ΒΆ

View Source
const DefaultMinRequiredSignatures = 4

DefaultMinRequiredSignatures is the minimum number of valid signatures required to verify an event. Calculated as F + 1, where F is the maximum number of faulty nodes the DON can tolerate. With F+1 signatures, at least one must be from an honest node, guaranteeing the data passed consensus.

The DON transmits once this minimum is reached, so reports will never contain more than F+1 signatures. Do not increase this value unless you are certain about the implicationsβ€”doing so will cause signature verification to fail.

Variables ΒΆ

View Source
var (
	// ErrBaseURLRequired is returned when the base URL is empty.
	ErrBaseURLRequired = errors.New("base URL is required")

	// ErrAPIKeyRequired is returned when the API key is empty.
	ErrAPIKeyRequired = errors.New("API key is required")

	// ErrInvalidEventVerificationConfig is returned when event verification is misconfigured.
	ErrInvalidEventVerificationConfig = errors.New("minRequiredSignatures must be > 0 when validSigners are provided")

	// ErrListNetworks is returned when listing networks fails.
	ErrListNetworks = errors.New("failed to list networks")
)

Client initialization errors

View Source
var DefaultValidSigners = []string{
	"0xff9b062fccb2f042311343048b9518068370f837",
	"0xe55fcaf921e76c6bbcf9415bba12b1236f07b0c3",
	"0x4d6cfd44f94408a39fb1af94a53c107a730ba161",
	"0xde5cd1dd4300a0b4854f8223add60d20e1dfe21b",
	"0xf3baa9a99b5ad64f50779f449bac83baac8bfdb6",
	"0xd7f22fb5382ff477d2ff5c702cab0ef8abf18233",
	"0xcdf20f8ffd41b02c680988b20e68735cc8c1ca17",
	"0x4d7d71c7e584cfa1f5c06275e5d283b9d3176924",
	"0x1a89c98e75983ec384ad8e83eaf7d0176eeaf155",
	"0x4f99b550623e77b807df7cbed9c79d55e1163b48",
}

DefaultValidSigners contains the production Zone A workflow node public keys. These are the keys used by the DON to sign events on Ethereum Mainnet. Updated keys can be found in the chainlink-deployments repository.

These keys rarely change. When they do, update the SDK to get new defaults.

Functions ΒΆ

This section is empty.

Types ΒΆ

type APIClient ΒΆ

type APIClient = apiClient.ClientWithResponses

APIClient is the underlying HTTP client for the CREC API. This type is exported to allow users to create individual sub-clients without using the full Client.

func NewAPIClient ΒΆ

func NewAPIClient(baseURL, apiKey string, opts ...Option) (*APIClient, error)

NewAPIClient creates an authenticated CREC API client that can be used to create individual sub-clients without instantiating the full Client.

This is useful when you only need a subset of the SDK's functionality.

Example:

api, err := crec.NewAPIClient("https://api.crec.example.com", "your-api-key")
if err != nil {
    log.Fatal(err)
}

// Create only the channels sub-client
channelsClient, err := channels.NewClient(&channels.Options{APIClient: api})

type Client ΒΆ

type Client struct {
	// Channels provides operations for managing CREC channels.
	Channels *channels.Client

	// Events provides operations for polling and verifying events from CREC.
	Events *events.Client

	// Transact provides operations for signing and sending operations to CREC.
	Transact *transact.Client

	// Wallets provides operations for managing CREC Smart Wallets.
	Wallets *wallets.Client

	// Watchers provides operations for managing CREC watchers.
	Watchers *watchers.Client
	// contains filtered or unexported fields
}

Client is the main entry point for the CREC SDK. It provides access to all sub-clients for interacting with different parts of the CREC system.

func NewClient ΒΆ

func NewClient(baseURL, apiKey string, opts ...Option) (*Client, error)

NewClient creates a new CREC SDK client with the provided base URL and API key.

Parameters:

  • baseURL: The base URL of the CREC API (e.g., "https://api.crec.example.com")
  • apiKey: The API key for authenticating with the CREC API
  • opts: Optional configuration options (see Option for available options)

Returns a configured Client or an error if initialization fails.

func (*Client) ListNetworks ΒΆ

func (c *Client) ListNetworks(ctx context.Context) ([]apiClient.Network, bool, error)

ListNetworks returns the list of available networks supported by the CREC platform. It delegates to the underlying API client (GET /networks) with no extra SDK logic.

Parameters:

  • ctx: The context for the request.

Returns the list of networks, a boolean indicating if there are more results (HasMore), and an error if the request fails.

type Option ΒΆ

type Option func(*clientConfig)

Option is a functional option for configuring the Client.

func WithEventVerification ΒΆ

func WithEventVerification(minRequiredSignatures int, validSigners []string) Option

WithEventVerification configures custom event verification settings. By default, the SDK uses DefaultValidSigners and DefaultMinRequiredSignatures. Use this option to override with custom keys or signature requirements.

Parameters:

  • minRequiredSignatures: Minimum number of valid signatures required to verify an event
  • validSigners: List of valid signer addresses (as hex strings)

func WithHTTPClient ΒΆ

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client for API requests. If not provided, http.DefaultClient is used.

func WithLogger ΒΆ

func WithLogger(logger *slog.Logger) Option

WithLogger sets a custom logger for the SDK. If not provided, slog.Default() is used.

func WithOrgID ΒΆ

func WithOrgID(orgID string) Option

WithOrgID sets the default organization ID for the events client. When set, [Client.Events].Verify and [Client.Events].VerifyOperationStatus can be called without passing an org ID. For multi-org use, omit this and use VerifyWithOrgID or VerifyOperationStatusWithOrgID with an explicit org ID per call.

func WithWatcherPolling ΒΆ

func WithWatcherPolling(pollInterval, eventualConsistencyWindow time.Duration) Option

WithWatcherPolling configures the Watchers client polling behavior.

Parameters:

  • pollInterval: Duration between polling attempts when waiting for watcher state changes
  • eventualConsistencyWindow: Duration to tolerate 404 errors after creation due to eventual consistency

func WithWorkflowOwner ΒΆ

func WithWorkflowOwner(workflowOwner string) Option

WithWorkflowOwner sets the default workflow owner address for the events client. When set, [Client.Events].VerifyWithWorkflowOwner and [Client.Events].VerifyOperationStatusWithWorkflowOwner can be called without passing the workflow owner. For multi-org or per-event workflow owner, pass it explicitly.

func WithoutEventVerification ΒΆ

func WithoutEventVerification() Option

WithoutEventVerification disables event verification entirely. Use this option if you don't need to verify event signatures.

Directories ΒΆ

Path Synopsis
Package channels provides operations for managing channels in the CREC platform.
Package channels provides operations for managing channels in the CREC platform.
Package events provides operations for polling and verifying events from CREC.
Package events provides operations for polling and verifying events from CREC.
extension
interfaces
mocks
Package parsing provides common utilities for parsing blockchain event data.
Package parsing provides common utilities for parsing blockchain event data.
eip712
Package eip712 provides functionality for computing EIP-712 hashes and signatures for CREC operations without requiring network connectivity or API client dependencies.
Package eip712 provides functionality for computing EIP-712 hashes and signatures for CREC operations without requiring network connectivity or API client dependencies.
signer
Package signer provides signing interfaces for the CREC SDK.
Package signer provides signing interfaces for the CREC SDK.
signer/fireblocks
Package fireblocks provides a signer.Signer implementation using Fireblocks' custody infrastructure.
Package fireblocks provides a signer.Signer implementation using Fireblocks' custody infrastructure.
signer/kms
Package kms provides a signer using AWS Key Management Service.
Package kms provides a signer using AWS Key Management Service.
signer/local
Package local provides a signer using local ECDSA private keys.
Package local provides a signer using local ECDSA private keys.
signer/privy
Package privy provides a signer using Privy's wallet-as-a-service platform.
Package privy provides a signer using Privy's wallet-as-a-service platform.
signer/vault
Package vault provides a signer using HashiCorp Vault Transit secrets engine.
Package vault provides a signer using HashiCorp Vault Transit secrets engine.
types
Package types provides data structures for CREC transact operations.
Package types provides data structures for CREC transact operations.
Package wallets provides operations for managing Smart Wallets in the CREC platform.
Package wallets provides operations for managing Smart Wallets in the CREC platform.
Package watchers provides operations for managing blockchain event watchers.
Package watchers provides operations for managing blockchain event watchers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL