watchers

package
v0.5.2 Latest Latest
Warning

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

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

Documentation

Overview

Package watchers provides operations for managing blockchain event watchers.

Watchers monitor specific smart contract events on blockchain networks and trigger workflows when those events occur. They can be configured with pre-defined service ABIs (dvp, dta, test_consumer) or custom event ABIs.

Usage

Watchers are typically accessed through the main SDK client:

client, _ := crec.NewClient(baseURL, apiKey)

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

For advanced use cases, create the client directly:

watchersClient, err := watchers.NewClient(&watchers.Options{
    APIClient: apiClient,
    Logger:    &logger,
})

Creating Watchers

Use Client.CreateWithService for known contract types (dvp, dta, test_consumer):

name := "My DVP Watcher"
watcher, err := client.Watchers.CreateWithService(ctx, channelID, CreateWithServiceInput{
    Name:          &name,
    ChainSelector: "16015286601757825753",
    Address:       "0x1234...",
    Service:       "dvp",
    Events:        []string{"OperationExecuted"},
})

Use Client.CreateWithABI for custom contracts with your own event definitions:

watcher, err := client.Watchers.CreateWithABI(ctx, channelID, CreateWithABIInput{
    ChainSelector: "16015286601757825753",
    Address:       "0x1234...",
    Events:        []string{"Transfer"},
    ABI: []EventABI{{
        Name: "Transfer",
        Type: "event",
        Inputs: []EventABIInput{
            {Name: "from", Type: "address", Indexed: true},
            {Name: "to", Type: "address", Indexed: true},
            {Name: "value", Type: "uint256", Indexed: false},
        },
    }},
})

Watcher Lifecycle

Watchers start in "pending" status and must be deployed before becoming "active". Use Client.WaitForActive to poll until ready:

activeWatcher, err := client.Watchers.WaitForActive(ctx, channelID, watcherID, 2*time.Minute)
if err != nil {
    if errors.Is(err, ErrWatcherDeploymentFailed) {
        // Handle deployment failure
    }
}

The watcher lifecycle states are:

  • pending: Created, deployment in progress
  • active: Deployed and monitoring events
  • failed: Deployment failed (terminal)
  • archiving: Archive in progress
  • archived: Successfully archived (terminal)
  • archive_failed: Archive operation failed

Listing and Filtering

Use Client.List with ListFilters to query watchers:

statusFilter := []apiClient.WatcherStatus{apiClient.WatcherStatusActive}
result, err := client.Watchers.List(ctx, channelID, ListFilters{
    Status: &statusFilter,
    Limit:  ptr(10),
})
for _, w := range result.Data {
    fmt.Printf("Watcher: %s\n", w.WatcherId)
}

Error Handling

All errors can be inspected with errors.Is:

if errors.Is(err, ErrWatcherNotFound) {
    // Handle 404
}
if errors.Is(err, ErrWatcherDeploymentFailed) {
    // Handle deployment failure
}
if errors.Is(err, ErrWaitForActiveTimeout) {
    // Handle timeout
}

The client automatically retries transient errors (5xx, 429, network issues) during polling operations like Client.WaitForActive and Client.WaitForArchived.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrWatcherNotFound is returned when a watcher is not found (404 response)
	ErrWatcherNotFound = errors.New("watcher not found")

	// Validation errors
	ErrChannelIDRequired     = errors.New("channel_id cannot be empty")
	ErrWatcherIDRequired     = errors.New("watcher_id cannot be empty")
	ErrNameRequired          = errors.New("name cannot be an empty string")
	ErrServiceRequired       = errors.New("service is required")
	ErrAddressRequired       = errors.New("address is required")
	ErrEventsRequired        = errors.New("events list cannot be empty")
	ErrABIRequired           = errors.New("abi cannot be empty")
	ErrOptionsRequired       = errors.New("Options is required")
	ErrAPIClientRequired     = errors.New("APIClient is required")
	ErrChainSelectorRequired = errors.New("chain_selector is required")
	ErrInvalidABIType        = errors.New("invalid ABI type, only 'event' is currently supported")
	ErrEventNotInABI         = errors.New("event not found in provided ABI")

	// Timeout errors
	ErrWaitForActiveTimeout   = errors.New("timeout waiting for watcher to become active")
	ErrWaitForArchivedTimeout = errors.New("timeout waiting for watcher to be archived")

	// Watcher state errors
	ErrWatcherDeploymentFailed = errors.New("watcher deployment failed")
	ErrWatcherIsArchiving      = errors.New("watcher is being archived and cannot become active")
	ErrWatcherAlreadyArchived  = errors.New("watcher has been archived and cannot become active")
	ErrWatcherArchiveFailed    = errors.New("watcher archive failed")

	// API response errors
	ErrEmptyResponse    = errors.New("unexpected empty response from API")
	ErrUnexpectedStatus = errors.New("unexpected watcher status")

	// API operation errors (base errors for wrapping)
	ErrCreateWatcherRequest = errors.New("failed to create watcher request")
	ErrCreateWatcherService = errors.New("failed to create watcher with service")
	ErrCreateWatcherABI     = errors.New("failed to create watcher with ABI")
	ErrListWatchers         = errors.New("failed to list watchers")
	ErrGetWatcher           = errors.New("failed to get watcher")
	ErrUpdateWatcher        = errors.New("failed to update watcher")
	ErrArchiveWatcher       = errors.New("failed to archive watcher")
	ErrCheckWatcherStatus   = errors.New("failed to check watcher status")
	ErrUnexpectedStatusCode = errors.New("unexpected status code")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides operations for managing CREC watchers. Watchers monitor blockchain events on specific smart contracts and trigger workflows.

