{"modulePath":"github.com/0xsequence/ethkit","version":"v1.47.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package ethmonitor\n\n## Variables\n\n```go\nvar (\n\tErrFatal                 = errors.New(\"ethmonitor: fatal error, stopping\")\n\tErrReorg                 = errors.New(\"ethmonitor: block reorg\")\n\tErrUnexpectedParentHash  = errors.New(\"ethmonitor: unexpected parent hash\")\n\tErrUnexpectedBlockNumber = errors.New(\"ethmonitor: unexpected block number\")\n\tErrQueueFull             = errors.New(\"ethmonitor: publish queue is full\")\n\tErrMaxAttempts           = errors.New(\"ethmonitor: max attempts hit\")\n\tErrMonitorStopped        = errors.New(\"ethmonitor: stopped\")\n)\n```\n\n```go\nvar DefaultOptions = Options{\n\tLogger:                           slog.New(slog.NewTextHandler(io.Discard, nil)),\n\tPollingInterval:                  1500 * time.Millisecond,\n\tStreamingErrorResetInterval:      2 * time.Minute,\n\tStreamingRetryAfter:              5 * time.Minute,\n\tStreamingErrNumToSwitchToPolling: 3,\n\tStreamHealthCheckInterval:        10 * time.Second,\n\tStreamHealthCheckStaleness:       60 * time.Second,\n\tStreamingDisabled:                false,\n\tUnsubscribeOnStop:                false,\n\tTimeout:                          20 * time.Second,\n\tStartBlockNumber:                 nil,\n\tTrailNumBlocksBehindHead:         0,\n\tBlockRetentionLimit:              200,\n\tWithLogs:                         false,\n\tLogTopics:                        []common.Hash{},\n\tDebugLogging:                     false,\n\tCacheExpiry:                      600 * time.Second,\n\tPrefetchConcurrency:              0,\n\tPrefetchWindow:                   0,\n\tAlerter:                          util.NoopAlerter(),\n\tMaxLogsAttempts:                  10,\n\tStrictLogs:                       false,\n}\n```\n\n## Functions\n\n```go\nfunc CacheKeyBlockByHash(chainID *big.Int, hash common.Hash) string\n```\n\n```go\nfunc CacheKeyBlockByNumber(chainID *big.Int, num *big.Int) string\n```\n\n```go\nfunc CacheKeyBlockLogs(chainID *big.Int, blockHash common.Hash, topics [][]common.Hash) string\n```\n\n```go\nfunc IsBlockEq(a, b *types.Block) bool\n```\n\n## Types\n\n```go\ntype Block struct {\n\t*types.Block\n\n\t// Event type where Block is Added or Removed (ie. reorged)\n\tEvent Event\n\n\t// Logs in the block, grouped by transactions:\n\t// [[txnA logs, ..], [txnB logs, ..], ..]\n\t// Logs [][]types.Log `json:\"logs\"`\n\tLogs []types.Log\n\n\t// OK flag which represents the block is ready for broadcasting\n\tOK bool\n\n\t// LogsUnconfirmed is set when the block was published without confirmed\n\t// logs: eth_getLogs and receipts both failed for its whole stay in the\n\t// chain cache. Logs is empty, but the block may have had logs. Never set\n\t// when StrictLogs is enabled.\n\tLogsUnconfirmed bool\n\t// contains filtered or unexported fields\n}\n```\nBlock contains a monitored block and its event data. Construct values with keyed composite literals: private canonical state makes positional literals unsupported.\n\n```go\nfunc (b *Block) CanonicalState() (incarnation uint64, canonical bool)\n```\nCanonicalState reports the monitor-assigned incarnation and whether it has remained canonical without a known removal. Zero means the block is untracked. Retention eviction preserves this state; in-memory copies share removal updates. Incarnations are local to a monitor chain. Serialized blocks are untracked until accepted by a monitor.\n\n```go\nfunc (b *Block) MarshalJSON() ([]byte, error)\n```\n\n```go\nfunc (b *Block) UnmarshalJSON(data []byte) error\n```\n\n```go\ntype Blocks []*Block\n```\n\n```go\nfunc (blocks Blocks) Copy() Blocks\n```\n\n```go\nfunc (blocks Blocks) EventExists(block *types.Block, event Event) bool\n```\n\n```go\nfunc (b Blocks) FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (*ethereum.FeeHistory, error)\n```\nFeeHistory approximates the behaviour of eth\\_feeHistory. It intentionally deviates from standard to avoid fetching transaction receipts. It uses transaction gas limits instead of actual gas used, and transaction priority fees instead of effective priority fees.\n\n```go\nfunc (blocks Blocks) FindBlock(blockHash common.Hash, optEvent ...Event) (*Block, bool)\n```\n\n```go\nfunc (b Blocks) Head() *Block\n```\n\n```go\nfunc (b Blocks) IsOK() bool\n```\n\n```go\nfunc (b Blocks) LatestBlock() *Block\n```\n\n```go\nfunc (b Blocks) Reorg() bool\n```\n\n```go\nfunc (b Blocks) Tail() *Block\n```\n\n```go\ntype Chain struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc (c *Chain) Blocks() Blocks\n```\n\n```go\nfunc (c *Chain) BootstrapFromBlocks(blocks []*Block) error\n```\nBootstrapFromBlocks will bootstrap the ethmonitor canonical chain from input blocks, while also verifying the chain hashes link together.\n\n```go\nfunc (c *Chain) BootstrapFromBlocksJSON(data []byte) error\n```\nBootstrapFromBlocksJSON is convenience method which accepts json and bootstraps the ethmonitor chain. This method is here mostly for debugging purposes and recommend that you use BootstrapFromBlocks and handle constructing block events outside of ethmonitor.\n\n```go\nfunc (c *Chain) GetAverageBlockTime() float64\n```\n\n```go\nfunc (c *Chain) GetBlock(hash common.Hash) *Block\n```\n\n```go\nfunc (c *Chain) GetBlockByNumber(blockNum uint64, event Event) *Block\n```\n\n```go\nfunc (c *Chain) GetTransaction(txnHash common.Hash) (*types.Transaction, Event)\n```\nGetTransaction searches our canonical chain of blocks (where each block points at previous), and returns the transaction. Aka, searches our chain for mined transactions. Keep in mind transactions can still be reorged, but you can check the blockNumber and compare it against the head to determine if its final.\n\n```go\nfunc (c *Chain) Head() *Block\n```\n\n```go\nfunc (c *Chain) PrintAllBlocks()\n```\n\n```go\nfunc (c *Chain) ReadyHead() *Block\n```\n\n```go\nfunc (c *Chain) Snapshot() ([]byte, error)\n```\n\n```go\nfunc (c *Chain) Tail() *Block\n```\n\n```go\ntype Event uint32\n```\n\n```go\nconst (\n\tAdded Event = iota\n\tRemoved\n)\n```\n\n```go\ntype Monitor struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewMonitor(provider ethrpc.RawInterface, options ...Options) (*Monitor, error)\n```\n\n```go\nfunc (m *Monitor) Chain() *Chain\n```\n\n```go\nfunc (m *Monitor) FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (*ethereum.FeeHistory, error)\n```\nFeeHistory approximates the behaviour of eth\\_feeHistory. It intentionally deviates from standard to avoid fetching transaction receipts. It uses transaction gas limits instead of actual gas used, and transaction priority fees instead of effective priority fees.\n\n```go\nfunc (m *Monitor) GetAverageBlockTime() float64\n```\nGetAverageBlockTime returns the average block time in seconds (including fractions)\n\n```go\nfunc (m *Monitor) GetBlock(blockHash common.Hash) *Block\n```\nGetBlock will search the retained blocks for the hash\n\n```go\nfunc (m *Monitor) GetTransaction(txnHash common.Hash) (*types.Transaction, Event)\n```\nGetTransaction will search within the retained canonical chain for the given transaction hash and will only return transactions which have not been removed from the chain via a reorg.\n\n```go\nfunc (m *Monitor) IsRunning() bool\n```\n\n```go\nfunc (m *Monitor) IsStreamingEnabled() bool\n```\n\n```go\nfunc (m *Monitor) IsStreamingMode() bool\n```\n\n```go\nfunc (m *Monitor) LatestBlock() *Block\n```\nLatestBlock will return the head block of the canonical chain\n\n```go\nfunc (m *Monitor) LatestBlockNum() *big.Int\n```\nLatestBlockNum returns the latest block number in the canonical chain\n\n```go\nfunc (m *Monitor) LatestFinalBlock(numBlocksToFinality int) *Block\n```\nLatestFinalBlock returns the latest block which has reached finality. The argument \\`numBlocksToFinality\\` should be a constant value of the number of blocks a particular chain needs to reach finality. Ie. on Polygon this value would be 120 and on Ethereum it would be 20. As the pubsub system publishes new blocks, this value will change, as the chain will progress forward. It's recommend / safe to call this method each time in a \\\u003c-sub.Blocks() code block.\n\n```go\nfunc (m *Monitor) LatestReadyBlock() *Block\n```\nLatestReadyBlock returns the latest block in the canonical chain which has block.OK state to true, as in all details are available for the block.\n\n```go\nfunc (m *Monitor) LatestReadyBlockNum() *big.Int\n```\nLatestReadyBlockNum returns the latest block number in the canonical chain which has block.OK state to true, as in all details are available for the block.\n\n```go\nfunc (m *Monitor) NumSubscribers() int\n```\n\n```go\nfunc (m *Monitor) OldestBlockNum() *big.Int\n```\n\n```go\nfunc (m *Monitor) Options() Options\n```\n\n```go\nfunc (m *Monitor) Provider() ethrpc.Interface\n```\n\n```go\nfunc (m *Monitor) PurgeHistory()\n```\nPurgeHistory clears all but the head of the chain. Useful for tests, but should almost never be used in a normal application.\n\n```go\nfunc (m *Monitor) Run(ctx context.Context) error\n```\n\n```go\nfunc (m *Monitor) Stop()\n```\n\n```go\nfunc (m *Monitor) Subscribe(optLabel ...string) Subscription\n```\n\n```go\nfunc (m *Monitor) UnsubscribeAll(err error)\n```\n\n```go\ntype Options struct {\n\t// Logger used by ethmonitor to log warnings and debug info\n\tLogger *slog.Logger\n\n\t// (optional) ChainID is the chainID to use for the monitor. We\n\t// also confirm it with the provider, but in case you're using a monitor\n\t// with a faulty node, this can be used to manually set the chainID.\n\tChainID *big.Int\n\n\t// PollingInterval to query the chain for new blocks\n\tPollingInterval time.Duration\n\n\t// StreamingErrorResetInterval is the time to reset the streaming error count\n\tStreamingErrorResetInterval time.Duration\n\n\t// StreamingRetryAfter is the time to wait before retrying the streaming again\n\tStreamingRetryAfter time.Duration\n\n\t// StreamingErrNumToSwitchToPolling is the number of errors before switching to polling\n\tStreamingErrNumToSwitchToPolling int\n\n\t// StreamHealthCheckInterval is how often the streaming listener verifies\n\t// the last received head is still fresh. 0 disables the check.\n\tStreamHealthCheckInterval time.Duration\n\n\t// StreamHealthCheckStaleness is the max age of the head last received\n\t// from the stream. When the head exceeds it, the node's head is fetched\n\t// over http and the subscription is dropped only if the node is ahead\n\t// of the stream, so idle chains stay streaming. Set it well above the\n\t// chain's block time.\n\tStreamHealthCheckStaleness time.Duration\n\n\t// StreamingDisabled flag to force disable streaming even if the provider supports it\n\tStreamingDisabled bool\n\n\t// Auto-unsubscribe on monitor stop or error\n\tUnsubscribeOnStop bool\n\n\t// Timeout duration used by the rpc client when fetching data from the remote node.\n\tTimeout time.Duration\n\n\t// StartBlockNumber to begin the monitor from.\n\tStartBlockNumber *big.Int\n\n\t// Bootstrap flag which indicates the monitor will expect the monitor's\n\t// events to be bootstrapped, and will continue from that point. This also\n\t// takes precedence over StartBlockNumber when set to true.\n\tBootstrap bool\n\n\t// TrailNumBlocksBehindHead is the number of blocks we trail behind\n\t// the head of the chain before broadcasting new events to the subscribers.\n\tTrailNumBlocksBehindHead int\n\n\t// BlockRetentionLimit is the number of blocks we keep on the canonical chain\n\t// cache.\n\tBlockRetentionLimit int\n\n\t// WithLogs will include logs with the blocks if specified true.\n\tWithLogs bool\n\n\t// LogTopics selects values for the first topic of each log. Empty filtered\n\t// results are accepted because a nonzero bloom does not prove a match.\n\tLogTopics []common.Hash\n\n\t// CacheBackend to use for caching block data\n\t// NOTE: do not use this unless you know what you're doing.\n\t// In most cases leave this nil.\n\tCacheBackend cachestore.Backend\n\n\t// CacheExpiry is how long to keep each record in cache\n\tCacheExpiry time.Duration\n\n\t// PrefetchConcurrency is the number of workers fetching blocks (and their\n\t// logs, when WithLogs is set) ahead of the monitor while it trails the chain\n\t// head. Prefetched payloads land in the cache, so the monitor's serial loop\n\t// reads them as cache hits instead of paying node round-trips per block.\n\t// Useful on chains whose block rate outpaces a serial fetch. If no\n\t// CacheBackend is set, an in-memory cache is used. 0 disables prefetching.\n\t// A prefetched block may be reorged out before it is read, producing an\n\t// Added then Removed event; subscribers must already handle such reorgs.\n\tPrefetchConcurrency int\n\n\t// PrefetchWindow is how many blocks past the monitor's next block the\n\t// prefetcher may fetch. Defaults to 4x PrefetchConcurrency.\n\tPrefetchWindow int\n\n\t// Alerter config via github.com/goware/alerter\n\tAlerter util.Alerter\n\n\t// MaxLogsAttempts is the number of failed eth_getLogs attempts for a block,\n\t// after which its logs are taken from its receipts. Defaults to 10.\n\tMaxLogsAttempts int\n\n\t// StrictLogs, when true, never publishes a block whose logs can't be\n\t// confirmed by eth_getLogs or its receipts. The monitor keeps retrying and\n\t// returns ErrFatal(ErrQueueFull) if the publish queue overflows, which was\n\t// the behaviour before this option existed. When false (the default), such\n\t// a block is published with empty logs once it leaves the chain cache\n\t// (BlockRetentionLimit), with an Error log and an alert.\n\tStrictLogs bool\n\n\t// DebugLogging toggle\n\tDebugLogging bool\n}\n```\n\n```go\ntype Subscription interface {\n\tBlocks() \u003c-chan Blocks\n\tDone() \u003c-chan struct{}\n\tErr() error\n\tUnsubscribe()\n}\n```\n\n","path":"github.com/0xsequence/ethkit/ethmonitor","name":"ethmonitor","synopsis":"","isRedistributable":true}
