common

package
v0.0.47 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EncodeUint256Result added in v0.0.45

func EncodeUint256Result(v *big.Int) ([]byte, error)

EncodeUint256Result canonically encodes a balance/amount as abi.encode(uint256) so read results are byte-identical across validators and decodable by the requesting contract. The bounds check guards against a malicious RPC value that would not fit (FillBytes panics on overflow).

func NewReadErrorResult added in v0.0.45

func NewReadErrorResult(code ucallbacktypes.ReadErrorCode) *ucallbacktypes.ReadResult

NewReadErrorResult builds an ERROR observation carrying a deterministic error code. ResultData stays empty and only the code (never local error text) is voted, so every validator observing the same failure converges on one ballot.

Types

type ChainClient

type ChainClient interface {
	// Start initializes and starts the chain client
	Start(ctx context.Context) error

	// Stop gracefully shuts down the chain client
	Stop() error

	// IsHealthy checks if the chain client is operational
	IsHealthy() bool

	// GetTxBuilder returns the TxBuilder for this chain
	// Returns an error if txBuilder is not supported for this chain (e.g., Push chain)
	GetTxBuilder() (TxBuilder, error)

	// GetReadRequestHandler returns the handler executing read requests
	// destined for this chain
	// Returns an error if reads are not available (e.g. client not started)
	GetReadRequestHandler() (ReadRequestHandler, error)
}

ChainClient defines the interface for chain-specific implementations

type ChainStore

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

ChainStore provides database operations for chain state and events

func NewChainStore

func NewChainStore(database *db.DB) *ChainStore

NewChainStore creates a new chain store

func (*ChainStore) DeleteTerminalEvents

func (cs *ChainStore) DeleteTerminalEvents(updatedBefore any) (int64, error)

DeleteTerminalEvents deletes events in terminal states (COMPLETED, REVERTED, EXPIRED) that were updated before the given time

func (*ChainStore) GetChainHeight

func (cs *ChainStore) GetChainHeight() (uint64, error)

GetChainHeight returns the last processed block height for the chain. Creates a new entry with height 0 if one doesn't exist (atomic via FirstOrCreate).

func (*ChainStore) GetConfirmedEvents

func (cs *ChainStore) GetConfirmedEvents(limit int) ([]store.Event, error)

GetConfirmedEvents fetches confirmed events ordered by creation time

func (*ChainStore) GetPendingEvents

func (cs *ChainStore) GetPendingEvents(limit int) ([]store.Event, error)

GetPendingEvents fetches pending events ordered by creation time

func (*ChainStore) InsertEventIfNotExists

func (cs *ChainStore) InsertEventIfNotExists(event *store.Event) (bool, error)

InsertEventIfNotExists inserts an event if it doesn't already exist (by EventID) Returns (true, nil) if a new event was inserted, (false, nil) if it already existed, or (false, error) if insertion failed

func (*ChainStore) UpdateChainHeight

func (cs *ChainStore) UpdateChainHeight(blockHeight uint64) error

UpdateChainHeight updates the last processed block height for the chain. Creates a new entry if one doesn't exist (atomic via FirstOrCreate). Only updates if the new height is greater than the current one.

func (*ChainStore) UpdateEventStatus

func (cs *ChainStore) UpdateEventStatus(eventID string, oldStatus, newStatus string) (int64, error)

UpdateEventStatus updates the status of an event by event ID

func (*ChainStore) UpdateStatusAndEventData

func (cs *ChainStore) UpdateStatusAndEventData(eventID, oldStatus, newStatus string, eventData []byte) (int64, error)

UpdateStatusAndEventData atomically flips the event status and updates the event data in one DB write. The update is conditional on the event currently having oldStatus (compare-and-swap semantics). Returns the number of rows affected (0 means the event was already in a different status).

func (*ChainStore) UpdateStatusAndVoteTxHash

func (cs *ChainStore) UpdateStatusAndVoteTxHash(eventID, oldStatus, newStatus, voteTxHash string) (int64, error)

UpdateStatusAndVoteTxHash atomically flips the event status and records the vote tx hash in one DB write. The update is conditional on the event currently having oldStatus (compare-and-swap semantics). Returns the number of rows affected (0 means the event was already in a different status).

type EventCleaner

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

EventCleaner handles periodic cleanup of old confirmed events for a chain

func NewEventCleaner

func NewEventCleaner(
	database *db.DB,
	cleanupIntervalSeconds *int,
	retentionPeriodSeconds *int,
	chainID string,
	logger zerolog.Logger,
) *EventCleaner

NewEventCleaner creates a new event cleaner for a chain

func (*EventCleaner) Start

func (ec *EventCleaner) Start(ctx context.Context) error

Start begins the periodic cleanup process

func (*EventCleaner) Stop

