watchers

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 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")

	// ErrChannelIDRequired is returned when the channel ID is nil or empty.
	ErrChannelIDRequired = errors.New("channel_id cannot be empty")
	// ErrWatcherIDRequired is returned when the watcher ID is nil or empty.
	ErrWatcherIDRequired = errors.New("watcher_id cannot be empty")
	// ErrNameRequired is returned when the name is required but empty.
	ErrNameRequired = errors.New("name cannot be an empty string")
	// ErrServiceRequired is returned when the service is required but empty.
	ErrServiceRequired = errors.New("service is required")
	// ErrAddressRequired is returned when the contract address is required but empty.
	ErrAddressRequired = errors.New("address is required")
	// ErrEventsRequired is returned when the events list is empty.
	ErrEventsRequired = errors.New("events list cannot be empty")
	// ErrABIRequired is returned when the ABI is required but empty.
	ErrABIRequired = errors.New("abi cannot be empty")
	// ErrOptionsRequired is returned when the options parameter is nil.
	ErrOptionsRequired = errors.New("Options is required")
	// ErrAPIClientRequired is returned when the API client is nil in options.
	ErrAPIClientRequired = errors.New("APIClient is required")
	// ErrChainSelectorRequired is returned when the chain selector is empty or zero.
	ErrChainSelectorRequired = errors.New("chain_selector is required")
	// ErrInvalidABIType is returned when an ABI entry is not of type "event".
	ErrInvalidABIType = errors.New("invalid ABI type, only 'event' is currently supported")
	// ErrEventNotInABI is returned when a requested event is not in the provided ABI.
	ErrEventNotInABI = errors.New("event not found in provided ABI")

	// ErrWaitForActiveTimeout is returned when the watcher does not become active before the timeout.
	ErrWaitForActiveTimeout = errors.New("timeout waiting for watcher to become active")
	// ErrWaitForArchivedTimeout is returned when the watcher is not archived before the timeout.
	ErrWaitForArchivedTimeout = errors.New("timeout waiting for watcher to be archived")

	// ErrWatcherDeploymentFailed is returned when the watcher deployment fails.
	ErrWatcherDeploymentFailed = errors.New("watcher deployment failed")
	// ErrWatcherIsArchiving is returned when the watcher is being archived and cannot become active.
	ErrWatcherIsArchiving = errors.New("watcher is being archived and cannot become active")
	// ErrWatcherAlreadyArchived is returned when the watcher has already been archived.
	ErrWatcherAlreadyArchived = errors.New("watcher has been archived and cannot become active")
	// ErrWatcherArchiveFailed is returned when the watcher archive operation fails.
	ErrWatcherArchiveFailed = errors.New("watcher archive failed")

	// ErrEmptyResponse is returned when the API returns an unexpected empty response.
	ErrEmptyResponse = errors.New("unexpected empty response from API")
	// ErrUnexpectedStatus is returned when the watcher has an unexpected status value.
	ErrUnexpectedStatus = errors.New("unexpected watcher status")

	// ErrCreateWatcherRequest is returned when the create watcher request cannot be built.
	ErrCreateWatcherRequest = errors.New("failed to create watcher request")
	// ErrCreateWatcherService is returned when creating a watcher with service fails.
	ErrCreateWatcherService = errors.New("failed to create watcher with service")
	// ErrCreateWatcherABI is returned when creating a watcher with ABI fails.
	ErrCreateWatcherABI = errors.New("failed to create watcher with ABI")
	// ErrListWatchers is returned when listing watchers fails.
	ErrListWatchers = errors.New("failed to list watchers")
	// ErrGetWatcher is returned when fetching a watcher fails.
	ErrGetWatcher = errors.New("failed to get watcher")
	// ErrUpdateWatcher is returned when updating a watcher fails.
	ErrUpdateWatcher = errors.New("failed to update watcher")
	// ErrArchiveWatcher is returned when archiving a watcher fails.
	ErrArchiveWatcher = errors.New("failed to archive watcher")
	// ErrCheckWatcherStatus is returned when checking watcher status fails.
	ErrCheckWatcherStatus = errors.New("failed to check watcher status")
	// ErrUnexpectedStatusCode is returned when the API returns an unexpected HTTP status code.
	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; use WaitForArchived to poll until the watcher reaches "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 a 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 using a predefined service (e.g., 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 ID 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, fails, or times out. Returns ErrWaitForActiveTimeout if maxWaitTime is exceeded before the watcher becomes active.

func (*Client) WaitForArchived

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

WaitForArchived polls the watcher until it reaches "archived" status or the timeout is reached. Returns ErrWaitForArchivedTimeout if maxWaitTime is exceeded before the watcher is archived.

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"`
}

CreateWithABIInput defines the input for creating a watcher with a custom event 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"`
}

CreateWithServiceInput defines the input for creating a watcher using a predefined service (e.g., dvp, dta).

type EventABI

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

EventABI describes an event definition in Solidity ABI format.

type EventABIInput

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

EventABIInput describes a single input parameter of an event in the ABI.

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"`
}

ListFilters defines optional filters for listing watchers (pagination, status, chain, etc.).

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"`
}

UpdateInput defines the input for updating a watcher.

Jump to

Keyboard shortcuts

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