func NewClient

func NewClient(opts *Options) (*Client, error)

NewClient creates a new CREC Watchers client with the provided options. Returns a pointer to the Client and an error if any issues occur during initialization.

  • opts: Options for configuring the CREC Watchers client, see Options for details.

func (*Client) Archive

func (c *Client) Archive(ctx context.Context, channelID uuid.UUID, watcherID uuid.UUID) (*apiClient.Watcher, error)

Archive archives a watcher by transitioning it to archived status via PATCH. Archiving is asynchronous: the PATCH returns 202 with the watcher in "archiving" status, with a final transition to "archived" (or "archive_failed").

func (*Client) CreateWithABI

func (c *Client) CreateWithABI(ctx context.Context, channelID uuid.UUID, input CreateWithABIInput) (*apiClient.Watcher, error)

CreateWithABI creates a new watcher with custom event ABI

func (*Client) CreateWithService

func (c *Client) CreateWithService(ctx context.Context, channelID uuid.UUID, input CreateWithServiceInput) (*apiClient.Watcher, error)

CreateWithService creates a new watcher with a service (dvp, dta, test_consumer)

func (*Client) Get

func (c *Client) Get(ctx context.Context, channelID uuid.UUID, watcherID uuid.UUID) (*apiClient.Watcher, error)

Get retrieves a specific watcher by channel and watcher ID

func (*Client) List

func (c *Client) List(ctx context.Context, channelID uuid.UUID, filters ListFilters) (*apiClient.WatcherList, error)

List retrieves watchers for a specific channel with optional filters

func (*Client) Update

func (c *Client) Update(ctx context.Context, channelID uuid.UUID, watcherID uuid.UUID, input UpdateInput) (*apiClient.Watcher, error)

Update updates a watcher's name

func (*Client) WaitForActive

func (c *Client) WaitForActive(ctx context.Context, channelID uuid.UUID, watcherID uuid.UUID, maxWaitTime time.Duration) (*apiClient.Watcher, error)

WaitForActive polls a watcher until it reaches active status or fails. TODO: Consider extracting status check logic into a helper method for improved readability.

func (*Client) WaitForArchived

func (c *Client) WaitForArchived(ctx context.Context, channelID uuid.UUID, watcherID uuid.UUID, maxWaitTime time.Duration) error

WaitForArchived waits for a watcher to be fully archived. The method polls the watcher status until it reaches "archived" state or the timeout is reached.

type CreateWithABIInput

type CreateWithABIInput struct {
	Name          string     `json:"name"`
	ChainSelector string     `json:"chain_selector"`
	Address       string     `json:"address"`
	Events        []string   `json:"events"`
	ABI           []EventABI `json:"abi"`
}

type CreateWithServiceInput

type CreateWithServiceInput struct {
	Name          *string                `json:"name,omitempty"`
	ChainSelector string                 `json:"chain_selector"`
	Service       string                 `json:"service"`
	Events        []string               `json:"events"`
	Address       string                 `json:"address"`
	ServiceConfig map[string]interface{} `json:"service_config,omitempty"`
}

type EventABI

type EventABI struct {
	Anonymous bool            `json:"anonymous"`
	Inputs    []EventABIInput `json:"inputs"`
	Name      string          `json:"name"`
	Type      string          `json:"type"`
}

type EventABIInput

type EventABIInput struct {
	Indexed      bool   `json:"indexed"`
	InternalType string `json:"internalType"`
	Name         string `json:"name"`
	Type         string `json:"type"`
}

type ListFilters

type ListFilters struct {
	Limit         *int                       `url:"limit,omitempty"`
	Offset        *int64                     `url:"offset,omitempty"`
	Name          *string                    `url:"name,omitempty"`
	Status        *[]apiClient.WatcherStatus `url:"status,omitempty"`
	ChainSelector *string                    `url:"chain_selector,omitempty"`
	Address       *string                    `url:"address,omitempty"`
	Service       *[]string                  `url:"service,omitempty"`
	EventName     *string                    `url:"event_name,omitempty"`
}

type Options

type Options struct {
	Logger                    *slog.Logger
	APIClient                 *apiClient.ClientWithResponses
	PollInterval              time.Duration
	EventualConsistencyWindow time.Duration
}

Options defines the options for creating a new CREC Watchers client.

  • Logger: Optional logger instance.
  • APIClient: The CREC API client instance.
  • PollInterval: Optional polling interval for WaitForActive. Defaults to 2 seconds if not set.
  • EventualConsistencyWindow: Optional duration to tolerate 404 errors after creation due to eventual consistency. Defaults to 2 seconds if not set.

type UpdateInput

type UpdateInput struct {
	Name string `json:"name"`
}

Jump to

Keyboard shortcuts

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