func (ec *EventCleaner) Stop()

Stop gracefully stops the event cleaner. No-op if not running.

type EventHandler added in v0.0.45

type EventHandler interface {
	HandleEvent(ctx context.Context, event *store.Event) error
}

EventHandler processes one CONFIRMED event of a registered type. Handlers own the event's status transitions; a returned error is logged and the event is retried next tick.

type EventProcessor

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

EventProcessor drains CONFIRMED events from the chain's database and dispatches them to the handler registered for their type. Event types without a handler are ignored.

func NewEventProcessor

func NewEventProcessor(
	database *db.DB,
	chainID string,
	logger zerolog.Logger,
) *EventProcessor

NewEventProcessor creates a new event processor. Register handlers before Start.

func (*EventProcessor) IsRunning

func (ep *EventProcessor) IsRunning() bool

IsRunning returns whether the processor is currently running

func (*EventProcessor) RegisterHandler added in v0.0.45

func (ep *EventProcessor) RegisterHandler(eventType string, handler EventHandler)

RegisterHandler registers a handler for an event type. Must be called before Start.

func (*EventProcessor) Start

func (ep *EventProcessor) Start(ctx context.Context) error

Start begins processing events

func (*EventProcessor) Stop

func (ep *EventProcessor) Stop() error

Stop gracefully stops the event processor

type FundMigrationData

type FundMigrationData struct {
	From     string   // Old TSS address (derived from old pubkey)
	To       string   // New TSS address (derived from current pubkey)
	GasPrice *big.Int // Gas price from the migration event
	GasLimit uint64   // Gas limit from the migration event
	L1GasFee *big.Int // Extra L1 data-availability fee (wei); 0 for non-L2 chains

	Balance *big.Int // if nil, builder queries chain
}

FundMigrationData contains the data needed to build a fund migration transaction. Populated by the coordinator from the migration event + derived addresses.

type InboundObservation added in v0.0.45

type InboundObservation struct {
	SourceChain         string `json:"sourceChain"`
	LogIndex            uint   `json:"logIndex"`
	Sender              string `json:"sender"`
	Recipient           string `json:"recipient"`
	Token               string `json:"bridgeToken"`
	Amount              string `json:"bridgeAmount"`         // uint256 as decimal string
	RawPayload          string `json:"rawPayload,omitempty"` // hex-encoded raw payload bytes from source chain
	VerificationData    string `json:"verificationData"`
	RevertFundRecipient string `json:"revertFundRecipient,omitempty"`
	TxType              uint   `json:"txType"`  // enum backing uint as decimal string
	FromCEA             bool   `json:"fromCEA"` // true if inbound is initiated by a CEA
}

InboundObservation is the inbound observation payload stored for INBOUND events

type InboundObservationEventProcessor added in v0.0.45

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

InboundObservationEventProcessor handles INBOUND events: it builds the inbound observation from the stored event and votes it on Push chain.

func NewInboundObservationEventProcessor added in v0.0.45

func NewInboundObservationEventProcessor(
	signer VoteSigner,
	database *db.DB,
	logger zerolog.Logger,
) *InboundObservationEventProcessor

NewInboundObservationEventProcessor creates the handler for INBOUND events.

func (*InboundObservationEventProcessor) HandleEvent added in v0.0.45

func (p *InboundObservationEventProcessor) HandleEvent(ctx context.Context, event *store.Event) error

HandleEvent implements EventHandler for INBOUND events.

type OutboundObservation added in v0.0.45

type OutboundObservation struct {
	TxID          string `json:"tx_id"`                  // bytes32 hex-encoded (0x...)
	UniversalTxID string `json:"universal_tx_id"`        // bytes32 hex-encoded (0x...)
	GasFeeUsed    string `json:"gas_fee_used,omitempty"` // gas fee used in wei (decimal string)
	// PC20 export only: wrapper token address deployed/minted on the destination
	// at settlement (observed in the finalize event). Core uses it to flip the
	// PC20 deploy flag; empty for non-PC20 settlements.
	Pc20WrapperAddress string `json:"pc20_wrapper_address,omitempty"`
}

OutboundObservation is the outbound observation payload stored for OUTBOUND events Event structure: - txID at 1st indexed position (bytes32) - universalTxID at 2nd indexed position (bytes32)

type OutboundObservationEventProcessor added in v0.0.45

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

OutboundObservationEventProcessor handles OUTBOUND events: it builds the outbound observation from the stored event and votes it on Push chain.

func NewOutboundObservationEventProcessor added in v0.0.45

func NewOutboundObservationEventProcessor(
	signer VoteSigner,
	database *db.DB,
	logger zerolog.Logger,
) *OutboundObservationEventProcessor

NewOutboundObservationEventProcessor creates the handler for OUTBOUND events.

func (*OutboundObservationEventProcessor) HandleEvent added in v0.0.45

func (p *OutboundObservationEventProcessor) HandleEvent(ctx context.Context, event *store.Event) error

HandleEvent implements EventHandler for OUTBOUND events.

type ReadRequestHandler added in v0.0.45

type ReadRequestHandler interface {
	ExecuteRead(ctx context.Context, req *ucallbacktypes.ReadRequest) (*ucallbacktypes.ReadResult, error)
}

ReadRequestHandler executes a read request on one destination chain. Consumed by the push watcher's read processor.

type TxBuilder

type TxBuilder interface {
	// GetOutboundSigningRequest creates a signing request from outbound event data
	GetOutboundSigningRequest(ctx context.Context, data *uetypes.OutboundCreatedEvent, nonce uint64) (*UnsignedSigningReq, error)

	// GetNextNonce returns the next nonce for the given signer on this chain (for seeding local nonce).
	// useFinalized: for EVM, if true use finalized block nonce (aggressive/replace stuck); if false use pending. SVM ignores this.
	GetNextNonce(ctx context.Context, signerAddress string, useFinalized bool) (uint64, error)

	// BroadcastOutboundSigningRequest assembles and broadcasts a signed transaction from the signing request, event data, and signature
	BroadcastOutboundSigningRequest(ctx context.Context, req *UnsignedSigningReq, data *uetypes.OutboundCreatedEvent, signature []byte) (string, error)

	// VerifyBroadcastedTx checks the status of a broadcasted transaction on the destination chain.
	// Returns (found, blockHeight, confirmations, status, error):
	// - found=false: tx not found or not yet mined
	// - found=true: tx exists on-chain
	//   - blockHeight: the block in which the tx was mined
	//   - confirmations: number of blocks since the tx was mined (0 = just mined)
	//   - status: 0 = failed/reverted, 1 = success
	VerifyBroadcastedTx(ctx context.Context, txHash string) (found bool, blockHeight uint64, confirmations uint64, status uint8, err error)

	// IsAlreadyExecuted checks whether a transaction with the given txID has already been
	// executed on the destination chain (e.g., by another relayer).
	// For SVM: checks if the ExecutedTx PDA exists on-chain, AND returns the
	//   unix timestamp of the latest finalized block. Callers use this as the
	//   cluster's "now" to gate deadline-based give-up/REVERT decisions and to
	//   detect cluster halt or finalization stall (queryBlockTime far behind
	//   wall-clock). 0 means freshness couldn't be determined.
	// For EVM: returns (false, 0, nil). EVM uses nonce-based replay protection.
	IsAlreadyExecuted(ctx context.Context, txID string) (executed bool, queryBlockTime int64, err error)

	// GetGasFeeUsed returns the gas fee used by a transaction on the destination chain.
	// EVM: fetches receipt and returns gasUsed * effectiveGasPrice as decimal string.
	// SVM: returns "0" (gas accounting is handled via vault gasFee reimbursement).
	// Returns "0" if the transaction is not found.
	GetGasFeeUsed(ctx context.Context, txHash string) (string, error)

	// GetFundMigrationSigningRequest builds a native token transfer for fund migration,
	// transferring the maximum possible balance (balance minus gas cost).
	GetFundMigrationSigningRequest(ctx context.Context, data *FundMigrationData, nonce uint64) (*UnsignedSigningReq, error)

	// BroadcastFundMigrationTx assembles and broadcasts a signed fund migration transaction.
	BroadcastFundMigrationTx(ctx context.Context, req *UnsignedSigningReq, data *FundMigrationData, signature []byte) (string, error)
}

TxBuilder builds and broadcasts transactions for outbound transfers

type UnsignedSigningReq

type UnsignedSigningReq struct {
	SigningHash []byte // Hash to be signed by TSS
	Nonce       uint64 // evm - TSS Address nonce | svm - PDA nonce

	// TSSFundMigrationAmount is the native value swept for a fund-migration tx, fixed at
	// signing time. Nil for outbound. Must be reused verbatim at broadcast — re-querying
	// balance there races with a successful sweep from another validator.
	TSSFundMigrationAmount *big.Int `json:"TSSFundMigrationAmount,omitempty"`
}

UnsignedSigningReq contains the request for signing an outbound or fund-migration transaction.

type VoteSigner added in v0.0.45

type VoteSigner interface {
	VoteInbound(ctx context.Context, inbound *uexecutortypes.Inbound) (string, error)
	VoteOutbound(ctx context.Context, txID string, utxID string, observation *uexecutortypes.OutboundObservation) (string, error)
}

VoteSigner is the subset of pushsigner.Signer used by the event processors. Defined here (consumer-side) so tests can provide mock implementations.

Jump to

Keyboard shortcuts

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