// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"net/http"
"github.com/celenium-io/celestia-indexer/cmd/api/handler"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
var accessDeniedErr = echo.Map{
"error": "access denied",
}
func AdminMiddleware() echo.MiddlewareFunc {
return checkOnAdminPermission
}
func checkOnAdminPermission(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
val := ctx.Get(handler.ApiKeyName)
apiKey, ok := val.(storage.ApiKey)
if !ok {
return ctx.JSON(http.StatusForbidden, accessDeniedErr)
}
if !apiKey.Admin {
return ctx.JSON(http.StatusForbidden, accessDeniedErr)
}
return next(ctx)
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package bus
import (
"context"
"sync"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/workerpool"
jsoniter "github.com/json-iterator/go"
"github.com/lib/pq"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
type Dispatcher struct {
listener storage.Listener
validators storage.IValidator
mx *sync.RWMutex
observers []*Observer
g workerpool.Group
}
func NewDispatcher(
factory storage.ListenerFactory,
validators storage.IValidator,
) (*Dispatcher, error) {
if factory == nil {
return nil, errors.New("nil listener factory")
}
listener := factory.CreateListener()
return &Dispatcher{
listener: listener,
validators: validators,
observers: make([]*Observer, 0),
mx: new(sync.RWMutex),
g: workerpool.NewGroup(),
}, nil
}
func (d *Dispatcher) Observe(channels ...string) *Observer {
if observer := NewObserver(channels...); observer != nil {
d.mx.Lock()
d.observers = append(d.observers, observer)
d.mx.Unlock()
return observer
}
return nil
}
func (d *Dispatcher) Start(ctx context.Context) {
if err := d.listener.Subscribe(ctx, storage.ChannelHead, storage.ChannelBlock); err != nil {
log.Err(err).Msg("subscribe on postgres notifications")
return
}
d.g.GoCtx(ctx, d.listen)
}
func (d *Dispatcher) Close() error {
d.g.Wait()
d.mx.Lock()
for i := range d.observers {
if err := d.observers[i].Close(); err != nil {
return err
}
}
d.mx.Unlock()
return nil
}
func (d *Dispatcher) listen(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case notification, ok := <-d.listener.Listen():
if !ok {
return
}
if notification == nil {
log.Warn().Msg("nil notification")
continue
}
if err := d.handleNotification(ctx, notification); err != nil {
log.Err(err).Str("channel", notification.Channel).Msg("handle notification")
}
}
}
}
func (d *Dispatcher) handleNotification(ctx context.Context, notification *pq.Notification) error {
switch notification.Channel {
case storage.ChannelHead:
return d.handleState(ctx, notification.Extra)
case storage.ChannelBlock:
return d.handleBlock(ctx, notification.Extra)
default:
return errors.Errorf("unknown channel name: %s", notification.Channel)
}
}
func (d *Dispatcher) handleBlock(ctx context.Context, payload string) error {
block := new(storage.Block)
if err := jsoniter.UnmarshalFromString(payload, block); err != nil {
return err
}
if block.ProposerId > 0 {
validator, err := d.validators.GetByID(ctx, block.ProposerId)
if err != nil {
return err
}
block.Proposer = *validator
}
d.mx.RLock()
for i := range d.observers {
d.observers[i].notifyBlocks(block)
}
d.mx.RUnlock()
return nil
}
func (d *Dispatcher) handleState(ctx context.Context, payload string) error {
var state storage.State
if err := jsoniter.UnmarshalFromString(payload, &state); err != nil {
return err
}
power, err := d.validators.TotalVotingPower(ctx)
if err != nil {
return err
}
state.TotalVotingPower = power
d.mx.RLock()
for i := range d.observers {
d.observers[i].notifyState(&state)
}
d.mx.RUnlock()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package bus
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/workerpool"
)
type Observer struct {
blocks chan *storage.Block
state chan *storage.State
listenBlocks bool
listenHead bool
g workerpool.Group
}
func NewObserver(channels ...string) *Observer {
if len(channels) == 0 {
return nil
}
observer := &Observer{
blocks: make(chan *storage.Block, 1024),
state: make(chan *storage.State, 1024),
g: workerpool.NewGroup(),
}
for i := range channels {
switch channels[i] {
case storage.ChannelBlock:
observer.listenBlocks = true
case storage.ChannelHead:
observer.listenHead = true
}
}
return observer
}
func (observer Observer) Close() error {
observer.g.Wait()
close(observer.blocks)
close(observer.state)
return nil
}
func (observer Observer) notifyBlocks(block *storage.Block) {
if observer.listenBlocks {
observer.blocks <- block
}
}
func (observer Observer) notifyState(state *storage.State) {
if observer.listenHead {
observer.state <- state
}
}
func (observer Observer) Blocks() <-chan *storage.Block {
return observer.blocks
}
func (observer Observer) Head() <-chan *storage.State {
return observer.state
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package cache
import (
"context"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
)
type CacheMiddleware struct {
cache ICache
skipper middleware.Skipper
expirationFunc ExpirationFunc
}
func Middleware(cache ICache, skipper middleware.Skipper, expirationFunc ExpirationFunc) echo.MiddlewareFunc {
mdlwr := CacheMiddleware{
cache: cache,
skipper: skipper,
expirationFunc: expirationFunc,
}
return mdlwr.Handler
}
func (m *CacheMiddleware) Handler(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if m.cache == nil {
return next(c)
}
if m.skipper != nil {
if m.skipper(c) {
return next(c)
}
}
path := c.Request().URL.String()
key := strings.ReplaceAll(strings.TrimPrefix(path, "/"), "/", ":")
if data, ok := m.cache.Get(c.Request().Context(), key); ok {
entry := new(CacheEntry)
if err := entry.Decode(data); err != nil {
return err
}
return entry.Replay(c.Response())
}
recorder := NewResponseRecorder(c.Response().Writer)
c.Response().Writer = recorder
if err := next(c); err != nil {
return err
}
return m.cacheResult(c.Request().Context(), key, recorder)
}
}
func (m *CacheMiddleware) cacheResult(ctx context.Context, key string, r *ResponseRecorder) error {
result := r.Result()
if !m.isStatusCacheable(result) {
return nil
}
data, err := result.Encode()
if err != nil {
return errors.Wrap(err, "unable to read recorded response")
}
return m.cache.Set(ctx, key, data, m.expirationFunc)
}
func (m *CacheMiddleware) isStatusCacheable(e *CacheEntry) bool {
return e.StatusCode == http.StatusOK || e.StatusCode == http.StatusNoContent
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package cache
import (
"bytes"
"encoding/gob"
"net/http"
"strings"
)
type ResponseRecorder struct {
http.ResponseWriter
status int
body bytes.Buffer
headers http.Header
headerCopied bool
}
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
return &ResponseRecorder{
ResponseWriter: w,
headers: make(http.Header),
}
}
func (w *ResponseRecorder) Write(b []byte) (int, error) {
w.copyHeaders()
i, err := w.ResponseWriter.Write(b)
if err != nil {
return i, err
}
return w.body.Write(b[:i])
}
func (r *ResponseRecorder) copyHeaders() {
if r.headerCopied {
return
}
r.headerCopied = true
copyHeaders(r.ResponseWriter.Header(), r.headers)
}
func (w *ResponseRecorder) WriteHeader(statusCode int) {
w.copyHeaders()
w.status = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
func (r *ResponseRecorder) Result() *CacheEntry {
r.copyHeaders()
return &CacheEntry{
Header: r.headers,
StatusCode: r.status,
Body: r.body.Bytes(),
}
}
func copyHeaders(src, dst http.Header) {
for k, v := range src {
for _, val := range v {
dst.Set(k, val)
}
}
}
type CacheEntry struct {
Header http.Header
StatusCode int
Body []byte
}
func (c *CacheEntry) Encode() (string, error) {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(c); err != nil {
return "", err
}
return buf.String(), nil
}
func (c *CacheEntry) Decode(b string) error {
dec := gob.NewDecoder(strings.NewReader(b))
return dec.Decode(c)
}
func (c *CacheEntry) Replay(w http.ResponseWriter) error {
copyHeaders(c.Header, w.Header())
if c.StatusCode != 0 {
w.WriteHeader(c.StatusCode)
}
if len(c.Body) == 0 {
return nil
}
_, err := w.Write(c.Body)
return err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package cache
import (
"context"
"time"
"github.com/pkg/errors"
valkey "github.com/valkey-io/valkey-go"
)
var _ ICache = (*ValKey)(nil)
type ValKey struct {
client valkey.Client
ttlSeconds int64
}
func NewValKey(url string, ttl time.Duration) (*ValKey, error) {
opts, err := valkey.ParseURL(url)
if err != nil {
return nil, errors.Wrap(err, "parse valkey url")
}
client, err := valkey.NewClient(opts)
if err != nil {
return nil, errors.Wrap(err, "create valkey client")
}
return &ValKey{
client: client,
ttlSeconds: int64(ttl.Seconds()),
}, nil
}
func (c *ValKey) Get(ctx context.Context, key string) (data string, found bool) {
val, err := c.client.Do(
ctx, c.client.B().Get().Key(key).Build(),
).ToString()
return val, err == nil
}
func (c *ValKey) Set(ctx context.Context, key string, data string, expirationFunc ExpirationFunc) error {
expiredAt := c.ttlSeconds
if expirationFunc != nil {
expiredAt = int64(expirationFunc().Seconds())
}
return c.client.Do(
ctx,
c.client.B().Set().Key(key).Value(data).ExSeconds(expiredAt).Build(),
).Error()
}
func (c *ValKey) Close() error {
c.client.Close()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package gas
import (
"sync"
"github.com/shopspring/decimal"
)
type GasPrice struct {
Slow string
Median string
Fast string
}
type info struct {
Height uint64
Percentiles []decimal.Decimal
TxCount int64
GasUsed int64
GasWanted int64
Fee decimal.Decimal
GasUsedRatio decimal.Decimal
BlockOccupancy float64
}
type queue struct {
data []info
capacity int
mx *sync.RWMutex
}
func newQueue(capacity int) *queue {
return &queue{
data: make([]info, 0),
capacity: capacity,
mx: new(sync.RWMutex),
}
}
func (q *queue) Push(item info) {
q.mx.Lock()
if len(q.data) == q.capacity {
q.data = q.data[:len(q.data)-2]
}
q.data = append([]info{item}, q.data...)
q.mx.Unlock()
}
func (q *queue) Range(handler func(item info) (bool, error)) error {
if handler == nil {
return nil
}
q.mx.RLock()
defer q.mx.RUnlock()
for i := range q.data {
br, err := handler(q.data[i])
if err != nil {
return err
}
if br {
return nil
}
}
return nil
}
func (q *queue) Size() int {
q.mx.RLock()
defer q.mx.RUnlock()
return len(q.data)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: interface.go
//
// Generated by this command:
//
// mockgen -source=interface.go -destination=mock -package=gas -typed
//
// Package gas is a generated GoMock package.
package gas
import (
context "context"
reflect "reflect"
gomock "go.uber.org/mock/gomock"
)
// MockITracker is a mock of ITracker interface.
type MockITracker struct {
ctrl *gomock.Controller
recorder *MockITrackerMockRecorder
}
// MockITrackerMockRecorder is the mock recorder for MockITracker.
type MockITrackerMockRecorder struct {
mock *MockITracker
}
// NewMockITracker creates a new mock instance.
func NewMockITracker(ctrl *gomock.Controller) *MockITracker {
mock := &MockITracker{ctrl: ctrl}
mock.recorder = &MockITrackerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockITracker) EXPECT() *MockITrackerMockRecorder {
return m.recorder
}
// Close mocks base method.
func (m *MockITracker) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *MockITrackerMockRecorder) Close() *MockITrackerCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockITracker)(nil).Close))
return &MockITrackerCloseCall{Call: call}
}
// MockITrackerCloseCall wrap *gomock.Call
type MockITrackerCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITrackerCloseCall) Return(arg0 error) *MockITrackerCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITrackerCloseCall) Do(f func() error) *MockITrackerCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITrackerCloseCall) DoAndReturn(f func() error) *MockITrackerCloseCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Init mocks base method.
func (m *MockITracker) Init(ctx context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Init", ctx)
ret0, _ := ret[0].(error)
return ret0
}
// Init indicates an expected call of Init.
func (mr *MockITrackerMockRecorder) Init(ctx any) *MockITrackerInitCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Init", reflect.TypeOf((*MockITracker)(nil).Init), ctx)
return &MockITrackerInitCall{Call: call}
}
// MockITrackerInitCall wrap *gomock.Call
type MockITrackerInitCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITrackerInitCall) Return(arg0 error) *MockITrackerInitCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITrackerInitCall) Do(f func(context.Context) error) *MockITrackerInitCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITrackerInitCall) DoAndReturn(f func(context.Context) error) *MockITrackerInitCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Start mocks base method.
func (m *MockITracker) Start(ctx context.Context) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Start", ctx)
}
// Start indicates an expected call of Start.
func (mr *MockITrackerMockRecorder) Start(ctx any) *MockITrackerStartCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockITracker)(nil).Start), ctx)
return &MockITrackerStartCall{Call: call}
}
// MockITrackerStartCall wrap *gomock.Call
type MockITrackerStartCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITrackerStartCall) Return() *MockITrackerStartCall {
c.Call = c.Call.Return()
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITrackerStartCall) Do(f func(context.Context)) *MockITrackerStartCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITrackerStartCall) DoAndReturn(f func(context.Context)) *MockITrackerStartCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// State mocks base method.
func (m *MockITracker) State() GasPrice {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "State")
ret0, _ := ret[0].(GasPrice)
return ret0
}
// State indicates an expected call of State.
func (mr *MockITrackerMockRecorder) State() *MockITrackerStateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "State", reflect.TypeOf((*MockITracker)(nil).State))
return &MockITrackerStateCall{Call: call}
}
// MockITrackerStateCall wrap *gomock.Call
type MockITrackerStateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITrackerStateCall) Return(arg0 GasPrice) *MockITrackerStateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITrackerStateCall) Do(f func() GasPrice) *MockITrackerStateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITrackerStateCall) DoAndReturn(f func() GasPrice) *MockITrackerStateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SubscribeOnCompute mocks base method.
func (m *MockITracker) SubscribeOnCompute(handler ComputeHandler) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SubscribeOnCompute", handler)
}
// SubscribeOnCompute indicates an expected call of SubscribeOnCompute.
func (mr *MockITrackerMockRecorder) SubscribeOnCompute(handler any) *MockITrackerSubscribeOnComputeCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeOnCompute", reflect.TypeOf((*MockITracker)(nil).SubscribeOnCompute), handler)
return &MockITrackerSubscribeOnComputeCall{Call: call}
}
// MockITrackerSubscribeOnComputeCall wrap *gomock.Call
type MockITrackerSubscribeOnComputeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITrackerSubscribeOnComputeCall) Return() *MockITrackerSubscribeOnComputeCall {
c.Call = c.Call.Return()
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITrackerSubscribeOnComputeCall) Do(f func(ComputeHandler)) *MockITrackerSubscribeOnComputeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITrackerSubscribeOnComputeCall) DoAndReturn(f func(ComputeHandler)) *MockITrackerSubscribeOnComputeCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package gas
import (
"context"
"sort"
"sync"
"github.com/celenium-io/celestia-indexer/cmd/api/bus"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celestiaorg/celestia-app/v3/pkg/appconsts"
"github.com/dipdup-io/workerpool"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/shopspring/decimal"
coreTypes "github.com/tendermint/tendermint/types"
)
const (
blockCount = 100
emptyBlockPercent = .90
)
var (
percentiles = []float64{.10, .50, .99}
maxBlockSize = coreTypes.MaxDataBytesNoEvidence(1974272, 100)
)
type ComputeHandler func(ctx context.Context, gasState GasPrice) error
type Tracker struct {
state storage.IState
stats storage.IBlockStats
tx storage.ITx
observer *bus.Observer
log zerolog.Logger
mx *sync.RWMutex
gasState GasPrice
q *queue
g workerpool.Group
computeHandler ComputeHandler
}
func NewTracker(
state storage.IState,
stats storage.IBlockStats,
tx storage.ITx,
observer *bus.Observer,
) *Tracker {
return &Tracker{
state: state,
stats: stats,
tx: tx,
observer: observer,
mx: new(sync.RWMutex),
gasState: GasPrice{
Slow: "0",
Median: "0",
Fast: "0",
},
log: log.With().Str("module", "gas_tracker").Logger(),
q: newQueue(blockCount),
g: workerpool.NewGroup(),
}
}
func (tracker *Tracker) SubscribeOnCompute(handler ComputeHandler) {
tracker.computeHandler = handler
}
func (tracker *Tracker) Start(ctx context.Context) {
tracker.g.GoCtx(ctx, tracker.listen)
}
func (tracker *Tracker) Close() error {
tracker.g.Wait()
return nil
}
func (tracker *Tracker) listen(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case block, ok := <-tracker.observer.Blocks():
if !ok {
return
}
if err := tracker.processBlock(ctx, block.Stats); err != nil {
log.Err(err).Msg("new block processing")
continue
}
if err := tracker.computeMetrics(); err != nil {
log.Err(err).Msg("compute metrics")
}
if tracker.computeHandler != nil {
tracker.g.GoCtx(ctx, func(ctx context.Context) {
if err := tracker.computeHandler(ctx, tracker.gasState); err != nil {
log.Err(err).Msg("error in compute handler of gas tracker")
}
})
}
}
}
}
func (tracker *Tracker) Init(ctx context.Context) error {
state, err := tracker.state.List(ctx, 1, 0, sdk.SortOrderAsc)
if err != nil {
return err
}
if len(state) == 0 {
return nil
}
blockStats, err := tracker.stats.LastFrom(ctx, state[0].LastHeight, blockCount)
if err != nil {
return err
}
for i := len(blockStats) - 1; i >= 0; i-- {
if err := tracker.processBlock(ctx, blockStats[i]); err != nil {
return err
}
}
return tracker.computeMetrics()
}
func (tracker *Tracker) processBlock(ctx context.Context, blockStat storage.BlockStats) error {
data := info{
Height: uint64(blockStat.Height),
TxCount: blockStat.TxCount,
GasUsed: blockStat.GasUsed,
GasWanted: blockStat.GasLimit,
Fee: blockStat.Fee,
GasUsedRatio: decimal.New(0, 1),
Percentiles: make([]decimal.Decimal, 0),
BlockOccupancy: float64(blockStat.BytesInBlock) / float64(maxBlockSize),
}
for range percentiles {
data.Percentiles = append(data.Percentiles, decimal.New(0, 1))
}
if data.GasWanted > 0 {
data.GasUsedRatio = decimal.NewFromInt(data.GasUsed).Div(decimal.NewFromInt(data.GasWanted))
}
if blockStat.TxCount == 0 {
tracker.q.Push(data)
return nil
}
txs, err := tracker.tx.Gas(ctx, blockStat.Height, blockStat.Time)
if err != nil {
return err
}
sort.Sort(storage.ByGasPrice(txs))
tracker.compute(txs, blockStat.GasLimit, &data)
if data.BlockOccupancy < emptyBlockPercent {
// If block occupancy is less than empty block threshold set all percentiles to slow.
for i := 1; i < len(data.Percentiles); i++ {
data.Percentiles[i] = data.Percentiles[0].Copy()
}
}
tracker.q.Push(data)
return nil
}
func (tracker *Tracker) compute(txs []storage.Gas, gasLimit int64, data *info) {
if len(txs) == 0 {
return
}
var (
txIndex = 0
sumGas = txs[txIndex].GasWanted
)
for i, p := range percentiles {
threshold := int64(float64(gasLimit) * p)
for sumGas < threshold && txIndex < len(txs)-1 {
txIndex++
sumGas += txs[txIndex].GasWanted
}
data.Percentiles[i] = txs[txIndex].GasPrice.Copy()
}
}
func (tracker *Tracker) State() GasPrice {
tracker.mx.RLock()
defer tracker.mx.RUnlock()
return tracker.gasState
}
var minGasPrice = decimal.NewFromFloat(appconsts.DefaultMinGasPrice)
func (tracker *Tracker) computeMetrics() error {
slow := decimal.New(0, 1)
median := decimal.New(0, 1)
fast := decimal.New(0, 1)
err := tracker.q.Range(func(item info) (bool, error) {
if len(item.Percentiles) < 3 {
return false, nil
}
slow = slow.Add(item.Percentiles[0])
median = median.Add(item.Percentiles[1])
fast = fast.Add(item.Percentiles[2])
return false, nil
})
if err != nil {
return err
}
count := int64(tracker.q.Size())
slow = slow.Div(decimal.NewFromInt(count))
median = median.Div(decimal.NewFromInt(count))
fast = fast.Div(decimal.NewFromInt(count))
if slow.LessThan(minGasPrice) {
slow = minGasPrice.Copy()
}
if median.LessThan(minGasPrice) {
median = minGasPrice.Copy()
}
if fast.LessThan(minGasPrice) {
fast = minGasPrice.Copy()
}
tracker.mx.Lock()
{
tracker.gasState.Slow = currency.StringTia(slow)
tracker.gasState.Median = currency.StringTia(median)
tracker.gasState.Fast = currency.StringTia(fast)
}
tracker.mx.Unlock()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
testsuite "github.com/celenium-io/celestia-indexer/internal/test_suite"
"github.com/celenium-io/celestia-indexer/pkg/types"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type AddressHandler struct {
address storage.IAddress
txs storage.ITx
blobLogs storage.IBlobLog
messages storage.IMessage
delegations storage.IDelegation
undelegations storage.IUndelegation
redelegations storage.IRedelegation
vestings storage.IVestingAccount
grants storage.IGrant
celestial celestials.ICelestial
state storage.IState
indexerName string
}
func NewAddressHandler(
address storage.IAddress,
txs storage.ITx,
blobLogs storage.IBlobLog,
messages storage.IMessage,
delegations storage.IDelegation,
undelegations storage.IUndelegation,
redelegations storage.IRedelegation,
vestings storage.IVestingAccount,
grants storage.IGrant,
celestial celestials.ICelestial,
state storage.IState,
indexerName string,
) *AddressHandler {
return &AddressHandler{
address: address,
txs: txs,
blobLogs: blobLogs,
messages: messages,
delegations: delegations,
undelegations: undelegations,
redelegations: redelegations,
vestings: vestings,
grants: grants,
celestial: celestial,
state: state,
indexerName: indexerName,
}
}
type getAddressRequest struct {
Hash string `param:"hash" validate:"required,address"`
}
// Get godoc
//
// @Summary Get address info
// @Description Get address info
// @Tags address
// @ID get-address
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Produce json
// @Success 200 {object} responses.Address
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash} [get]
func (handler *AddressHandler) Get(c echo.Context) error {
req, err := bindAndValidate[getAddressRequest](c)
if err != nil {
return badRequestError(c, err)
}
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
address, err := handler.address.ByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.address)
}
return c.JSON(http.StatusOK, responses.NewAddress(address))
}
type addressListRequest struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=id spendable delegated unbonding first_height last_height"`
}
func (p *addressListRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
}
// List godoc
//
// @Summary List address info
// @Description List address info
// @Tags address
// @ID list-address
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Param sort_by query string false "Sort field" Enums(id, delegated, spendable, unbonding, first_height, last_height)
// @Produce json
// @Success 200 {array} responses.Address
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address [get]
func (handler *AddressHandler) List(c echo.Context) error {
req, err := bindAndValidate[addressListRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
fltrs := storage.AddressListFilter{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortField: req.SortBy,
}
address, err := handler.address.ListWithBalance(c.Request().Context(), fltrs)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Address, len(address))
for i := range address {
response[i] = responses.NewAddress(address[i])
}
return returnArray(c, response)
}
// Transactions godoc
//
// @Summary Get address transactions
// @Description Get address transactions
// @Tags address
// @ID address-transactions
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Param status query storageTypes.Status false "Comma-separated status list"
// @Param msg_type query storageTypes.MsgType false "Comma-separated message types list"
// @Param from query integer false "Time from in unix timestamp" minimum(1)
// @Param to query integer false "Time to in unix timestamp" minimum(1)
// @Param height query integer false "Block number" minimum(1)
// @Produce json
// @Success 200 {array} responses.Tx
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/txs [get]
func (handler *AddressHandler) Transactions(c echo.Context) error {
req, err := bindAndValidate[addressTxRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
fltrs := storage.TxFilter{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
Status: req.Status,
Height: req.Height,
MessageTypes: storageTypes.NewMsgTypeBitMask(),
}
if req.From > 0 {
fltrs.TimeFrom = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
fltrs.TimeTo = time.Unix(req.To, 0).UTC()
}
for i := range req.MsgType {
fltrs.MessageTypes.SetByMsgType(storageTypes.MsgType(req.MsgType[i]))
}
txs, err := handler.txs.ByAddress(c.Request().Context(), addressId, fltrs)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[i])
}
return returnArray(c, response)
}
type getAddressMessages struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
MsgType StringArray `query:"msg_type" validate:"omitempty,dive,msg_type"`
}
func (p *getAddressMessages) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
if p.MsgType == nil {
p.MsgType = make(StringArray, 0)
}
}
func (p *getAddressMessages) ToFilters() storage.AddressMsgsFilter {
return storage.AddressMsgsFilter{
Limit: p.Limit,
Offset: p.Offset,
Sort: pgSort(p.Sort),
MessageTypes: p.MsgType,
}
}
// Messages godoc
//
// @Summary Get address messages
// @Description Get address messages
// @Tags address
// @ID address-messages
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Param msg_type query storageTypes.MsgType false "Comma-separated message types list"
// @Produce json
// @Success 200 {array} responses.MessageForAddress
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/messages [get]
func (handler *AddressHandler) Messages(c echo.Context) error {
req, err := bindAndValidate[getAddressMessages](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
filters := req.ToFilters()
msgs, err := handler.messages.ByAddress(c.Request().Context(), addressId, filters)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.MessageForAddress, len(msgs))
for i := range msgs {
response[i] = responses.NewMessageForAddress(msgs[i])
}
return returnArray(c, response)
}
type getBlobLogsForAddress struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
Joins *bool `query:"joins" validate:"omitempty"`
}
func (req *getBlobLogsForAddress) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
if req.Sort == "" {
req.Sort = desc
}
if req.Joins == nil {
req.Joins = testsuite.Ptr(true)
}
}
// Blobs godoc
//
// @Summary Get blobs pushed by address
// @Description Get blobs pushed by address
// @Tags address
// @ID address-blobs
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Param joins query boolean false "Flag indicating whether entities of transaction and namespace should be attached or not. Default: true"
// @Produce json
// @Success 200 {array} responses.BlobLog
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/blobs [get]
func (handler *AddressHandler) Blobs(c echo.Context) error {
req, err := bindAndValidate[getBlobLogsForAddress](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
logs, err := handler.blobLogs.BySigner(
c.Request().Context(),
addressId,
storage.BlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
Joins: *req.Joins,
},
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.BlobLog, len(logs))
for i := range response {
response[i] = responses.NewBlobLog(logs[i])
}
return returnArray(c, response)
}
// Count godoc
//
// @Summary Get count of addresses in network
// @Description Get count of addresses in network
// @Tags address
// @ID get-address-count
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /address/count [get]
func (handler *AddressHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err != nil {
return handleError(c, err, handler.address)
}
return c.JSON(http.StatusOK, state.TotalAccounts)
}
type getAddressDelegations struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
ShowZero bool `query:"show_zero" validate:"omitempty"`
}
func (req *getAddressDelegations) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// Delegations godoc
//
// @Summary Get delegations made by address
// @Description Get delegations made by address
// @Tags address
// @ID address-delegations
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param show_zero query boolean false "Show zero delegations"
// @Produce json
// @Success 200 {array} responses.Delegation
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/delegations [get]
func (handler *AddressHandler) Delegations(c echo.Context) error {
req, err := bindAndValidate[getAddressDelegations](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
delegations, err := handler.delegations.ByAddress(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
req.ShowZero,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Delegation, len(delegations))
for i := range response {
response[i] = responses.NewDelegation(delegations[i])
}
return returnArray(c, response)
}
type getAddressPageable struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (req *getAddressPageable) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// Undelegations godoc
//
// @Summary Get undelegations made by address
// @Description Get undelegations made by address
// @Tags address
// @ID address-undelegations
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Undelegation
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/undelegations [get]
func (handler *AddressHandler) Undelegations(c echo.Context) error {
req, err := bindAndValidate[getAddressPageable](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
undelegations, err := handler.undelegations.ByAddress(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Undelegation, len(undelegations))
for i := range response {
response[i] = responses.NewUndelegation(undelegations[i])
}
return returnArray(c, response)
}
// Redelegations godoc
//
// @Summary Get redelegations made by address
// @Description Get redelegations made by address
// @Tags address
// @ID address-redelegations
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Redelegation
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/redelegations [get]
func (handler *AddressHandler) Redelegations(c echo.Context) error {
req, err := bindAndValidate[getAddressPageable](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
redelegations, err := handler.redelegations.ByAddress(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Redelegation, len(redelegations))
for i := range response {
response[i] = responses.NewRedelegation(redelegations[i])
}
return returnArray(c, response)
}
type getAddressVestings struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
ShowEnded bool `query:"show_ended" validate:"omitempty"`
}
func (req *getAddressVestings) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// Vestings godoc
//
// @Summary Get vesting for address
// @Description Get vesting for address
// @Tags address
// @ID address-vesting
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param show_ended query boolean false "Show finished vestings delegations"
// @Produce json
// @Success 200 {array} responses.Vesting
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/vestings [get]
func (handler *AddressHandler) Vestings(c echo.Context) error {
req, err := bindAndValidate[getAddressVestings](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
vestings, err := handler.vestings.ByAddress(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
req.ShowEnded,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Vesting, len(vestings))
for i := range response {
response[i] = responses.NewVesting(vestings[i])
}
return returnArray(c, response)
}
// Grants godoc
//
// @Summary Get grants made by address
// @Description Get grants made by address
// @Tags address
// @ID address-grants
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Grant
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/grants [get]
func (handler *AddressHandler) Grants(c echo.Context) error {
req, err := bindAndValidate[getAddressPageable](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
grants, err := handler.grants.ByGranter(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Grant, len(grants))
for i := range response {
response[i] = responses.NewGrant(grants[i])
}
return returnArray(c, response)
}
// Grantee godoc
//
// @Summary Get grants where address is grantee
// @Description Get grants where address is grantee
// @Tags address
// @ID address-grantee
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Grant
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/granters [get]
func (handler *AddressHandler) Grantee(c echo.Context) error {
req, err := bindAndValidate[getAddressPageable](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
grants, err := handler.grants.ByGrantee(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.Grant, len(grants))
for i := range response {
response[i] = responses.NewGrant(grants[i])
}
return returnArray(c, response)
}
type addressStatsRequest struct {
Hash string `example:"celestia1glfkehhpvl55amdew2fnm6wxt7egy560mxdrj7" param:"hash" swaggertype:"string" validate:"required,address"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day month"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=gas_used gas_wanted fee tx_count"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Stats godoc
//
// @Summary Get address stats
// @Description Get address stats
// @Tags address
// @ID address-stats
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param name path string true "Series name" Enums(gas_used, gas_wanted, fee, tx_count)
// @Param timeframe path string true "Timeframe" Enums(hour, day, month)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.HistogramItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/stats/{name}/{timeframe} [get]
func (handler *AddressHandler) Stats(c echo.Context) error {
req, err := bindAndValidate[addressStatsRequest](c)
if err != nil {
return badRequestError(c, err)
}
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
series, err := handler.address.Series(
c.Request().Context(),
addressId,
storage.Timeframe(req.Timeframe),
req.SeriesName,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]responses.HistogramItem, len(series))
for i := range series {
response[i] = responses.NewHistogramItem(series[i])
}
return returnArray(c, response)
}
func (handler *AddressHandler) getIdByHash(ctx context.Context, hash []byte, address string) (uint64, error) {
addressId, err := handler.address.IdByHash(ctx, hash)
if err != nil {
return 0, err
}
switch len(addressId) {
case 0:
return 0, errors.Wrap(errUnknownAddress, address)
case 1:
return addressId[0], nil
default:
return handler.address.IdByAddress(ctx, address, addressId...)
}
}
// Celestials godoc
//
// @Summary Get list of celestial id for address
// @Description Get list of celestial id for address
// @Tags address
// @ID address-celestials
// @Param hash path string true "Hash" minlength(47) maxlength(47)
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Celestial
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /address/{hash}/celestials [get]
func (handler *AddressHandler) Celestials(c echo.Context) error {
req, err := bindAndValidate[getAddressPageable](c)
if err != nil {
return badRequestError(c, err)
}
_, hash, err := types.Address(req.Hash).Decode()
if err != nil {
return badRequestError(c, err)
}
addressId, err := handler.getIdByHash(c.Request().Context(), hash, req.Hash)
if err != nil {
return handleError(c, err, handler.address)
}
celestials, err := handler.celestial.ByAddressId(
c.Request().Context(),
addressId,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.address)
}
response := make([]*responses.Celestial, len(celestials))
for i := range celestials {
response[i] = responses.NewCelestial(&celestials[i])
}
return returnArray(c, response)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/pkg/node"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celestiaorg/celestia-app/v3/pkg/appconsts"
"github.com/celestiaorg/celestia-app/v3/pkg/da"
"github.com/celestiaorg/go-square/shares"
"github.com/celestiaorg/go-square/square"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type BlockHandler struct {
block storage.IBlock
blockStats storage.IBlockStats
events storage.IEvent
namespace storage.INamespace
blobLogs storage.IBlobLog
message storage.IMessage
state storage.IState
node node.Api
indexerName string
}
func NewBlockHandler(
block storage.IBlock,
blockStats storage.IBlockStats,
events storage.IEvent,
namespace storage.INamespace,
message storage.IMessage,
blobLogs storage.IBlobLog,
state storage.IState,
node node.Api,
indexerName string,
) *BlockHandler {
return &BlockHandler{
block: block,
blockStats: blockStats,
events: events,
namespace: namespace,
blobLogs: blobLogs,
message: message,
state: state,
node: node,
indexerName: indexerName,
}
}
type getBlockByHeightRequest struct {
Height types.Level `param:"height" validate:"min=0"`
}
type getBlockRequest struct {
Height types.Level `param:"height" validate:"min=0"`
Stats bool `query:"stats" validate:"omitempty"`
}
// Get godoc
//
// @Summary Get block info
// @Description Get block info
// @Tags block
// @ID get-block
// @Param height path integer true "Block height" minimum(1)
// @Param stats query boolean false "Need join stats for block"
// @Produce json
// @Success 200 {object} responses.Block
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height} [get]
func (handler *BlockHandler) Get(c echo.Context) error {
req, err := bindAndValidate[getBlockRequest](c)
if err != nil {
return badRequestError(c, err)
}
var block storage.Block
if req.Stats {
block, err = handler.block.ByHeightWithStats(c.Request().Context(), req.Height)
} else {
block, err = handler.block.ByHeight(c.Request().Context(), req.Height)
}
if err != nil {
return handleError(c, err, handler.block)
}
return c.JSON(http.StatusOK, responses.NewBlock(block, req.Stats))
}
type blockListRequest struct {
Limit uint64 `query:"limit" validate:"omitempty,min=1,max=100"`
Offset uint64 `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
Stats bool `query:"stats" validate:"omitempty"`
}
func (p *blockListRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
}
// List godoc
//
// @Summary List blocks info
// @Description List blocks info
// @Tags block
// @ID list-block
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Param stats query boolean false "Need join stats for block"
// @Produce json
// @Success 200 {array} responses.Block
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block [get]
func (handler *BlockHandler) List(c echo.Context) error {
req, err := bindAndValidate[blockListRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
var blocks []*storage.Block
if req.Stats {
blocks, err = handler.block.ListWithStats(c.Request().Context(), req.Limit, req.Offset, pgSort(req.Sort))
} else {
blocks, err = handler.block.List(c.Request().Context(), req.Limit, req.Offset, pgSort(req.Sort))
}
if err != nil {
return handleError(c, err, handler.block)
}
response := make([]responses.Block, len(blocks))
for i := range blocks {
response[i] = responses.NewBlock(*blocks[i], req.Stats)
}
return returnArray(c, response)
}
type getBlockEvents struct {
Height types.Level `param:"height" validate:"min=0"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (p *getBlockEvents) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
// GetEvents godoc
//
// @Summary Get events from begin and end of block
// @Description Get events from begin and end of block
// @Tags block
// @ID get-block-events
// @Param height path integer true "Block height" minimum(1)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.Event
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/events [get]
func (handler *BlockHandler) GetEvents(c echo.Context) error {
req, err := bindAndValidate[getBlockEvents](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
blockTime, err := handler.block.Time(c.Request().Context(), req.Height)
if err != nil {
if handler.block.IsNoRows(err) {
return returnArray(c, []any{})
}
return handleError(c, err, handler.block)
}
fltrs := storage.EventFilter{
Limit: req.Limit,
Offset: req.Offset,
Time: blockTime.UTC(),
}
events, err := handler.events.ByBlock(c.Request().Context(), req.Height, fltrs)
if err != nil {
return handleError(c, err, handler.block)
}
response := make([]responses.Event, len(events))
for i := range events {
response[i] = responses.NewEvent(events[i])
}
return returnArray(c, response)
}
// GetStats godoc
//
// @Summary Get block stats by height
// @Description Get block stats by height
// @Tags block
// @ID get-block-stats
// @Param height path integer true "Block height" minimum(1)
// @Produce json
// @Success 200 {object} responses.BlockStats
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/stats [get]
func (handler *BlockHandler) GetStats(c echo.Context) error {
req, err := bindAndValidate[getBlockByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
stats, err := handler.blockStats.ByHeight(c.Request().Context(), req.Height)
if err != nil {
return handleError(c, err, handler.block)
}
return c.JSON(http.StatusOK, responses.NewBlockStats(stats))
}
// Count godoc
//
// @Summary Get count of blocks in network
// @Description Get count of blocks in network
// @Tags block
// @ID get-block-count
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /block/count [get]
func (handler *BlockHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err != nil {
return handleError(c, err, handler.block)
}
return c.JSON(http.StatusOK, state.LastHeight+1) // + genesis block
}
// GetMessages godoc
//
// @Summary Get messages contained in the block
// @Description Get messages contained in the block
// @Tags block
// @ID get-block-messages
// @Param height path integer true "Block height" minimum(1)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param msg_type query types.MsgType false "Comma-separated message types list"
// @Param excluded_msg_type query types.MsgType false "Comma-separated message types which should be excluded from list"
// @Produce json
// @Success 200 {array} responses.Message
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/messages [get]
func (handler *BlockHandler) GetMessages(c echo.Context) error {
req, err := bindAndValidate[listMessageByBlockRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
fltrs := storage.MessageListWithTxFilters{
Limit: req.Limit,
Offset: req.Offset,
Height: req.Height,
MessageTypes: req.MsgType,
ExcludedMessageTypes: req.ExcludedMsgType,
}
messages, err := handler.message.ListWithTx(c.Request().Context(), fltrs)
if err != nil {
return handleError(c, err, handler.block)
}
response := make([]responses.Message, len(messages))
for i := range response {
msg := responses.NewMessageWithTx(messages[i])
response[i] = msg
}
return c.JSON(http.StatusOK, response)
}
type getBlobsForBlock struct {
Height types.Level `param:"height" validate:"min=0"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
}
func (req *getBlobsForBlock) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
if req.Sort == "" {
req.Sort = desc
}
}
// Blobs godoc
//
// @Summary List blobs which was pushed in the block
// @Description List blobs which was pushed in the block
// @Tags block
// @ID get-block-blobs
// @Param height path integer true "Block height" minimum(1)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Produce json
// @Success 200 {array} responses.BlobLog
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/blobs [get]
func (handler *BlockHandler) Blobs(c echo.Context) error {
req, err := bindAndValidate[getBlobsForBlock](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
blockTime, err := handler.block.Time(c.Request().Context(), req.Height)
if err != nil {
if handler.block.IsNoRows(err) {
return returnArray(c, []any{})
}
return handleError(c, err, handler.block)
}
blobs, err := handler.blobLogs.ByHeight(
c.Request().Context(),
req.Height,
storage.BlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
// using time filters to take certain partition
From: blockTime,
To: blockTime.Add(time.Minute),
},
)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
response := make([]responses.BlobLog, len(blobs))
for i := range blobs {
response[i] = responses.NewBlobLog(blobs[i])
}
return returnArray(c, response)
}
// BlobsCount godoc
//
// @Summary Count of blobs which was pushed by transaction
// @Description Count of blobs which was pushed by transaction
// @Tags block
// @ID block-blobs-count
// @Param height path integer true "Block height" minimum(1)
// @Produce json
// @Success 200 {integer} uint64
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/blobs/count [get]
func (handler *BlockHandler) BlobsCount(c echo.Context) error {
req, err := bindAndValidate[getBlockByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
stats, err := handler.blockStats.ByHeight(c.Request().Context(), req.Height)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
return c.JSON(http.StatusOK, stats.BlobsCount)
}
// BlockODS godoc
//
// @Summary ODS for block
// @Description ODS for block
// @Tags block
// @ID block-ods
// @Param height path integer true "Block height" minimum(1)
// @Produce json
// @x-internal true
// @Success 200 {object} responses.ODS
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /block/{height}/ods [get]
func (handler *BlockHandler) BlockODS(c echo.Context) error {
req, err := bindAndValidate[getBlockByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
blockStats, err := handler.blockStats.ByHeight(c.Request().Context(), req.Height)
if err != nil {
return handleError(c, err, handler.block)
}
if blockStats.TxCount == 0 {
return c.JSON(http.StatusOK, responses.ODS{
Width: 1,
Items: []responses.ODSItem{
{
From: []uint{0, 0},
To: []uint{0, 0},
Namespace: "//////////////////////////////////////4=",
Type: responses.TailPaddingNamespace,
},
},
})
}
block, err := handler.node.Block(c.Request().Context(), req.Height)
if err != nil {
return handleError(c, err, handler.block)
}
dataSquare, err := square.Construct(
block.Block.Data.Txs.ToSliceOfBytes(),
appconsts.SquareSizeUpperBound(0),
appconsts.SubtreeRootThreshold(0),
)
if err != nil {
return internalServerError(c, err)
}
eds, err := da.ExtendShares(shares.ToBytes(dataSquare))
if err != nil {
return internalServerError(c, err)
}
ods, err := responses.NewODS(eds)
if err != nil {
return internalServerError(c, err)
}
return c.JSON(http.StatusOK, ods)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type ConstantHandler struct {
constants storage.IConstant
denomMetadata storage.IDenomMetadata
rollup storage.IRollup
}
func NewConstantHandler(
constants storage.IConstant,
denomMetadata storage.IDenomMetadata,
rollup storage.IRollup,
) *ConstantHandler {
return &ConstantHandler{
constants: constants,
denomMetadata: denomMetadata,
rollup: rollup,
}
}
// Get godoc
//
// @Summary Get network constants
// @Description Get network constants
// @Tags general
// @ID get-constants
// @Produce json
// @Success 200 {object} responses.Constants
// @Success 204
// @Failure 500 {object} Error
// @Router /constants [get]
func (handler *ConstantHandler) Get(c echo.Context) error {
consts, err := handler.constants.All(c.Request().Context())
if err != nil {
return handleError(c, err, handler.rollup)
}
dm, err := handler.denomMetadata.All(c.Request().Context())
if err != nil {
return handleError(c, err, handler.rollup)
}
return c.JSON(http.StatusOK, responses.NewConstants(consts, dm))
}
// Enums godoc
//
// @Summary Get celenium enumerators
// @Description Get celenium enumerators
// @Tags general
// @ID get-enums
// @Produce json
// @Success 200 {object} responses.Enums
// @Router /enums [get]
func (handler *ConstantHandler) Enums(c echo.Context) error {
tags, err := handler.rollup.Tags(c.Request().Context())
if err != nil {
return handleError(c, err, handler.rollup)
}
return c.JSON(http.StatusOK, responses.NewEnums(tags))
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"net/http"
sentryecho "github.com/getsentry/sentry-go/echo"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
var (
errInvalidHashLength = errors.New("invalid hash: should be 32 bytes length")
errInvalidAddress = errors.New("invalid address")
errUnknownAddress = errors.New("unknown address")
errUnknownNamespace = errors.New("unknown namespace")
errInvalidApiKey = errors.New("invalid api key")
errCancelRequest = "pq: canceling statement due to user request"
)
type NoRows interface {
IsNoRows(err error) bool
}
type Error struct {
Message string `json:"message"`
}
func badRequestError(c echo.Context, err error) error {
return c.JSON(http.StatusBadRequest, Error{
Message: err.Error(),
})
}
func internalServerError(c echo.Context, err error) error {
if hub := sentryecho.GetHubFromContext(c); hub != nil {
hub.CaptureMessage(err.Error())
}
return c.JSON(http.StatusInternalServerError, Error{
Message: err.Error(),
})
}
func handleError(c echo.Context, err error, noRows NoRows) error {
if err == nil {
return nil
}
if err.Error() == errCancelRequest {
return nil
}
if errors.Is(err, context.DeadlineExceeded) {
return c.JSON(http.StatusRequestTimeout, Error{
Message: "timeout",
})
}
if errors.Is(err, context.Canceled) {
return c.JSON(http.StatusBadGateway, Error{
Message: err.Error(),
})
}
if noRows.IsNoRows(err) {
return c.NoContent(http.StatusNoContent)
}
if errors.Is(err, errInvalidAddress) || errors.Is(err, errUnknownAddress) {
return badRequestError(c, err)
}
return internalServerError(c, err)
}
func success(c echo.Context) error {
return c.JSON(http.StatusOK, echo.Map{
"message": "success",
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"strconv"
"github.com/celenium-io/celestia-indexer/cmd/api/gas"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
blobtypes "github.com/celestiaorg/celestia-app/v3/x/blob/types"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
// GasHandler -
type GasHandler struct {
state storage.IState
tx storage.ITx
constant storage.IConstant
blockStats storage.IBlockStats
tracker gas.ITracker
}
func NewGasHandler(
state storage.IState,
tx storage.ITx,
constant storage.IConstant,
blockStats storage.IBlockStats,
tracker gas.ITracker,
) GasHandler {
return GasHandler{
state: state,
tx: tx,
blockStats: blockStats,
constant: constant,
tracker: tracker,
}
}
type estimatePfbGas struct {
Sizes StringArray `query:"sizes" validate:"required"`
}
// EstimateForPfb godoc
//
// @Summary Get estimated gas for pay for blob
// @Description Get estimated gas for pay for blob message with certain values of blob sizes
// @Tags gas
// @ID gas-estimate-for-pfb
// @Param sizes query string true "Comma-separated array of blob sizes"
// @Produce json
// @Success 200 {object} uint64
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /gas/estimate_for_pfb [get]
func (handler GasHandler) EstimateForPfb(c echo.Context) error {
req, err := bindAndValidate[estimatePfbGas](c)
if err != nil {
return badRequestError(c, err)
}
sizes := make([]uint32, len(req.Sizes))
for i := range req.Sizes {
size, err := strconv.ParseUint(req.Sizes[i], 10, 32)
if err != nil {
return badRequestError(c, err)
}
//nolint:gosec
sizes[i] = uint32(size)
}
gasPerBlobByteConst, err := handler.constant.Get(c.Request().Context(), types.ModuleNameBlob, "gas_per_blob_byte")
if err != nil {
return handleError(c, err, handler.tx)
}
gasPerBlobByte := gasPerBlobByteConst.MustUint32()
txSizeCostConst, err := handler.constant.Get(c.Request().Context(), types.ModuleNameAuth, "tx_size_cost_per_byte")
if err != nil {
return handleError(c, err, handler.tx)
}
txSizeCost := txSizeCostConst.MustUint64()
return c.JSON(http.StatusOK, blobtypes.EstimateGas(sizes, gasPerBlobByte, txSizeCost))
}
// EstimatePrice godoc
//
// @Summary Get estimated gas price
// @Description Get estimated gas price based on historical data
// @Tags gas
// @ID gas-price
// @Produce json
// @Success 200 {object} responses.GasPrice
// @Router /gas/price [get]
func (handler GasHandler) EstimatePrice(c echo.Context) error {
data := handler.tracker.State()
return c.JSON(http.StatusOK, responses.GasPrice{
Slow: data.Slow,
Median: data.Median,
Fast: data.Fast,
})
}
type estimatePricePriorityRequest struct {
Priority string `param:"priority" validate:"required,oneof=slow median fast"`
}
// EstimatePricePriority godoc
//
// @Summary Get estimated gas price with priority filter
// @Description Get estimated gas price with priority filter based on historical data
// @Tags gas
// @ID gas-price-priority
// @Param priority path string true "Priority" Enums(slow, median, fast)
// @Produce json
// @Success 200 {string} string
// @Router /gas/price/{priority} [get]
func (handler GasHandler) EstimatePricePriority(c echo.Context) error {
req, err := bindAndValidate[estimatePricePriorityRequest](c)
if err != nil {
return badRequestError(c, err)
}
data := handler.tracker.State()
switch req.Priority {
case "slow":
return c.JSON(http.StatusOK, data.Slow)
case "median":
return c.JSON(http.StatusOK, data.Median)
case "fast":
return c.JSON(http.StatusOK, data.Fast)
default:
return badRequestError(c, errors.Errorf("invalid priority: %s", req.Priority))
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"encoding/base64"
"encoding/hex"
"net/http"
"time"
"github.com/celestiaorg/celestia-app/v3/pkg/appconsts"
"github.com/celestiaorg/celestia-app/v3/pkg/da"
"github.com/celestiaorg/go-square/v2/share"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celestiaorg/go-square/v2"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
testsuite "github.com/celenium-io/celestia-indexer/internal/test_suite"
"github.com/celenium-io/celestia-indexer/pkg/node"
"github.com/celestiaorg/celestia-app/v3/pkg/proof"
"github.com/labstack/echo/v4"
)
type NamespaceHandler struct {
namespace storage.INamespace
blobLogs storage.IBlobLog
rollups storage.IRollup
address storage.IAddress
blob node.DalApi
state storage.IState
node node.Api
indexerName string
}
func NewNamespaceHandler(
namespace storage.INamespace,
blobLogs storage.IBlobLog,
rollups storage.IRollup,
address storage.IAddress,
state storage.IState,
indexerName string,
blob node.DalApi,
node node.Api,
) *NamespaceHandler {
return &NamespaceHandler{
namespace: namespace,
blobLogs: blobLogs,
rollups: rollups,
address: address,
blob: blob,
state: state,
indexerName: indexerName,
node: node,
}
}
type getNamespaceRequest struct {
Id string `param:"id" validate:"required,hexadecimal,len=56"`
}
// Get godoc
//
// @Summary Get namespace info
// @Description Returns array of namespace versions
// @Tags namespace
// @ID get-namespace
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Produce json
// @Success 200 {array} responses.Namespace
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace/{id} [get]
func (handler *NamespaceHandler) Get(c echo.Context) error {
req, err := bindAndValidate[getNamespaceRequest](c)
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
namespace, err := handler.namespace.ByNamespaceId(c.Request().Context(), namespaceId)
if err != nil {
return handleError(c, err, handler.namespace)
}
response := make([]responses.Namespace, len(namespace))
for i := range namespace {
response[i] = responses.NewNamespace(namespace[i])
}
return returnArray(c, response)
}
type getNamespaceByHashRequest struct {
Hash string `param:"hash" validate:"required,base64,namespace"`
}
// GetByHash godoc
//
// @Summary Get namespace info by base64
// @Description Returns namespace by base64 encoded identity
// @Tags namespace
// @ID get-namespace-base64
// @Param hash path string true "Base64-encoded namespace id and version"
// @Produce json
// @Success 200 {object} responses.Namespace
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace_by_hash/{hash} [get]
func (handler *NamespaceHandler) GetByHash(c echo.Context) error {
req, err := bindAndValidate[getNamespaceByHashRequest](c)
if err != nil {
return badRequestError(c, err)
}
hash, err := base64.StdEncoding.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
version := hash[0]
namespaceId := hash[1:]
namespace, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, version)
if err != nil {
return handleError(c, err, handler.namespace)
}
return c.JSON(http.StatusOK, responses.NewNamespace(namespace))
}
type getNamespaceWithVersionRequest struct {
Id string `param:"id" validate:"required,hexadecimal,len=56"`
Version byte `param:"version"`
}
// GetWithVersion godoc
//
// @Summary Get namespace info by id and version
// @Description Returns namespace by version byte and namespace id
// @Tags namespace
// @ID get-namespace-by-version-and-id
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param version path integer true "Version of namespace"
// @Produce json
// @Success 200 {object} responses.Namespace
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace/{id}/{version} [get]
func (handler *NamespaceHandler) GetWithVersion(c echo.Context) error {
req, err := bindAndValidate[getNamespaceWithVersionRequest](c)
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
namespace, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, req.Version)
if err != nil {
return handleError(c, err, handler.namespace)
}
return c.JSON(http.StatusOK, responses.NewNamespace(namespace))
}
// List godoc
//
// @Summary List namespace info
// @Description List namespace info
// @Tags namespace
// @ID list-namespace
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, pfb_count, size)
// @Produce json
// @Success 200 {array} responses.Namespace
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace [get]
func (handler *NamespaceHandler) List(c echo.Context) error {
req, err := bindAndValidate[namespaceList](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
namespace, err := handler.namespace.ListWithSort(c.Request().Context(), req.SortBy, pgSort(req.Sort), req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.namespace)
}
response := make([]responses.Namespace, len(namespace))
for i := range namespace {
response[i] = responses.NewNamespace(namespace[i])
}
return returnArray(c, response)
}
type getBlobsRequest struct {
Hash string `param:"hash" validate:"required,base64"`
Height types.Level `param:"height" validation:"required,min=1"`
}
// GetBlobs godoc
//
// @Summary Get namespace blobs on height
// @Description Returns blobs
// @Tags namespace
// @ID get-namespace-blobs
// @Param hash path string true "Base64-encoded namespace id and version"
// @Param height path integer true "Block heigth" minimum(1)
// @Produce json
// @Success 200 {array} responses.Blob
// @Failure 400 {object} Error
// @Router /namespace_by_hash/{hash}/{height} [get]
func (handler *NamespaceHandler) GetBlobs(c echo.Context) error {
req, err := bindAndValidate[getBlobsRequest](c)
if err != nil {
return badRequestError(c, err)
}
blobs, err := handler.blob.Blobs(c.Request().Context(), req.Height, req.Hash)
if err != nil {
return badRequestError(c, err)
}
return c.JSON(http.StatusOK, blobs)
}
type listByNamespace struct {
Id string `param:"id" validate:"required,hexadecimal,len=56"`
Version byte `param:"version"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (req *listByNamespace) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// GetMessages godoc
//
// @Summary Get namespace messages by id and version
// @Description Returns namespace messages by version byte and namespace id
// @Tags namespace
// @ID get-namespace-messages
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param version path integer true "Version of namespace"
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.NamespaceMessage
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace/{id}/{version}/messages [get]
func (handler *NamespaceHandler) GetMessages(c echo.Context) error {
req, err := bindAndValidate[listByNamespace](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
ns, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, req.Version)
if err != nil {
return handleError(c, err, handler.namespace)
}
messages, err := handler.namespace.Messages(c.Request().Context(), ns.Id, req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.namespace)
}
response := make([]responses.NamespaceMessage, len(messages))
for i := range response {
msg, err := responses.NewNamespaceMessage(messages[i])
if err != nil {
return handleError(c, err, handler.namespace)
}
response[i] = msg
}
return returnArray(c, response)
}
type listBlobsRequest struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
Commitment string `query:"commitment" validate:"omitempty,base64url"`
Signers StringArray `query:"signers" validate:"omitempty,dive,address"`
Namespaces StringArray `query:"namespaces" validate:"omitempty,dive,namespace"`
Cursor uint64 `query:"cursor" validate:"omitempty,min=0"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
func (req *listBlobsRequest) SetDefault() {
if req.Limit == 0 {
req.Limit = 0
}
if req.Sort == "" {
req.Sort = desc
}
}
func (req listBlobsRequest) toDbRequest(ctx context.Context, ns storage.INamespace, addrs storage.IAddress) (storage.ListBlobLogFilters, error) {
fltrs := storage.ListBlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
Commitment: req.Commitment,
Cursor: req.Cursor,
Namespaces: make([]uint64, len(req.Namespaces)),
}
if req.From > 0 {
fltrs.From = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
fltrs.To = time.Unix(req.To, 0).UTC()
}
var err error
if len(req.Namespaces) > 0 {
for i := range req.Namespaces {
hash, err := base64.StdEncoding.DecodeString(req.Namespaces[i])
if err != nil {
return fltrs, err
}
n, err := ns.ByNamespaceIdAndVersion(ctx, hash[1:], hash[0])
if err != nil {
return fltrs, err
}
fltrs.Namespaces[i] = n.Id
}
}
if len(req.Signers) > 0 {
hash := make([][]byte, len(req.Signers))
for i := range req.Signers {
if _, hash[i], err = types.Address(req.Signers[i]).Decode(); err != nil {
return fltrs, err
}
}
if fltrs.Signers, err = addrs.IdByHash(ctx, hash...); err != nil {
return fltrs, err
}
}
return fltrs, nil
}
// Blobs godoc
//
// @Summary List all blobs with filters
// @Description Returns blobs
// @Tags namespace
// @ID get-blobs
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Param commitment query string false "Commitment value in URLbase64 format"
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Param signers query string false "Comma-separated celestia addresses"
// @Param namespaces query string false "Comma-separated celestia namespaces"
// @Param cursor query integer false "Last entity id which is used for cursor pagination" mininum(1)
// @Accept json
// @Produce json
// @Success 200 {array} responses.LightBlobLog
// @Failure 400 {object} Error
// @Router /blob [get]
func (handler *NamespaceHandler) Blobs(c echo.Context) error {
req, err := bindAndValidate[listBlobsRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
fltrs, err := req.toDbRequest(c.Request().Context(), handler.namespace, handler.address)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
blob, err := handler.blobLogs.ListBlobs(c.Request().Context(), fltrs)
if err != nil {
return badRequestError(c, err)
}
response := make([]responses.LightBlobLog, len(blob))
for i := range blob {
response[i] = responses.NewLightBlobLog(blob[i])
}
return returnArray(c, response)
}
type postBlobRequest struct {
Hash string `example:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAs2bWWU6FOB0=" json:"hash" validate:"required,namespace"`
Height types.Level `example:"123456" json:"height" validate:"required,min=1"`
Commitment string `example:"vbGakK59+Non81TE3ULg5Ve5ufT9SFm/bCyY+WLR3gg=" json:"commitment" validate:"required,base64"`
}
// Blob godoc
//
// @Summary Get namespace blob by commitment on height
// @Description Returns blob.
// @Tags namespace
// @ID get-blob
// @Param request body postBlobRequest true "Request body containing height, commitment and namespace hash"
// @Accept json
// @Produce json
// @Success 200 {object} responses.Blob
// @Failure 400 {object} Error
// @Router /blob [post]
//
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name apikey
// @description To authorize your requests you have to select the required tariff on our site. Then you receive api key to authorize. Api key should be passed via request header `apikey`.
func (handler *NamespaceHandler) Blob(c echo.Context) error {
req, err := bindAndValidate[postBlobRequest](c)
if err != nil {
return badRequestError(c, err)
}
blob, err := handler.blob.Blob(c.Request().Context(), req.Height, req.Hash, req.Commitment)
if err != nil {
return badRequestError(c, err)
}
response, err := responses.NewBlob(blob)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
return c.JSON(http.StatusOK, response)
}
// BlobMetadata godoc
//
// @Summary Get blob metadata by commitment on height
// @Description Returns blob metadata
// @Tags namespace
// @ID get-blob-metadata
// @Param request body postBlobRequest true "Request body containing height, commitment and namespace hash"
// @Accept json
// @Produce json
// @Success 200 {object} responses.BlobLog
// @Failure 400 {object} Error
// @Router /blob/metadata [post]
//
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name apikey
// @description To authorize your requests you have to select the required tariff on our site. Then you receive api key to authorize. Api key should be passed via request header `apikey`.
func (handler *NamespaceHandler) BlobMetadata(c echo.Context) error {
req, err := bindAndValidate[postBlobRequest](c)
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := base64.StdEncoding.DecodeString(req.Hash)
if err != nil {
return handleError(c, err, handler.namespace)
}
ns, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId[1:], namespaceId[0])
if err != nil {
return handleError(c, err, handler.namespace)
}
blobMetadata, err := handler.blobLogs.Blob(c.Request().Context(), req.Height, ns.Id, req.Commitment)
if err != nil {
return handleError(c, err, handler.namespace)
}
return c.JSON(http.StatusOK, responses.NewBlobLog(blobMetadata))
}
type getBlobLogsForNamespace struct {
Id string `param:"id" validate:"required,hexadecimal,len=56"`
Version byte `param:"version"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
Commitment string `query:"commitment" validate:"omitempty,base64url"`
Joins *bool `query:"joins" validate:"omitempty"`
Signers StringArray `query:"signers" validate:"omitempty,dive,address"`
Cursor uint64 `query:"cursor" validate:"omitempty,min=0"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
func (req getBlobLogsForNamespace) getCommitment() (string, error) {
if req.Commitment == "" {
return "", nil
}
data, err := base64.URLEncoding.DecodeString(req.Commitment)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
func (req *getBlobLogsForNamespace) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
if req.Sort == "" {
req.Sort = desc
}
if req.Joins == nil {
req.Joins = testsuite.Ptr(true)
}
}
// GetBlobLogs godoc
//
// @Summary Get blob changes for namespace
// @Description Returns blob changes for namespace
// @Tags namespace
// @ID get-blob-logs
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param version path integer true "Version of namespace"
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Param commitment query string false "Commitment value in URLbase64 format"
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Param joins query boolean false "Flag indicating whether entities of rollup, transaction and signer should be attached or not. Default: true"
// @Param signers query string false "Comma-separated celestia addresses"
// @Param cursor query integer false "Last entity id which is used for cursor pagination" mininum(1)
// @Produce json
// @Success 200 {array} responses.BlobLog
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace/{id}/{version}/blobs [get]
func (handler *NamespaceHandler) GetBlobLogs(c echo.Context) error {
req, err := bindAndValidate[getBlobLogsForNamespace](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
cm, err := req.getCommitment()
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
ns, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, req.Version)
if err != nil {
return handleError(c, err, handler.namespace)
}
var ids []uint64
if len(req.Signers) > 0 {
hash := make([][]byte, len(req.Signers))
for i := range req.Signers {
_, h, err := types.Address(req.Signers[i]).Decode()
if err != nil {
return badRequestError(c, err)
}
hash[i] = h
}
ids, err = handler.address.IdByHash(c.Request().Context(), hash...)
if err != nil {
return handleError(c, err, handler.namespace)
}
}
fltrs := storage.BlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
Commitment: cm,
Joins: *req.Joins,
Signers: ids,
Cursor: req.Cursor,
}
if req.From > 0 {
fltrs.From = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
fltrs.To = time.Unix(req.To, 0).UTC()
}
logs, err := handler.blobLogs.ByNamespace(
c.Request().Context(),
ns.Id,
fltrs,
)
if err != nil {
return handleError(c, err, handler.namespace)
}
response := make([]responses.BlobLog, len(logs))
for i := range response {
response[i] = responses.NewBlobLog(logs[i])
}
return returnArray(c, response)
}
// Rollups godoc
//
// @Summary List rollups using the namespace
// @Description List rollups using the namespace
// @Tags namespace
// @ID get-namespace-rollups
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param version path integer true "Version of namespace"
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.Rollup
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /namespace/{id}/{version}/rollups [get]
func (handler *NamespaceHandler) Rollups(c echo.Context) error {
req, err := bindAndValidate[listByNamespace](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
ns, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, req.Version)
if err != nil {
return handleError(c, err, handler.namespace)
}
rollups, err := handler.rollups.RollupsByNamespace(
c.Request().Context(),
ns.Id,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.namespace)
}
response := make([]responses.Rollup, len(rollups))
for i := range response {
response[i] = responses.NewRollup(&rollups[i])
}
return returnArray(c, response)
}
// BlobProofs godoc
//
// @Summary Get blob inclusion proofs
// @Description Returns blob inclusion proofs
// @Tags namespace
// @ID get-blob-proof
// @Param request body postBlobRequest true "Request body containing height, commitment and namespace hash"
// @Accept json
// @Produce json
// @Success 200 {object} responses.BlobLog
// @Failure 400 {object} Error
// @Router /blob/proofs [get]
func (handler *NamespaceHandler) BlobProofs(c echo.Context) error {
req, err := bindAndValidate[postBlobRequest](c)
if err != nil {
return badRequestError(c, err)
}
block, err := handler.node.Block(c.Request().Context(), req.Height)
if err != nil {
return handleError(c, err, handler.namespace)
}
dataSquare, err := square.Construct(
block.Block.Data.Txs.ToSliceOfBytes(),
appconsts.SquareSizeUpperBound(0),
appconsts.SubtreeRootThreshold(0),
)
if err != nil {
return internalServerError(c, err)
}
startBlobIndex, endBlobIndex, err := responses.GetBlobShareIndexes(dataSquare, req.Hash, req.Commitment)
if err != nil {
return internalServerError(c, err)
}
blobSharesRange := share.Range{
Start: startBlobIndex,
End: endBlobIndex,
}
eds, err := da.ExtendShares(share.ToBytes(dataSquare))
if err != nil {
return internalServerError(c, err)
}
namespaceBytes, err := base64.StdEncoding.DecodeString(req.Hash)
if err != nil {
return internalServerError(c, err)
}
namespace, err := share.NewNamespaceFromBytes(namespaceBytes)
if err != nil {
return internalServerError(c, err)
}
proofs, err := proof.NewShareInclusionProofFromEDS(eds, namespace, blobSharesRange)
if err != nil {
return handleError(c, err, handler.namespace)
}
return c.JSON(http.StatusOK, responses.NewProofs(proofs.ShareProofs))
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"strings"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/labstack/echo/v4"
)
const (
asc = "asc"
desc = "desc"
)
type limitOffsetPagination struct {
Limit int `json:"limit" param:"limit" query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `json:"offset" param:"offset" query:"offset" validate:"omitempty,min=0"`
Sort string `json:"sort" param:"sort" query:"sort" validate:"omitempty,oneof=asc desc"`
}
func (p *limitOffsetPagination) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
}
func pgSort(sort string) storage.SortOrder {
switch sort {
case asc:
return storage.SortOrderAsc
case desc:
return storage.SortOrderDesc
default:
return storage.SortOrderAsc
}
}
type txListRequest struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
Height *uint64 `query:"height" validate:"omitempty,min=0"`
Status StringArray `query:"status" validate:"omitempty,dive,status"`
MsgType StringArray `query:"msg_type" validate:"omitempty,dive,msg_type"`
ExcludedMsgType StringArray `query:"excluded_msg_type" validate:"omitempty,dive,msg_type"`
Messages bool `query:"messages" validate:"omitempty"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
func (p *txListRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
}
type StringArray []string
func (s *StringArray) UnmarshalParam(param string) error {
*s = StringArray(strings.Split(param, ","))
return nil
}
type StatusArray StringArray
type MsgTypeArray StringArray
func bindAndValidate[T any](c echo.Context) (*T, error) {
req := new(T)
if err := c.Bind(req); err != nil {
return req, err
}
if err := c.Validate(req); err != nil {
return req, err
}
return req, nil
}
type addressTxRequest struct {
Hash string `param:"hash" validate:"required,address"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
Height *uint64 `query:"height" validate:"omitempty,min=0"`
Status StringArray `query:"status" validate:"omitempty,dive,status"`
MsgType StringArray `query:"msg_type" validate:"omitempty,dive,msg_type"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
func (p *addressTxRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
}
type listMessageByBlockRequest struct {
Height pkgTypes.Level `param:"height" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
MsgType StringArray `query:"msg_type" validate:"omitempty,dive,msg_type"`
ExcludedMsgType StringArray `query:"excluded_msg_type" validate:"omitempty,dive,msg_type"`
}
func (p *listMessageByBlockRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
type namespaceList struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time pfb_count size"`
}
func (p *namespaceList) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = desc
}
}
type getById struct {
Id uint64 `param:"id" validate:"required,min=1"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/labstack/echo/v4"
)
func returnArray[T any](c echo.Context, arr []T) error {
if arr == nil {
return c.JSON(http.StatusOK, []any{})
}
return c.JSON(http.StatusOK, arr)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
)
// Address model info
//
// @Description Celestia address information
type Address struct {
Id uint64 `example:"321" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" json:"first_height" swaggertype:"integer"`
LastHeight pkgTypes.Level `example:"100" json:"last_height" swaggertype:"integer"`
Hash string `example:"celestia1jc92qdnty48pafummfr8ava2tjtuhfdw774w60" json:"hash" swaggertype:"string"`
Balance Balance `json:"balance"`
Celestials *Celestial `json:"celestials,omitempty"`
}
func NewAddress(addr storage.Address) Address {
address := Address{
Id: addr.Id,
Height: addr.Height,
LastHeight: addr.LastHeight,
Hash: addr.Address,
Balance: Balance{
Currency: addr.Balance.Currency,
Spendable: addr.Balance.Spendable.String(),
Delegated: addr.Balance.Delegated.String(),
Unbonding: addr.Balance.Unbonding.String(),
},
}
address.AddCelestails(addr.Celestials)
return address
}
func (address *Address) AddCelestails(celestials *celestials.Celestial) {
if celestials != nil {
address.Celestials = NewCelestial(celestials)
}
}
// Balance info
//
// @Description Balance of address information
type Balance struct {
Currency string `example:"utia" json:"currency" swaggertype:"string"`
Spendable string `example:"10000000000" json:"spendable" swaggertype:"string"`
Delegated string `example:"10000000000" json:"delegated" swaggertype:"string"`
Unbonding string `example:"10000000000" json:"unbonding" swaggertype:"string"`
}
// Celestial ID
//
// @Description Linked celestial id
type Celestial struct {
Name string `example:"name" json:"name" swaggertype:"string"`
ImageUrl string `example:"https://ipfs.io/ipfs/QmUi269vE25fagqhyMCCTNSoiW6x4LHCwwQb3keSrEXAmC" json:"image_url" swaggertype:"string"`
Status string `example:"VERIFIED" json:"status,omitempty" swaggertype:"string"`
IsPrimary bool `example:"true" json:"primary,omitempty" swaggertype:"boolean"`
}
func NewCelestial(c *celestials.Celestial) *Celestial {
return &Celestial{
ImageUrl: c.ImageUrl,
Name: c.Id,
IsPrimary: c.Status == celestials.StatusPRIMARY,
Status: c.Status.String(),
}
}
type ShortAddress struct {
Hash string `example:"celestia1jc92qdnty48pafummfr8ava2tjtuhfdw774w60" json:"hash" swaggertype:"string"`
Celestials *Celestial `json:"celestials,omitempty"`
}
func NewShortAddress(address *storage.Address) *ShortAddress {
if address == nil {
return nil
}
result := new(ShortAddress)
result.Hash = address.Address
if address.Celestials != nil {
result.Celestials = NewCelestial(address.Celestials)
}
return result
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/base64"
"encoding/hex"
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
)
type Blob struct {
Namespace string `example:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAs2bWWU6FOB0=" format:"base64" json:"namespace" swaggertype:"string"`
Data string `example:"b2sgZGVtbyBkYQ==" format:"base64" json:"data" swaggertype:"string"`
ShareVersion int `example:"0" format:"integer" json:"share_version" swaggertype:"integer"`
Commitment string `example:"vbGakK59+Non81TE3ULg5Ve5ufT9SFm/bCyY+WLR3gg=" format:"base64" json:"commitment" swaggertype:"string"`
ContentType string `example:"image/png" format:"string" json:"content_type" swaggertype:"string"`
}
func NewBlob(blob types.Blob) (Blob, error) {
b := Blob{
Namespace: blob.Namespace,
Data: blob.Data,
Commitment: blob.Commitment,
ShareVersion: blob.ShareVersion,
}
data, err := base64.StdEncoding.DecodeString(blob.Data)
if err != nil {
return b, err
}
b.ContentType = http.DetectContentType(data)
return b, nil
}
type BlobLog struct {
Id uint64 `example:"200" format:"integer" json:"id" swaggertype:"integer"`
Commitment string `example:"vbGakK59+Non81TE3ULg5Ve5ufT9SFm/bCyY+WLR3gg=" format:"base64" json:"commitment" swaggertype:"string"`
Size int64 `example:"10" format:"integer" json:"size" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"integer" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
ContentType string `example:"image/png" format:"string" json:"content_type" swaggertype:"string"`
Namespace *Namespace `json:"namespace,omitempty"`
Tx *Tx `json:"tx,omitempty"`
Rollup *ShortRollup `json:"rollup,omitempty"`
Signer *ShortAddress `json:"signer,omitempty"`
}
func NewBlobLog(blob storage.BlobLog) BlobLog {
b := BlobLog{
Id: blob.Id,
Commitment: blob.Commitment,
Size: blob.Size,
Height: blob.Height,
Time: blob.Time,
ContentType: blob.ContentType,
Rollup: NewShortRollup(blob.Rollup),
Signer: NewShortAddress(blob.Signer),
}
if blob.Namespace != nil {
ns := NewNamespace(*blob.Namespace)
b.Namespace = &ns
}
if blob.Tx != nil {
tx := NewTx(*blob.Tx)
b.Tx = &tx
}
return b
}
type LightBlobLog struct {
Id uint64 `example:"200" format:"integer" json:"id" swaggertype:"integer"`
Commitment string `example:"vbGakK59+Non81TE3ULg5Ve5ufT9SFm/bCyY+WLR3gg=" format:"base64" json:"commitment" swaggertype:"string"`
Size int64 `example:"10" format:"integer" json:"size" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"integer" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
ContentType string `example:"image/png" format:"string" json:"content_type" swaggertype:"string"`
Namespace string `example:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAs2bWWU6FOB0=" format:"base64" json:"namespace" swaggertype:"string"`
TxHash string `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" format:"binary" json:"tx_hash" swaggertype:"string"`
Signer *ShortAddress `json:"signer,omitempty"`
}
func NewLightBlobLog(blob storage.BlobLog) LightBlobLog {
b := LightBlobLog{
Id: blob.Id,
Commitment: blob.Commitment,
Size: blob.Size,
Height: blob.Height,
Time: blob.Time,
ContentType: blob.ContentType,
Signer: NewShortAddress(blob.Signer),
}
if blob.Namespace != nil {
b.Namespace = blob.Namespace.Hash()
}
if blob.Tx != nil {
b.TxHash = hex.EncodeToString(blob.Tx.Hash)
}
return b
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"github.com/celestiaorg/celestia-app/v3/pkg/proof"
)
type BlobProof struct {
Start int32 `example:"0" format:"integer" json:"start" swaggertype:"integer"`
End int32 `example:"16" format:"integer" json:"end" swaggertype:"integer"`
Nodes [][]byte `json:"nodes"`
}
func NewProofs(proofs []*proof.NMTProof) []BlobProof {
result := make([]BlobProof, len(proofs))
for i := range proofs {
result[i] = BlobProof{
Start: proofs[i].Start,
End: proofs[i].End,
Nodes: proofs[i].Nodes,
}
}
return result
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"fmt"
"strconv"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
coreTypes "github.com/tendermint/tendermint/types"
)
type Block struct {
Id uint64 `example:"321" json:"id" swaggertype:"integer"`
Height uint64 `example:"100" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" json:"time" swaggertype:"string"`
VersionBlock string `example:"11" json:"version_block" swaggertype:"string"`
VersionApp string `example:"1" json:"version_app" swaggertype:"string"`
Hash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"hash" swaggertype:"string"`
ParentHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"parent_hash" swaggertype:"string"`
LastCommitHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"last_commit_hash" swaggertype:"string"`
DataHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"data_hash" swaggertype:"string"`
ValidatorsHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"validators_hash" swaggertype:"string"`
NextValidatorsHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"next_validators_hash" swaggertype:"string"`
ConsensusHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"consensus_hash" swaggertype:"string"`
AppHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"app_hash" swaggertype:"string"`
LastResultsHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"last_results_hash" swaggertype:"string"`
EvidenceHash pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"evidence_hash" swaggertype:"string"`
Proposer *ShortValidator `json:"proposer,omitempty"`
MessageTypes []types.MsgType `example:"MsgSend,MsgUnjail" json:"message_types" swaggertype:"array,string"`
Stats *BlockStats `json:"stats,omitempty"`
}
func NewBlock(block storage.Block, withStats bool) Block {
result := Block{
Id: block.Id,
Height: uint64(block.Height),
Time: block.Time,
VersionBlock: strconv.FormatUint(block.VersionBlock, 10),
VersionApp: strconv.FormatUint(block.VersionApp, 10),
Hash: block.Hash,
ParentHash: block.ParentHash,
LastCommitHash: block.LastCommitHash,
DataHash: block.DataHash,
ValidatorsHash: block.ValidatorsHash,
NextValidatorsHash: block.NextValidatorsHash,
ConsensusHash: block.ConsensusHash,
AppHash: block.AppHash,
LastResultsHash: block.LastResultsHash,
EvidenceHash: block.EvidenceHash,
MessageTypes: block.MessageTypes.Names(),
}
result.Proposer = NewShortValidator(block.Proposer)
if withStats {
result.Stats = NewBlockStats(block.Stats)
}
return result
}
type BlockStats struct {
TxCount int64 `example:"12" json:"tx_count" swaggertype:"integer"`
EventsCount int64 `example:"18" json:"events_count" swaggertype:"integer"`
BlobsSize int64 `example:"12354" json:"blobs_size" swaggertype:"integer"`
BlobsCount int `example:"100" json:"blobs_count" swaggertype:"integer"`
Fee string `example:"28347628346" json:"fee" swaggertype:"string"`
SupplyChange string `example:"8635234" json:"supply_change" swaggertype:"string"`
InflationRate string `example:"0.0800000" json:"inflation_rate" swaggertype:"string"`
FillRate string `example:"0.0800" json:"fill_rate" swaggertype:"string"`
Rewards string `example:"102102812" json:"rewards" swaggertype:"string"`
Commissions string `example:"123133" json:"commissions" swaggertype:"string"`
BlockTime uint64 `example:"12354" json:"block_time" swaggertype:"integer"`
GasLimit int64 `example:"1234" json:"gas_limit" swaggertype:"integer"`
GasUsed int64 `example:"1234" json:"gas_used" swaggertype:"integer"`
BytesInBlock int64 `example:"1234" json:"bytes_in_block" swaggertype:"integer"`
SquareSize uint64 `example:"16" json:"square_size" swaggertype:"integer"`
}
var (
maxSize = coreTypes.MaxDataBytesNoEvidence(1974272, 100)
)
func NewBlockStats(stats storage.BlockStats) *BlockStats {
return &BlockStats{
TxCount: stats.TxCount,
EventsCount: stats.EventsCount,
BlobsSize: stats.BlobsSize,
BlobsCount: stats.BlobsCount,
Fee: stats.Fee.String(),
SupplyChange: stats.SupplyChange.String(),
InflationRate: stats.InflationRate.String(),
Commissions: stats.Commissions.String(),
Rewards: stats.Rewards.String(),
BlockTime: stats.BlockTime,
GasLimit: stats.GasLimit,
GasUsed: stats.GasUsed,
BytesInBlock: stats.BytesInBlock,
SquareSize: stats.SquareSize,
FillRate: fmt.Sprintf("%.4f", float64(stats.BytesInBlock)/float64(maxSize)),
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
"github.com/goccy/go-json"
"github.com/shopspring/decimal"
)
type Constants struct {
Module map[string]Params `json:"module"`
DenomMetadata []DenomMetadata `json:"denom_metadata"`
}
type Params map[string]string
type DenomMetadata struct {
Description string `example:"Some description" json:"description" swaggertype:"string"`
Base string `example:"utia" json:"base" swaggertype:"string"`
Display string `example:"TIA" json:"display" swaggertype:"string"`
Name string `example:"TIA" json:"name" swaggertype:"string"`
Symbol string `example:"TIA" json:"symbol" swaggertype:"string"`
Uri string `example:"https://example.com" json:"uri" swaggertype:"string"`
Units json.RawMessage `json:"units"`
}
func roundCounstant(val string) string {
d, err := decimal.NewFromString(val)
if err != nil {
return val
}
return d.String()
}
func NewConstants(consts []storage.Constant, denomMetadata []storage.DenomMetadata) Constants {
response := Constants{
Module: make(map[string]Params),
DenomMetadata: make([]DenomMetadata, len(denomMetadata)),
}
for i := range consts {
if params, ok := response.Module[string(consts[i].Module)]; ok {
params[consts[i].Name] = roundCounstant(consts[i].Value)
} else {
response.Module[string(consts[i].Module)] = Params{
consts[i].Name: roundCounstant(consts[i].Value),
}
}
}
for i := range denomMetadata {
response.DenomMetadata[i].Base = denomMetadata[i].Base
response.DenomMetadata[i].Symbol = denomMetadata[i].Symbol
response.DenomMetadata[i].Name = denomMetadata[i].Name
response.DenomMetadata[i].Description = denomMetadata[i].Description
response.DenomMetadata[i].Display = denomMetadata[i].Display
response.DenomMetadata[i].Uri = denomMetadata[i].Uri
response.DenomMetadata[i].Units = denomMetadata[i].Units
}
return response
}
type Enums struct {
Status []string `json:"status"`
MessageType []string `json:"message_type"`
EventType []string `json:"event_type"`
Categories []string `json:"categories"`
RollupTypes []string `json:"rollup_type"`
Tags []string `json:"tags"`
CelestialsStatuses []string `json:"celestials_statuses"`
}
func NewEnums(tags []string) Enums {
return Enums{
Status: types.StatusNames(),
MessageType: types.MsgTypeNames(),
EventType: types.EventTypeNames(),
Categories: types.RollupCategoryNames(),
RollupTypes: types.RollupTypeNames(),
Tags: tags,
CelestialsStatuses: celestials.StatusNames(),
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
)
type Delegation struct {
Amount string `example:"0.1" json:"amount" swaggertype:"string"`
Delegator *ShortAddress `json:"delegator,omitempty"`
Validator *ShortValidator `json:"validator,omitempty"`
}
func NewDelegation(d storage.Delegation) Delegation {
delegation := Delegation{
Amount: d.Amount.String(),
Delegator: NewShortAddress(d.Address),
}
if d.Validator != nil {
delegation.Validator = NewShortValidator(*d.Validator)
}
return delegation
}
type Undelegation struct {
Height pkgTypes.Level `example:"100" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" json:"time" swaggertype:"string"`
CompletionTime time.Time `example:"2023-07-04T03:10:57+00:00" json:"completion_time" swaggertype:"string"`
Amount string `example:"0.1" json:"amount" swaggertype:"string"`
Delegator *ShortAddress `json:"delegator,omitempty"`
Validator *ShortValidator `json:"validator,omitempty"`
}
func NewUndelegation(d storage.Undelegation) Undelegation {
undelegation := Undelegation{
Amount: d.Amount.String(),
Time: d.Time,
CompletionTime: d.CompletionTime,
Height: d.Height,
Delegator: NewShortAddress(d.Address),
}
if d.Validator != nil {
undelegation.Validator = NewShortValidator(*d.Validator)
}
return undelegation
}
type Redelegation struct {
Height pkgTypes.Level `example:"100" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" json:"time" swaggertype:"string"`
CompletionTime time.Time `example:"2023-07-04T03:10:57+00:00" json:"completion_time" swaggertype:"string"`
Amount string `example:"0.1" json:"amount" swaggertype:"string"`
Delegator *ShortAddress `json:"delegator,omitempty"`
Source *ShortValidator `json:"source,omitempty"`
Destination *ShortValidator `json:"destination,omitempty"`
}
func NewRedelegation(d storage.Redelegation) Redelegation {
redelegation := Redelegation{
Amount: d.Amount.String(),
Time: d.Time,
CompletionTime: d.CompletionTime,
Height: d.Height,
Delegator: NewShortAddress(d.Address),
}
if d.Source != nil {
redelegation.Source = NewShortValidator(*d.Source)
}
if d.Destination != nil {
redelegation.Destination = NewShortValidator(*d.Destination)
}
return redelegation
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
)
type Event struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"int64" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Position int64 `example:"1" format:"int64" json:"position" swaggertype:"integer"`
TxId uint64 `example:"11" format:"int64" json:"tx_id,omitempty" swaggertype:"integer"`
Type types.EventType `example:"commission" json:"type"`
Data map[string]any `json:"data"`
}
func NewEvent(event storage.Event) Event {
result := Event{
Id: event.Id,
Height: event.Height,
Time: event.Time,
Position: event.Position,
Type: event.Type,
Data: event.Data,
}
if event.TxId != nil {
result.TxId = *event.TxId
}
return result
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
type Grant struct {
Authorization string `example:"/cosmos.staking.v1beta1.MsgDelegate" json:"authorization" swaggertype:"string"`
Expiration *time.Time `example:"2023-07-04T03:10:57+00:00" json:"expiration,omitempty" swaggertype:"string"`
Revoked bool `example:"true" json:"revoked" swaggertype:"boolean"`
RevokeHeight uint64 `example:"123123" json:"revoke_height,omitempty" swaggertype:"integer"`
Height uint64 `example:"123123" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" json:"time" swaggertype:"string"`
Params map[string]any `json:"params"`
Granter *ShortAddress `json:"granter,omitempty"`
Grantee *ShortAddress `json:"grantee,omitempty"`
}
func NewGrant(g storage.Grant) Grant {
grant := Grant{
Height: uint64(g.Height),
Authorization: g.Authorization,
Expiration: g.Expiration,
Revoked: g.Revoked,
Params: g.Params,
Time: g.Time,
Granter: NewShortAddress(g.Granter),
Grantee: NewShortAddress(g.Grantee),
}
if g.RevokeHeight != nil {
grant.RevokeHeight = uint64(*g.RevokeHeight)
}
return grant
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
type HistogramItem struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Value string `example:"2223424" format:"string" json:"value" swaggertype:"string"`
}
func NewHistogramItem(item storage.HistogramItem) HistogramItem {
return HistogramItem{
Time: item.Time,
Value: item.Value,
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
)
type Message struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"int64" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Position int64 `example:"2" format:"int64" json:"position" swaggertype:"integer"`
Size int `example:"2" format:"int" json:"size" swaggertype:"integer"`
TxId uint64 `example:"11" format:"int64" json:"tx_id,omitempty" swaggertype:"integer"`
Type types.MsgType `example:"MsgCreatePeriodicVestingAccount" json:"type"`
Data map[string]any `json:"data"`
Tx *Tx `json:"tx,omitempty"`
}
func NewMessage(msg storage.Message) Message {
return Message{
Id: msg.Id,
Height: msg.Height,
Time: msg.Time,
Position: msg.Position,
Type: msg.Type,
TxId: msg.TxId,
Size: msg.Size,
Data: msg.Data,
}
}
func NewMessageWithTx(msg storage.MessageWithTx) Message {
message := Message{
Id: msg.Id,
Height: msg.Height,
Time: msg.Time,
Position: msg.Position,
Type: msg.Type,
TxId: msg.TxId,
Size: msg.Size,
Data: msg.Data,
}
if msg.Tx != nil {
tx := NewTx(*msg.Tx)
message.Tx = &tx
}
return message
}
type MessageForAddress struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"int64" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Position int64 `example:"2" format:"int64" json:"position" swaggertype:"integer"`
Size int `example:"2" format:"int" json:"size" swaggertype:"integer"`
TxId uint64 `example:"11" format:"int64" json:"tx_id,omitempty" swaggertype:"integer"`
Type types.MsgType `example:"MsgCreatePeriodicVestingAccount" json:"type"`
InvocationType types.MsgAddressType `example:"fromAddress" json:"invocation_type"`
Data map[string]any `json:"data"`
Tx TxForAddress `json:"tx"`
}
func NewMessageForAddress(msg storage.AddressMessageWithTx) MessageForAddress {
message := MessageForAddress{
Id: msg.MsgId,
Height: msg.Msg.Height,
Time: msg.Msg.Time,
Position: msg.Msg.Position,
TxId: msg.Msg.TxId,
Type: msg.Msg.Type,
Size: msg.Msg.Size,
Data: msg.Msg.Data,
Tx: NewTxForAddress(msg.Tx),
InvocationType: msg.Type,
}
return message
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"bytes"
"encoding/hex"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
type Namespace struct {
ID uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Size int64 `example:"12345" format:"integer" json:"size" swaggertype:"integer"`
BlobsCount int64 `example:"10000" format:"integer" json:"blobs_count" swaggertype:"integer"`
Version byte `examle:"1" format:"byte" json:"version" swaggertype:"integer"`
NamespaceID string `example:"4723ce10b187716adfc55ff7e6d9179c226e6b5440b02577cca49d02" format:"binary" json:"namespace_id" swaggertype:"string"`
Hash string `example:"U3dhZ2dlciByb2Nrcw==" format:"base64" json:"hash" swaggertype:"string"`
PfbCount int64 `example:"12" format:"integer" json:"pfb_count" swaggertype:"integer"`
LastHeight pkgTypes.Level `example:"100" format:"int64" json:"last_height" swaggertype:"integer"`
LastMessageTime time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"last_message_time" swaggertype:"string"`
Name string `example:"name" format:"string" json:"name" swaggertype:"string"`
Reserved bool `example:"true" json:"reserved"`
}
func NewNamespace(ns storage.Namespace) Namespace {
return Namespace{
ID: ns.Id,
Size: ns.Size,
BlobsCount: ns.BlobsCount,
Version: ns.Version,
NamespaceID: hex.EncodeToString(ns.NamespaceID),
Name: decodeName(ns.NamespaceID),
Hash: ns.Hash(),
Reserved: ns.Reserved,
PfbCount: ns.PfbCount,
LastHeight: ns.LastHeight,
LastMessageTime: ns.LastMessageTime,
}
}
func decodeName(nsId []byte) string {
var (
trimmed = bytes.TrimLeft(nsId, "\x00")
data = make([]byte, 0)
isDecodable = true
)
for i := range trimmed {
if trimmed[i] < 0x20 || trimmed[i] > 0x7f {
isDecodable = false
}
data = append(data, trimmed[i])
}
if isDecodable {
return string(data)
}
return hex.EncodeToString(data)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/pkg/errors"
)
type NamespaceMessage struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Height int64 `example:"100" format:"int64" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Position int64 `example:"2" format:"int64" json:"position" swaggertype:"integer"`
Type string `enums:"MsgWithdrawValidatorCommission,MsgWithdrawDelegatorReward,MsgEditValidator,MsgBeginRedelegate,MsgCreateValidator,MsgDelegate,MsgUndelegate,MsgUnjail,MsgSend,MsgCreateVestingAccount,MsgCreatePeriodicVestingAccount,MsgPayForBlobs,MsgGrantAllowance" example:"MsgCreatePeriodicVestingAccount" format:"string" json:"type" swaggertype:"string"`
Data map[string]any `json:"data"`
Tx Tx `json:"tx"`
Namespace Namespace `json:"namespace"`
}
func NewNamespaceMessage(msg storage.NamespaceMessage) (NamespaceMessage, error) {
if msg.Message == nil {
return NamespaceMessage{}, errors.New("nil message in namespace message constructor")
}
if msg.Tx == nil {
return NamespaceMessage{}, errors.New("nil tx in namespace message constructor")
}
if msg.Namespace == nil {
return NamespaceMessage{}, errors.New("nil namespace in namespace message constructor")
}
return NamespaceMessage{
Id: msg.Message.Id,
Height: int64(msg.Message.Height),
Time: msg.Message.Time,
Position: msg.Message.Position,
Type: string(msg.Message.Type),
Data: msg.Message.Data,
Tx: NewTx(*msg.Tx),
Namespace: NewNamespace(*msg.Namespace),
}, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"bytes"
"encoding/base64"
"github.com/celestiaorg/celestia-app/v3/pkg/appconsts"
"github.com/celestiaorg/go-square/namespace"
"github.com/celestiaorg/go-square/shares"
"github.com/celestiaorg/go-square/v2/inclusion"
"github.com/celestiaorg/go-square/v2/share"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/merkle"
_ "github.com/celestiaorg/go-square/v2/share"
"github.com/celestiaorg/rsmt2d"
)
type ODS struct {
Width uint `example:"2" json:"width" swaggertype:"integer"`
Items []ODSItem `json:"items"`
}
type ODSItem struct {
From []uint `json:"from"`
To []uint `json:"to"`
Namespace string `json:"namespace"`
Type NamespaceKind `json:"type"`
}
func NewODS(eds *rsmt2d.ExtendedDataSquare) (ODS, error) {
ods := ODS{
Width: eds.Width() / 2,
Items: make([]ODSItem, 0),
}
var current ODSItem
for i := uint(0); i < ods.Width; i++ {
for j := uint(0); j < ods.Width; j++ {
cell := eds.GetCell(i, j)
share, err := shares.NewShare(cell)
if err != nil {
return ods, err
}
namespace, err := share.Namespace()
if err != nil {
return ods, err
}
base64Namespace := base64.StdEncoding.EncodeToString(namespace.Bytes())
if base64Namespace != current.Namespace {
if current.Namespace != "" {
ods.Items = append(ods.Items, current)
}
current = ODSItem{
From: []uint{i, j},
Namespace: base64Namespace,
Type: getNamespaceType(namespace),
}
}
current.To = []uint{i, j}
}
}
ods.Items = append(ods.Items, current)
return ods, nil
}
type NamespaceKind string
const (
PayForBlobNamespace NamespaceKind = "pay_for_blob"
TailPaddingNamespace NamespaceKind = "tail_padding"
TxNamespace NamespaceKind = "tx"
ParitySharesNamespace NamespaceKind = "parity_shares"
PrimaryReservedNamespace NamespaceKind = "primary_reserved_padding"
DefaultNamespace NamespaceKind = "namespace"
)
func getNamespaceType(ns namespace.Namespace) NamespaceKind {
switch {
case ns.IsPayForBlob():
return PayForBlobNamespace
case ns.IsTailPadding():
return TailPaddingNamespace
case ns.IsTx():
return TxNamespace
case ns.IsParityShares():
return ParitySharesNamespace
case ns.IsPrimaryReservedPadding():
return PrimaryReservedNamespace
default:
return DefaultNamespace
}
}
type sequence struct {
ns share.Namespace
shareVersion uint8
startShareIdx int
endShareIdx int
data []byte
sequenceLen uint32
signer []byte
}
func GetBlobShareIndexes(
shares []share.Share,
base64namespace string,
base64commitment string,
) (blobStartIndex, blobEndIndex int, err error) {
if len(shares) == 0 {
return 0, 0, errors.New("invalid shares length")
}
sequences := make([]sequence, 0)
namespaceBytes, err := base64.StdEncoding.DecodeString(base64namespace)
if err != nil {
return 0, 0, errors.Wrap(err, "decoding base64 namespace")
}
for shareIndex, s := range shares {
if !(s.Version() <= 1) {
return 0, 0, errors.New("unsupported share version")
}
if s.IsPadding() {
continue
}
if !bytes.Equal(s.Namespace().Bytes(), namespaceBytes) {
continue
}
if s.IsSequenceStart() {
sequences = append(sequences, sequence{
ns: s.Namespace(),
shareVersion: s.Version(),
startShareIdx: shareIndex,
endShareIdx: shareIndex,
data: s.RawData(),
sequenceLen: s.SequenceLen(),
signer: share.GetSigner(s),
})
} else {
if len(sequences) == 0 {
return 0, 0, errors.New("continuation share without a s start share")
}
prev := &sequences[len(sequences)-1]
prev.data = append(prev.data, s.RawData()...)
prev.endShareIdx = shareIndex
}
}
for _, s := range sequences {
s.data = s.data[:s.sequenceLen]
blob, err := share.NewBlob(s.ns, s.data, s.shareVersion, s.signer)
if err != nil {
return 0, 0, errors.Wrap(err, "creating blob")
}
commitment, err := inclusion.CreateCommitment(blob, merkle.HashFromByteSlices, appconsts.SubtreeRootThreshold(0))
if err != nil {
return 0, 0, errors.Wrap(err, "creating commitment")
}
if base64.StdEncoding.EncodeToString(commitment) == base64commitment {
return s.startShareIdx, s.endShareIdx + 1, err
}
}
return 0, 0, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/shopspring/decimal"
)
type RollupWithStats struct {
Id uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Name string `example:"Rollup name" format:"string" json:"name" swaggertype:"string"`
Description string `example:"Long rollup description" format:"string" json:"description,omitempty" swaggertype:"string"`
Website string `example:"https://website.com" format:"string" json:"website,omitempty" swaggertype:"string"`
Twitter string `example:"https://x.com/account" format:"string" json:"twitter,omitempty" swaggertype:"string"`
Github string `example:"https://github.com/account" format:"string" json:"github,omitempty" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Slug string `example:"rollup_slug" format:"string" json:"slug" swaggertype:"string"`
L2Beat string `example:"https://l2beat.com/scaling/projects/karak" format:"string" json:"l2_beat,omitempty" swaggertype:"string"`
DeFiLama string `example:"Manta" format:"string" json:"defi_lama,omitempty" swaggertype:"string"`
Explorer string `example:"https://explorer.karak.network/" format:"string" json:"explorer,omitempty" swaggertype:"string"`
BridgeContract string `example:"https://github.com/account" format:"string" json:"bridge,omitempty" swaggertype:"string"`
Stack string `example:"op_stack" format:"string" json:"stack,omitempty" swaggertype:"string"`
Type string `example:"settled" format:"string" json:"type,omitempty" swaggertype:"string"`
Category string `example:"nft" format:"string" json:"category,omitempty" swaggertype:"string"`
VM string `example:"evm" format:"string" json:"vm,omitempty" swaggertype:"string"`
Provider string `example:"name" format:"string" json:"provider,omitempty" swaggertype:"string"`
Compression string `example:"zip" format:"string" json:"compression,omitempty" swaggertype:"string"`
BlobsCount int64 `example:"2" format:"integer" json:"blobs_count" swaggertype:"integer"`
Size int64 `example:"1000" format:"integer" json:"size" swaggertype:"integer"`
LastAction time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"last_message_time" swaggertype:"string"`
FirstAction time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"first_message_time" swaggertype:"string"`
Fee string `example:"123.456789" format:"string" json:"fee" swaggertype:"string"`
SizePct float64 `example:"0.9876" format:"float" json:"size_pct" swaggertype:"number"`
FeePct float64 `example:"0.9876" format:"float" json:"fee_pct" swaggertype:"number"`
BlobsCountPct float64 `example:"0.9876" format:"float" json:"blobs_count_pct" swaggertype:"number"`
DAPct float64 `example:"0.9876" format:"float" json:"da_pct" swaggertype:"number"`
Tags []string `json:"tags,omitempty"`
Links []string `json:"links,omitempty"`
}
func NewRollupWithStats(r storage.RollupWithStats) RollupWithStats {
return RollupWithStats{
Id: r.Id,
Name: r.Name,
Description: r.Description,
Github: r.GitHub,
Twitter: r.Twitter,
Website: r.Website,
Logo: r.Logo,
L2Beat: r.L2Beat,
DeFiLama: r.DeFiLama,
Explorer: r.Explorer,
BridgeContract: r.BridgeContract,
Links: r.Links,
Stack: r.Stack,
Slug: r.Slug,
BlobsCount: r.BlobsCount,
Size: r.Size,
SizePct: r.SizePct,
BlobsCountPct: r.BlobsCountPct,
DAPct: r.DAPct,
FeePct: r.FeePct,
LastAction: r.LastActionTime,
FirstAction: r.FirstActionTime,
Compression: r.Compression,
Category: r.Category.String(),
Type: r.Type.String(),
Provider: r.Provider,
VM: r.VM,
Fee: r.Fee.StringFixed(0),
Tags: r.Tags,
}
}
type Rollup struct {
Id uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Name string `example:"Rollup name" format:"string" json:"name" swaggertype:"string"`
Description string `example:"Long rollup description" format:"string" json:"description,omitempty" swaggertype:"string"`
Website string `example:"https://website.com" format:"string" json:"website,omitempty" swaggertype:"string"`
Twitter string `example:"https://x.com/account" format:"string" json:"twitter,omitempty" swaggertype:"string"`
Github string `example:"https://github.com/account" format:"string" json:"github,omitempty" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Slug string `example:"rollup_slug" format:"string" json:"slug" swaggertype:"string"`
L2Beat string `example:"https://github.com/account" format:"string" json:"l2_beat,omitempty" swaggertype:"string"`
DeFiLama string `example:"Manta" format:"string" json:"defi_lama,omitempty" swaggertype:"string"`
Explorer string `example:"https://explorer.karak.network/" format:"string" json:"explorer,omitempty" swaggertype:"string"`
BridgeContract string `example:"https://github.com/account" format:"string" json:"bridge,omitempty" swaggertype:"string"`
Stack string `example:"op_stack" format:"string" json:"stack,omitempty" swaggertype:"string"`
Type string `example:"settled" format:"string" json:"type,omitempty" swaggertype:"string"`
Category string `example:"nft" format:"string" json:"category,omitempty" swaggertype:"string"`
Provider string `example:"name" format:"string" json:"provider,omitempty" swaggertype:"string"`
Compression string `example:"zip" format:"string" json:"compression,omitempty" swaggertype:"string"`
VM string `example:"evm" format:"string" json:"vm,omitempty" swaggertype:"string"`
Tags []string `json:"tags,omitempty"`
Links []string `json:"links,omitempty"`
}
func NewRollup(r *storage.Rollup) Rollup {
return Rollup{
Id: r.Id,
Name: r.Name,
Description: r.Description,
Github: r.GitHub,
Twitter: r.Twitter,
Website: r.Website,
Logo: r.Logo,
Slug: r.Slug,
L2Beat: r.L2Beat,
DeFiLama: r.DeFiLama,
BridgeContract: r.BridgeContract,
Stack: r.Stack,
Explorer: r.Explorer,
Links: r.Links,
Compression: r.Compression,
Category: r.Category.String(),
Type: r.Type.String(),
Provider: r.Provider,
VM: r.VM,
Tags: r.Tags,
}
}
type ShortRollup struct {
Id uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Name string `example:"Rollup name" format:"string" json:"name" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Slug string `example:"rollup_slug" format:"string" json:"slug" swaggertype:"string"`
}
func NewShortRollup(r *storage.Rollup) *ShortRollup {
if r == nil {
return nil
}
return &ShortRollup{
Id: r.Id,
Name: r.Name,
Logo: r.Logo,
Slug: r.Slug,
}
}
type RollupWithDayStats struct {
Id uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Name string `example:"Rollup name" format:"string" json:"name" swaggertype:"string"`
Description string `example:"Long rollup description" format:"string" json:"description,omitempty" swaggertype:"string"`
Website string `example:"https://website.com" format:"string" json:"website,omitempty" swaggertype:"string"`
Twitter string `example:"https://x.com/account" format:"string" json:"twitter,omitempty" swaggertype:"string"`
Github string `example:"https://github.com/account" format:"string" json:"github,omitempty" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Slug string `example:"rollup_slug" format:"string" json:"slug" swaggertype:"string"`
L2Beat string `example:"https://l2beat.com/scaling/projects/karak" format:"string" json:"l2_beat,omitempty" swaggertype:"string"`
DeFiLama string `example:"Manta" format:"string" json:"defi_lama,omitempty" swaggertype:"string"`
Explorer string `example:"https://explorer.karak.network/" format:"string" json:"explorer,omitempty" swaggertype:"string"`
BridgeContract string `example:"https://github.com/account" format:"string" json:"bridge,omitempty" swaggertype:"string"`
Stack string `example:"op_stack" format:"string" json:"stack,omitempty" swaggertype:"string"`
Type string `example:"settled" format:"string" json:"type,omitempty" swaggertype:"string"`
Category string `example:"nft" format:"string" json:"category,omitempty" swaggertype:"string"`
Provider string `example:"name" format:"string" json:"provider,omitempty" swaggertype:"string"`
Compression string `example:"zip" format:"string" json:"compression,omitempty" swaggertype:"string"`
VM string `example:"evm" format:"string" json:"vm,omitempty" swaggertype:"string"`
AvgSize int64 `example:"100" format:"integer" json:"avg_size" swaggertype:"integer"`
BlobsCount int64 `example:"100" format:"integer" json:"blobs_count" swaggertype:"integer"`
TotalSize int64 `example:"100" format:"integer" json:"total_size" swaggertype:"integer"`
Throghput int64 `example:"100" format:"integer" json:"throughput" swaggertype:"integer"`
NamespaceCount int64 `example:"100" format:"integer" json:"namespace_count" swaggertype:"integer"`
PfbCount int64 `example:"100" format:"integer" json:"pfb_count" swaggertype:"integer"`
TotalFee string `example:"100" format:"string" json:"total_fee" swaggertype:"string"`
MBPrice string `example:"100" format:"string" json:"mb_price" swaggertype:"string"`
FeePerPfb string `example:"100" format:"string" json:"fee_per_pfb" swaggertype:"string"`
BlobsPerPfb float64 `example:"100" format:"float" json:"blobs_per_pfb" swaggertype:"number"`
}
func NewRollupWithDayStats(r storage.RollupWithDayStats) RollupWithDayStats {
response := RollupWithDayStats{
Id: r.Id,
Name: r.Name,
Description: r.Description,
Github: r.GitHub,
Twitter: r.Twitter,
Website: r.Website,
Logo: r.Logo,
L2Beat: r.L2Beat,
DeFiLama: r.DeFiLama,
Explorer: r.Explorer,
BridgeContract: r.BridgeContract,
Stack: r.Stack,
Compression: r.Compression,
Category: r.Category.String(),
Type: r.Type.String(),
Provider: r.Provider,
VM: r.VM,
Slug: r.Slug,
BlobsCount: r.BlobsCount,
AvgSize: int64(r.AvgSize),
TotalSize: r.TotalSize,
Throghput: r.Throghput,
NamespaceCount: r.NamespaceCount,
PfbCount: r.PfbCount,
TotalFee: r.TotalFee.String(),
MBPrice: r.MBPrice.String(),
FeePerPfb: decimal.Zero.String(),
}
if r.PfbCount > 0 {
response.BlobsPerPfb = float64(r.BlobsCount / r.PfbCount)
response.FeePerPfb = r.TotalFee.Div(decimal.NewFromInt(r.PfbCount)).String()
}
return response
}
type RollupGroupedStats struct {
Fee float64 `example:"123.456789" format:"string" json:"fee" swaggertype:"string"`
Size float64 `example:"1000" format:"integer" json:"size" swaggertype:"integer"`
BlobsCount int64 `example:"2" format:"integer" json:"blobs_count" swaggertype:"integer"`
Group string `example:"group" format:"string" json:"group" swaggertype:"string"`
}
func NewRollupGroupedStats(r storage.RollupGroupedStats) RollupGroupedStats {
response := RollupGroupedStats{
Fee: r.Fee,
Size: r.Size,
BlobsCount: r.BlobsCount,
Group: r.Group,
}
return response
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
type State struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Name string `example:"indexer" format:"string" json:"name" swaggertype:"string"`
ChainId string `example:"mocha-4" format:"string" json:"chain_id" swaggertype:"string"`
LastHeight pkgTypes.Level `example:"100" format:"int64" json:"last_height" swaggertype:"integer"`
LastHash string `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" format:"string" json:"hash" swaggertype:"string"`
LastTime time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"last_time" swaggertype:"string"`
TotalTx int64 `example:"23456" format:"int64" json:"total_tx" swaggertype:"integer"`
TotalAccounts int64 `example:"43" format:"int64" json:"total_accounts" swaggertype:"integer"`
TotalFee string `example:"312" format:"string" json:"total_fee" swaggertype:"string"`
TotalBlobsSize int64 `example:"56789" format:"int64" json:"total_blobs_size" swaggertype:"integer"`
TotalValidators int `example:"100" format:"int64" json:"total_validators" swaggertype:"integer"`
TotalSupply string `example:"312" format:"string" json:"total_supply" swaggertype:"string"`
TotalStake string `example:"312" format:"string" json:"total_stake" swaggertype:"string"`
TotalVotingPower string `example:"312" format:"string" json:"total_voting_power" swaggertype:"string"`
TotalNamespaces int64 `example:"312" format:"string" json:"total_namespaces" swaggertype:"integer"`
Synced bool `example:"true" format:"boolean" json:"synced" swaggertype:"boolean"`
}
func NewState(state storage.State) State {
return State{
Id: state.Id,
Name: state.Name,
ChainId: state.ChainId,
LastHeight: state.LastHeight,
LastHash: hex.EncodeToString(state.LastHash),
LastTime: state.LastTime,
TotalTx: state.TotalTx,
TotalAccounts: state.TotalAccounts,
TotalFee: state.TotalFee.String(),
TotalBlobsSize: state.TotalBlobsSize,
TotalValidators: state.TotalValidators,
TotalNamespaces: state.TotalNamespaces,
TotalSupply: state.TotalSupply.String(),
TotalStake: state.TotalStake.String(),
TotalVotingPower: state.TotalVotingPower.String(),
Synced: !state.LastTime.UTC().Add(2 * time.Minute).Before(time.Now().UTC()),
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
"strconv"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
type TPS struct {
High float64 `example:"1.023" format:"float" json:"high" swaggertype:"number"`
Low float64 `example:"0.123" format:"float" json:"low" swaggertype:"number"`
Current float64 `example:"0.567" format:"float" json:"current" swaggertype:"number"`
ChangeLastHourPct float64 `example:"0.275" format:"float" json:"change_last_hour_pct" swaggertype:"number"`
}
func NewTPS(tps storage.TPS) TPS {
return TPS{
High: tps.High,
Low: tps.Low,
Current: tps.Current,
ChangeLastHourPct: tps.ChangeLastHourPct,
}
}
type Change24hBlockStats struct {
TxCount float64 `example:"0.1234" format:"float" json:"tx_count_24h" swaggertype:"number"`
Fee float64 `example:"0.1234" format:"float" json:"fee_24h" swaggertype:"number"`
BytesInBlock float64 `example:"0.1234" format:"float" json:"bytes_in_block_24h" swaggertype:"number"`
BlobsSize float64 `example:"0.1234" format:"float" json:"blobs_size_24h" swaggertype:"number"`
}
func NewChange24hBlockStats(response storage.Change24hBlockStats) Change24hBlockStats {
return Change24hBlockStats{
TxCount: response.TxCount,
Fee: response.Fee,
BytesInBlock: response.BytesInBlock,
BlobsSize: response.BlobsSize,
}
}
type NamespaceUsage struct {
Name string `example:"00112233" format:"string" json:"name" swaggertype:"string"`
Version *byte `examle:"1" format:"byte" json:"version,omitempty" swaggertype:"integer"`
NamespaceID string `example:"4723ce10b187716adfc55ff7e6d9179c226e6b5440b02577cca49d02" format:"binary" json:"namespace_id,omitempty" swaggertype:"string"`
Size int64 `example:"1283518" format:"integer" json:"size" swaggertype:"number"`
}
func NewNamespaceUsage(ns storage.Namespace) NamespaceUsage {
return NamespaceUsage{
Name: decodeName(ns.NamespaceID),
Size: ns.Size,
Version: &ns.Version,
NamespaceID: hex.EncodeToString(ns.NamespaceID),
}
}
type SeriesItem struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Value string `example:"0.17632" format:"string" json:"value" swaggertype:"string"`
Max string `example:"0.17632" format:"string" json:"max,omitempty" swaggertype:"string"`
Min string `example:"0.17632" format:"string" json:"min,omitempty" swaggertype:"string"`
}
func NewSeriesItem(item storage.SeriesItem) SeriesItem {
return SeriesItem{
Time: item.Time,
Value: item.Value,
Max: item.Max,
Min: item.Min,
}
}
type Price struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Open string `example:"0.17632" format:"string" json:"open" swaggertype:"string"`
High string `example:"0.17632" format:"string" json:"high" swaggertype:"string"`
Low string `example:"0.17632" format:"string" json:"low" swaggertype:"string"`
Close string `example:"0.17632" format:"string" json:"close" swaggertype:"string"`
}
func NewPrice(price storage.Price) Price {
return Price{
Time: price.Time,
Open: price.Open.String(),
High: price.High.String(),
Low: price.Low.String(),
Close: price.Close.String(),
}
}
type DistributionItem struct {
Name string `example:"12" format:"string" json:"name" swaggertype:"string"`
Value string `example:"0.17632" format:"string" json:"value" swaggertype:"string"`
}
func NewDistributionItem(item storage.DistributionItem, tf string) (result DistributionItem) {
result.Value = item.Value
switch tf {
case "day":
result.Name = time.Weekday(item.Name % 7).String()
case "hour":
result.Name = strconv.FormatInt(int64(item.Name), 10)
default:
result.Name = strconv.FormatInt(int64(item.Name), 10)
}
return
}
type TimeValueItem struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Value string `example:"0.17632" format:"string" json:"value" swaggertype:"string"`
}
type SquareSizeResponse map[int][]TimeValueItem
func NewSquareSizeResponse(m map[int][]storage.SeriesItem) SquareSizeResponse {
response := make(SquareSizeResponse)
for key, value := range m {
response[key] = make([]TimeValueItem, len(value))
for i := range value {
response[key][i].Time = value[i].Time
response[key][i].Value = value[i].Value
}
}
return response
}
type RollupStats24h struct {
Id int64 `example:"321" format:"integer" json:"id,omitempty" swaggertype:"integer"`
Name string `example:"Rollup name" format:"string" json:"name,omitempty" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Size int64 `example:"123" format:"integer" json:"size" swaggertype:"integer"`
Fee float64 `example:"123" format:"number" json:"fee" swaggertype:"integer"`
BlobsCount int64 `example:"123" format:"integer" json:"blobs_count" swaggertype:"integer"`
}
func NewRollupStats24h(stats storage.RollupStats24h) RollupStats24h {
return RollupStats24h{
Id: stats.RollupId,
Name: stats.Name,
Logo: stats.Logo,
Size: stats.Size,
Fee: stats.Fee,
BlobsCount: stats.BlobsCount,
}
}
type CountItem struct {
Name string `example:"test" format:"string" json:"name" swaggertype:"string"`
Value int64 `example:"17632" format:"string" json:"value" swaggertype:"string"`
}
func NewCountItem(item storage.CountItem) CountItem {
return CountItem{
Name: item.Name,
Value: item.Value,
}
}
type RollupAllSeriesItem struct {
Name string `example:"Rollup name" format:"string" json:"name,omitempty" swaggertype:"string"`
Logo string `example:"https://some_link.com/image.png" format:"string" json:"logo,omitempty" swaggertype:"string"`
Size int64 `example:"123" format:"integer" json:"size" swaggertype:"integer"`
Fee string `example:"123" format:"string" json:"fee" swaggertype:"string"`
BlobsCount int64 `example:"123" format:"integer" json:"blobs_count" swaggertype:"integer"`
}
func NewRollupAllSeriesItem(stats storage.RollupHistogramItem) RollupAllSeriesItem {
return RollupAllSeriesItem{
Name: stats.Name,
Logo: stats.Logo,
Size: stats.Size,
Fee: stats.Fee,
BlobsCount: stats.BlobsCount,
}
}
type RollupAllSeriesResponse struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Items []RollupAllSeriesItem `json:"items"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
)
type Tx struct {
Id uint64 `example:"321" format:"int64" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"int64" json:"height" swaggertype:"integer"`
Position int64 `example:"11" format:"int64" json:"position" swaggertype:"integer"`
GasWanted int64 `example:"9348" format:"int64" json:"gas_wanted" swaggertype:"integer"`
GasUsed int64 `example:"4253" format:"int64" json:"gas_used" swaggertype:"integer"`
TimeoutHeight uint64 `example:"0" format:"int64" json:"timeout_height" swaggertype:"integer"`
EventsCount int64 `example:"2" format:"int64" json:"events_count" swaggertype:"integer"`
MessagesCount int64 `example:"1" format:"int64" json:"messages_count" swaggertype:"integer"`
Hash string `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" format:"binary" json:"hash" swaggertype:"string"`
Fee string `example:"9348" format:"int64" json:"fee" swaggertype:"string"`
Error string `example:"" format:"string" json:"error,omitempty" swaggertype:"string"`
Codespace string `example:"sdk" format:"string" json:"codespace,omitempty" swaggertype:"string"`
Memo string `example:"Transfer to private account" format:"string" json:"memo,omitempty" swaggertype:"string"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Messages []Message `json:"messages,omitempty"`
Signers []*ShortAddress `json:"signers,omitempty"`
MessageTypes []types.MsgType `example:"MsgSend,MsgUnjail" json:"message_types"`
Status types.Status `example:"success" json:"status"`
MsgTypeMask types.MsgTypeBits `json:"-"`
}
func NewTx(tx storage.Tx) Tx {
result := Tx{
Id: tx.Id,
Height: tx.Height,
Time: tx.Time,
Position: tx.Position,
GasWanted: tx.GasWanted,
GasUsed: tx.GasUsed,
TimeoutHeight: tx.TimeoutHeight,
EventsCount: tx.EventsCount,
MessagesCount: tx.MessagesCount,
Fee: tx.Fee.String(),
Status: tx.Status,
Error: tx.Error,
Codespace: tx.Codespace,
Hash: hex.EncodeToString(tx.Hash),
Memo: tx.Memo,
MessageTypes: tx.MessageTypes.Names(),
MsgTypeMask: tx.MessageTypes,
Messages: make([]Message, 0),
Signers: make([]*ShortAddress, len(tx.Signers)),
}
for i := range tx.Messages {
result.Messages = append(result.Messages, NewMessage(tx.Messages[i]))
}
for i := range tx.Signers {
result.Signers[i] = NewShortAddress(&tx.Signers[i])
}
return result
}
type TxForAddress struct {
MessagesCount int64 `example:"1" format:"int64" json:"messages_count" swaggertype:"integer"`
Hash string `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" format:"binary" json:"hash" swaggertype:"string"`
Fee string `example:"9348" format:"int64" json:"fee" swaggertype:"string"`
MessageTypes []types.MsgType `example:"MsgSend,MsgUnjail" json:"message_types"`
Status types.Status `example:"success" json:"status"`
}
func NewTxForAddress(tx *storage.Tx) TxForAddress {
result := TxForAddress{
MessagesCount: tx.MessagesCount,
Fee: tx.Fee.String(),
Status: tx.Status,
Hash: hex.EncodeToString(tx.Hash),
MessageTypes: tx.MessageTypes.Names(),
}
return result
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"fmt"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/shopspring/decimal"
)
type Validator struct {
Id uint64 `example:"321" json:"id" swaggertype:"integer"`
ConsAddress string `example:"E641C7A2C964833E556AEF934FBF166B712874B6" json:"cons_address" swaggertype:"string"`
Moniker string `example:"Easy 2 Stake" json:"moniker" swaggertype:"string"`
Website string `example:"https://www.easy2stake.com/" json:"website" swaggertype:"string"`
Identity string `example:"2C877AC873132C91" json:"identity" swaggertype:"string"`
Contacts string `example:"security@0xfury.com" json:"contacts" swaggertype:"string"`
Details string `example:"Some long text about validator" json:"details" swaggertype:"string"`
Rate string `example:"0.03" json:"rate" swaggertype:"string"`
MaxRate string `example:"0.1" json:"max_rate" swaggertype:"string"`
MaxChangeRate string `example:"0.01" json:"max_change_rate" swaggertype:"string"`
MinSelfDelegation string `example:"1" json:"min_self_delegation" swaggertype:"string"`
Stake string `example:"1" json:"stake" swaggertype:"string"`
Rewards string `example:"1" json:"rewards" swaggertype:"string"`
Commissions string `example:"1" json:"commissions" swaggertype:"string"`
VotingPower string `example:"1" json:"voting_power" swaggertype:"string"`
Jailed bool `example:"false" json:"jailed" swaggertype:"boolean"`
Address *ShortAddress `json:"address"`
Delegator *ShortAddress `json:"delegator"`
}
func NewValidator(val storage.Validator) *Validator {
if val.Id == 0 { // for genesis block
return nil
}
return &Validator{
Id: val.Id,
Delegator: &ShortAddress{
Hash: val.Delegator,
},
Address: &ShortAddress{
Hash: val.Address,
},
ConsAddress: val.ConsAddress,
Moniker: val.Moniker,
Website: val.Website,
Identity: val.Identity,
Contacts: val.Contacts,
Details: val.Details,
Rate: val.Rate.String(),
MaxRate: val.MaxRate.String(),
MaxChangeRate: val.MaxChangeRate.String(),
MinSelfDelegation: val.MinSelfDelegation.String(),
Stake: val.Stake.String(),
Rewards: val.Rewards.Floor().String(),
Commissions: val.Commissions.Floor().String(),
Jailed: *val.Jailed,
VotingPower: val.Stake.Div(decimal.NewFromInt(1_000_000)).Floor().String(),
}
}
type ShortValidator struct {
Id uint64 `example:"321" json:"id" swaggertype:"integer"`
ConsAddress string `example:"E641C7A2C964833E556AEF934FBF166B712874B6" json:"cons_address" swaggertype:"string"`
Moniker string `example:"Easy 2 Stake" json:"moniker" swaggertype:"string"`
}
func NewShortValidator(val storage.Validator) *ShortValidator {
if val.Id == 0 { // for genesis block
return nil
}
return &ShortValidator{
Id: val.Id,
ConsAddress: val.ConsAddress,
Moniker: val.Moniker,
}
}
type ValidatorUptime struct {
Uptime string `example:"0.97" json:"uptime" swaggertype:"string"`
Blocks []SignedBlocks `json:"blocks"`
}
type SignedBlocks struct {
Height types.Level `example:"100" json:"height" swaggertype:"integer"`
Signed bool `example:"true" json:"signed" swaggertype:"boolean"`
}
func NewValidatorUptime(levels []types.Level, currentLevel types.Level, count types.Level) (uptime ValidatorUptime) {
var (
levelIndex = 0
threshold = count
)
if threshold > currentLevel {
threshold = currentLevel
}
uptime.Blocks = make([]SignedBlocks, 0)
for i := currentLevel; i > currentLevel-threshold; i-- {
if levelIndex < len(levels) && levels[levelIndex] == i {
levelIndex++
uptime.Blocks = append(uptime.Blocks, SignedBlocks{
Signed: true,
Height: i,
})
} else {
uptime.Blocks = append(uptime.Blocks, SignedBlocks{
Signed: false,
Height: i,
})
}
}
uptime.Uptime = fmt.Sprintf("%.4f", float64(levelIndex)/float64(threshold))
return uptime
}
type Jail struct {
Height types.Level `example:"100" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" json:"time" swaggertype:"string"`
Reason string `example:"double_sign" json:"reason" swaggertype:"string"`
Burned string `example:"10000000000" json:"burned" swaggertype:"string"`
Validator *ShortValidator `json:"validator,omitempty"`
}
func NewJail(jail storage.Jail) Jail {
j := Jail{
Height: jail.Height,
Time: jail.Time,
Reason: jail.Reason,
Burned: jail.Burned.String(),
}
if jail.Validator != nil {
j.Validator = NewShortValidator(*jail.Validator)
}
return j
}
type ValidatorCount struct {
Total int `example:"100" json:"total" swaggertype:"integer"`
Jailed int `example:"100" json:"jailed" swaggertype:"integer"`
Active int `example:"100" json:"active" swaggertype:"integer"`
Inactive int `example:"100" json:"inactive" swaggertype:"integer"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
)
type Vesting struct {
Id uint64 `example:"12" format:"integer" json:"id" swaggertype:"integer"`
Height pkgTypes.Level `example:"100" format:"integer" json:"height" swaggertype:"integer"`
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
StartTime *time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"start_time,omitempty" swaggertype:"string"`
EndTime *time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"end_time,omitempty" swaggertype:"string"`
Hash string `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" format:"binary" json:"hash,omitempty" swaggertype:"string"`
Type types.VestingType `example:"delayed" format:"string" json:"type" swaggertype:"string"`
Amount string `example:"123.13333" format:"string" json:"amount" swaggertype:"string"`
}
var startOfTime = time.Unix(0, 0).UTC()
func NewVesting(v storage.VestingAccount) Vesting {
vesting := Vesting{
Id: v.Id,
Height: v.Height,
Time: v.Time,
Type: v.Type,
Amount: v.Amount.String(),
}
switch v.Type {
case types.VestingTypeContinuous:
if v.StartTime != nil {
vesting.StartTime = v.StartTime
} else {
vesting.StartTime = &startOfTime
}
if v.EndTime != nil {
vesting.EndTime = v.EndTime
} else {
vesting.EndTime = &startOfTime
}
case types.VestingTypePeriodic:
if v.StartTime != nil {
vesting.StartTime = v.StartTime
} else {
vesting.StartTime = &startOfTime
}
if v.EndTime != nil {
vesting.EndTime = v.EndTime
}
case types.VestingTypeDelayed:
if v.EndTime != nil {
vesting.EndTime = v.EndTime
} else {
vesting.EndTime = &startOfTime
}
case types.VestingTypePermanent:
}
if v.Tx != nil {
vesting.Hash = hex.EncodeToString(v.Tx.Hash)
}
return vesting
}
type VestingPeriod struct {
Time time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"time" swaggertype:"string"`
Amount string `example:"123.13333" format:"string" json:"amount" swaggertype:"string"`
}
func NewVestingPeriod(v storage.VestingPeriod) VestingPeriod {
return VestingPeriod{
Time: v.Time,
Amount: v.Amount.String(),
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
testsuite "github.com/celenium-io/celestia-indexer/internal/test_suite"
"github.com/labstack/echo/v4"
)
type RollupHandler struct {
rollups storage.IRollup
namespace storage.INamespace
blobs storage.IBlobLog
}
func NewRollupHandler(
rollups storage.IRollup,
namespace storage.INamespace,
blobs storage.IBlobLog,
) RollupHandler {
return RollupHandler{
rollups: rollups,
namespace: namespace,
blobs: blobs,
}
}
type rollupList struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time blobs_count size fee"`
Tags StringArray `query:"tags" validate:"omitempty"`
Stack StringArray `query:"stack" validate:"omitempty"`
Provider StringArray `query:"provider" validate:"omitempty"`
Category StringArray `query:"category" validate:"omitempty,dive,category"`
Type StringArray `query:"type" validate:"omitempty,dive,type"`
}
func (p *rollupList) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = desc
}
if p.SortBy == "" {
p.SortBy = "size"
}
}
// Leaderboard godoc
//
// @Summary List rollups info
// @Description List rollups info
// @Tags rollup
// @ID list-rollup
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. Default: size" Enums(time, blobs_count, size, fee)
// @Param category query string false "Comma-separated rollup category list"
// @Param tags query string false "Comma-separated rollup tags list"
// @Param stack query string false "Comma-separated rollup stack list"
// @Param provider query string false "Comma-separated rollup provider list"
// @Produce json
// @Success 200 {array} responses.RollupWithStats
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup [get]
func (handler RollupHandler) Leaderboard(c echo.Context) error {
req, err := bindAndValidate[rollupList](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
rollupTypes := make([]types.RollupType, len(req.Type))
for i := range rollupTypes {
rollupTypes[i] = types.RollupType(req.Type[i])
}
categories := make([]types.RollupCategory, len(req.Category))
for i := range categories {
categories[i] = types.RollupCategory(req.Category[i])
}
rollups, err := handler.rollups.Leaderboard(c.Request().Context(), storage.LeaderboardFilters{
SortField: req.SortBy,
Sort: pgSort(req.Sort),
Limit: req.Limit,
Offset: req.Offset,
Category: categories,
Tags: req.Tags,
Type: rollupTypes,
Stack: req.Stack,
Provider: req.Provider,
})
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.RollupWithStats, len(rollups))
for i := range rollups {
response[i] = responses.NewRollupWithStats(rollups[i])
}
return returnArray(c, response)
}
type rollupDayList struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=avg_size blobs_count total_size total_fee throughput namespace_count pfb_count mb_price"`
Stack StringArray `query:"stack" validate:"omitempty"`
Provider StringArray `query:"provider" validate:"omitempty"`
Category StringArray `query:"category" validate:"omitempty,dive,category"`
Tags StringArray `query:"tags" validate:"omitempty"`
Type StringArray `query:"type" validate:"omitempty,dive,type"`
}
func (p *rollupDayList) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = desc
}
if p.SortBy == "" {
p.SortBy = "throughput"
}
}
// LeaderboardDay godoc
//
// @Summary List rollups info with stats by previous 24 hours
// @Description List rollups info with stats by previous 24 hours
// @Tags rollup
// @ID list-rollup-24h
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. Default: mb_price" Enums(avg_size, blobs_count, total_size, total_fee, throughput, namespace_count, pfb_count, mb_price)
// @Param category query string false "Comma-separated rollup category list"
// @Param tags query string false "Comma-separated rollup tags list"
// @Param stack query string false "Comma-separated rollup stack list"
// @Param provider query string false "Comma-separated rollup provider list"
// @Produce json
// @Success 200 {array} responses.RollupWithDayStats
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/day [get]
func (handler RollupHandler) LeaderboardDay(c echo.Context) error {
req, err := bindAndValidate[rollupDayList](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
rollupTypes := make([]types.RollupType, len(req.Type))
for i := range rollupTypes {
rollupTypes[i] = types.RollupType(req.Type[i])
}
categories := make([]types.RollupCategory, len(req.Category))
for i := range categories {
categories[i] = types.RollupCategory(req.Category[i])
}
rollups, err := handler.rollups.LeaderboardDay(c.Request().Context(), storage.LeaderboardFilters{
SortField: req.SortBy,
Sort: pgSort(req.Sort),
Limit: req.Limit,
Offset: req.Offset,
Tags: req.Tags,
Category: categories,
Type: rollupTypes,
Stack: req.Stack,
Provider: req.Provider,
})
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.RollupWithDayStats, len(rollups))
for i := range rollups {
response[i] = responses.NewRollupWithDayStats(rollups[i])
}
return returnArray(c, response)
}
// Get godoc
//
// @Summary Get rollup info
// @Description Get rollup info
// @Tags rollup
// @ID get-rollup
// @Param id path integer true "Internal identity" mininum(1)
// @Produce json
// @Success 200 {object} responses.Rollup
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id} [get]
func (handler RollupHandler) Get(c echo.Context) error {
req, err := bindAndValidate[getById](c)
if err != nil {
return badRequestError(c, err)
}
rollup, err := handler.rollups.ById(c.Request().Context(), req.Id)
if err != nil {
return handleError(c, err, handler.rollups)
}
return c.JSON(http.StatusOK, responses.NewRollupWithStats(rollup))
}
type getRollupPages struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (req *getRollupPages) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// GetNamespaces godoc
//
// @Summary Get rollup namespaces info
// @Description Get rollup namespaces info
// @Tags rollup
// @ID get-rollup-namespaces
// @Param id path integer true "Internal identity" mininum(1)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.Namespace
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id}/namespaces [get]
func (handler RollupHandler) GetNamespaces(c echo.Context) error {
req, err := bindAndValidate[getRollupPages](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
namespaceIds, err := handler.rollups.Namespaces(c.Request().Context(), req.Id, req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.rollups)
}
if len(namespaceIds) == 0 {
return c.JSON(http.StatusOK, []any{})
}
namespaces, err := handler.namespace.GetByIds(c.Request().Context(), namespaceIds...)
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.Namespace, len(namespaces))
for i := range namespaces {
response[i] = responses.NewNamespace(namespaces[i])
}
return returnArray(c, response)
}
type getRollupPagesWithSort struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
Joins *bool `query:"joins" validate:"omitempty"`
}
func (p *getRollupPagesWithSort) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = desc
}
if p.Joins == nil {
p.Joins = testsuite.Ptr(true)
}
}
// GetBlobs godoc
//
// @Summary Get rollup blobs
// @Description Get rollup blobs
// @Tags rollup
// @ID get-rollup-blobs
// @Param id path integer true "Internal identity" mininum(1)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Param joins query boolean false "Flag indicating whether entities of transaction and signer should be attached or not. Default: true"
// @Produce json
// @Success 200 {array} responses.BlobLog
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id}/blobs [get]
func (handler RollupHandler) GetBlobs(c echo.Context) error {
req, err := bindAndValidate[getRollupPagesWithSort](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
providers, err := handler.rollups.Providers(c.Request().Context(), req.Id)
if err != nil {
return handleError(c, err, handler.rollups)
}
if len(providers) == 0 {
return c.JSON(http.StatusOK, []any{})
}
blobs, err := handler.blobs.ByProviders(c.Request().Context(), providers, storage.BlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
Joins: *req.Joins,
})
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.BlobLog, len(blobs))
for i := range blobs {
response[i] = responses.NewBlobLog(blobs[i])
}
return returnArray(c, response)
}
type rollupStatsRequest struct {
Id uint64 `example:"1" param:"id" swaggertype:"integer" validate:"required,min=1"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day month"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=blobs_count size size_per_blob fee"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Stats godoc
//
// @Summary Get rollup stats
// @Description Get rollup stats
// @Tags rollup
// @ID get-rollup-stats
// @Param id path integer true "Internal identity" mininum(1)
// @Param name path string true "Series name" Enums(blobs_count, size, size_per_blob, fee)
// @Param timeframe path string true "Timeframe" Enums(hour, day, month)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.HistogramItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id}/stats/{name}/{timeframe} [get]
func (handler RollupHandler) Stats(c echo.Context) error {
req, err := bindAndValidate[rollupStatsRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := handler.rollups.Series(
c.Request().Context(),
req.Id,
storage.Timeframe(req.Timeframe),
req.SeriesName,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.HistogramItem, len(histogram))
for i := range histogram {
response[i] = responses.NewHistogramItem(histogram[i])
}
return returnArray(c, response)
}
type rollupAllSeriesRequest struct {
Timeframe storage.Timeframe `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day month"`
}
// AllSeries godoc
//
// @Summary Get series for all rollups
// @Description Get series for all rollups
// @Tags rollup
// @ID get-rollup-all-series
// @Param timeframe path string true "Timeframe" Enums(hour, day, month)
// @Produce json
// @Success 200 {array} responses.RollupAllSeriesResponse
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/stats/series/{timeframe} [get]
func (handler RollupHandler) AllSeries(c echo.Context) error {
req, err := bindAndValidate[rollupAllSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := handler.rollups.AllSeries(
c.Request().Context(),
req.Timeframe,
)
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.RollupAllSeriesResponse, 0)
for i := range histogram {
key := histogram[i].Time
value := responses.NewRollupAllSeriesItem(histogram[i])
var found bool
for j := range response {
if response[j].Time.Equal(key) {
response[j].Items = append(response[j].Items, value)
found = true
}
}
if !found {
response = append(response, responses.RollupAllSeriesResponse{
Time: key,
Items: []responses.RollupAllSeriesItem{value},
})
}
}
return c.JSON(http.StatusOK, response)
}
// Count godoc
//
// @Summary Get count of rollups in network
// @Description Get count of rollups in network
// @Tags rollup
// @ID get-rollups-count
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /rollup/count [get]
func (handler RollupHandler) Count(c echo.Context) error {
count, err := handler.rollups.Count(c.Request().Context())
if err != nil {
return handleError(c, err, handler.rollups)
}
return c.JSON(http.StatusOK, count)
}
type rollupBySlugRequest struct {
Slug string `param:"slug" validate:"required"`
}
// BySlug godoc
//
// @Summary Get rollup by slug
// @Description Get rollup by slug
// @Tags rollup
// @ID get-rollup-by-slug
// @Param slug path string true "Slug"
// @Produce json
// @Success 200 {object} responses.Rollup
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/slug/{slug} [get]
func (handler RollupHandler) BySlug(c echo.Context) error {
req, err := bindAndValidate[rollupBySlugRequest](c)
if err != nil {
return badRequestError(c, err)
}
rollup, err := handler.rollups.BySlug(c.Request().Context(), req.Slug)
if err != nil {
return handleError(c, err, handler.rollups)
}
return c.JSON(http.StatusOK, responses.NewRollupWithStats(rollup))
}
type rollupDistributionRequest struct {
Id uint64 `example:"1" param:"id" swaggertype:"integer" validate:"required,min=1"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=blobs_count size size_per_blob fee_per_blob"`
}
// Distribution godoc
//
// @Summary Get rollup distribution
// @Description Get rollup distribution
// @Tags rollup
// @ID get-rollup-distribution
// @Param id path integer true "Internal identity" mininum(1)
// @Param name path string true "Series name" Enums(blobs_count, size, size_per_blob, fee_per_blob)
// @Param timeframe path string true "Timeframe" Enums(hour, day)
// @Produce json
// @Success 200 {array} responses.DistributionItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id}/distribution/{name}/{timeframe} [get]
func (handler RollupHandler) Distribution(c echo.Context) error {
req, err := bindAndValidate[rollupDistributionRequest](c)
if err != nil {
return badRequestError(c, err)
}
distr, err := handler.rollups.Distribution(
c.Request().Context(),
req.Id,
req.SeriesName,
storage.Timeframe(req.Timeframe),
)
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.DistributionItem, len(distr))
for i := range distr {
response[i] = responses.NewDistributionItem(distr[i], req.Timeframe)
}
return returnArray(c, response)
}
type exportBlobsRequest struct {
Id uint64 `example:"10" param:"id" swaggertype:"integer" validate:"required,min=1"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// ExportBlobs godoc
//
// @Summary Export rollup blobs
// @Description Export rollup blobs
// @Tags rollup
// @ID rollup-export
// @Param id path integer true "Internal identity" mininum(1)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Success 200
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/{id}/export [get]
func (handler RollupHandler) ExportBlobs(c echo.Context) error {
req, err := bindAndValidate[exportBlobsRequest](c)
if err != nil {
return badRequestError(c, err)
}
providers, err := handler.rollups.Providers(c.Request().Context(), req.Id)
if err != nil {
return handleError(c, err, handler.rollups)
}
if len(providers) == 0 {
return c.JSON(http.StatusOK, []any{})
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextPlain)
c.Response().WriteHeader(http.StatusOK)
var (
from time.Time
to time.Time
)
if req.From > 0 {
from = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
to = time.Unix(req.To, 0).UTC()
}
err = handler.blobs.ExportByProviders(
c.Request().Context(),
providers,
from,
to,
c.Response(),
)
if err != nil {
return handleError(c, err, handler.rollups)
}
return nil
}
type rollupGroupStats struct {
Func string `query:"func" validate:"oneof=sum avg"`
Column string `query:"column" validate:"oneof=stack type category vm provider"`
}
// RollupGroupedStats godoc
//
// @Summary Rollup Grouped Statistics
// @Description Rollup Grouped Statistics
// @Tags rollup
// @ID rollup-grouped-statistics
// @Param func query string false "Aggregate function" Enums(sum, avg)
// @Param column query string false "Group column" Enums(stack, type, category, vm, provider)
// @Produce json
// @Success 200 {array} responses.RollupGroupedStats
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /rollup/group [get]
func (handler RollupHandler) RollupGroupedStats(c echo.Context) error {
req, err := bindAndValidate[rollupGroupStats](c)
if err != nil {
return badRequestError(c, err)
}
rollups, err := handler.rollups.RollupStatsGrouping(c.Request().Context(), storage.RollupGroupStatsFilters{
Func: req.Func,
Column: req.Column,
})
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.RollupGroupedStats, len(rollups))
for i := range rollups {
response[i] = responses.NewRollupGroupedStats(rollups[i])
}
return returnArray(c, response)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"encoding/base64"
"net/http"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
enums "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/types"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/gosimple/slug"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type RollupAuthHandler struct {
address storage.IAddress
namespace storage.INamespace
rollups storage.IRollup
tx sdk.Transactable
}
func NewRollupAuthHandler(
rollups storage.IRollup,
address storage.IAddress,
namespace storage.INamespace,
tx sdk.Transactable,
) RollupAuthHandler {
return RollupAuthHandler{
rollups: rollups,
address: address,
namespace: namespace,
tx: tx,
}
}
type createRollupRequest struct {
Name string `json:"name" validate:"required,min=1"`
Description string `json:"description" validate:"required,min=1"`
Website string `json:"website" validate:"omitempty,url"`
GitHub string `json:"github" validate:"omitempty,url"`
Twitter string `json:"twitter" validate:"omitempty,url"`
Logo string `json:"logo" validate:"required,url"`
L2Beat string `json:"l2_beat" validate:"omitempty,url"`
DeFiLama string `json:"defi_lama" validate:"omitempty"`
Bridge string `json:"bridge" validate:"omitempty,eth_addr"`
Explorer string `json:"explorer" validate:"omitempty,url"`
Stack string `json:"stack" validate:"omitempty"`
Links []string `json:"links" validate:"omitempty,dive,url"`
Category string `json:"category" validate:"omitempty,category"`
Tags []string `json:"tags" validate:"omitempty"`
Type string `json:"type" validate:"omitempty,oneof=settled sovereign"`
Compression string `json:"compression" validate:"omitempty"`
VM string `json:"vm" validate:"omitempty"`
Provider string `json:"provider" validate:"omitempty"`
Providers []rollupProvider `json:"providers" validate:"required,min=1"`
}
type rollupProvider struct {
Namespace string `json:"namespace" validate:"omitempty,base64,namespace"`
Address string `json:"address" validate:"required,address"`
}
func (handler RollupAuthHandler) Create(c echo.Context) error {
val := c.Get(ApiKeyName)
apiKey, ok := val.(storage.ApiKey)
if !ok {
return handleError(c, errInvalidApiKey, handler.address)
}
req, err := bindAndValidate[createRollupRequest](c)
if err != nil {
return badRequestError(c, err)
}
rollupId, err := handler.createRollup(c.Request().Context(), req, apiKey.Admin)
if err != nil {
return handleError(c, err, handler.rollups)
}
return c.JSON(http.StatusOK, echo.Map{
"id": rollupId,
})
}
func (handler RollupAuthHandler) createRollup(ctx context.Context, req *createRollupRequest, isAdmin bool) (uint64, error) {
tx, err := postgres.BeginTransaction(ctx, handler.tx)
if err != nil {
return 0, err
}
rollup := storage.Rollup{
Name: req.Name,
Description: req.Description,
Website: req.Website,
GitHub: req.GitHub,
Twitter: req.Twitter,
Logo: req.Logo,
L2Beat: req.L2Beat,
DeFiLama: req.DeFiLama,
Explorer: req.Explorer,
BridgeContract: req.Bridge,
Stack: req.Stack,
Links: req.Links,
Compression: req.Compression,
Provider: req.Provider,
VM: req.VM,
Type: enums.RollupType(req.Type),
Category: enums.RollupCategory(req.Category),
Slug: slug.Make(req.Name),
Tags: req.Tags,
Verified: isAdmin,
}
if err := tx.SaveRollup(ctx, &rollup); err != nil {
return 0, tx.HandleError(ctx, err)
}
providers, err := handler.createProviders(ctx, rollup.Id, req.Providers...)
if err != nil {
return 0, tx.HandleError(ctx, err)
}
if err := tx.SaveProviders(ctx, providers...); err != nil {
return 0, tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
return 0, err
}
return rollup.Id, nil
}
func (handler RollupAuthHandler) createProviders(ctx context.Context, rollupId uint64, data ...rollupProvider) ([]storage.RollupProvider, error) {
providers := make([]storage.RollupProvider, len(data))
for i := range data {
providers[i].RollupId = rollupId
_, hashAddress, err := types.Address(data[i].Address).Decode()
if err != nil {
return nil, err
}
address, err := handler.address.ByHash(ctx, hashAddress)
if err != nil {
if handler.address.IsNoRows(err) {
return nil, errors.Wrap(errUnknownAddress, data[i].Address)
}
return nil, err
}
providers[i].AddressId = address.Id
if data[i].Namespace != "" {
hashNs, err := base64.StdEncoding.DecodeString(data[i].Namespace)
if err != nil {
return nil, err
}
ns, err := handler.namespace.ByNamespaceIdAndVersion(ctx, hashNs[1:], hashNs[0])
if err != nil {
if handler.namespace.IsNoRows(err) {
return nil, errors.Wrap(errUnknownNamespace, data[i].Namespace)
}
return nil, err
}
providers[i].NamespaceId = ns.Id
}
}
return providers, nil
}
type updateRollupRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
Name string `json:"name" validate:"omitempty,min=1"`
Description string `json:"description" validate:"omitempty,min=1"`
Website string `json:"website" validate:"omitempty,url"`
GitHub string `json:"github" validate:"omitempty,url"`
Twitter string `json:"twitter" validate:"omitempty,url"`
Logo string `json:"logo" validate:"omitempty,url"`
L2Beat string `json:"l2_beat" validate:"omitempty,url"`
DeFiLama string `json:"defi_lama" validate:"omitempty"`
Bridge string `json:"bridge" validate:"omitempty,eth_addr"`
Explorer string `json:"explorer" validate:"omitempty,url"`
Stack string `json:"stack" validate:"omitempty"`
Category string `json:"category" validate:"omitempty,category"`
Type string `json:"type" validate:"omitempty,oneof=settled sovereign"`
Compression string `json:"compression" validate:"omitempty"`
Provider string `json:"provider" validate:"omitempty"`
VM string `json:"vm" validate:"omitempty"`
Links []string `json:"links" validate:"omitempty,dive,url"`
Providers []rollupProvider `json:"providers" validate:"omitempty,min=1"`
Tags []string `json:"tags" validate:"omitempty"`
}
func (handler RollupAuthHandler) Update(c echo.Context) error {
val := c.Get(ApiKeyName)
apiKey, ok := val.(storage.ApiKey)
if !ok {
return handleError(c, errInvalidApiKey, handler.address)
}
req, err := bindAndValidate[updateRollupRequest](c)
if err != nil {
return badRequestError(c, err)
}
if err := handler.updateRollup(c.Request().Context(), req, apiKey.Admin); err != nil {
return handleError(c, err, handler.rollups)
}
return success(c)
}
func (handler RollupAuthHandler) updateRollup(ctx context.Context, req *updateRollupRequest, isAdmin bool) error {
tx, err := postgres.BeginTransaction(ctx, handler.tx)
if err != nil {
return err
}
if _, err := handler.rollups.GetByID(ctx, req.Id); err != nil {
return err
}
rollup := storage.Rollup{
Id: req.Id,
Name: req.Name,
Slug: slug.Make(req.Name),
Description: req.Description,
Website: req.Website,
GitHub: req.GitHub,
Twitter: req.Twitter,
Logo: req.Logo,
L2Beat: req.L2Beat,
DeFiLama: req.DeFiLama,
Explorer: req.Explorer,
BridgeContract: req.Bridge,
Stack: req.Stack,
Compression: req.Compression,
Provider: req.Provider,
VM: req.VM,
Type: enums.RollupType(req.Type),
Category: enums.RollupCategory(req.Category),
Links: req.Links,
Tags: req.Tags,
Verified: isAdmin,
}
if err := tx.UpdateRollup(ctx, &rollup); err != nil {
return tx.HandleError(ctx, err)
}
if len(req.Providers) > 0 {
if err := tx.DeleteProviders(ctx, req.Id); err != nil {
return tx.HandleError(ctx, err)
}
providers, err := handler.createProviders(ctx, rollup.Id, req.Providers...)
if err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.SaveProviders(ctx, providers...); err != nil {
return tx.HandleError(ctx, err)
}
}
return tx.Flush(ctx)
}
type deleteRollupRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
}
func (handler RollupAuthHandler) Delete(c echo.Context) error {
req, err := bindAndValidate[deleteRollupRequest](c)
if err != nil {
return badRequestError(c, err)
}
if err := handler.deleteRollup(c.Request().Context(), req.Id); err != nil {
return handleError(c, err, handler.rollups)
}
return success(c)
}
func (handler RollupAuthHandler) deleteRollup(ctx context.Context, id uint64) error {
tx, err := postgres.BeginTransaction(ctx, handler.tx)
if err != nil {
return err
}
if err := tx.DeleteProviders(ctx, id); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.DeleteRollup(ctx, id); err != nil {
return tx.HandleError(ctx, err)
}
return tx.Flush(ctx)
}
func (handler RollupAuthHandler) Unverified(c echo.Context) error {
rollups, err := handler.rollups.Unverified(c.Request().Context())
if err != nil {
return handleError(c, err, handler.rollups)
}
response := make([]responses.Rollup, len(rollups))
for i := range rollups {
response[i] = responses.NewRollup(&rollups[i])
}
return returnArray(c, response)
}
type verifyRollupRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
}
func (handler RollupAuthHandler) Verify(c echo.Context) error {
req, err := bindAndValidate[verifyRollupRequest](c)
if err != nil {
return badRequestError(c, err)
}
if err := handler.verify(c.Request().Context(), req.Id); err != nil {
return handleError(c, err, handler.address)
}
return success(c)
}
func (handler RollupAuthHandler) verify(ctx context.Context, id uint64) error {
tx, err := postgres.BeginTransaction(ctx, handler.tx)
if err != nil {
return err
}
err = tx.UpdateRollup(ctx, &storage.Rollup{
Id: id,
Verified: true,
})
if err != nil {
return tx.HandleError(ctx, err)
}
return tx.Flush(ctx)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"context"
"encoding/base64"
"encoding/hex"
"regexp"
"strconv"
"strings"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type SearchHandler struct {
search storage.ISearch
address storage.IAddress
block storage.IBlock
tx storage.ITx
namespace storage.INamespace
validator storage.IValidator
rollup storage.IRollup
celestials celestials.ICelestial
}
func NewSearchHandler(
search storage.ISearch,
address storage.IAddress,
block storage.IBlock,
tx storage.ITx,
namespace storage.INamespace,
validator storage.IValidator,
rollup storage.IRollup,
celestials celestials.ICelestial,
) SearchHandler {
return SearchHandler{
search: search,
address: address,
block: block,
tx: tx,
namespace: namespace,
validator: validator,
rollup: rollup,
celestials: celestials,
}
}
type searchRequest struct {
Search string `query:"query" validate:"required"`
}
var (
hashRegexp = regexp.MustCompile("^(0x)?[a-fA-F0-9]{64}$")
namespaceRegexp = regexp.MustCompile("^[a-fA-f0-9]{58}$")
)
// Search godoc
//
// @Summary Search by hash
// @Description.markdown search
// @Tags search
// @ID search
// @Param query query string true "Search string"
// @Produce json
// @Success 200 {array} responses.SearchItem
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /search [get]
func (handler SearchHandler) Search(c echo.Context) error {
req, err := bindAndValidate[searchRequest](c)
if err != nil {
return badRequestError(c, err)
}
data := make([]responses.SearchItem, 0)
if height, err := strconv.ParseInt(req.Search, 10, 64); err == nil {
block, err := handler.block.ByHeight(c.Request().Context(), types.Level(height))
if err == nil {
data = append(data, responses.SearchItem{
Type: "block",
Result: responses.NewBlock(block, false),
})
}
}
var response []responses.SearchItem
switch {
case isAddress(req.Search):
response, err = handler.searchAddress(c.Request().Context(), req.Search)
case isValoperAddress(req.Search):
response, err = handler.searchValoperAddress(c.Request().Context(), req.Search)
case hashRegexp.MatchString(req.Search):
response, err = handler.searchHash(c.Request().Context(), req.Search)
case namespaceRegexp.MatchString(req.Search):
response, err = handler.searchNamespaceById(c.Request().Context(), req.Search)
case isNamespace(req.Search):
response, err = handler.searchNamespaceByBase64(c.Request().Context(), req.Search)
default:
response, err = handler.searchText(c.Request().Context(), req.Search)
}
if err != nil {
if !handler.address.IsNoRows(err) {
return handleError(c, err, handler.address)
}
}
data = append(data, response...)
return returnArray(c, data)
}
func (handler SearchHandler) searchAddress(ctx context.Context, search string) ([]responses.SearchItem, error) {
_, hash, err := types.Address(search).Decode()
if err != nil {
return nil, err
}
address, err := handler.address.ByHash(ctx, hash)
if err != nil {
return nil, err
}
result := responses.SearchItem{
Type: "address",
Result: responses.NewAddress(address),
}
return []responses.SearchItem{result}, nil
}
func (handler SearchHandler) searchValoperAddress(ctx context.Context, search string) ([]responses.SearchItem, error) {
_, hash, err := types.Address(search).Decode()
if err != nil {
return nil, err
}
address, err := handler.address.ByHash(ctx, hash)
if err != nil {
return nil, err
}
validator, err := handler.validator.ByAddress(ctx, search)
if err != nil {
return nil, err
}
return []responses.SearchItem{
{
Type: "validator",
Result: responses.NewValidator(validator),
}, {
Type: "address",
Result: responses.NewAddress(address),
},
}, nil
}
func (handler SearchHandler) searchHash(ctx context.Context, search string) ([]responses.SearchItem, error) {
search = strings.TrimPrefix(search, "0x")
data, err := hex.DecodeString(search)
if err != nil {
return nil, err
}
if len(data) != 32 {
return nil, errors.Wrapf(errInvalidHashLength, "got %d", len(data))
}
result, err := handler.search.Search(ctx, data)
if err != nil {
return nil, err
}
response := make([]responses.SearchItem, len(result))
for i := range result {
response[i].Type = result[i].Type
switch response[i].Type {
case "tx":
tx, err := handler.tx.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
response[i].Result = responses.NewTx(*tx)
case "block":
block, err := handler.block.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
response[i].Result = responses.NewBlock(*block, false)
}
}
return response, nil
}
func (handler SearchHandler) searchNamespaceById(ctx context.Context, search string) ([]responses.SearchItem, error) {
data, err := hex.DecodeString(search)
if err != nil {
return nil, err
}
return handler.getNamespace(ctx, data)
}
func (handler SearchHandler) searchNamespaceByBase64(ctx context.Context, search string) ([]responses.SearchItem, error) {
data, err := base64.StdEncoding.DecodeString(search)
if err != nil {
return nil, err
}
return handler.getNamespace(ctx, data)
}
func (handler SearchHandler) getNamespace(ctx context.Context, data []byte) ([]responses.SearchItem, error) {
version := data[0]
namespaceId := data[1:]
ns, err := handler.namespace.ByNamespaceIdAndVersion(ctx, namespaceId, version)
if err != nil {
return nil, err
}
result := responses.SearchItem{
Type: "namespace",
Result: responses.NewNamespace(ns),
}
return []responses.SearchItem{result}, nil
}
func (handler SearchHandler) searchText(ctx context.Context, text string) ([]responses.SearchItem, error) {
result, err := handler.search.SearchText(ctx, text)
if err != nil {
return nil, err
}
response := make([]responses.SearchItem, len(result))
for i := range result {
response[i].Type = result[i].Type
switch response[i].Type {
case "validator":
validator, err := handler.validator.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
response[i].Result = responses.NewValidator(*validator)
case "rollup":
rollup, err := handler.rollup.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
response[i].Result = responses.NewRollup(rollup)
case "namespace":
namespace, err := handler.namespace.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
response[i].Result = responses.NewNamespace(*namespace)
case "celestial":
address, err := handler.address.GetByID(ctx, result[i].Id)
if err != nil {
return nil, err
}
addr := responses.NewAddress(*address)
celestial, err := handler.celestials.ById(ctx, result[i].Value)
if err != nil {
return nil, err
}
addr.AddCelestails(&celestial)
response[i].Result = addr
response[i].Type = "address"
default:
return nil, errors.Errorf("unknown search text type: %s", response[i].Type)
}
}
return response, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type StateHandler struct {
state storage.IState
validator storage.IValidator
indexerName string
}
func NewStateHandler(state storage.IState, validator storage.IValidator, indexerName string) *StateHandler {
return &StateHandler{
state: state,
validator: validator,
indexerName: indexerName,
}
}
// Head godoc
//
// @Summary Get current indexer head
// @Description Get current indexer head
// @Tags general
// @ID head
// @Produce json
// @Success 200 {object} responses.State
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /head [get]
func (sh *StateHandler) Head(c echo.Context) error {
state, err := sh.state.ByName(c.Request().Context(), sh.indexerName)
if err != nil {
return handleError(c, err, sh.state)
}
votingPower, err := sh.validator.TotalVotingPower(c.Request().Context())
if err != nil {
return handleError(c, err, sh.state)
}
state.TotalVotingPower = votingPower
return c.JSON(http.StatusOK, responses.NewState(state))
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/hex"
"errors"
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/labstack/echo/v4"
)
type StatsHandler struct {
repo storage.IStats
nsRepo storage.INamespace
price storage.IPrice
state storage.IState
}
func NewStatsHandler(repo storage.IStats, nsRepo storage.INamespace, price storage.IPrice, state storage.IState) StatsHandler {
return StatsHandler{
repo: repo,
nsRepo: nsRepo,
price: price,
state: state,
}
}
type summaryRequest struct {
Table string `example:"block" param:"table" swaggertype:"string" validate:"required,oneof=block block_stats tx event message validator"`
Function string `example:"count" param:"function" swaggertype:"string" validate:"required,oneof=avg sum min max count"`
Column string `example:"fee" query:"column" swaggertype:"string" validate:"omitempty"`
From uint64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To uint64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Summary godoc
//
// @Summary Get value by table and function
// @Description.markdown summary
// @Tags stats
// @ID stats-summary
// @Param table path string true "Table name" Enums(block, block_stats, tx, event, message, validator)
// @Param function path string true "Function name" Enums(min, max, avg, sum, count)
// @Param column query string false "Column name which will be used for computation. Optional for count."
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {object} string
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/summary/{table}/{function} [get]
func (sh StatsHandler) Summary(c echo.Context) error {
req, err := bindAndValidate[summaryRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
summary string
countRequest = storage.CountRequest{
Table: req.Table,
From: req.From,
To: req.To,
}
)
if req.Function == "count" {
summary, err = sh.repo.Count(c.Request().Context(), countRequest)
} else {
summary, err = sh.repo.Summary(c.Request().Context(), storage.SummaryRequest{
CountRequest: countRequest,
Function: req.Function,
Column: req.Column,
})
}
if err != nil {
if errors.Is(err, storage.ErrValidation) {
return badRequestError(c, err)
}
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, summary)
}
// TPS godoc
//
// @Summary Get tps
// @Description Returns transaction per seconds statistics
// @Tags stats
// @ID stats-tps
// @x-internal true
// @Produce json
// @Success 200 {object} responses.TPS
// @Failure 500 {object} Error
// @Router /stats/tps [get]
func (sh StatsHandler) TPS(c echo.Context) error {
tps, err := sh.repo.TPS(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewTPS(tps))
}
// Change24hBlockStats godoc
//
// @Summary Get changes for 24 hours
// @Description Get changes for 24 hours
// @Tags stats
// @ID stats-24h-changes
// @Produce json
// @Success 200 {array} responses.Change24hBlockStats
// @Failure 500 {object} Error
// @Router /stats/changes_24h [get]
func (sh StatsHandler) Change24hBlockStats(c echo.Context) error {
data, err := sh.repo.Change24hBlockStats(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewChange24hBlockStats(data))
}
type namespaceUsageRequest struct {
Top *int `example:"100" query:"top" validate:"omitempty,min=1,max=100"`
}
// NamespaceUsage godoc
//
// @Summary Get namespaces with sorting by size.
// @Description Get namespaces with sorting by size. Returns top 100 namespaces. Namespaces which is not included to top 100 grouped into 'others' item
// @Tags stats
// @ID stats-namespace-usage
// @Param top query integer false "Count of entities" mininum(1) maximum(100)
// @Produce json
// @Success 200 {array} responses.NamespaceUsage
// @Failure 500 {object} Error
// @Router /stats/namespace/usage [get]
func (sh StatsHandler) NamespaceUsage(c echo.Context) error {
req, err := bindAndValidate[namespaceUsageRequest](c)
if err != nil {
return badRequestError(c, err)
}
if req.Top == nil {
top := 10
req.Top = &top
}
namespaces, err := sh.nsRepo.ListWithSort(c.Request().Context(), "size", sdk.SortOrderDesc, *req.Top, 0)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
var top100Size int64
response := make([]responses.NamespaceUsage, len(namespaces)+1)
for i := range namespaces {
response[i] = responses.NewNamespaceUsage(namespaces[i])
top100Size += response[i].Size
}
state, err := sh.state.List(c.Request().Context(), 1, 0, sdk.SortOrderAsc)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
if len(state) == 0 {
return returnArray(c, response)
}
response[len(namespaces)] = responses.NamespaceUsage{
Name: "others",
Size: state[0].TotalBlobsSize - top100Size,
Version: nil,
}
return returnArray(c, response)
}
type seriesRequest struct {
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=blobs_size blobs_count tps bps fee supply_change block_time tx_count events_count gas_price gas_efficiency gas_used gas_limit bytes_in_block rewards commissions"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// Series godoc
//
// @Summary Get histogram with precomputed stats
// @Description Get histogram with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-series
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param name path string true "Series name" Enums(blobs_size, blobs_count, tps, bps, fee, supply_change, block_time, tx_count, events_count, gas_price, gas_efficiency, gas_used, gas_limit, bytes_in_block, rewards, commissions)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/series/{name}/{timeframe} [get]
func (sh StatsHandler) Series(c echo.Context) error {
req, err := bindAndValidate[seriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := sh.repo.Series(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type seriesCumulativeRequest struct {
Timeframe string `example:"day" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
SeriesName string `example:"tps" param:"name" swaggertype:"string" validate:"required,oneof=blobs_size blobs_count fee tx_count gas_used gas_limit bytes_in_block supply_change"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// SeriesCumulative godoc
//
// @Summary Get cumulative histogram with precomputed stats
// @Description Get cumulative histogram with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-series-cumulative
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param name path string true "Series name" Enums(blobs_size, blobs_count, fee, tx_count, gas_used, gas_limit, bytes_in_block, supply_change)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/series/{name}/{timeframe}/cumulative [get]
func (sh StatsHandler) SeriesCumulative(c echo.Context) error {
req, err := bindAndValidate[seriesCumulativeRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := sh.repo.CumulativeSeries(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type namespaceSeriesRequest struct {
Id string `example:"0011223344" param:"id" swaggertype:"string" validate:"required,hexadecimal,len=56"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
SeriesName string `example:"size" param:"name" swaggertype:"string" validate:"required,oneof=pfb_count size"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// NamespaceSeries godoc
//
// @Summary Get histogram for namespace with precomputed stats
// @Description Get histogram for namespace with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-ns-series
// @Param id path string true "Namespace id in hexadecimal" minlength(56) maxlength(56)
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @Param name path string true "Series name" Enums(pfb_count, size)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/namespace/series/{id}/{name}/{timeframe} [get]
func (sh StatsHandler) NamespaceSeries(c echo.Context) error {
req, err := bindAndValidate[namespaceSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
namespaceId, err := hex.DecodeString(req.Id)
if err != nil {
return badRequestError(c, err)
}
namespace, err := sh.nsRepo.ByNamespaceId(c.Request().Context(), namespaceId)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
if len(namespace) == 0 {
return c.JSON(http.StatusOK, []any{})
}
histogram, err := sh.repo.NamespaceSeries(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
namespace[0].Id,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type priceSeriesRequest struct {
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=1m 1h 1d"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// PriceSeries godoc
//
// @Summary Get histogram with TIA price
// @Description Get histogram with TIA price
// @Tags stats
// @ID stats-price-series
// @Param timeframe path string true "Timeframe" Enums(1m, 1h, 1d)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.Price
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/price/series/{timeframe} [get]
func (sh StatsHandler) PriceSeries(c echo.Context) error {
req, err := bindAndValidate[priceSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
from time.Time
to time.Time
)
if req.From > 0 {
from = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
to = time.Unix(req.To, 0).UTC()
}
histogram, err := sh.price.Get(c.Request().Context(), req.Timeframe, from, to, 100)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.Price, len(histogram))
for i := range histogram {
response[i] = responses.NewPrice(histogram[i])
}
return returnArray(c, response)
}
// PriceCurrent godoc
//
// @Summary Get current TIA price
// @Description Get current TIA price
// @Tags stats
// @ID stats-price-current
// @Produce json
// @Success 200 {object} responses.Price
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/price/current [get]
func (sh StatsHandler) PriceCurrent(c echo.Context) error {
price, err := sh.price.Last(c.Request().Context())
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewPrice(price))
}
type stakingSeriesRequest struct {
Id uint64 `example:"123" param:"id" swaggertype:"integer" validate:"required,min=1"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day month"`
SeriesName string `example:"size" param:"name" swaggertype:"string" validate:"required,oneof=rewards commissions flow"`
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// StakingSeries godoc
//
// @Summary Get histogram for staking with precomputed stats
// @Description Get histogram for staking with precomputed stats by series name and timeframe
// @Tags stats
// @ID stats-staking-series
// @Param id path string true "Validator id" minlength(56) maxlength(56)
// @Param timeframe path string true "Timeframe" Enums(hour, day, month)
// @Param name path string true "Series name" Enums(rewards, commissions, flow)
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SeriesItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/staking/series/{id}/{name}/{timeframe} [get]
func (sh StatsHandler) StakingSeries(c echo.Context) error {
req, err := bindAndValidate[stakingSeriesRequest](c)
if err != nil {
return badRequestError(c, err)
}
histogram, err := sh.repo.StakingSeries(
c.Request().Context(),
storage.Timeframe(req.Timeframe),
req.SeriesName,
req.Id,
storage.NewSeriesRequest(req.From, req.To),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.SeriesItem, len(histogram))
for i := range histogram {
response[i] = responses.NewSeriesItem(histogram[i])
}
return returnArray(c, response)
}
type squareSizeRequest struct {
From int64 `example:"1692892095" query:"from" swaggertype:"integer" validate:"omitempty,min=1"`
To int64 `example:"1692892095" query:"to" swaggertype:"integer" validate:"omitempty,min=1"`
}
// SquareSize godoc
//
// @Summary Get histogram for square size distribution
// @Description Get histogram for square size distribution
// @Tags stats
// @ID stats-square-size
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Produce json
// @Success 200 {array} responses.SquareSizeResponse
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/square_size [get]
func (sh StatsHandler) SquareSize(c echo.Context) error {
req, err := bindAndValidate[squareSizeRequest](c)
if err != nil {
return badRequestError(c, err)
}
var from, to *time.Time
if req.From > 0 {
t := time.Unix(req.From, 0).UTC()
from = &t
}
if req.To > 0 {
t := time.Unix(req.To, 0).UTC()
to = &t
}
histogram, err := sh.repo.SquareSize(
c.Request().Context(),
from,
to,
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
return c.JSON(http.StatusOK, responses.NewSquareSizeResponse(histogram))
}
// RollupStats24h godoc
//
// @Summary Get rollups stats for last 24 hours
// @Description Get rollups stats for last 24 hours
// @Tags stats
// @ID stats-rollup-24h
// @Produce json
// @Success 200 {array} responses.RollupStats24h
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /stats/rollup_stats_24h [get]
func (sh StatsHandler) RollupStats24h(c echo.Context) error {
items, err := sh.repo.RollupStats24h(
c.Request().Context(),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.RollupStats24h, len(items))
for i := range items {
response[i] = responses.NewRollupStats24h(items[i])
}
return returnArray(c, response)
}
// MessagesCount24h godoc
//
// @Summary Get messages distribution for the last 24 hours
// @Description Get messages distribution for the last 24 hours
// @Tags stats
// @ID stats-messages-count-24h
// @Produce json
// @Success 200 {array} responses.CountItem
// @Failure 500 {object} Error
// @Router /stats/messages_count_24h [get]
func (sh StatsHandler) MessagesCount24h(c echo.Context) error {
items, err := sh.repo.MessagesCount24h(
c.Request().Context(),
)
if err != nil {
return handleError(c, err, sh.nsRepo)
}
response := make([]responses.CountItem, len(items))
for i := range items {
response[i] = responses.NewCountItem(items[i])
}
return returnArray(c, response)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/hex"
"net/http"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/labstack/echo/v4"
)
type TxHandler struct {
tx storage.ITx
events storage.IEvent
messages storage.IMessage
namespaces storage.INamespace
blobLogs storage.IBlobLog
state storage.IState
indexerName string
}
func NewTxHandler(
tx storage.ITx,
events storage.IEvent,
messages storage.IMessage,
namespaces storage.INamespace,
blobLogs storage.IBlobLog,
state storage.IState,
indexerName string,
) *TxHandler {
return &TxHandler{
tx: tx,
events: events,
messages: messages,
namespaces: namespaces,
blobLogs: blobLogs,
state: state,
indexerName: indexerName,
}
}
type getTxRequest struct {
Hash string `param:"hash" validate:"required,hexadecimal,len=64"`
}
// Get godoc
//
// @Summary Get transaction by hash
// @Description Get transaction by hash
// @Tags transactions
// @ID get-transaction
// @Param hash path string true "Transaction hash in hexadecimal" minlength(64) maxlength(64)
// @Produce json
// @Success 200 {object} responses.Tx
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/{hash} [get]
func (handler *TxHandler) Get(c echo.Context) error {
req, err := bindAndValidate[getTxRequest](c)
if err != nil {
return badRequestError(c, err)
}
hash, err := hex.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
tx, err := handler.tx.ByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.tx)
}
return c.JSON(http.StatusOK, responses.NewTx(tx))
}
// List godoc
//
// @Summary List transactions info
// @Description List transactions info
// @Tags transactions
// @ID list-transactions
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Param status query types.Status false "Comma-separated status list"
// @Param msg_type query types.MsgType false "Comma-separated message types list"
// @Param excluded_msg_type query types.MsgType false "Comma-separated message types list which should be excluded"
// @Param from query integer false "Time from in unix timestamp" mininum(1)
// @Param to query integer false "Time to in unix timestamp" mininum(1)
// @Param height query integer false "Block number" mininum(1)
// @Param messages query boolean false "If true join messages" mininum(1)
// @Produce json
// @Success 200 {array} responses.Tx
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx [get]
func (handler *TxHandler) List(c echo.Context) error {
req, err := bindAndValidate[txListRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
fltrs := storage.TxFilter{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
Status: req.Status,
Height: req.Height,
MessageTypes: types.NewMsgTypeBitMask(),
ExcludedMessageTypes: types.NewMsgTypeBitMask(),
WithMessages: req.Messages,
}
if req.From > 0 {
fltrs.TimeFrom = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
fltrs.TimeTo = time.Unix(req.To, 0).UTC()
}
for i := range req.MsgType {
fltrs.MessageTypes.SetByMsgType(types.MsgType(req.MsgType[i]))
}
for i := range req.ExcludedMsgType {
fltrs.ExcludedMessageTypes.SetByMsgType(types.MsgType(req.ExcludedMsgType[i]))
}
txs, err := handler.tx.Filter(c.Request().Context(), fltrs)
if err != nil {
return handleError(c, err, handler.tx)
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[i])
}
return returnArray(c, response)
}
type getTxRequestWithPagination struct {
Hash string `param:"hash" validate:"required,hexadecimal,len=64"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (p *getTxRequestWithPagination) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
// GetEvents godoc
//
// @Summary Get transaction events
// @Description Get transaction events
// @Tags transactions
// @ID get-transaction-events
// @Param hash path string true "Transaction hash in hexadecimal" minlength(64) maxlength(64)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.Event
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/{hash}/events [get]
func (handler *TxHandler) GetEvents(c echo.Context) error {
req, err := bindAndValidate[getTxRequestWithPagination](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
hash, err := hex.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
txId, txTime, err := handler.tx.IdAndTimeByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.tx)
}
fltrs := storage.EventFilter{
Limit: req.Limit,
Offset: req.Offset,
Time: txTime.UTC(),
}
events, err := handler.events.ByTxId(c.Request().Context(), txId, fltrs)
if err != nil {
return handleError(c, err, handler.tx)
}
response := make([]responses.Event, len(events))
for i := range events {
response[i] = responses.NewEvent(events[i])
}
return returnArray(c, response)
}
// GetMessages godoc
//
// @Summary Get transaction messages
// @Description Get transaction messages
// @Tags transactions
// @ID get-transaction-messages
// @Param hash path string true "Transaction hash in hexadecimal" minlength(64) maxlength(64)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {array} responses.Message
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/{hash}/messages [get]
func (handler *TxHandler) GetMessages(c echo.Context) error {
req, err := bindAndValidate[getTxRequestWithPagination](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
hash, err := hex.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
txId, _, err := handler.tx.IdAndTimeByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.tx)
}
messages, err := handler.messages.ByTxId(c.Request().Context(), txId, req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.tx)
}
response := make([]responses.Message, len(messages))
for i := range messages {
response[i] = responses.NewMessage(messages[i])
}
return returnArray(c, response)
}
// Count godoc
//
// @Summary Get count of transactions in network
// @Description Get count of transactions in network
// @Tags transactions
// @ID get-transactions-count
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /tx/count [get]
func (handler *TxHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err != nil {
return handleError(c, err, handler.tx)
}
return c.JSON(http.StatusOK, state.TotalTx)
}
// Genesis godoc
//
// @Summary List genesis transactions info
// @Description List genesis transactions info
// @Tags transactions
// @ID list-genesis-transactions
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order" Enums(asc, desc)
// @Produce json
// @Success 200 {array} responses.Tx
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/genesis [get]
func (handler *TxHandler) Genesis(c echo.Context) error {
req, err := bindAndValidate[limitOffsetPagination](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
txs, err := handler.tx.Genesis(c.Request().Context(), req.Limit, req.Offset, pgSort(req.Sort))
if err != nil {
return handleError(c, err, handler.tx)
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[i])
}
return returnArray(c, response)
}
type getBlobsForTx struct {
Hash string `param:"hash" validate:"required,hexadecimal,len=64"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
SortBy string `query:"sort_by" validate:"omitempty,oneof=time size"`
}
func (req *getBlobsForTx) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
if req.Sort == "" {
req.Sort = desc
}
}
// Blobs godoc
//
// @Summary List blobs which was pushed by transaction
// @Description List blobs which was pushed by transaction
// @Tags transactions
// @ID list-transaction-blobs
// @Param hash path string true "Transaction hash in hexadecimal" minlength(64) maxlength(64)
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param sort query string false "Sort order. Default: desc" Enums(asc, desc)
// @Param sort_by query string false "Sort field. If it's empty internal id is used" Enums(time, size)
// @Produce json
// @Success 200 {array} responses.BlobLog
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/{hash}/blobs [get]
func (handler *TxHandler) Blobs(c echo.Context) error {
req, err := bindAndValidate[getBlobsForTx](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
hash, err := hex.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
txId, _, err := handler.tx.IdAndTimeByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.tx)
}
blobs, err := handler.blobLogs.ByTxId(
c.Request().Context(),
txId,
storage.BlobLogFilters{
Limit: req.Limit,
Offset: req.Offset,
Sort: pgSort(req.Sort),
SortBy: req.SortBy,
},
)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
response := make([]responses.BlobLog, len(blobs))
for i := range blobs {
response[i] = responses.NewBlobLog(blobs[i])
}
return returnArray(c, response)
}
// BlobsCount godoc
//
// @Summary Count of blobs which was pushed by transaction
// @Description Count of blobs which was pushed by transaction
// @Tags transactions
// @ID transaction-blobs-count
// @Param hash path string true "Transaction hash in hexadecimal" minlength(64) maxlength(64)
// @Produce json
// @Success 200 {integer} uint64
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /tx/{hash}/blobs/count [get]
func (handler *TxHandler) BlobsCount(c echo.Context) error {
req, err := bindAndValidate[getTxRequest](c)
if err != nil {
return badRequestError(c, err)
}
hash, err := hex.DecodeString(req.Hash)
if err != nil {
return badRequestError(c, err)
}
txId, _, err := handler.tx.IdAndTimeByHash(c.Request().Context(), hash)
if err != nil {
return handleError(c, err, handler.tx)
}
count, err := handler.blobLogs.CountByTxId(c.Request().Context(), txId)
if err != nil {
return handleError(c, err, handler.blobLogs)
}
return c.JSON(http.StatusOK, count)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"strconv"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/math"
"github.com/celenium-io/celestia-indexer/internal/storage"
st "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/labstack/echo/v4"
)
type ValidatorHandler struct {
validators storage.IValidator
blocks storage.IBlock
blockSignatures storage.IBlockSignature
delegations storage.IDelegation
constants storage.IConstant
jails storage.IJail
state storage.IState
indexerName string
}
func NewValidatorHandler(
validators storage.IValidator,
blocks storage.IBlock,
blockSignatures storage.IBlockSignature,
delegations storage.IDelegation,
constants storage.IConstant,
jails storage.IJail,
state storage.IState,
indexerName string,
) *ValidatorHandler {
return &ValidatorHandler{
validators: validators,
blocks: blocks,
blockSignatures: blockSignatures,
delegations: delegations,
constants: constants,
jails: jails,
state: state,
indexerName: indexerName,
}
}
type validatorRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
}
// Get godoc
//
// @Summary Get validator info
// @Description Get validator info
// @Tags validator
// @ID get-validator
// @Param id path integer true "Internal validator id"
// @Produce json
// @Success 200 {object} responses.Validator
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/{id} [get]
func (handler *ValidatorHandler) Get(c echo.Context) error {
req, err := bindAndValidate[validatorRequest](c)
if err != nil {
return badRequestError(c, err)
}
validator, err := handler.validators.GetByID(c.Request().Context(), req.Id)
if err != nil {
return handleError(c, err, handler.validators)
}
return c.JSON(http.StatusOK, responses.NewValidator(*validator))
}
type validatorsPagination struct {
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
Jailed *bool `query:"jailed" validate:"omitempty"`
}
func (req *validatorsPagination) SetDefault() {
if req.Limit == 0 {
req.Limit = 10
}
}
// List godoc
//
// @Summary List validators
// @Description List validators
// @Tags validator
// @ID list-validator
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Param jailed query boolean false "Return only jailed validators"
// @Produce json
// @Success 200 {array} responses.Validator
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators [get]
func (handler *ValidatorHandler) List(c echo.Context) error {
req, err := bindAndValidate[validatorsPagination](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
validators, err := handler.validators.ListByPower(c.Request().Context(), storage.ValidatorFilters{
Limit: req.Limit,
Offset: req.Offset,
Jailed: req.Jailed,
})
if err != nil {
return handleError(c, err, handler.validators)
}
response := make([]responses.Validator, len(validators))
for i := range validators {
response[i] = *responses.NewValidator(validators[i])
}
return returnArray(c, response)
}
type validatorPageableRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
func (p *validatorPageableRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
// Blocks godoc
//
// @Summary Get blocks which was proposed by validator
// @Description Get blocks which was proposed by validator
// @Tags validator
// @ID get-validator-blocks
// @Param id path integer true "Internal validator id"
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {object} responses.Block
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/{id}/blocks [get]
func (handler *ValidatorHandler) Blocks(c echo.Context) error {
req, err := bindAndValidate[validatorPageableRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
blocks, err := handler.blocks.ByProposer(c.Request().Context(), req.Id, req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.validators)
}
response := make([]responses.Block, len(blocks))
for i := range blocks {
response[i] = responses.NewBlock(blocks[i], true)
}
return returnArray(c, response)
}
type validatorUptimeRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit types.Level `query:"limit" validate:"omitempty,min=1,max=100"`
}
func (r *validatorUptimeRequest) SetDefault() {
if r.Limit == 0 {
r.Limit = 10
}
}
// Uptime godoc
//
// @Summary Get validator's uptime and history of signed block
// @Description Get validator's uptime and history of signed block
// @Tags validator
// @ID get-validator-uptime
// @Param id path integer true "Internal validator id"
// @Param limit query integer false "Count of requested blocks" mininum(1) maximum(100)
// @Produce json
// @Success 200 {object} responses.ValidatorUptime
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/{id}/uptime [get]
func (handler *ValidatorHandler) Uptime(c echo.Context) error {
req, err := bindAndValidate[validatorUptimeRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err != nil {
return handleError(c, err, handler.blockSignatures)
}
startHeight := state.LastHeight - req.Limit - 1
levels, err := handler.blockSignatures.LevelsByValidator(c.Request().Context(), req.Id, startHeight)
if err != nil {
return handleError(c, err, handler.blockSignatures)
}
response := responses.NewValidatorUptime(levels, state.LastHeight-1, req.Limit)
return c.JSON(http.StatusOK, response)
}
type validatorDelegationsRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
ShowZero bool `query:"show_zero" validate:"omitempty"`
}
func (p *validatorDelegationsRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
// Delegators godoc
//
// @Summary Get validator's delegators
// @Description Get validator's delegators
// @Tags validator
// @ID validator-delegators
// @Param id path integer true "Internal validator id"
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Param show_zero query boolean false "Show zero delegations"
// @Produce json
// @Success 200 {array} responses.Delegation
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/{id}/delegators [get]
func (handler *ValidatorHandler) Delegators(c echo.Context) error {
req, err := bindAndValidate[validatorDelegationsRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
delegations, err := handler.delegations.ByValidator(
c.Request().Context(),
req.Id,
req.Limit,
req.Offset,
req.ShowZero,
)
if err != nil {
return handleError(c, err, handler.delegations)
}
response := make([]responses.Delegation, len(delegations))
for i := range response {
response[i] = responses.NewDelegation(delegations[i])
}
return returnArray(c, response)
}
// Jails godoc
//
// @Summary Get validator's jails
// @Description Get validator's jails
// @Tags validator
// @ID validator-jails
// @Param id path integer true "Internal validator id"
// @Param limit query integer false "Count of requested entities" minimum(1) maximum(100)
// @Param offset query integer false "Offset" minimum(1)
// @Produce json
// @Success 200 {array} responses.Jail
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/{id}/jails [get]
func (handler *ValidatorHandler) Jails(c echo.Context) error {
req, err := bindAndValidate[validatorPageableRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
jails, err := handler.jails.ByValidator(
c.Request().Context(),
req.Id,
req.Limit,
req.Offset,
)
if err != nil {
return handleError(c, err, handler.delegations)
}
response := make([]responses.Jail, len(jails))
for i := range response {
response[i] = responses.NewJail(jails[i])
}
return returnArray(c, response)
}
// Count godoc
//
// @Summary Get validator's count by status
// @Description Get validator's count by status
// @Tags validator
// @ID validator-count
// @Produce json
// @Success 200 {object} responses.ValidatorCount
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /validators/count [get]
func (handler *ValidatorHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err != nil {
return handleError(c, err, handler.state)
}
jailed, err := handler.validators.JailedCount(c.Request().Context())
if err != nil {
return handleError(c, err, handler.validators)
}
constant, err := handler.constants.Get(c.Request().Context(), st.ModuleNameStaking, "max_validators")
if err != nil {
return handleError(c, err, handler.validators)
}
max, err := strconv.ParseInt(constant.Value, 10, 32)
if err != nil {
return handleError(c, err, handler.validators)
}
active := math.Min(int(max), state.TotalValidators-jailed)
return c.JSON(http.StatusOK, responses.ValidatorCount{
Total: state.TotalValidators,
Jailed: jailed,
Active: active,
Inactive: state.TotalValidators - jailed - active,
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/base64"
"net/http"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
)
type CelestiaApiValidator struct {
validator *validator.Validate
}
func NewCelestiaApiValidator() *CelestiaApiValidator {
v := validator.New()
if err := v.RegisterValidation("address", addressValidator()); err != nil {
panic(err)
}
if err := v.RegisterValidation("status", statusValidator()); err != nil {
panic(err)
}
if err := v.RegisterValidation("msg_type", msgTypeValidator()); err != nil {
panic(err)
}
if err := v.RegisterValidation("namespace", namespaceValidator()); err != nil {
panic(err)
}
if err := v.RegisterValidation("category", categoryValidator()); err != nil {
panic(err)
}
if err := v.RegisterValidation("type", typeValidator()); err != nil {
panic(err)
}
return &CelestiaApiValidator{validator: v}
}
func (v *CelestiaApiValidator) Validate(i interface{}) error {
if err := v.validator.Struct(i); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return nil
}
func isAddress(address string) bool {
return validateAddress(address, pkgTypes.AddressPrefixCelestia, 47, 128)
}
func isValoperAddress(address string) bool {
return validateAddress(address, pkgTypes.AddressPrefixValoper, 54)
}
func validateAddress(address string, wantPrefix string, length ...int) bool {
addrLen := len(address)
switch len(length) {
case 1:
if addrLen != length[0] {
return false
}
case 2:
if addrLen < length[0] || addrLen > length[1] {
return false
}
default:
return false
}
prefix, _, err := bech32.DecodeAndConvert(address)
if err != nil {
return false
}
return prefix == wantPrefix
}
func addressValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
return isAddress(fl.Field().String()) || isValoperAddress(fl.Field().String())
}
}
func statusValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
_, err := types.ParseStatus(fl.Field().String())
return err == nil
}
}
func msgTypeValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
_, err := types.ParseMsgType(fl.Field().String())
return err == nil
}
}
func isNamespace(s string) bool {
hash, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return false
}
if len(hash) != 29 {
return false
}
return true
}
func namespaceValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
return isNamespace(fl.Field().String())
}
}
func categoryValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
_, err := types.ParseRollupCategory(fl.Field().String())
return err == nil
}
}
func typeValidator() validator.Func {
return func(fl validator.FieldLevel) bool {
_, err := types.ParseRollupType(fl.Field().String())
return err == nil
}
}
type KeyValidator struct {
apiKeys storage.IApiKey
errChecker NoRows
}
func NewKeyValidator(apiKeys storage.IApiKey, errChecker NoRows) KeyValidator {
return KeyValidator{apiKeys: apiKeys, errChecker: errChecker}
}
const ApiKeyName = "api_key"
func (kv KeyValidator) Validate(key string, c echo.Context) (bool, error) {
apiKey, err := kv.apiKeys.Get(c.Request().Context(), key)
if err != nil {
if kv.errChecker.IsNoRows(err) {
return false, nil
}
return false, err
}
c.Logger().Infof("using apikey: %s", apiKey.Description)
c.Set(ApiKeyName, apiKey)
return true, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type VestingHandler struct {
vestings storage.IVestingPeriod
}
func NewVestingHandler(vestings storage.IVestingPeriod) *VestingHandler {
return &VestingHandler{
vestings: vestings,
}
}
type getVestingPeriodsRequest struct {
Id uint64 `param:"id" validate:"required,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Offset int `query:"offset" validate:"omitempty,min=0"`
}
// Periods godoc
//
// @Summary Periods vesting periods by id
// @Description Periods vesting periods by id. Returns not empty array only for periodic vestings.
// @Tags vesting
// @ID get-vesting-periods
// @Param id path integer true "Internal identity"
// @Param limit query integer false "Count of requested entities" mininum(1) maximum(100)
// @Param offset query integer false "Offset" mininum(1)
// @Produce json
// @Success 200 {object} responses.VestingPeriod
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /vesting/{id}/periods [get]
func (handler *VestingHandler) Periods(c echo.Context) error {
req, err := bindAndValidate[getVestingPeriodsRequest](c)
if err != nil {
return badRequestError(c, err)
}
vestingPeriods, err := handler.vestings.ByVesting(c.Request().Context(), req.Id, req.Limit, req.Offset)
if err != nil {
return handleError(c, err, handler.vestings)
}
response := make([]responses.VestingPeriod, len(vestingPeriods))
for i := range vestingPeriods {
response[i] = responses.NewVestingPeriod(vestingPeriods[i])
}
return returnArray(c, response)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
sdkSync "github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/pkg/errors"
)
type processor[I any, M INotification] func(data I) Notification[M]
type Channel[I any, M INotification] struct {
clients *sdkSync.Map[uint64, client]
processor processor[I, M]
filters Filterable[M]
}
func NewChannel[I any, M INotification](processor processor[I, M], filters Filterable[M]) *Channel[I, M] {
return &Channel[I, M]{
clients: sdkSync.NewMap[uint64, client](),
processor: processor,
filters: filters,
}
}
func (channel *Channel[I, M]) AddClient(c client) {
channel.clients.Set(c.Id(), c)
}
func (channel *Channel[I, M]) RemoveClient(id uint64) {
channel.clients.Delete(id)
}
func (channel *Channel[I, M]) processMessage(msg I) error {
if channel.clients.Len() == 0 {
return nil
}
data := channel.processor(msg)
if err := channel.clients.Range(func(_ uint64, value client) (error, bool) {
if channel.filters.Filter(value, data) {
value.Notify(data)
}
return nil, false
}); err != nil {
return errors.Wrap(err, "write message to client")
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
"io"
"net"
"sync/atomic"
"time"
"github.com/dipdup-io/workerpool"
"github.com/goccy/go-json"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type client interface {
Id() uint64
ApplyFilters(msg Subscribe) error
DetachFilters(msg Unsubscribe) error
Notify(msg any)
WriteMessages(ctx context.Context, ws *websocket.Conn, log echo.Logger)
ReadMessages(ctx context.Context, ws *websocket.Conn, log echo.Logger)
Filters() *Filters
io.Closer
}
const (
// pongWait is how long we will await a pong response from client
pongWait = 10 * time.Second
// pingInterval has to be less than pongWait, We cant multiply by 0.9 to get 90% of time
// Because that can make decimals, so instead *9 / 10 to get 90%
// The reason why it has to be less than PingRequency is because otherwise it will send a new Ping before getting response
pingInterval = (pongWait * 9) / 10
)
type ClientHandler func(string, *Client)
type Client struct {
id uint64
filters *Filters
ch chan any
g workerpool.Group
subscribeHandler ClientHandler
unsubscribeHandler ClientHandler
closed *atomic.Bool
}
func newClient(id uint64, subscribeHandler, unsubscribeHandler ClientHandler) *Client {
closed := new(atomic.Bool)
closed.Store(false)
return &Client{
id: id,
ch: make(chan any, 128),
g: workerpool.NewGroup(),
subscribeHandler: subscribeHandler,
unsubscribeHandler: unsubscribeHandler,
closed: closed,
}
}
func (c *Client) Id() uint64 {
return c.id
}
func (c *Client) Filters() *Filters {
return c.filters
}
func (c *Client) ApplyFilters(msg Subscribe) error {
if c.filters == nil {
c.filters = &Filters{}
}
switch msg.Channel {
case ChannelHead:
c.filters.head = true
case ChannelBlocks:
c.filters.blocks = true
case ChannelGasPrice:
c.filters.gasPrice = true
default:
return errors.Wrap(ErrUnknownChannel, msg.Channel)
}
return nil
}
func (c *Client) DetachFilters(msg Unsubscribe) error {
if c.filters == nil {
return nil
}
switch msg.Channel {
case ChannelHead:
c.filters.head = false
case ChannelBlocks:
c.filters.blocks = false
case ChannelGasPrice:
c.filters.gasPrice = false
default:
return errors.Wrap(ErrUnknownChannel, msg.Channel)
}
return nil
}
func (c *Client) Notify(msg any) {
if c.closed.Load() {
return
}
c.ch <- msg
}
func (c *Client) Close() error {
c.g.Wait()
c.closed.Store(true)
close(c.ch)
c.subscribeHandler = nil
c.unsubscribeHandler = nil
return nil
}
func (c *Client) writeThread(ctx context.Context, ws *websocket.Conn, log echo.Logger) {
ticker := time.NewTicker(pingInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
log.Errorf("writemsg: %s", err)
return
}
case msg, ok := <-c.ch:
if !ok {
if err := ws.WriteMessage(websocket.CloseMessage, nil); err != nil {
log.Errorf("send close message: %s", err)
}
return
}
if err := ws.WriteJSON(msg); err != nil {
log.Errorf("send client message: %s", err)
}
}
}
}
func (c *Client) WriteMessages(ctx context.Context, ws *websocket.Conn, log echo.Logger) {
c.g.GoCtx(ctx, func(ctx context.Context) {
c.writeThread(ctx, ws, log)
})
}
func (c *Client) ReadMessages(ctx context.Context, ws *websocket.Conn, log echo.Logger) {
if err := ws.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
log.Error(err)
return
}
ws.SetPongHandler(func(_ string) error {
return ws.SetReadDeadline(time.Now().Add(pongWait))
})
for {
select {
case <-ctx.Done():
return
default:
if err := c.read(ws); err != nil {
timeoutErr, ok := err.(net.Error)
switch {
case err == io.EOF:
return
case errors.Is(err, websocket.ErrCloseSent):
return
case ok && timeoutErr.Timeout():
return
case websocket.IsCloseError(err,
websocket.CloseNormalClosure,
websocket.CloseAbnormalClosure,
websocket.CloseNoStatusReceived,
websocket.CloseGoingAway):
if c.unsubscribeHandler != nil {
c.unsubscribeHandler(ChannelHead, c)
c.unsubscribeHandler(ChannelBlocks, c)
}
return
}
log.Errorf("read websocket message: %s", err.Error())
}
}
}
}
func (c *Client) read(ws *websocket.Conn) error {
var msg Message
if err := ws.ReadJSON(&msg); err != nil {
return err
}
switch msg.Method {
case MethodSubscribe:
return c.handleSubscribeMessage(msg)
case MethodUnsubscribe:
return c.handleUnsubscribeMessage(msg)
default:
return errors.Wrap(ErrUnknownMethod, msg.Method)
}
}
func (c *Client) handleSubscribeMessage(msg Message) error {
var subscribeMsg Subscribe
if err := json.Unmarshal(msg.Body, &subscribeMsg); err != nil {
return err
}
if err := c.ApplyFilters(subscribeMsg); err != nil {
return err
}
if c.subscribeHandler != nil {
c.subscribeHandler(subscribeMsg.Channel, c)
}
return nil
}
func (c *Client) handleUnsubscribeMessage(msg Message) error {
var unsubscribeMsg Unsubscribe
if err := json.Unmarshal(msg.Body, &unsubscribeMsg); err != nil {
return err
}
if err := c.DetachFilters(unsubscribeMsg); err != nil {
return err
}
if c.unsubscribeHandler != nil {
c.unsubscribeHandler(unsubscribeMsg.Channel, c)
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
)
type Filterable[M INotification] interface {
Filter(c client, msg Notification[M]) bool
}
type BlockFilter struct{}
func (f BlockFilter) Filter(c client, msg Notification[*responses.Block]) bool {
if msg.Body == nil {
return false
}
fltrs := c.Filters()
if fltrs == nil {
return false
}
return fltrs.blocks
}
type HeadFilter struct{}
func (f HeadFilter) Filter(c client, msg Notification[*responses.State]) bool {
if msg.Body == nil {
return false
}
fltrs := c.Filters()
if fltrs == nil {
return false
}
return fltrs.head
}
type GasPriceFilter struct{}
func (f GasPriceFilter) Filter(c client, msg Notification[*responses.GasPrice]) bool {
if msg.Body == nil {
return false
}
fltrs := c.Filters()
if fltrs == nil {
return false
}
return fltrs.gasPrice
}
type Filters struct {
head bool
blocks bool
gasPrice bool
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
"net/http"
"sync/atomic"
"github.com/dipdup-io/workerpool"
sdkSync "github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/celenium-io/celestia-indexer/cmd/api/bus"
"github.com/celenium-io/celestia-indexer/cmd/api/gas"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
)
type Manager struct {
upgrader websocket.Upgrader
clientId *atomic.Uint64
clients *sdkSync.Map[uint64, *Client]
observer *bus.Observer
blocks *Channel[storage.Block, *responses.Block]
head *Channel[storage.State, *responses.State]
gasPrice *Channel[gas.GasPrice, *responses.GasPrice]
g workerpool.Group
}
func NewManager(observer *bus.Observer) *Manager {
manager := &Manager{
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
observer: observer,
clientId: new(atomic.Uint64),
clients: sdkSync.NewMap[uint64, *Client](),
g: workerpool.NewGroup(),
}
manager.blocks = NewChannel(
blockProcessor,
BlockFilter{},
)
manager.head = NewChannel(
headProcessor,
HeadFilter{},
)
manager.gasPrice = NewChannel(
gasPriceProcessor,
GasPriceFilter{},
)
return manager
}
func (manager *Manager) listen(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case block := <-manager.observer.Blocks():
if err := manager.blocks.processMessage(*block); err != nil {
log.Err(err).Msg("handle block")
}
case state := <-manager.observer.Head():
if err := manager.head.processMessage(*state); err != nil {
log.Err(err).Msg("handle state")
}
}
}
}
// Handle godoc
//
// @Summary Websocket API
// @Description.markdown websocket
// @Tags websocket
// @ID websocket
// @x-internal true
// @Produce json
// @Router /ws [get]
func (manager *Manager) Handle(c echo.Context) error {
ws, err := manager.upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
ws.SetReadLimit(1024 * 10) // 10KB
sId := manager.clientId.Add(1)
sub := newClient(sId, manager.AddClientToChannel, manager.RemoveClientFromChannel)
manager.clients.Set(sId, sub)
ctx, cancel := context.WithCancel(c.Request().Context())
sub.WriteMessages(ctx, ws, c.Logger())
sub.ReadMessages(ctx, ws, c.Logger())
manager.clients.Delete(sId)
cancel()
if err := sub.Close(); err != nil {
return err
}
return ws.Close()
}
func (manager *Manager) Start(ctx context.Context) {
manager.g.GoCtx(ctx, manager.listen)
}
func (manager *Manager) Close() error {
manager.g.Wait()
return manager.clients.Range(func(_ uint64, value *Client) (error, bool) {
if err := value.Close(); err != nil {
return err, false
}
return nil, false
})
}
func (manager *Manager) AddClientToChannel(channel string, client *Client) {
switch channel {
case ChannelHead:
manager.head.AddClient(client)
case ChannelBlocks:
manager.blocks.AddClient(client)
case ChannelGasPrice:
manager.gasPrice.AddClient(client)
default:
log.Error().Str("channel", channel).Msg("unknown channel name")
}
}
func (manager *Manager) RemoveClientFromChannel(channel string, client *Client) {
switch channel {
case ChannelHead:
manager.head.RemoveClient(client.id)
case ChannelBlocks:
manager.blocks.RemoveClient(client.id)
case ChannelGasPrice:
manager.gasPrice.RemoveClient(client.id)
default:
log.Error().Str("channel", channel).Msg("unknown channel name")
}
}
func (manager *Manager) GasTrackerHandler(_ context.Context, state gas.GasPrice) error {
return manager.gasPrice.processMessage(state)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/goccy/go-json"
)
// methods
const (
MethodSubscribe = "subscribe"
MethodUnsubscribe = "unsubscribe"
)
// channels
const (
ChannelHead = "head"
ChannelBlocks = "blocks"
ChannelGasPrice = "gas_price"
)
type Message struct {
Method string `json:"method" validate:"required,oneof=subscribe,unsubscribe"`
Body json.RawMessage `json:"body" validate:"required"`
}
type Subscribe struct {
Channel string `json:"channel" validate:"required,oneof=head tx"`
Filters json.RawMessage `json:"filters" validate:"required"`
}
type Unsubscribe struct {
Channel string `json:"channel" validate:"required,oneof=head tx"`
}
type TransactionFilters struct {
Status []string `json:"status,omitempty"`
Messages []string `json:"msg_type,omitempty"`
}
type INotification interface {
*responses.Block | *responses.State | *responses.GasPrice
}
type Notification[T INotification] struct {
Channel string `json:"channel"`
Body T `json:"body"`
}
func NewBlockNotification(block responses.Block) Notification[*responses.Block] {
return Notification[*responses.Block]{
Channel: ChannelBlocks,
Body: &block,
}
}
func NewStateNotification(state responses.State) Notification[*responses.State] {
return Notification[*responses.State]{
Channel: ChannelHead,
Body: &state,
}
}
func NewGasPriceNotification(value responses.GasPrice) Notification[*responses.GasPrice] {
return Notification[*responses.GasPrice]{
Channel: ChannelGasPrice,
Body: &value,
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"github.com/celenium-io/celestia-indexer/cmd/api/gas"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/responses"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
func blockProcessor(block storage.Block) Notification[*responses.Block] {
response := responses.NewBlock(block, true)
return NewBlockNotification(response)
}
func headProcessor(state storage.State) Notification[*responses.State] {
response := responses.NewState(state)
return NewStateNotification(response)
}
func gasPriceProcessor(data gas.GasPrice) Notification[*responses.GasPrice] {
return NewGasPriceNotification(responses.GasPrice{
Slow: data.Slow,
Median: data.Median,
Fast: data.Fast,
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/celenium-io/celestia-indexer/cmd/api/bus"
"github.com/celenium-io/celestia-indexer/cmd/api/cache"
"github.com/celenium-io/celestia-indexer/cmd/api/gas"
"github.com/celenium-io/celestia-indexer/cmd/api/handler"
"github.com/celenium-io/celestia-indexer/cmd/api/handler/websocket"
"github.com/celenium-io/celestia-indexer/internal/blob"
"github.com/celenium-io/celestia-indexer/internal/profiler"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/pkg/node"
nodeApi "github.com/celenium-io/celestia-indexer/pkg/node/dal"
"github.com/celenium-io/celestia-indexer/pkg/node/rpc"
"github.com/dipdup-net/go-lib/config"
"github.com/getsentry/sentry-go"
"github.com/grafana/pyroscope-go"
"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
"github.com/MarceloPetrucio/go-scalar-api-reference"
)
func init() {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006-01-02 15:04:05",
})
}
func initConfig() (*Config, error) {
configPath := rootCmd.PersistentFlags().StringP("config", "c", "dipdup.yml", "path to YAML config file")
if err := rootCmd.Execute(); err != nil {
log.Panic().Err(err).Msg("command line execute")
return nil, err
}
if err := rootCmd.MarkFlagRequired("config"); err != nil {
log.Panic().Err(err).Msg("config command line arg is required")
return nil, err
}
var cfg Config
if err := config.Parse(*configPath, &cfg); err != nil {
log.Panic().Err(err).Msg("parsing config file")
return nil, err
}
if cfg.LogLevel == "" {
cfg.LogLevel = zerolog.LevelInfoValue
}
return &cfg, nil
}
func initLogger(level string) error {
logLevel, err := zerolog.ParseLevel(level)
if err != nil {
log.Panic().Err(err).Msg("parsing log level")
return err
}
zerolog.SetGlobalLevel(logLevel)
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.Logger.With().Caller().Logger()
return nil
}
var prscp *pyroscope.Profiler
func initProflier(cfg *profiler.Config) (err error) {
prscp, err = profiler.New(cfg, "api")
return
}
func websocketSkipper(c echo.Context) bool {
return c.Path() == "/v1/ws"
}
func metricsSkipper(c echo.Context) bool {
return c.Path() == "/metrics"
}
func postSkipper(c echo.Context) bool {
if c.Request().Method != http.MethodPost {
return true
}
if strings.HasPrefix(c.Path(), "/v1/blob") {
return true
}
if strings.HasPrefix(c.Path(), "/v1/auth") {
return true
}
return false
}
func gzipSkipper(c echo.Context) bool {
if c.Path() == "/v1/swagger/doc.json" {
return true
}
if metricsSkipper(c) {
return true
}
return websocketSkipper(c)
}
func observableCacheSkipper(c echo.Context) bool {
if c.Request().Method != http.MethodGet {
return true
}
if websocketSkipper(c) {
return true
}
if metricsSkipper(c) {
return true
}
if c.Path() == "/v1/head" {
return true
}
if strings.Contains(c.Path(), "/v1/block/:height") {
return true
}
if strings.Contains(c.Path(), "/v1/tx/:hash") {
return true
}
return false
}
func initEcho(cfg ApiConfig, env string) *echo.Echo {
e := echo.New()
e.Validator = handler.NewCelestiaApiValidator()
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogLatency: true,
LogMethod: true,
LogUserAgent: true,
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
switch {
case v.Status == http.StatusOK || v.Status == http.StatusNoContent:
log.Info().
Str("uri", v.URI).
Int("status", v.Status).
Dur("latency", v.Latency).
Str("method", v.Method).
Str("user-agent", v.UserAgent).
Str("ip", c.RealIP()).
Msg("request")
case v.Status >= 500:
log.Error().
Str("uri", v.URI).
Int("status", v.Status).
Dur("latency", v.Latency).
Str("method", v.Method).
Str("user-agent", v.UserAgent).
Str("ip", c.RealIP()).
Msg("request")
default:
log.Warn().
Str("uri", v.URI).
Int("status", v.Status).
Dur("latency", v.Latency).
Str("method", v.Method).
Str("user-agent", v.UserAgent).
Str("ip", c.RealIP()).
Msg("request")
}
return nil
},
}))
timeout := 30 * time.Second
if cfg.RequestTimeout > 0 {
timeout = time.Duration(cfg.RequestTimeout) * time.Second
}
e.Use(RequestTimeout(timeout, websocketSkipper))
e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
Skipper: gzipSkipper,
}))
e.Use(middleware.DecompressWithConfig(middleware.DecompressConfig{
Skipper: websocketSkipper,
}))
e.Use(middleware.BodyLimit("2M"))
e.Use(middleware.CSRFWithConfig(
middleware.CSRFConfig{
Skipper: func(c echo.Context) bool {
return websocketSkipper(c) || postSkipper(c)
},
},
))
e.Use(middleware.Recover())
e.Use(middleware.Secure())
e.Pre(middleware.RemoveTrailingSlash())
if cfg.Prometheus {
e.Use(echoprometheus.NewMiddlewareWithConfig(echoprometheus.MiddlewareConfig{
Namespace: "celestia_api",
Skipper: websocketSkipper,
}))
}
if cfg.RateLimit > 0 {
e.Use(middleware.RateLimiterWithConfig(middleware.RateLimiterConfig{
Skipper: websocketSkipper,
Store: middleware.NewRateLimiterMemoryStore(rate.Limit(cfg.RateLimit)),
}))
}
if err := initSentry(e, cfg.SentryDsn, env); err != nil {
log.Err(err).Msg("sentry")
}
e.Server.IdleTimeout = time.Second * 30
return e
}
var dispatcher *bus.Dispatcher
func initDispatcher(ctx context.Context, db postgres.Storage) {
d, err := bus.NewDispatcher(db, db.Validator)
if err != nil {
panic(err)
}
dispatcher = d
dispatcher.Start(ctx)
}
func initDatabase(cfg config.Database, viewsDir string) postgres.Storage {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
db, err := postgres.Create(ctx, cfg, viewsDir, false)
if err != nil {
panic(err)
}
return db
}
var ttlCache cache.ICache
func initCache(url string) {
if url != "" {
c, err := cache.NewValKey(url, time.Hour)
if err != nil {
panic(err)
}
ttlCache = c
}
}
func initHandlers(ctx context.Context, e *echo.Echo, cfg Config, db postgres.Storage) {
if cfg.ApiConfig.Prometheus {
e.GET("/metrics", echoprometheus.NewHandler())
}
v1 := e.Group("v1")
stateHandlers := handler.NewStateHandler(db.State, db.Validator, cfg.Indexer.Name)
v1.GET("/head", stateHandlers.Head)
defaultMiddlewareCache := cache.Middleware(ttlCache, nil, nil)
statsMiddlewareCache := cache.Middleware(ttlCache, nil, func() time.Duration {
now := time.Now()
diff := now.Truncate(time.Hour).Add(time.Hour).Sub(now)
if diff > time.Minute*10 {
return time.Minute * 10
}
return diff
})
constantsHandler := handler.NewConstantHandler(db.Constants, db.DenomMetadata, db.Rollup)
v1.GET("/constants", constantsHandler.Get, defaultMiddlewareCache)
v1.GET("/enums", constantsHandler.Enums, defaultMiddlewareCache)
searchHandler := handler.NewSearchHandler(db.Search, db.Address, db.Blocks, db.Tx, db.Namespace, db.Validator, db.Rollup, db.Celestials)
v1.GET("/search", searchHandler.Search)
addressHandlers := handler.NewAddressHandler(db.Address, db.Tx, db.BlobLogs, db.Message, db.Delegation, db.Undelegation, db.Redelegation, db.VestingAccounts, db.Grants, db.Celestials, db.State, cfg.Indexer.Name)
addressesGroup := v1.Group("/address")
{
addressesGroup.GET("", addressHandlers.List)
addressesGroup.GET("/count", addressHandlers.Count)
addressGroup := addressesGroup.Group("/:hash")
{
addressGroup.GET("", addressHandlers.Get)
addressGroup.GET("/txs", addressHandlers.Transactions)
addressGroup.GET("/messages", addressHandlers.Messages)
addressGroup.GET("/blobs", addressHandlers.Blobs)
addressGroup.GET("/delegations", addressHandlers.Delegations)
addressGroup.GET("/undelegations", addressHandlers.Undelegations)
addressGroup.GET("/redelegations", addressHandlers.Redelegations)
addressGroup.GET("/vestings", addressHandlers.Vestings)
addressGroup.GET("/grants", addressHandlers.Grants)
addressGroup.GET("/granters", addressHandlers.Grantee)
addressGroup.GET("/celestials", addressHandlers.Celestials)
addressGroup.GET("/stats/:name/:timeframe", addressHandlers.Stats, statsMiddlewareCache)
}
}
ds, ok := cfg.DataSources["node_rpc"]
if !ok {
panic("can't find node data source: node_rpc")
}
node := rpc.NewAPI(ds)
blockHandlers := handler.NewBlockHandler(db.Blocks, db.BlockStats, db.Event, db.Namespace, db.Message, db.BlobLogs, db.State, &node, cfg.Indexer.Name)
blockGroup := v1.Group("/block")
{
blockGroup.GET("", blockHandlers.List)
blockGroup.GET("/count", blockHandlers.Count)
heightGroup := blockGroup.Group("/:height")
{
heightGroup.GET("", blockHandlers.Get, defaultMiddlewareCache)
heightGroup.GET("/events", blockHandlers.GetEvents, defaultMiddlewareCache)
heightGroup.GET("/messages", blockHandlers.GetMessages, defaultMiddlewareCache)
heightGroup.GET("/stats", blockHandlers.GetStats, defaultMiddlewareCache)
heightGroup.GET("/blobs", blockHandlers.Blobs, defaultMiddlewareCache)
heightGroup.GET("/blobs/count", blockHandlers.BlobsCount, defaultMiddlewareCache)
heightGroup.GET("/ods", blockHandlers.BlockODS, defaultMiddlewareCache)
}
}
txHandlers := handler.NewTxHandler(db.Tx, db.Event, db.Message, db.Namespace, db.BlobLogs, db.State, cfg.Indexer.Name)
txGroup := v1.Group("/tx")
{
txGroup.GET("", txHandlers.List)
txGroup.GET("/count", txHandlers.Count)
txGroup.GET("/genesis", txHandlers.Genesis, defaultMiddlewareCache)
hashGroup := txGroup.Group("/:hash")
{
hashGroup.GET("", txHandlers.Get, defaultMiddlewareCache)
hashGroup.GET("/events", txHandlers.GetEvents, defaultMiddlewareCache)
hashGroup.GET("/messages", txHandlers.GetMessages, defaultMiddlewareCache)
hashGroup.GET("/blobs", txHandlers.Blobs, defaultMiddlewareCache)
hashGroup.GET("/blobs/count", txHandlers.BlobsCount, defaultMiddlewareCache)
}
}
blobReceiver, err := initBlobReceiver(ctx, cfg)
if err != nil {
panic(err)
}
namespaceHandlers := handler.NewNamespaceHandler(
db.Namespace,
db.BlobLogs,
db.Rollup,
db.Address,
db.State,
cfg.Indexer.Name,
blobReceiver,
&node,
)
blobGroup := v1.Group("/blob")
{
blobGroup.GET("", namespaceHandlers.Blobs)
blobGroup.POST("", namespaceHandlers.Blob)
blobGroup.POST("/metadata", namespaceHandlers.BlobMetadata)
blobGroup.POST("/proofs", namespaceHandlers.BlobProofs)
}
namespaceGroup := v1.Group("/namespace")
{
namespaceGroup.GET("", namespaceHandlers.List)
namespaceGroup.GET("/:id", namespaceHandlers.Get)
namespaceGroup.GET("/:id/:version", namespaceHandlers.GetWithVersion)
namespaceGroup.GET("/:id/:version/messages", namespaceHandlers.GetMessages)
namespaceGroup.GET("/:id/:version/blobs", namespaceHandlers.GetBlobLogs)
namespaceGroup.GET("/:id/:version/rollups", namespaceHandlers.Rollups)
}
namespaceByHash := v1.Group("/namespace_by_hash")
{
namespaceByHash.GET("/:hash", namespaceHandlers.GetByHash)
namespaceByHash.GET("/:hash/:height", namespaceHandlers.GetBlobs)
}
validatorsHandler := handler.NewValidatorHandler(db.Validator, db.Blocks, db.BlockSignatures, db.Delegation, db.Constants, db.Jails, db.State, cfg.Indexer.Name)
validators := v1.Group("/validators")
{
validators.GET("", validatorsHandler.List)
validators.GET("/count", validatorsHandler.Count)
validator := validators.Group("/:id")
{
validator.GET("", validatorsHandler.Get)
validator.GET("/blocks", validatorsHandler.Blocks)
validator.GET("/uptime", validatorsHandler.Uptime)
validator.GET("/delegators", validatorsHandler.Delegators)
validator.GET("/jails", validatorsHandler.Jails)
}
}
statsHandler := handler.NewStatsHandler(db.Stats, db.Namespace, db.Price, db.State)
stats := v1.Group("/stats")
{
stats.GET("/summary/:table/:function", statsHandler.Summary)
stats.GET("/tps", statsHandler.TPS)
stats.GET("/changes_24h", statsHandler.Change24hBlockStats)
stats.GET("/rollup_stats_24h", statsHandler.RollupStats24h)
stats.GET("/square_size", statsHandler.SquareSize)
stats.GET("/messages_count_24h", statsHandler.MessagesCount24h)
price := stats.Group("/price")
{
price.GET("/current", statsHandler.PriceCurrent)
price.GET("/series/:timeframe", statsHandler.PriceSeries, statsMiddlewareCache)
}
namespace := stats.Group("/namespace")
{
namespace.GET("/usage", statsHandler.NamespaceUsage)
namespace.GET("/series/:id/:name/:timeframe", statsHandler.NamespaceSeries, statsMiddlewareCache)
}
staking := stats.Group("/staking")
{
staking.GET("/series/:id/:name/:timeframe", statsHandler.StakingSeries, statsMiddlewareCache)
}
series := stats.Group("/series")
{
series.GET("/:name/:timeframe", statsHandler.Series, statsMiddlewareCache)
series.GET("/:name/:timeframe/cumulative", statsHandler.SeriesCumulative, statsMiddlewareCache)
}
}
gasHandler := handler.NewGasHandler(db.State, db.Tx, db.Constants, db.BlockStats, gasTracker)
gas := v1.Group("/gas")
{
gas.GET("/estimate_for_pfb", gasHandler.EstimateForPfb)
gas.GET("/price", gasHandler.EstimatePrice)
gas.GET("/price/:priority", gasHandler.EstimatePricePriority)
}
vestingHandler := handler.NewVestingHandler(db.VestingPeriods)
vesting := v1.Group("/vesting")
{
vesting.GET("/:id/periods", vestingHandler.Periods)
}
htmlContent, err := scalar.ApiReferenceHTML(&scalar.Options{
SpecURL: "./docs/swagger.json",
CustomOptions: scalar.CustomOptions{
PageTitle: "Celenium API",
},
DarkMode: true,
ShowSidebar: true,
})
if err != nil {
panic(err)
}
v1.GET("/docs", func(c echo.Context) error {
return c.HTML(http.StatusOK, htmlContent)
})
f, err := os.Open("./docs/swagger.json")
if err != nil {
panic(err)
}
defer f.Close()
docsJson, err := io.ReadAll(f)
if err != nil {
panic(err)
}
v1.GET("/swagger/doc.json", func(c echo.Context) error {
return c.Blob(http.StatusOK, "application/json", docsJson)
})
if cfg.ApiConfig.Websocket {
initWebsocket(ctx, v1)
}
rollupHandler := handler.NewRollupHandler(db.Rollup, db.Namespace, db.BlobLogs)
rollups := v1.Group("/rollup")
{
rollups.GET("", rollupHandler.Leaderboard)
rollups.GET("/count", rollupHandler.Count)
rollups.GET("/day", rollupHandler.LeaderboardDay)
rollups.GET("/group", rollupHandler.RollupGroupedStats, statsMiddlewareCache)
rollups.GET("/stats/series/:timeframe", rollupHandler.AllSeries, statsMiddlewareCache)
rollups.GET("/slug/:slug", rollupHandler.BySlug)
rollup := rollups.Group("/:id")
{
rollup.GET("", rollupHandler.Get)
rollup.GET("/namespaces", rollupHandler.GetNamespaces)
rollup.GET("/blobs", rollupHandler.GetBlobs)
rollup.GET("/stats/:name/:timeframe", rollupHandler.Stats, statsMiddlewareCache)
rollup.GET("/distribution/:name/:timeframe", rollupHandler.Distribution, statsMiddlewareCache)
rollup.GET("/export", rollupHandler.ExportBlobs)
}
}
auth := v1.Group("/auth")
{
keyValidator := handler.NewKeyValidator(db.ApiKeys, db.BlobLogs)
keyMiddleware := middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
KeyLookup: "header:Authorization",
Validator: keyValidator.Validate,
})
adminMiddleware := AdminMiddleware()
rollupAuthHandler := handler.NewRollupAuthHandler(db.Rollup, db.Address, db.Namespace, db.Transactable)
rollup := auth.Group("/rollup")
{
rollup.POST("/new", rollupAuthHandler.Create, keyMiddleware)
rollup.PATCH("/:id", rollupAuthHandler.Update, keyMiddleware)
rollup.DELETE("/:id", rollupAuthHandler.Delete, keyMiddleware, adminMiddleware)
rollup.PATCH("/:id/verify", rollupAuthHandler.Verify, keyMiddleware, adminMiddleware)
rollup.GET("/unverified", rollupAuthHandler.Unverified, keyMiddleware, adminMiddleware)
}
}
log.Info().Msg("API routes:")
for _, route := range e.Routes() {
log.Info().Msgf("[%s] %s -> %s", route.Method, route.Path, route.Name)
}
}
func initSentry(e *echo.Echo, dsn, environment string) error {
if dsn == "" {
return nil
}
if err := sentry.Init(sentry.ClientOptions{
Dsn: dsn,
AttachStacktrace: true,
Environment: environment,
EnableTracing: true,
TracesSampleRate: 0.1,
Release: os.Getenv("TAG"),
IgnoreTransactions: []string{
"GET /v1/ws",
},
}); err != nil {
return errors.Wrap(err, "initialization")
}
e.Use(SentryMiddleware())
return nil
}
var (
wsManager *websocket.Manager
)
func initWebsocket(ctx context.Context, group *echo.Group) {
observer := dispatcher.Observe(storage.ChannelHead, storage.ChannelBlock)
wsManager = websocket.NewManager(observer)
if gasTracker != nil {
gasTracker.SubscribeOnCompute(wsManager.GasTrackerHandler)
}
wsManager.Start(ctx)
group.GET("/ws", wsManager.Handle)
}
var gasTracker *gas.Tracker
func initGasTracker(ctx context.Context, db postgres.Storage) {
observer := dispatcher.Observe(storage.ChannelBlock)
gasTracker = gas.NewTracker(db.State, db.BlockStats, db.Tx, observer)
if err := gasTracker.Init(ctx); err != nil {
panic(err)
}
gasTracker.Start(ctx)
}
func initBlobReceiver(ctx context.Context, cfg Config) (node.DalApi, error) {
switch cfg.ApiConfig.BlobReceiver {
case "r2":
r2 := blob.NewR2(blob.R2Config{
BucketName: os.Getenv("R2_BUCKET"),
AccountId: os.Getenv("R2_ACCOUNT_ID"),
AccessKeyId: os.Getenv("R2_ACCESS_KEY_ID"),
AccessKeySecret: os.Getenv("R2_ACCESS_KEY_SECRET"),
})
err := r2.Init(ctx)
return r2, err
default:
datasource, ok := cfg.DataSources[cfg.ApiConfig.BlobReceiver]
if !ok {
return nil, errors.Errorf("unknown data source pointed in blob_receiver: %s", cfg.ApiConfig.BlobReceiver)
}
return nodeApi.New(datasource.URL).
WithAuthToken(os.Getenv("CELESTIA_NODE_AUTH_TOKEN")).
WithRateLimit(datasource.RequestsPerSecond), nil
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "api",
Short: "DipDup Verticals | Celenium API",
}
// @title Celenium API
// @version 1.0
// @description Celenium API is a powerful tool to access all blockchain data that is processed and indexed by our proprietary indexer. With Celenium API you can retrieve all historical data, off-chain data, blobs and statistics through our REST API. Celenium API indexer are open source, which allows you to not depend on third-party services. You can clone, build and run them independently, giving you full control over all components. If you have any questions or feature requests, please feel free to contact us. We appreciate your feedback!
// @host api-mainnet.celenium.io
// @schemes https
// @BasePath /v1
//
// @contact.name Support
// @contact.url https://discord.gg/3k83Przqk8
// @contact.email celenium@pklabs.me
//
// @externalDocs.description Full documentation
// @externalDocs.url https://api-docs.celenium.io/
//
// @x-servers [{"url": "api-mainnet.celenium.io", "description": "Celenium Mainnet API"},{"url": "api-mocha.celenium.io", "description": "Celenium Mocha API"},{"url": "api-arabica.celenium.io", "description": "Celenium Arabica API"}]
// @query.collection.format multi
//
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name apikey
// @description To authorize your requests you have to select the required tariff on our site. Then you receive api key to authorize. Api key should be passed via request header `apikey`.
func main() {
cfg, err := initConfig()
if err != nil {
return
}
if err = initLogger(cfg.LogLevel); err != nil {
return
}
if err := initProflier(cfg.Profiler); err != nil {
return
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
initCache(cfg.ApiConfig.Cache)
db := initDatabase(cfg.Database, cfg.Indexer.ScriptsDir)
e := initEcho(cfg.ApiConfig, cfg.Environment)
initDispatcher(ctx, db)
initGasTracker(ctx, db)
initHandlers(ctx, e, *cfg, db)
go func() {
if err := e.Start(cfg.ApiConfig.Bind); err != nil && errors.Is(err, http.ErrServerClosed) {
e.Logger.Fatal("shutting down the server")
}
}()
<-ctx.Done()
cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
if gasTracker != nil {
if err := gasTracker.Close(); err != nil {
e.Logger.Fatal(err)
}
}
if wsManager != nil {
if err := wsManager.Close(); err != nil {
e.Logger.Fatal(err)
}
}
if dispatcher != nil {
if err := dispatcher.Close(); err != nil {
e.Logger.Fatal(err)
}
}
if prscp != nil {
if err := prscp.Stop(); err != nil {
e.Logger.Fatal(err)
}
}
if err := db.Close(); err != nil {
e.Logger.Fatal(err)
}
if ttlCache != nil {
if err := ttlCache.Close(); err != nil {
e.Logger.Fatal(err)
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/getsentry/sentry-go"
"github.com/labstack/echo/v4"
)
const sdkIdentifier = "sentry.go.http"
func SentryMiddleware() echo.MiddlewareFunc {
return handleSentry
}
func handleSentry(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
hub := sentry.GetHubFromContext(ctx.Request().Context())
if hub == nil {
hub = sentry.CurrentHub().Clone()
}
if client := hub.Client(); client != nil {
client.SetSDKIdentifier(sdkIdentifier)
}
ctx.Set("sentry", hub)
req := ctx.Request()
options := []sentry.SpanOption{
sentry.WithOpName("http.server"),
sentry.ContinueFromRequest(req),
sentry.WithTransactionSource(sentry.SourceURL),
}
transaction := sentry.StartTransaction(ctx.Request().Context(),
fmt.Sprintf("%s %s", req.Method, req.URL.Path),
options...,
)
defer func() {
transaction.Status = sentry.HTTPtoSpanStatus(ctx.Response().Status)
transaction.Finish()
}()
req = req.WithContext(transaction.Context())
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetUser(sentry.User{
IPAddress: ctx.RealIP(),
})
scope.SetRequest(req)
})
defer recoverWithSentry(hub, req)
ctx.SetRequest(req)
return next(ctx)
}
}
func recoverWithSentry(hub *sentry.Hub, r *http.Request) {
if err := recover(); err != nil {
eventID := hub.RecoverWithContext(
context.WithValue(r.Context(), sentry.RequestContextKey, r),
err,
)
if eventID != nil {
hub.Flush(time.Second * 10)
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"time"
"github.com/labstack/echo/v4"
)
func RequestTimeout(timeout time.Duration, skipper func(echo.Context) bool) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if skipper != nil {
if skipper(c) {
return next(c)
}
}
timeoutCtx, cancel := context.WithTimeout(c.Request().Context(), timeout)
c.SetRequest(c.Request().WithContext(timeoutCtx))
defer cancel()
return next(c)
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"os"
"strconv"
goLibConfig "github.com/dipdup-net/go-lib/config"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func init() {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006-01-02 15:04:05",
})
}
func initConfig() (*Config, error) {
configPath := rootCmd.PersistentFlags().StringP("config", "c", "dipdup.yml", "path to YAML config file")
if err := rootCmd.Execute(); err != nil {
log.Panic().Err(err).Msg("command line execute")
return nil, err
}
if err := rootCmd.MarkFlagRequired("config"); err != nil {
log.Panic().Err(err).Msg("config command line arg is required")
return nil, err
}
var cfg Config
if err := goLibConfig.Parse(*configPath, &cfg); err != nil {
log.Panic().Err(err).Msg("parsing config file")
return nil, err
}
if cfg.LogLevel == "" {
cfg.LogLevel = zerolog.LevelInfoValue
}
return &cfg, nil
}
func initLogger(level string) error {
logLevel, err := zerolog.ParseLevel(level)
if err != nil {
log.Panic().Err(err).Msg("parsing log level")
return err
}
zerolog.SetGlobalLevel(logLevel)
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.Logger.With().Caller().Logger()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/pkg/types"
celestials "github.com/celenium-io/celestial-module/pkg/module"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "celestials",
Short: "DipDup Verticals | Celestials indexer for Celenium",
}
func main() {
cfg, err := initConfig()
if err != nil {
return
}
if err = initLogger(cfg.LogLevel); err != nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
notifyCtx, notifyCancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
defer notifyCancel()
celestialsDatasource, ok := cfg.DataSources["celestials"]
if !ok {
log.Panic().Err(err).Msg("can't find celestials data source")
return
}
pg, err := postgres.Create(ctx, cfg.Database, cfg.Indexer.ScriptsDir, false)
if err != nil {
log.Panic().Err(err).Msg("can't create database connection")
return
}
log.Info().Str("chain_id", cfg.Celestials.ChainId).Msg("running module")
handler := func(ctx context.Context, address string) (uint64, error) {
return addressHandler(ctx, pg.Address, address)
}
module := celestials.New(
celestialsDatasource,
handler,
pg.Celestials,
pg.CelestialState,
pg.Transactable,
cfg.Indexer.Name,
cfg.Celestials.ChainId,
)
module.Start(ctx)
<-notifyCtx.Done()
cancel()
if err := module.Close(); err != nil {
log.Panic().Err(err).Msg("stopping celestials indexer")
}
log.Info().Msg("stopped")
}
func addressHandler(ctx context.Context, repo storage.IAddress, address string) (uint64, error) {
prefix, hash, err := types.Address(address).Decode()
if err != nil {
return 0, errors.Wrap(err, "decoding address")
}
if prefix != types.AddressPrefixCelestia {
return 0, errors.Errorf("invalid prefix: %s", prefix)
}
addressId, err := repo.IdByHash(ctx, hash)
if err != nil || len(addressId) == 0 {
return 0, errors.Errorf("can't find address %s in database", address)
}
return addressId[0], nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"os"
"strconv"
"github.com/celenium-io/celestia-indexer/internal/profiler"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
goLibConfig "github.com/dipdup-net/go-lib/config"
"github.com/grafana/pyroscope-go"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func init() {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006-01-02 15:04:05",
})
}
func initConfig() (*config.Config, error) {
configPath := rootCmd.PersistentFlags().StringP("config", "c", "dipdup.yml", "path to YAML config file")
if err := rootCmd.Execute(); err != nil {
log.Panic().Err(err).Msg("command line execute")
return nil, err
}
if err := rootCmd.MarkFlagRequired("config"); err != nil {
log.Panic().Err(err).Msg("config command line arg is required")
return nil, err
}
var cfg config.Config
if err := goLibConfig.Parse(*configPath, &cfg); err != nil {
log.Panic().Err(err).Msg("parsing config file")
return nil, err
}
if cfg.LogLevel == "" {
cfg.LogLevel = zerolog.LevelInfoValue
}
return &cfg, nil
}
func initLogger(level string) error {
logLevel, err := zerolog.ParseLevel(level)
if err != nil {
log.Panic().Err(err).Msg("parsing log level")
return err
}
zerolog.SetGlobalLevel(logLevel)
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.Logger.With().Caller().Logger()
return nil
}
var prscp *pyroscope.Profiler
func initProflier(cfg *profiler.Config) (err error) {
prscp, err = profiler.New(cfg, "indexer")
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/dipdup-net/indexer-sdk/pkg/modules/stopper"
"github.com/celenium-io/celestia-indexer/pkg/indexer"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "indexer",
Short: "DipDup Verticals | Celenium Indexer",
}
func main() {
cfg, err := initConfig()
if err != nil {
return
}
if err = initLogger(cfg.LogLevel); err != nil {
return
}
if err = initProflier(cfg.Profiler); err != nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
notifyCtx, notifyCancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
defer notifyCancel()
stopperModule := stopper.NewModule(cancel)
indexerModule, err := indexer.New(ctx, *cfg, &stopperModule)
if err != nil {
log.Panic().Err(err).Msg("error during indexer module creation")
return
}
stopperModule.Start(ctx)
indexerModule.Start(ctx)
<-notifyCtx.Done()
cancel()
if err := indexerModule.Close(); err != nil {
log.Panic().Err(err).Msg("stopping indexer")
}
if prscp != nil {
if err := prscp.Stop(); err != nil {
log.Panic().Err(err).Msg("stopping pyroscope")
}
}
log.Info().Msg("stopped")
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"os"
"strconv"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
goLibConfig "github.com/dipdup-net/go-lib/config"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func init() {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006-01-02 15:04:05",
})
}
func initConfig() (*config.Config, error) {
configPath := rootCmd.PersistentFlags().StringP("config", "c", "dipdup.yml", "path to YAML config file")
if err := rootCmd.Execute(); err != nil {
log.Panic().Err(err).Msg("command line execute")
return nil, err
}
if err := rootCmd.MarkFlagRequired("config"); err != nil {
log.Panic().Err(err).Msg("config command line arg is required")
return nil, err
}
var cfg config.Config
if err := goLibConfig.Parse(*configPath, &cfg); err != nil {
log.Panic().Err(err).Msg("parsing config file")
return nil, err
}
if cfg.LogLevel == "" {
cfg.LogLevel = zerolog.LevelInfoValue
}
return &cfg, nil
}
func initLogger(level string) error {
logLevel, err := zerolog.ParseLevel(level)
if err != nil {
log.Panic().Err(err).Msg("parsing log level")
return err
}
zerolog.SetGlobalLevel(logLevel)
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.Logger.With().Caller().Logger()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/pkg/quotes"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "indexer",
Short: "DipDup Verticals | Celenium Quotes Indexer",
}
func main() {
cfg, err := initConfig()
if err != nil {
return
}
if err = initLogger(cfg.LogLevel); err != nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
notifyCtx, notifyCancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
defer notifyCancel()
binanceDatasource, ok := cfg.DataSources["binance"]
if !ok {
log.Panic().Err(err).Msg("can't find binance data source")
return
}
pg, err := postgres.Create(ctx, cfg.Database, cfg.Indexer.ScriptsDir, false)
if err != nil {
log.Panic().Err(err).Msg("can't create database connection")
return
}
module := quotes.New(binanceDatasource, pg.Price)
module.Start(ctx)
<-notifyCtx.Done()
cancel()
if err := module.Close(); err != nil {
log.Panic().Err(err).Msg("stopping quotes module")
}
log.Info().Msg("stopped")
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package binance
import (
"context"
"io"
"net/http"
"net/url"
"time"
"github.com/dipdup-net/go-lib/config"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type API struct {
client *http.Client
cfg config.DataSource
rateLimit *rate.Limiter
log zerolog.Logger
}
func NewAPI(cfg config.DataSource) API {
rps := cfg.RequestsPerSecond
if cfg.RequestsPerSecond < 1 || cfg.RequestsPerSecond > 100 {
rps = 10
}
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = rps
t.MaxConnsPerHost = rps
t.MaxIdleConnsPerHost = rps
return API{
client: &http.Client{
Transport: t,
},
cfg: cfg,
rateLimit: rate.NewLimiter(rate.Every(time.Second/time.Duration(rps)), rps),
log: log.With().Str("module", "binance_api").Logger(),
}
}
func (api *API) get(ctx context.Context, path string, args map[string]string, output any) error {
u, err := url.Parse(api.cfg.URL)
if err != nil {
return err
}
u.Path, err = url.JoinPath(u.Path, path)
if err != nil {
return err
}
values := u.Query()
for key, value := range args {
values.Add(key, value)
}
u.RawQuery = values.Encode()
if api.rateLimit != nil {
if err := api.rateLimit.Wait(ctx); err != nil {
return err
}
}
start := time.Now()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
response, err := api.client.Do(req)
if err != nil {
return err
}
defer closeWithLogError(response.Body, api.log)
api.log.Trace().
Int64("ms", time.Since(start).Milliseconds()).
Str("url", u.String()).
Msg("request")
if response.StatusCode != http.StatusOK {
return errors.Errorf("invalid status: %d", response.StatusCode)
}
err = json.NewDecoder(response.Body).Decode(output)
return err
}
func closeWithLogError(stream io.ReadCloser, log zerolog.Logger) {
if _, err := io.Copy(io.Discard, stream); err != nil {
log.Err(err).Msg("binance api copy GET body response to discard")
}
if err := stream.Close(); err != nil {
log.Err(err).Msg("binance api close GET body request")
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: interface.go
//
// Generated by this command:
//
// mockgen -source=interface.go -destination=mock/interface.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
binance "github.com/celenium-io/celestia-indexer/internal/binance"
gomock "go.uber.org/mock/gomock"
)
// MockIApi is a mock of IApi interface.
type MockIApi struct {
ctrl *gomock.Controller
recorder *MockIApiMockRecorder
}
// MockIApiMockRecorder is the mock recorder for MockIApi.
type MockIApiMockRecorder struct {
mock *MockIApi
}
// NewMockIApi creates a new mock instance.
func NewMockIApi(ctrl *gomock.Controller) *MockIApi {
mock := &MockIApi{ctrl: ctrl}
mock.recorder = &MockIApiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIApi) EXPECT() *MockIApiMockRecorder {
return m.recorder
}
// OHLC mocks base method.
func (m *MockIApi) OHLC(ctx context.Context, symbol, interval string, arguments *binance.OHLCArgs) ([]binance.OHLC, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "OHLC", ctx, symbol, interval, arguments)
ret0, _ := ret[0].([]binance.OHLC)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// OHLC indicates an expected call of OHLC.
func (mr *MockIApiMockRecorder) OHLC(ctx, symbol, interval, arguments any) *MockIApiOHLCCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OHLC", reflect.TypeOf((*MockIApi)(nil).OHLC), ctx, symbol, interval, arguments)
return &MockIApiOHLCCall{Call: call}
}
// MockIApiOHLCCall wrap *gomock.Call
type MockIApiOHLCCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIApiOHLCCall) Return(candles []binance.OHLC, err error) *MockIApiOHLCCall {
c.Call = c.Call.Return(candles, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIApiOHLCCall) Do(f func(context.Context, string, string, *binance.OHLCArgs) ([]binance.OHLC, error)) *MockIApiOHLCCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIApiOHLCCall) DoAndReturn(f func(context.Context, string, string, *binance.OHLCArgs) ([]binance.OHLC, error)) *MockIApiOHLCCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package binance
import (
"context"
"strconv"
"time"
"github.com/shopspring/decimal"
)
type OHLC struct {
Time time.Time
Open decimal.Decimal
High decimal.Decimal
Low decimal.Decimal
Close decimal.Decimal
}
func (ohlc *OHLC) UnmarshalJSON(data []byte) error {
var ts int64
if err := json.Unmarshal(data, &[]any{
&ts, &ohlc.Open, &ohlc.High, &ohlc.Low, &ohlc.Close,
}); err != nil {
return err
}
ohlc.Time = time.Unix(ts/1000, 0).UTC()
return nil
}
type OHLCArgs struct {
Start int64
End int64
Limit int64
TimeZone string
}
func (api API) OHLC(ctx context.Context, symbol, interval string, arguments *OHLCArgs) (candles []OHLC, err error) {
args := map[string]string{
"symbol": symbol,
"interval": interval,
}
if arguments != nil {
if arguments.Start > 0 {
args["startTime"] = strconv.FormatInt(arguments.Start, 10)
}
if arguments.End > 0 {
args["endTime"] = strconv.FormatInt(arguments.End, 10)
}
if arguments.Limit > 0 {
args["limit"] = strconv.FormatInt(arguments.Limit, 10)
}
if arguments.TimeZone != "" {
args["timeZone"] = arguments.TimeZone
}
}
err = api.get(ctx, "api/v3/klines", args, &candles)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: storage.go
//
// Generated by this command:
//
// mockgen -source=storage.go -destination=mock.go -package=blob -typed
//
// Package blob is a generated GoMock package.
package blob
import (
context "context"
reflect "reflect"
gomock "go.uber.org/mock/gomock"
)
// MockStorage is a mock of Storage interface.
type MockStorage struct {
ctrl *gomock.Controller
recorder *MockStorageMockRecorder
}
// MockStorageMockRecorder is the mock recorder for MockStorage.
type MockStorageMockRecorder struct {
mock *MockStorage
}
// NewMockStorage creates a new mock instance.
func NewMockStorage(ctrl *gomock.Controller) *MockStorage {
mock := &MockStorage{ctrl: ctrl}
mock.recorder = &MockStorageMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockStorage) EXPECT() *MockStorageMockRecorder {
return m.recorder
}
// Head mocks base method.
func (m *MockStorage) Head(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Head", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Head indicates an expected call of Head.
func (mr *MockStorageMockRecorder) Head(ctx any) *MockStorageHeadCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Head", reflect.TypeOf((*MockStorage)(nil).Head), ctx)
return &MockStorageHeadCall{Call: call}
}
// MockStorageHeadCall wrap *gomock.Call
type MockStorageHeadCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockStorageHeadCall) Return(arg0 uint64, arg1 error) *MockStorageHeadCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockStorageHeadCall) Do(f func(context.Context) (uint64, error)) *MockStorageHeadCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockStorageHeadCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockStorageHeadCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m *MockStorage) Save(ctx context.Context, blob Blob) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Save", ctx, blob)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockStorageMockRecorder) Save(ctx, blob any) *MockStorageSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockStorage)(nil).Save), ctx, blob)
return &MockStorageSaveCall{Call: call}
}
// MockStorageSaveCall wrap *gomock.Call
type MockStorageSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockStorageSaveCall) Return(arg0 error) *MockStorageSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockStorageSaveCall) Do(f func(context.Context, Blob) error) *MockStorageSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockStorageSaveCall) DoAndReturn(f func(context.Context, Blob) error) *MockStorageSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveBulk mocks base method.
func (m *MockStorage) SaveBulk(ctx context.Context, blobs []Blob) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SaveBulk", ctx, blobs)
ret0, _ := ret[0].(error)
return ret0
}
// SaveBulk indicates an expected call of SaveBulk.
func (mr *MockStorageMockRecorder) SaveBulk(ctx, blobs any) *MockStorageSaveBulkCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveBulk", reflect.TypeOf((*MockStorage)(nil).SaveBulk), ctx, blobs)
return &MockStorageSaveBulkCall{Call: call}
}
// MockStorageSaveBulkCall wrap *gomock.Call
type MockStorageSaveBulkCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockStorageSaveBulkCall) Return(arg0 error) *MockStorageSaveBulkCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockStorageSaveBulkCall) Do(f func(context.Context, []Blob) error) *MockStorageSaveBulkCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockStorageSaveBulkCall) DoAndReturn(f func(context.Context, []Blob) error) *MockStorageSaveBulkCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// UpdateHead mocks base method.
func (m *MockStorage) UpdateHead(ctx context.Context, head uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateHead", ctx, head)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateHead indicates an expected call of UpdateHead.
func (mr *MockStorageMockRecorder) UpdateHead(ctx, head any) *MockStorageUpdateHeadCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateHead", reflect.TypeOf((*MockStorage)(nil).UpdateHead), ctx, head)
return &MockStorageUpdateHeadCall{Call: call}
}
// MockStorageUpdateHeadCall wrap *gomock.Call
type MockStorageUpdateHeadCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockStorageUpdateHeadCall) Return(arg0 error) *MockStorageUpdateHeadCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockStorageUpdateHeadCall) Do(f func(context.Context, uint64) error) *MockStorageUpdateHeadCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockStorageUpdateHeadCall) DoAndReturn(f func(context.Context, uint64) error) *MockStorageUpdateHeadCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package blob
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsConfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
serviceS3 "github.com/aws/aws-sdk-go-v2/service/s3"
s3Types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
nodeTypes "github.com/celenium-io/celestia-indexer/pkg/node/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-io/workerpool"
"github.com/rs/zerolog/log"
)
const (
headFile = "head.json"
)
type R2Config struct {
BucketName string
AccountId string
AccessKeyId string
AccessKeySecret string
}
func (cfg R2Config) R2Url() string {
return fmt.Sprintf("https://%s.r2.cloudflarestorage.com", cfg.AccountId)
}
type R2 struct {
cfg R2Config
client *serviceS3.Client
pool *workerpool.Pool[Blob]
}
func NewR2(cfg R2Config) R2 {
r2 := R2{
cfg: cfg,
}
return r2
}
func (r2 *R2) Init(ctx context.Context) error {
r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: r2.cfg.R2Url(),
}, nil
})
cfg, err := awsConfig.LoadDefaultConfig(ctx,
awsConfig.WithEndpointResolverWithOptions(r2Resolver),
awsConfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(r2.cfg.AccessKeyId, r2.cfg.AccessKeySecret, "")),
awsConfig.WithRegion("auto"),
awsConfig.WithRetryMode(aws.RetryModeAdaptive),
)
if err != nil {
return err
}
r2.client = serviceS3.NewFromConfig(cfg)
r2.pool = workerpool.NewPool(r2.saveBlob, 16)
r2.pool.Start(ctx)
return nil
}
func (r2 R2) Save(ctx context.Context, blob Blob) error {
_, err := r2.client.PutObject(ctx, &serviceS3.PutObjectInput{
Bucket: aws.String(r2.cfg.BucketName),
Key: aws.String(blob.String()),
Body: bytes.NewBuffer(blob.Data),
ContentType: aws.String(blob.ContentType()),
ContentLength: aws.Int64(int64(len(blob.Data))),
})
return err
}
func (r2 R2) SaveBulk(ctx context.Context, blobs []Blob) error {
if len(blobs) == 0 {
return nil
}
for i := range blobs {
r2.pool.AddTask(blobs[i])
}
return nil
}
func (r2 R2) Head(ctx context.Context) (uint64, error) {
output, err := r2.client.GetObject(ctx, &serviceS3.GetObjectInput{
Bucket: aws.String(r2.cfg.BucketName),
Key: aws.String(headFile),
})
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.(type) {
case *s3Types.NoSuchKey, *s3Types.NotFound:
return 0, nil
default:
return 0, err
}
}
return 0, err
}
var head uint64
err = json.NewDecoder(output.Body).Decode(&head)
return head, err
}
func (r2 R2) UpdateHead(ctx context.Context, head uint64) error {
data, err := json.Marshal(head)
if err != nil {
return err
}
_, err = r2.client.PutObject(ctx, &serviceS3.PutObjectInput{
Bucket: aws.String(r2.cfg.BucketName),
Key: aws.String(headFile),
Body: bytes.NewBuffer(data),
})
return err
}
func (r2 R2) Blob(ctx context.Context, height pkgTypes.Level, namespace, commitment string) (blob nodeTypes.Blob, err error) {
ns, err := Base64ToUrl(namespace)
if err != nil {
return
}
cm, err := Base64ToUrl(commitment)
if err != nil {
return
}
fileName := fmt.Sprintf("%s/%d/%s", ns, height, cm)
obj, err := r2.client.GetObject(ctx, &serviceS3.GetObjectInput{
Bucket: aws.String(r2.cfg.BucketName),
Key: aws.String(fileName),
})
if err != nil {
return
}
buf := new(bytes.Buffer)
encoder := base64.NewEncoder(base64.StdEncoding, buf)
if _, err := io.Copy(encoder, obj.Body); err != nil {
return blob, err
}
if err := encoder.Close(); err != nil {
return blob, err
}
blob.Data = buf.String()
blob.ShareVersion = 0
blob.Commitment = commitment
blob.Namespace = namespace
return
}
func (r2 R2) Blobs(ctx context.Context, height pkgTypes.Level, hash ...string) ([]nodeTypes.Blob, error) {
return nil, errors.New("not implemented")
}
func (r2 *R2) saveBlob(ctx context.Context, blob Blob) {
timeoutCtx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel()
log.Info().Str("blob", blob.String()).Int("size", blob.Size()).Msg("saving blob...")
if err := r2.Save(timeoutCtx, blob); err != nil {
log.Err(err).Str("blob", blob.String()).Int("size", blob.Size()).Msg("blob saving")
go func() {
// if error occurred try again
r2.pool.AddTask(blob)
}()
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package blob
import (
"context"
"encoding/base64"
"fmt"
"github.com/gabriel-vasile/mimetype"
blobTypes "github.com/tendermint/tendermint/proto/tendermint/types"
)
type Blob struct {
*blobTypes.Blob
Commitment []byte
Height uint64
}
func (blob Blob) String() string {
hash := []byte{byte(blob.ShareVersion)}
ns := base64.URLEncoding.EncodeToString(append(hash, blob.NamespaceId...))
cm := base64.URLEncoding.EncodeToString(blob.Commitment)
return fmt.Sprintf("%s/%d/%s", ns, blob.Height, cm)
}
func (blob Blob) ContentType() string {
contentType := mimetype.Detect(blob.Data)
return contentType.String()
}
//go:generate mockgen -source=$GOFILE -destination=mock.go -package=blob -typed
type Storage interface {
Save(ctx context.Context, blob Blob) error
SaveBulk(ctx context.Context, blobs []Blob) error
Head(ctx context.Context) (uint64, error)
UpdateHead(ctx context.Context, head uint64) error
}
func Base64ToUrl(s string) (string, error) {
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package currency
import "github.com/shopspring/decimal"
const (
Utia string = "utia"
Tia string = "tia"
)
const (
DefaultCurrency = "utia"
)
func StringTia(val decimal.Decimal) string {
return val.StringFixed(6)
}
func StringUtia(val decimal.Decimal) string {
return val.StringFixed(0)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package math
import "golang.org/x/exp/constraints"
func Min[T constraints.Ordered](x, y T) T {
if x < y {
return x
}
return y
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package profiler
import (
"fmt"
"runtime"
"github.com/grafana/pyroscope-go"
)
type Config struct {
Server string `validate:"omitempty,http_url" yaml:"server"`
Project string `validate:"omitempty" yaml:"project"`
}
func New(cfg *Config, service string) (*pyroscope.Profiler, error) {
if cfg == nil || cfg.Server == "" {
return nil, nil
}
runtime.SetMutexProfileFraction(5)
runtime.SetBlockProfileRate(5)
return pyroscope.Start(pyroscope.Config{
ApplicationName: fmt.Sprintf("%s-%s", cfg.Project, service),
ServerAddress: cfg.Server,
Tags: map[string]string{
"project": cfg.Project,
"service": service,
},
ProfileTypes: []pyroscope.ProfileType{
pyroscope.ProfileCPU,
pyroscope.ProfileAllocObjects,
pyroscope.ProfileAllocSpace,
pyroscope.ProfileInuseObjects,
pyroscope.ProfileInuseSpace,
pyroscope.ProfileGoroutines,
pyroscope.ProfileMutexCount,
pyroscope.ProfileMutexDuration,
pyroscope.ProfileBlockCount,
pyroscope.ProfileBlockDuration,
},
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package stats
import (
"reflect"
"strings"
"github.com/dipdup-net/go-lib/hasura"
"github.com/pkg/errors"
)
var (
Tables = make(map[string]Table)
ValidFuncs = map[string]struct{}{
"count": {},
"avg": {},
"max": {},
"min": {},
"sum": {},
}
)
type Table struct {
Columns map[string]Column
}
type Column struct {
Functions map[string]struct{}
Filterable bool
}
func Init(models ...any) error {
for i := range models {
if err := InitModel(models[i]); err != nil {
return err
}
}
return nil
}
const (
statsTagName = "stats"
bunTagName = "bun"
)
func InitModel(model any) error {
typ := reflect.TypeOf(model)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
var (
tableName string
table = Table{
Columns: make(map[string]Column, 0),
}
)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
bunTag := field.Tag.Get(bunTagName)
if bunTag == "" || bunTag == "-" {
continue
}
bunTagValues := strings.Split(bunTag, ",")
if len(bunTagValues) == 0 {
continue
}
switch field.Name {
case "BaseModel":
tableName = strings.TrimPrefix(bunTagValues[0], "table:")
if tableName == "" {
tableName = hasura.ToSnakeCase(typ.Name())
}
default:
statsTag := field.Tag.Get(statsTagName)
if statsTag == "" || statsTag == "-" {
continue
}
statsTagValues := strings.Split(statsTag, ",")
if len(statsTagValues) == 0 {
continue
}
column := Column{
Functions: make(map[string]struct{}),
}
for _, value := range statsTagValues {
switch {
case strings.HasPrefix(value, "func:"):
funcs := strings.Split(strings.TrimPrefix(value, "func:"), " ")
for _, fnc := range funcs {
if _, ok := ValidFuncs[fnc]; !ok {
return errors.Errorf("unknown stats function: %s", value)
}
column.Functions[fnc] = struct{}{}
}
case value == "filterable":
column.Filterable = true
}
}
columnName := bunTagValues[0]
if columnName == "" {
columnName = hasura.ToSnakeCase(field.Name)
}
table.Columns[columnName] = column
}
}
Tables[tableName] = table
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/pkg/types"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
type AddressListFilter struct {
Limit int
Offset int
Sort storage.SortOrder
SortField string
}
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IAddress interface {
storage.Table[*Address]
ByHash(ctx context.Context, hash []byte) (Address, error)
ListWithBalance(ctx context.Context, filters AddressListFilter) ([]Address, error)
Series(ctx context.Context, addressId uint64, timeframe Timeframe, column string, req SeriesRequest) (items []HistogramItem, err error)
IdByHash(ctx context.Context, hash ...[]byte) ([]uint64, error)
IdByAddress(ctx context.Context, address string, ids ...uint64) (uint64, error)
}
// Address -
type Address struct {
bun.BaseModel `bun:"address" comment:"Table with celestia addresses."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Height types.Level `bun:"height" comment:"Block number of the first address occurrence."`
LastHeight types.Level `bun:"last_height" comment:"Block number of the last address occurrence."`
Hash []byte `bun:"hash" comment:"Address hash."`
Address string `bun:"address,unique:address_idx" comment:"Human-readable address."`
Balance Balance `bun:"rel:has-one,join:id=id"`
Celestials *celestials.Celestial `bun:"rel:has-one,join:id=address_id"`
}
// TableName -
func (Address) TableName() string {
return "address"
}
func (address Address) String() string {
return address.Address
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IApiKey interface {
Get(ctx context.Context, key string) (ApiKey, error)
}
type ApiKey struct {
bun.BaseModel `bun:"apikey" comment:"Table with private api keys"`
Key string `bun:"key,pk,notnull" comment:"Key"`
Description string `bun:"description" comment:"Additional info about issuer and user"`
Admin bool `bun:"admin" comment:"Verified user"`
}
func (ApiKey) TableName() string {
return "apikey"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IBalance interface {
storage.Table[*Balance]
}
type Balance struct {
bun.BaseModel `bun:"balance" comment:"Table with account balances."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Currency string `bun:"currency,pk,notnull" comment:"Balance currency"`
Spendable decimal.Decimal `bun:"spendable,type:numeric" comment:"Spendable balance"`
Delegated decimal.Decimal `bun:"delegated,type:numeric" comment:"Delegated balance"`
Unbonding decimal.Decimal `bun:"unbonding,type:numeric" comment:"Unbonding balance"`
}
func (Balance) TableName() string {
return "balance"
}
func (b Balance) IsEmpty() bool {
return b.Currency == "" && b.Spendable.IsZero()
}
func EmptyBalance() Balance {
return Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"io"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
type BlobLogFilters struct {
Limit int
Offset int
Sort sdk.SortOrder
SortBy string
From time.Time
To time.Time
Commitment string
Joins bool
Signers []uint64
Cursor uint64
}
type ListBlobLogFilters struct {
Limit int
Offset int
Sort sdk.SortOrder
SortBy string
From time.Time
To time.Time
Commitment string
Signers []uint64
Namespaces []uint64
Cursor uint64
}
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IBlobLog interface {
sdk.Table[*BlobLog]
ByNamespace(ctx context.Context, nsId uint64, fltrs BlobLogFilters) ([]BlobLog, error)
ByProviders(ctx context.Context, providers []RollupProvider, fltrs BlobLogFilters) ([]BlobLog, error)
BySigner(ctx context.Context, signerId uint64, fltrs BlobLogFilters) ([]BlobLog, error)
ByTxId(ctx context.Context, txId uint64, fltrs BlobLogFilters) ([]BlobLog, error)
ByHeight(ctx context.Context, height types.Level, fltrs BlobLogFilters) ([]BlobLog, error)
CountByTxId(ctx context.Context, txId uint64) (int, error)
ExportByProviders(ctx context.Context, providers []RollupProvider, from, to time.Time, stream io.Writer) (err error)
Blob(ctx context.Context, height types.Level, nsId uint64, commitment string) (BlobLog, error)
ListBlobs(ctx context.Context, fltrs ListBlobLogFilters) ([]BlobLog, error)
}
type BlobLog struct {
bun.BaseModel `bun:"blob_log" comment:"Table with flatted blob entities."`
Id uint64 `bun:"id,pk,autoincrement" comment:"Unique internal identity"`
Time time.Time `bun:"time,notnull,pk" comment:"Message time"`
Height types.Level `bun:"height" comment:"Message block height"`
Size int64 `bun:"size" comment:"Blob size"`
Commitment string `bun:"commitment" comment:"Blob commitment"`
ContentType string `bun:"content_type" comment:"Blob content type"`
Fee decimal.Decimal `bun:"fee,type:numeric" comment:"Fee per blob"`
SignerId uint64 `bun:"signer_id" comment:"Blob signer identity"`
NamespaceId uint64 `bun:"namespace_id" comment:"Namespace internal id"`
MsgId uint64 `bun:"msg_id" comment:"Message id"`
TxId uint64 `bun:"tx_id" comment:"Transaction id"`
Message *Message `bun:"rel:belongs-to,join:msg_id=id"`
Namespace *Namespace `bun:"rel:belongs-to,join:namespace_id=id"`
Tx *Tx `bun:"rel:belongs-to,join:tx_id=id"`
Signer *Address `bun:"rel:belongs-to,join:signer_id=id"`
Rollup *Rollup `bun:"rel:belongs-to"`
}
func (BlobLog) TableName() string {
return "blob_log"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IBlock interface {
storage.Table[*Block]
Last(ctx context.Context) (Block, error)
ByIdWithRelations(ctx context.Context, id uint64) (Block, error)
ByHeight(ctx context.Context, height pkgTypes.Level) (Block, error)
ByHeightWithStats(ctx context.Context, height pkgTypes.Level) (Block, error)
ByHash(ctx context.Context, hash []byte) (Block, error)
ByProposer(ctx context.Context, proposerId uint64, limit, offset int) ([]Block, error)
ListWithStats(ctx context.Context, limit, offset uint64, order storage.SortOrder) ([]*Block, error)
Time(ctx context.Context, height pkgTypes.Level) (time.Time, error)
}
// Block -
type Block struct {
bun.BaseModel `bun:"table:block" comment:"Table with celestia blocks."`
Id uint64 `bun:",pk,notnull,autoincrement" comment:"Unique internal identity"`
Height pkgTypes.Level `bun:"height" comment:"The number (height) of this block" stats:"func:min max,filterable"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
VersionBlock uint64 `bun:"version_block" comment:"Block version"`
VersionApp uint64 `bun:"version_app" comment:"App version"`
MessageTypes types.MsgTypeBits `bun:"message_types,type:bit(76)" comment:"Bit mask with containing messages"`
Hash pkgTypes.Hex `bun:"hash" comment:"Block hash"`
ParentHash pkgTypes.Hex `bun:"parent_hash" comment:"Hash of parent block"`
LastCommitHash pkgTypes.Hex `bun:"last_commit_hash" comment:"Last commit hash"`
DataHash pkgTypes.Hex `bun:"data_hash" comment:"Data hash"`
ValidatorsHash pkgTypes.Hex `bun:"validators_hash" comment:"Validators hash"`
NextValidatorsHash pkgTypes.Hex `bun:"next_validators_hash" comment:"Next validators hash"`
ConsensusHash pkgTypes.Hex `bun:"consensus_hash" comment:"Consensus hash"`
AppHash pkgTypes.Hex `bun:"app_hash" comment:"App hash"`
LastResultsHash pkgTypes.Hex `bun:"last_results_hash" comment:"Last results hash"`
EvidenceHash pkgTypes.Hex `bun:"evidence_hash" comment:"Evidence hash"`
ProposerId uint64 `bun:"proposer_id,nullzero" comment:"Proposer internal id"`
ChainId string `bun:"-" json:"-"` // internal field for filling state
ProposerAddress string `bun:"-" json:"-"` // internal field for proposer
BlockSignatures []BlockSignature `bun:"-" json:"-"` // internal field for block signature
Txs []Tx `bun:"rel:has-many" json:"-"`
Events []Event `bun:"rel:has-many" json:"-"`
Stats BlockStats `bun:"rel:has-one,join:height=height"`
Proposer Validator `bun:"rel:belongs-to" json:"-"`
}
// TableName -
func (Block) TableName() string {
return "block"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IBlockSignature interface {
storage.Table[*BlockSignature]
LevelsByValidator(ctx context.Context, validatorId uint64, startHeight types.Level) ([]types.Level, error)
}
type BlockSignature struct {
bun.BaseModel `bun:"block_signature" comment:"Table with block signatures"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Height types.Level `bun:",notnull" comment:"The number (height) of this block"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block"`
ValidatorId uint64 `bun:"validator_id" comment:"Validator's internal identity"`
Validator *Validator `bun:"rel:belongs-to"`
}
func (BlockSignature) TableName() string {
return "block_signature"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IBlockStats interface {
ByHeight(ctx context.Context, height pkgTypes.Level) (BlockStats, error)
LastFrom(ctx context.Context, head pkgTypes.Level, limit int) ([]BlockStats, error)
}
type BlockStats struct {
bun.BaseModel `bun:"table:block_stats" comment:"Table with celestia block stats."`
Id uint64 `bun:",pk,notnull,autoincrement" comment:"Unique internal identity"`
Height pkgTypes.Level `bun:"height" comment:"The number (height) of this block" stats:"func:min max,filterable"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
TxCount int64 `bun:"tx_count" comment:"Count of transactions in block" stats:"func:min max sum avg"`
EventsCount int64 `bun:"events_count" comment:"Count of events in begin and end of block" stats:"func:min max sum avg"`
BlobsSize int64 `bun:"blobs_size" comment:"Summary blocks size from pay for blob" stats:"func:min max sum avg"`
BlobsCount int `bun:"blobs_count" comment:"Summary blobs count in the block" stats:"func:min max sum avg"`
BlockTime uint64 `bun:"block_time" comment:"Time in milliseconds between current and previous block" stats:"func:min max sum avg"`
GasLimit int64 `bun:"gas_limit" comment:"Total gas limit in the block" stats:"func:min max sum avg"`
GasUsed int64 `bun:"gas_used" comment:"Total gas used in the block" stats:"func:min max sum avg"`
SupplyChange decimal.Decimal `bun:",type:numeric" comment:"Change of total supply in the block" stats:"func:min max sum avg"`
InflationRate decimal.Decimal `bun:",type:numeric" comment:"Inflation rate" stats:"func:min max avg"`
Fee decimal.Decimal `bun:"fee,type:numeric" comment:"Summary block fee" stats:"func:min max sum avg"`
Rewards decimal.Decimal `bun:"rewards,type:numeric" comment:"Total rewards per block" stats:"func:min max sum avg"`
Commissions decimal.Decimal `bun:"commissions,type:numeric" comment:"Total commissions per block" stats:"func:min max sum avg"`
BytesInBlock int64 `bun:"bytes_in_block" comment:"Size of all transactions in bytes" stats:"func:min max sum avg"`
SquareSize uint64 `bun:"square_size" comment:"Size of the square after splitting all the block data into shares"`
}
func (BlockStats) TableName() string {
return "block_stats"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"strconv"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IConstant interface {
Get(ctx context.Context, module types.ModuleName, name string) (Constant, error)
ByModule(ctx context.Context, module types.ModuleName) ([]Constant, error)
All(ctx context.Context) ([]Constant, error)
}
type Constant struct {
bun.BaseModel `bun:"table:constant" comment:"Table with celestia constants."`
Module types.ModuleName `bun:"module,pk,type:module_name" comment:"Module name which declares constant"`
Name string `bun:"name,pk,type:text" comment:"Constant name"`
Value string `bun:"value,type:text" comment:"Constant value"`
}
func (Constant) TableName() string {
return "constant"
}
func (c Constant) MustUint64() uint64 {
i, err := strconv.ParseUint(c.Value, 10, 64)
if err != nil {
panic(err)
}
return i
}
func (c Constant) MustUint32() uint32 {
i, err := strconv.ParseUint(c.Value, 10, 32)
if err != nil {
panic(err)
}
//nolint:gosec
return uint32(i)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"strings"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IDelegation interface {
storage.Table[*Delegation]
ByAddress(ctx context.Context, addressId uint64, limit, offset int, showZero bool) ([]Delegation, error)
ByValidator(ctx context.Context, validatorId uint64, limit, offset int, showZero bool) ([]Delegation, error)
}
// Delegation -
type Delegation struct {
bun.BaseModel `bun:"delegation" comment:"Table with delegations"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
AddressId uint64 `bun:"address_id,unique:delegation_pair" comment:"Internal address id"`
ValidatorId uint64 `bun:"validator_id,unique:delegation_pair" comment:"Internal validator id"`
Amount decimal.Decimal `bun:"amount,type:numeric" comment:"Delegated amount"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Validator *Validator `bun:"rel:belongs-to,join:validator_id=id"`
}
// TableName -
func (Delegation) TableName() string {
return "delegation"
}
func (d Delegation) String() string {
sb := new(strings.Builder)
if d.Address != nil {
sb.WriteString(d.Address.Address)
}
if d.Validator != nil {
sb.WriteString(d.Validator.Address)
}
return sb.String()
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IDenomMetadata interface {
All(ctx context.Context) ([]DenomMetadata, error)
}
type DenomMetadata struct {
bun.BaseModel `bun:"table:denom_metadata" comment:"Table with celestia coins metadata."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Internal unique identity"`
Description string `bun:"description,type:text" comment:"Denom description"`
Base string `bun:"base,type:text" comment:"Denom base"`
Display string `bun:"display,type:text" comment:"Denom display"`
Name string `bun:"name,type:text" comment:"Denom name"`
Symbol string `bun:"symbol,type:text" comment:"Denom symbol"`
Uri string `bun:"uri,type:text" comment:"Denom uri"`
Units []byte `bun:"units,type:bytea" comment:"Denom units information"`
}
func (DenomMetadata) TableName() string {
return "denom_metadata"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
type EventFilter struct {
Limit int
Offset int
Time time.Time
}
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IEvent interface {
storage.Table[*Event]
ByTxId(ctx context.Context, txId uint64, fltrs EventFilter) ([]Event, error)
ByBlock(ctx context.Context, height pkgTypes.Level, fltrs EventFilter) ([]Event, error)
}
// Event -
type Event struct {
bun.BaseModel `bun:"event" comment:"Table with celestia events."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Height pkgTypes.Level `bun:"height,notnull" comment:"The number (height) of this block" stats:"func:min max,filterable"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
Position int64 `bun:"position" comment:"Position in transaction"`
Type types.EventType `bun:",type:event_type" comment:"Event type" stats:"filterable"`
TxId *uint64 `bun:"tx_id" comment:"Transaction id"`
Data map[string]any `bun:"data,msgpack,type:bytea,nullzero" comment:"Event data"`
}
// TableName -
func (Event) TableName() string {
return "event"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"fmt"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IGrant interface {
storage.Table[*Grant]
ByGranter(ctx context.Context, id uint64, limit, offset int) ([]Grant, error)
ByGrantee(ctx context.Context, id uint64, limit, offset int) ([]Grant, error)
}
type Grant struct {
bun.BaseModel `bun:"grant" comment:"Table with grants"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Height types.Level `bun:"height" comment:"Block height"`
RevokeHeight *types.Level `bun:"revoke_height" comment:"Block height when grant was revoked"`
Time time.Time `bun:"time" comment:"The time of block"`
GranterId uint64 `bun:"granter_id,unique:grant_key" comment:"Granter internal identity"`
GranteeId uint64 `bun:"grantee_id,unique:grant_key" comment:"Grantee internal identity"`
Authorization string `bun:"authorization,unique:grant_key" comment:"Authorization type"`
Expiration *time.Time `bun:"expiration" comment:"Expiration time"`
Revoked bool `bun:"revoked" comment:"Is grant revoked"`
Params map[string]any `bun:"params,type:jsonb,nullzero" comment:"Authorization parameters"`
Granter *Address `bun:"rel:has-one"`
Grantee *Address `bun:"rel:has-one"`
}
func (Grant) TableName() string {
return "grant"
}
func (g Grant) String() string {
return fmt.Sprintf("%s_%s_%s", g.Authorization, g.Granter.Address, g.Grantee.Address)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IJail interface {
storage.Table[*Jail]
ByValidator(ctx context.Context, id uint64, limit, offset int) ([]Jail, error)
}
// Jail -
type Jail struct {
bun.BaseModel `bun:"jail" comment:"Table with all jailed events."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block"`
Height pkgTypes.Level `bun:"height,notnull" comment:"The number (height) of this block"`
ValidatorId uint64 `bun:"validator_id,notnull" comment:"Internal validator id"`
Reason string `bun:"reason" comment:"Reason"`
Burned decimal.Decimal `bun:"burned,type:numeric" comment:"Burned coins"`
Validator *Validator `bun:"rel:belongs-to,join:validator_id=id"`
}
// TableName -
func (Jail) TableName() string {
return "jail"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
type MessageListWithTxFilters struct {
Height pkgTypes.Level
Limit int
Offset int
ExcludedMessageTypes []string
MessageTypes []string
}
type AddressMsgsFilter struct {
Limit int
Offset int
Sort storage.SortOrder
MessageTypes []string
}
type MessageWithTx struct {
bun.BaseModel `bun:"message,alias:message"`
Message
Tx *Tx `bun:"rel:belongs-to"`
}
type AddressMessageWithTx struct {
bun.BaseModel `bun:"message,alias:message"`
MsgAddress
Msg *Message `bun:"rel:belongs-to,join:msg_id=id"`
Tx *Tx `bun:"rel:belongs-to,join:msg__tx_id=id"`
}
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IMessage interface {
storage.Table[*Message]
ByTxId(ctx context.Context, txId uint64, limit, offset int) ([]Message, error)
ListWithTx(ctx context.Context, filters MessageListWithTxFilters) ([]MessageWithTx, error)
ByAddress(ctx context.Context, id uint64, filters AddressMsgsFilter) ([]AddressMessageWithTx, error)
}
// Message -
type Message struct {
bun.BaseModel `bun:"message" comment:"Table with celestia messages."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Height pkgTypes.Level `bun:",notnull" comment:"The number (height) of this block" stats:"func:min max,filterable"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
Position int64 `bun:"position" comment:"Position in transaction"`
Type types.MsgType `bun:",type:msg_type" comment:"Message type" stats:"filterable"`
TxId uint64 `bun:"tx_id" comment:"Parent transaction id"`
Size int `bun:"size" comment:"Message size in bytes"`
Data types.PackedBytes `bun:"data,type:bytea,nullzero" comment:"Message data"`
Namespace []Namespace `bun:"m2m:namespace_message,join:Message=Namespace"`
Addresses []AddressWithType `bun:"-"`
BlobLogs []*BlobLog `bun:"-"`
Grants []Grant `bun:"-"`
InternalMsgs []string `bun:"-"` // field for parsing MsgExec internal messages
VestingAccount *VestingAccount `bun:"-"` // internal field
}
// TableName -
func (Message) TableName() string {
return "message"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"fmt"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/uptrace/bun"
)
type MsgAddress struct {
bun.BaseModel `bun:"msg_address" comment:"Table with relation tx to address"`
AddressId uint64 `bun:"address_id,pk" comment:"Address internal id"`
MsgId uint64 `bun:"msg_id,pk" comment:"Message internal id"`
Type types.MsgAddressType `bun:",pk,type:msg_address_type" comment:"The reason why address link to transaction"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Msg *Message `bun:"rel:belongs-to,join:msg_id=id"`
}
func (MsgAddress) TableName() string {
return "msg_address"
}
func (m MsgAddress) String() string {
return fmt.Sprintf("%d_%d_%s", m.AddressId, m.MsgId, m.Type)
}
type AddressWithType struct {
Address
Type types.MsgAddressType
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: address.go
//
// Generated by this command:
//
// mockgen -source=address.go -destination=mock/address.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIAddress is a mock of IAddress interface.
type MockIAddress struct {
ctrl *gomock.Controller
recorder *MockIAddressMockRecorder
}
// MockIAddressMockRecorder is the mock recorder for MockIAddress.
type MockIAddressMockRecorder struct {
mock *MockIAddress
}
// NewMockIAddress creates a new mock instance.
func NewMockIAddress(ctrl *gomock.Controller) *MockIAddress {
mock := &MockIAddress{ctrl: ctrl}
mock.recorder = &MockIAddressMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIAddress) EXPECT() *MockIAddressMockRecorder {
return m.recorder
}
// ByHash mocks base method.
func (m *MockIAddress) ByHash(ctx context.Context, hash []byte) (storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHash", ctx, hash)
ret0, _ := ret[0].(storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHash indicates an expected call of ByHash.
func (mr *MockIAddressMockRecorder) ByHash(ctx, hash any) *MockIAddressByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockIAddress)(nil).ByHash), ctx, hash)
return &MockIAddressByHashCall{Call: call}
}
// MockIAddressByHashCall wrap *gomock.Call
type MockIAddressByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressByHashCall) Return(arg0 storage.Address, arg1 error) *MockIAddressByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressByHashCall) Do(f func(context.Context, []byte) (storage.Address, error)) *MockIAddressByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Address, error)) *MockIAddressByHashCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIAddress) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIAddressMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIAddressCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIAddress)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIAddressCursorListCall{Call: call}
}
// MockIAddressCursorListCall wrap *gomock.Call
type MockIAddressCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressCursorListCall) Return(arg0 []*storage.Address, arg1 error) *MockIAddressCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Address, error)) *MockIAddressCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Address, error)) *MockIAddressCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIAddress) GetByID(ctx context.Context, id uint64) (*storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIAddressMockRecorder) GetByID(ctx, id any) *MockIAddressGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIAddress)(nil).GetByID), ctx, id)
return &MockIAddressGetByIDCall{Call: call}
}
// MockIAddressGetByIDCall wrap *gomock.Call
type MockIAddressGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressGetByIDCall) Return(arg0 *storage.Address, arg1 error) *MockIAddressGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressGetByIDCall) Do(f func(context.Context, uint64) (*storage.Address, error)) *MockIAddressGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Address, error)) *MockIAddressGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IdByAddress mocks base method.
func (m *MockIAddress) IdByAddress(ctx context.Context, address string, ids ...uint64) (uint64, error) {
m.ctrl.T.Helper()
varargs := []any{ctx, address}
for _, a := range ids {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "IdByAddress", varargs...)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// IdByAddress indicates an expected call of IdByAddress.
func (mr *MockIAddressMockRecorder) IdByAddress(ctx, address any, ids ...any) *MockIAddressIdByAddressCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, address}, ids...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdByAddress", reflect.TypeOf((*MockIAddress)(nil).IdByAddress), varargs...)
return &MockIAddressIdByAddressCall{Call: call}
}
// MockIAddressIdByAddressCall wrap *gomock.Call
type MockIAddressIdByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressIdByAddressCall) Return(arg0 uint64, arg1 error) *MockIAddressIdByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressIdByAddressCall) Do(f func(context.Context, string, ...uint64) (uint64, error)) *MockIAddressIdByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressIdByAddressCall) DoAndReturn(f func(context.Context, string, ...uint64) (uint64, error)) *MockIAddressIdByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IdByHash mocks base method.
func (m *MockIAddress) IdByHash(ctx context.Context, hash ...[]byte) ([]uint64, error) {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range hash {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "IdByHash", varargs...)
ret0, _ := ret[0].([]uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// IdByHash indicates an expected call of IdByHash.
func (mr *MockIAddressMockRecorder) IdByHash(ctx any, hash ...any) *MockIAddressIdByHashCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, hash...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdByHash", reflect.TypeOf((*MockIAddress)(nil).IdByHash), varargs...)
return &MockIAddressIdByHashCall{Call: call}
}
// MockIAddressIdByHashCall wrap *gomock.Call
type MockIAddressIdByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressIdByHashCall) Return(arg0 []uint64, arg1 error) *MockIAddressIdByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressIdByHashCall) Do(f func(context.Context, ...[]byte) ([]uint64, error)) *MockIAddressIdByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressIdByHashCall) DoAndReturn(f func(context.Context, ...[]byte) ([]uint64, error)) *MockIAddressIdByHashCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIAddress) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIAddressMockRecorder) IsNoRows(err any) *MockIAddressIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIAddress)(nil).IsNoRows), err)
return &MockIAddressIsNoRowsCall{Call: call}
}
// MockIAddressIsNoRowsCall wrap *gomock.Call
type MockIAddressIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressIsNoRowsCall) Return(arg0 bool) *MockIAddressIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressIsNoRowsCall) Do(f func(error) bool) *MockIAddressIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIAddressIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIAddress) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIAddressMockRecorder) LastID(ctx any) *MockIAddressLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIAddress)(nil).LastID), ctx)
return &MockIAddressLastIDCall{Call: call}
}
// MockIAddressLastIDCall wrap *gomock.Call
type MockIAddressLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressLastIDCall) Return(arg0 uint64, arg1 error) *MockIAddressLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIAddressLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIAddressLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIAddress) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIAddressMockRecorder) List(ctx, limit, offset, order any) *MockIAddressListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIAddress)(nil).List), ctx, limit, offset, order)
return &MockIAddressListCall{Call: call}
}
// MockIAddressListCall wrap *gomock.Call
type MockIAddressListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressListCall) Return(arg0 []*storage.Address, arg1 error) *MockIAddressListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Address, error)) *MockIAddressListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Address, error)) *MockIAddressListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListWithBalance mocks base method.
func (m *MockIAddress) ListWithBalance(ctx context.Context, filters storage.AddressListFilter) ([]storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListWithBalance", ctx, filters)
ret0, _ := ret[0].([]storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListWithBalance indicates an expected call of ListWithBalance.
func (mr *MockIAddressMockRecorder) ListWithBalance(ctx, filters any) *MockIAddressListWithBalanceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithBalance", reflect.TypeOf((*MockIAddress)(nil).ListWithBalance), ctx, filters)
return &MockIAddressListWithBalanceCall{Call: call}
}
// MockIAddressListWithBalanceCall wrap *gomock.Call
type MockIAddressListWithBalanceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressListWithBalanceCall) Return(arg0 []storage.Address, arg1 error) *MockIAddressListWithBalanceCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressListWithBalanceCall) Do(f func(context.Context, storage.AddressListFilter) ([]storage.Address, error)) *MockIAddressListWithBalanceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressListWithBalanceCall) DoAndReturn(f func(context.Context, storage.AddressListFilter) ([]storage.Address, error)) *MockIAddressListWithBalanceCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIAddress) Save(ctx context.Context, m *storage.Address) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIAddressMockRecorder) Save(ctx, m any) *MockIAddressSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIAddress)(nil).Save), ctx, m)
return &MockIAddressSaveCall{Call: call}
}
// MockIAddressSaveCall wrap *gomock.Call
type MockIAddressSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressSaveCall) Return(arg0 error) *MockIAddressSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressSaveCall) Do(f func(context.Context, *storage.Address) error) *MockIAddressSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressSaveCall) DoAndReturn(f func(context.Context, *storage.Address) error) *MockIAddressSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Series mocks base method.
func (m *MockIAddress) Series(ctx context.Context, addressId uint64, timeframe storage.Timeframe, column string, req storage.SeriesRequest) ([]storage.HistogramItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Series", ctx, addressId, timeframe, column, req)
ret0, _ := ret[0].([]storage.HistogramItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Series indicates an expected call of Series.
func (mr *MockIAddressMockRecorder) Series(ctx, addressId, timeframe, column, req any) *MockIAddressSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Series", reflect.TypeOf((*MockIAddress)(nil).Series), ctx, addressId, timeframe, column, req)
return &MockIAddressSeriesCall{Call: call}
}
// MockIAddressSeriesCall wrap *gomock.Call
type MockIAddressSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressSeriesCall) Return(items []storage.HistogramItem, err error) *MockIAddressSeriesCall {
c.Call = c.Call.Return(items, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressSeriesCall) Do(f func(context.Context, uint64, storage.Timeframe, string, storage.SeriesRequest) ([]storage.HistogramItem, error)) *MockIAddressSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressSeriesCall) DoAndReturn(f func(context.Context, uint64, storage.Timeframe, string, storage.SeriesRequest) ([]storage.HistogramItem, error)) *MockIAddressSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIAddress) Update(ctx context.Context, m *storage.Address) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIAddressMockRecorder) Update(ctx, m any) *MockIAddressUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIAddress)(nil).Update), ctx, m)
return &MockIAddressUpdateCall{Call: call}
}
// MockIAddressUpdateCall wrap *gomock.Call
type MockIAddressUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIAddressUpdateCall) Return(arg0 error) *MockIAddressUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIAddressUpdateCall) Do(f func(context.Context, *storage.Address) error) *MockIAddressUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIAddressUpdateCall) DoAndReturn(f func(context.Context, *storage.Address) error) *MockIAddressUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: api_key.go
//
// Generated by this command:
//
// mockgen -source=api_key.go -destination=mock/api_key.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIApiKey is a mock of IApiKey interface.
type MockIApiKey struct {
ctrl *gomock.Controller
recorder *MockIApiKeyMockRecorder
}
// MockIApiKeyMockRecorder is the mock recorder for MockIApiKey.
type MockIApiKeyMockRecorder struct {
mock *MockIApiKey
}
// NewMockIApiKey creates a new mock instance.
func NewMockIApiKey(ctrl *gomock.Controller) *MockIApiKey {
mock := &MockIApiKey{ctrl: ctrl}
mock.recorder = &MockIApiKeyMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIApiKey) EXPECT() *MockIApiKeyMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockIApiKey) Get(ctx context.Context, key string) (storage.ApiKey, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", ctx, key)
ret0, _ := ret[0].(storage.ApiKey)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockIApiKeyMockRecorder) Get(ctx, key any) *MockIApiKeyGetCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIApiKey)(nil).Get), ctx, key)
return &MockIApiKeyGetCall{Call: call}
}
// MockIApiKeyGetCall wrap *gomock.Call
type MockIApiKeyGetCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIApiKeyGetCall) Return(arg0 storage.ApiKey, arg1 error) *MockIApiKeyGetCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIApiKeyGetCall) Do(f func(context.Context, string) (storage.ApiKey, error)) *MockIApiKeyGetCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIApiKeyGetCall) DoAndReturn(f func(context.Context, string) (storage.ApiKey, error)) *MockIApiKeyGetCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: balance.go
//
// Generated by this command:
//
// mockgen -source=balance.go -destination=mock/balance.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIBalance is a mock of IBalance interface.
type MockIBalance struct {
ctrl *gomock.Controller
recorder *MockIBalanceMockRecorder
}
// MockIBalanceMockRecorder is the mock recorder for MockIBalance.
type MockIBalanceMockRecorder struct {
mock *MockIBalance
}
// NewMockIBalance creates a new mock instance.
func NewMockIBalance(ctrl *gomock.Controller) *MockIBalance {
mock := &MockIBalance{ctrl: ctrl}
mock.recorder = &MockIBalanceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIBalance) EXPECT() *MockIBalanceMockRecorder {
return m.recorder
}
// CursorList mocks base method.
func (m *MockIBalance) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Balance, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Balance)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIBalanceMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIBalanceCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBalance)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIBalanceCursorListCall{Call: call}
}
// MockIBalanceCursorListCall wrap *gomock.Call
type MockIBalanceCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceCursorListCall) Return(arg0 []*storage.Balance, arg1 error) *MockIBalanceCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Balance, error)) *MockIBalanceCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Balance, error)) *MockIBalanceCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIBalance) GetByID(ctx context.Context, id uint64) (*storage.Balance, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Balance)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIBalanceMockRecorder) GetByID(ctx, id any) *MockIBalanceGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBalance)(nil).GetByID), ctx, id)
return &MockIBalanceGetByIDCall{Call: call}
}
// MockIBalanceGetByIDCall wrap *gomock.Call
type MockIBalanceGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceGetByIDCall) Return(arg0 *storage.Balance, arg1 error) *MockIBalanceGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceGetByIDCall) Do(f func(context.Context, uint64) (*storage.Balance, error)) *MockIBalanceGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Balance, error)) *MockIBalanceGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIBalance) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIBalanceMockRecorder) IsNoRows(err any) *MockIBalanceIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBalance)(nil).IsNoRows), err)
return &MockIBalanceIsNoRowsCall{Call: call}
}
// MockIBalanceIsNoRowsCall wrap *gomock.Call
type MockIBalanceIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceIsNoRowsCall) Return(arg0 bool) *MockIBalanceIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceIsNoRowsCall) Do(f func(error) bool) *MockIBalanceIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIBalanceIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIBalance) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIBalanceMockRecorder) LastID(ctx any) *MockIBalanceLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBalance)(nil).LastID), ctx)
return &MockIBalanceLastIDCall{Call: call}
}
// MockIBalanceLastIDCall wrap *gomock.Call
type MockIBalanceLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceLastIDCall) Return(arg0 uint64, arg1 error) *MockIBalanceLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIBalanceLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIBalanceLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIBalance) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Balance, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Balance)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIBalanceMockRecorder) List(ctx, limit, offset, order any) *MockIBalanceListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBalance)(nil).List), ctx, limit, offset, order)
return &MockIBalanceListCall{Call: call}
}
// MockIBalanceListCall wrap *gomock.Call
type MockIBalanceListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceListCall) Return(arg0 []*storage.Balance, arg1 error) *MockIBalanceListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Balance, error)) *MockIBalanceListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Balance, error)) *MockIBalanceListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIBalance) Save(ctx context.Context, m *storage.Balance) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIBalanceMockRecorder) Save(ctx, m any) *MockIBalanceSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBalance)(nil).Save), ctx, m)
return &MockIBalanceSaveCall{Call: call}
}
// MockIBalanceSaveCall wrap *gomock.Call
type MockIBalanceSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceSaveCall) Return(arg0 error) *MockIBalanceSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceSaveCall) Do(f func(context.Context, *storage.Balance) error) *MockIBalanceSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceSaveCall) DoAndReturn(f func(context.Context, *storage.Balance) error) *MockIBalanceSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIBalance) Update(ctx context.Context, m *storage.Balance) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIBalanceMockRecorder) Update(ctx, m any) *MockIBalanceUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBalance)(nil).Update), ctx, m)
return &MockIBalanceUpdateCall{Call: call}
}
// MockIBalanceUpdateCall wrap *gomock.Call
type MockIBalanceUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBalanceUpdateCall) Return(arg0 error) *MockIBalanceUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBalanceUpdateCall) Do(f func(context.Context, *storage.Balance) error) *MockIBalanceUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBalanceUpdateCall) DoAndReturn(f func(context.Context, *storage.Balance) error) *MockIBalanceUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: blob_log.go
//
// Generated by this command:
//
// mockgen -source=blob_log.go -destination=mock/blob_log.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
io "io"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIBlobLog is a mock of IBlobLog interface.
type MockIBlobLog struct {
ctrl *gomock.Controller
recorder *MockIBlobLogMockRecorder
}
// MockIBlobLogMockRecorder is the mock recorder for MockIBlobLog.
type MockIBlobLogMockRecorder struct {
mock *MockIBlobLog
}
// NewMockIBlobLog creates a new mock instance.
func NewMockIBlobLog(ctrl *gomock.Controller) *MockIBlobLog {
mock := &MockIBlobLog{ctrl: ctrl}
mock.recorder = &MockIBlobLogMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIBlobLog) EXPECT() *MockIBlobLogMockRecorder {
return m.recorder
}
// Blob mocks base method.
func (m *MockIBlobLog) Blob(ctx context.Context, height types.Level, nsId uint64, commitment string) (storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Blob", ctx, height, nsId, commitment)
ret0, _ := ret[0].(storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Blob indicates an expected call of Blob.
func (mr *MockIBlobLogMockRecorder) Blob(ctx, height, nsId, commitment any) *MockIBlobLogBlobCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Blob", reflect.TypeOf((*MockIBlobLog)(nil).Blob), ctx, height, nsId, commitment)
return &MockIBlobLogBlobCall{Call: call}
}
// MockIBlobLogBlobCall wrap *gomock.Call
type MockIBlobLogBlobCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogBlobCall) Return(arg0 storage.BlobLog, arg1 error) *MockIBlobLogBlobCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogBlobCall) Do(f func(context.Context, types.Level, uint64, string) (storage.BlobLog, error)) *MockIBlobLogBlobCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogBlobCall) DoAndReturn(f func(context.Context, types.Level, uint64, string) (storage.BlobLog, error)) *MockIBlobLogBlobCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByHeight mocks base method.
func (m *MockIBlobLog) ByHeight(ctx context.Context, height types.Level, fltrs storage.BlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHeight", ctx, height, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHeight indicates an expected call of ByHeight.
func (mr *MockIBlobLogMockRecorder) ByHeight(ctx, height, fltrs any) *MockIBlobLogByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeight", reflect.TypeOf((*MockIBlobLog)(nil).ByHeight), ctx, height, fltrs)
return &MockIBlobLogByHeightCall{Call: call}
}
// MockIBlobLogByHeightCall wrap *gomock.Call
type MockIBlobLogByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogByHeightCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogByHeightCall) Do(f func(context.Context, types.Level, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogByHeightCall) DoAndReturn(f func(context.Context, types.Level, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByHeightCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByNamespace mocks base method.
func (m *MockIBlobLog) ByNamespace(ctx context.Context, nsId uint64, fltrs storage.BlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByNamespace", ctx, nsId, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByNamespace indicates an expected call of ByNamespace.
func (mr *MockIBlobLogMockRecorder) ByNamespace(ctx, nsId, fltrs any) *MockIBlobLogByNamespaceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByNamespace", reflect.TypeOf((*MockIBlobLog)(nil).ByNamespace), ctx, nsId, fltrs)
return &MockIBlobLogByNamespaceCall{Call: call}
}
// MockIBlobLogByNamespaceCall wrap *gomock.Call
type MockIBlobLogByNamespaceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogByNamespaceCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogByNamespaceCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogByNamespaceCall) Do(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByNamespaceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogByNamespaceCall) DoAndReturn(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByNamespaceCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByProviders mocks base method.
func (m *MockIBlobLog) ByProviders(ctx context.Context, providers []storage.RollupProvider, fltrs storage.BlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByProviders", ctx, providers, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByProviders indicates an expected call of ByProviders.
func (mr *MockIBlobLogMockRecorder) ByProviders(ctx, providers, fltrs any) *MockIBlobLogByProvidersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByProviders", reflect.TypeOf((*MockIBlobLog)(nil).ByProviders), ctx, providers, fltrs)
return &MockIBlobLogByProvidersCall{Call: call}
}
// MockIBlobLogByProvidersCall wrap *gomock.Call
type MockIBlobLogByProvidersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogByProvidersCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogByProvidersCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogByProvidersCall) Do(f func(context.Context, []storage.RollupProvider, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByProvidersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogByProvidersCall) DoAndReturn(f func(context.Context, []storage.RollupProvider, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByProvidersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BySigner mocks base method.
func (m *MockIBlobLog) BySigner(ctx context.Context, signerId uint64, fltrs storage.BlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BySigner", ctx, signerId, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BySigner indicates an expected call of BySigner.
func (mr *MockIBlobLogMockRecorder) BySigner(ctx, signerId, fltrs any) *MockIBlobLogBySignerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BySigner", reflect.TypeOf((*MockIBlobLog)(nil).BySigner), ctx, signerId, fltrs)
return &MockIBlobLogBySignerCall{Call: call}
}
// MockIBlobLogBySignerCall wrap *gomock.Call
type MockIBlobLogBySignerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogBySignerCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogBySignerCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogBySignerCall) Do(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogBySignerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogBySignerCall) DoAndReturn(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogBySignerCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByTxId mocks base method.
func (m *MockIBlobLog) ByTxId(ctx context.Context, txId uint64, fltrs storage.BlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByTxId", ctx, txId, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByTxId indicates an expected call of ByTxId.
func (mr *MockIBlobLogMockRecorder) ByTxId(ctx, txId, fltrs any) *MockIBlobLogByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByTxId", reflect.TypeOf((*MockIBlobLog)(nil).ByTxId), ctx, txId, fltrs)
return &MockIBlobLogByTxIdCall{Call: call}
}
// MockIBlobLogByTxIdCall wrap *gomock.Call
type MockIBlobLogByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogByTxIdCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogByTxIdCall) Do(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogByTxIdCall) DoAndReturn(f func(context.Context, uint64, storage.BlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogByTxIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CountByTxId mocks base method.
func (m *MockIBlobLog) CountByTxId(ctx context.Context, txId uint64) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CountByTxId", ctx, txId)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CountByTxId indicates an expected call of CountByTxId.
func (mr *MockIBlobLogMockRecorder) CountByTxId(ctx, txId any) *MockIBlobLogCountByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountByTxId", reflect.TypeOf((*MockIBlobLog)(nil).CountByTxId), ctx, txId)
return &MockIBlobLogCountByTxIdCall{Call: call}
}
// MockIBlobLogCountByTxIdCall wrap *gomock.Call
type MockIBlobLogCountByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogCountByTxIdCall) Return(arg0 int, arg1 error) *MockIBlobLogCountByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogCountByTxIdCall) Do(f func(context.Context, uint64) (int, error)) *MockIBlobLogCountByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogCountByTxIdCall) DoAndReturn(f func(context.Context, uint64) (int, error)) *MockIBlobLogCountByTxIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIBlobLog) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIBlobLogMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIBlobLogCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBlobLog)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIBlobLogCursorListCall{Call: call}
}
// MockIBlobLogCursorListCall wrap *gomock.Call
type MockIBlobLogCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogCursorListCall) Return(arg0 []*storage.BlobLog, arg1 error) *MockIBlobLogCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.BlobLog, error)) *MockIBlobLogCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.BlobLog, error)) *MockIBlobLogCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ExportByProviders mocks base method.
func (m *MockIBlobLog) ExportByProviders(ctx context.Context, providers []storage.RollupProvider, from, to time.Time, stream io.Writer) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ExportByProviders", ctx, providers, from, to, stream)
ret0, _ := ret[0].(error)
return ret0
}
// ExportByProviders indicates an expected call of ExportByProviders.
func (mr *MockIBlobLogMockRecorder) ExportByProviders(ctx, providers, from, to, stream any) *MockIBlobLogExportByProvidersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportByProviders", reflect.TypeOf((*MockIBlobLog)(nil).ExportByProviders), ctx, providers, from, to, stream)
return &MockIBlobLogExportByProvidersCall{Call: call}
}
// MockIBlobLogExportByProvidersCall wrap *gomock.Call
type MockIBlobLogExportByProvidersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogExportByProvidersCall) Return(err error) *MockIBlobLogExportByProvidersCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogExportByProvidersCall) Do(f func(context.Context, []storage.RollupProvider, time.Time, time.Time, io.Writer) error) *MockIBlobLogExportByProvidersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogExportByProvidersCall) DoAndReturn(f func(context.Context, []storage.RollupProvider, time.Time, time.Time, io.Writer) error) *MockIBlobLogExportByProvidersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIBlobLog) GetByID(ctx context.Context, id uint64) (*storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIBlobLogMockRecorder) GetByID(ctx, id any) *MockIBlobLogGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBlobLog)(nil).GetByID), ctx, id)
return &MockIBlobLogGetByIDCall{Call: call}
}
// MockIBlobLogGetByIDCall wrap *gomock.Call
type MockIBlobLogGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogGetByIDCall) Return(arg0 *storage.BlobLog, arg1 error) *MockIBlobLogGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogGetByIDCall) Do(f func(context.Context, uint64) (*storage.BlobLog, error)) *MockIBlobLogGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.BlobLog, error)) *MockIBlobLogGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIBlobLog) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIBlobLogMockRecorder) IsNoRows(err any) *MockIBlobLogIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBlobLog)(nil).IsNoRows), err)
return &MockIBlobLogIsNoRowsCall{Call: call}
}
// MockIBlobLogIsNoRowsCall wrap *gomock.Call
type MockIBlobLogIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogIsNoRowsCall) Return(arg0 bool) *MockIBlobLogIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogIsNoRowsCall) Do(f func(error) bool) *MockIBlobLogIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIBlobLogIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIBlobLog) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIBlobLogMockRecorder) LastID(ctx any) *MockIBlobLogLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBlobLog)(nil).LastID), ctx)
return &MockIBlobLogLastIDCall{Call: call}
}
// MockIBlobLogLastIDCall wrap *gomock.Call
type MockIBlobLogLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogLastIDCall) Return(arg0 uint64, arg1 error) *MockIBlobLogLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIBlobLogLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIBlobLogLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIBlobLog) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIBlobLogMockRecorder) List(ctx, limit, offset, order any) *MockIBlobLogListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBlobLog)(nil).List), ctx, limit, offset, order)
return &MockIBlobLogListCall{Call: call}
}
// MockIBlobLogListCall wrap *gomock.Call
type MockIBlobLogListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogListCall) Return(arg0 []*storage.BlobLog, arg1 error) *MockIBlobLogListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.BlobLog, error)) *MockIBlobLogListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.BlobLog, error)) *MockIBlobLogListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListBlobs mocks base method.
func (m *MockIBlobLog) ListBlobs(ctx context.Context, fltrs storage.ListBlobLogFilters) ([]storage.BlobLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListBlobs", ctx, fltrs)
ret0, _ := ret[0].([]storage.BlobLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListBlobs indicates an expected call of ListBlobs.
func (mr *MockIBlobLogMockRecorder) ListBlobs(ctx, fltrs any) *MockIBlobLogListBlobsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBlobs", reflect.TypeOf((*MockIBlobLog)(nil).ListBlobs), ctx, fltrs)
return &MockIBlobLogListBlobsCall{Call: call}
}
// MockIBlobLogListBlobsCall wrap *gomock.Call
type MockIBlobLogListBlobsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogListBlobsCall) Return(arg0 []storage.BlobLog, arg1 error) *MockIBlobLogListBlobsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogListBlobsCall) Do(f func(context.Context, storage.ListBlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogListBlobsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogListBlobsCall) DoAndReturn(f func(context.Context, storage.ListBlobLogFilters) ([]storage.BlobLog, error)) *MockIBlobLogListBlobsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIBlobLog) Save(ctx context.Context, m *storage.BlobLog) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIBlobLogMockRecorder) Save(ctx, m any) *MockIBlobLogSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBlobLog)(nil).Save), ctx, m)
return &MockIBlobLogSaveCall{Call: call}
}
// MockIBlobLogSaveCall wrap *gomock.Call
type MockIBlobLogSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogSaveCall) Return(arg0 error) *MockIBlobLogSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogSaveCall) Do(f func(context.Context, *storage.BlobLog) error) *MockIBlobLogSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogSaveCall) DoAndReturn(f func(context.Context, *storage.BlobLog) error) *MockIBlobLogSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIBlobLog) Update(ctx context.Context, m *storage.BlobLog) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIBlobLogMockRecorder) Update(ctx, m any) *MockIBlobLogUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBlobLog)(nil).Update), ctx, m)
return &MockIBlobLogUpdateCall{Call: call}
}
// MockIBlobLogUpdateCall wrap *gomock.Call
type MockIBlobLogUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlobLogUpdateCall) Return(arg0 error) *MockIBlobLogUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlobLogUpdateCall) Do(f func(context.Context, *storage.BlobLog) error) *MockIBlobLogUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlobLogUpdateCall) DoAndReturn(f func(context.Context, *storage.BlobLog) error) *MockIBlobLogUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: block.go
//
// Generated by this command:
//
// mockgen -source=block.go -destination=mock/block.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIBlock is a mock of IBlock interface.
type MockIBlock struct {
ctrl *gomock.Controller
recorder *MockIBlockMockRecorder
}
// MockIBlockMockRecorder is the mock recorder for MockIBlock.
type MockIBlockMockRecorder struct {
mock *MockIBlock
}
// NewMockIBlock creates a new mock instance.
func NewMockIBlock(ctrl *gomock.Controller) *MockIBlock {
mock := &MockIBlock{ctrl: ctrl}
mock.recorder = &MockIBlockMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIBlock) EXPECT() *MockIBlockMockRecorder {
return m.recorder
}
// ByHash mocks base method.
func (m *MockIBlock) ByHash(ctx context.Context, hash []byte) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHash", ctx, hash)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHash indicates an expected call of ByHash.
func (mr *MockIBlockMockRecorder) ByHash(ctx, hash any) *MockIBlockByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockIBlock)(nil).ByHash), ctx, hash)
return &MockIBlockByHashCall{Call: call}
}
// MockIBlockByHashCall wrap *gomock.Call
type MockIBlockByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockByHashCall) Return(arg0 storage.Block, arg1 error) *MockIBlockByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockByHashCall) Do(f func(context.Context, []byte) (storage.Block, error)) *MockIBlockByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Block, error)) *MockIBlockByHashCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByHeight mocks base method.
func (m *MockIBlock) ByHeight(ctx context.Context, height types.Level) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHeight", ctx, height)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHeight indicates an expected call of ByHeight.
func (mr *MockIBlockMockRecorder) ByHeight(ctx, height any) *MockIBlockByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeight", reflect.TypeOf((*MockIBlock)(nil).ByHeight), ctx, height)
return &MockIBlockByHeightCall{Call: call}
}
// MockIBlockByHeightCall wrap *gomock.Call
type MockIBlockByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockByHeightCall) Return(arg0 storage.Block, arg1 error) *MockIBlockByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockByHeightCall) Do(f func(context.Context, types.Level) (storage.Block, error)) *MockIBlockByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockByHeightCall) DoAndReturn(f func(context.Context, types.Level) (storage.Block, error)) *MockIBlockByHeightCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByHeightWithStats mocks base method.
func (m *MockIBlock) ByHeightWithStats(ctx context.Context, height types.Level) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHeightWithStats", ctx, height)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHeightWithStats indicates an expected call of ByHeightWithStats.
func (mr *MockIBlockMockRecorder) ByHeightWithStats(ctx, height any) *MockIBlockByHeightWithStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeightWithStats", reflect.TypeOf((*MockIBlock)(nil).ByHeightWithStats), ctx, height)
return &MockIBlockByHeightWithStatsCall{Call: call}
}
// MockIBlockByHeightWithStatsCall wrap *gomock.Call
type MockIBlockByHeightWithStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockByHeightWithStatsCall) Return(arg0 storage.Block, arg1 error) *MockIBlockByHeightWithStatsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockByHeightWithStatsCall) Do(f func(context.Context, types.Level) (storage.Block, error)) *MockIBlockByHeightWithStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockByHeightWithStatsCall) DoAndReturn(f func(context.Context, types.Level) (storage.Block, error)) *MockIBlockByHeightWithStatsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByIdWithRelations mocks base method.
func (m *MockIBlock) ByIdWithRelations(ctx context.Context, id uint64) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByIdWithRelations", ctx, id)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByIdWithRelations indicates an expected call of ByIdWithRelations.
func (mr *MockIBlockMockRecorder) ByIdWithRelations(ctx, id any) *MockIBlockByIdWithRelationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByIdWithRelations", reflect.TypeOf((*MockIBlock)(nil).ByIdWithRelations), ctx, id)
return &MockIBlockByIdWithRelationsCall{Call: call}
}
// MockIBlockByIdWithRelationsCall wrap *gomock.Call
type MockIBlockByIdWithRelationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockByIdWithRelationsCall) Return(arg0 storage.Block, arg1 error) *MockIBlockByIdWithRelationsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockByIdWithRelationsCall) Do(f func(context.Context, uint64) (storage.Block, error)) *MockIBlockByIdWithRelationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockByIdWithRelationsCall) DoAndReturn(f func(context.Context, uint64) (storage.Block, error)) *MockIBlockByIdWithRelationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByProposer mocks base method.
func (m *MockIBlock) ByProposer(ctx context.Context, proposerId uint64, limit, offset int) ([]storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByProposer", ctx, proposerId, limit, offset)
ret0, _ := ret[0].([]storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByProposer indicates an expected call of ByProposer.
func (mr *MockIBlockMockRecorder) ByProposer(ctx, proposerId, limit, offset any) *MockIBlockByProposerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByProposer", reflect.TypeOf((*MockIBlock)(nil).ByProposer), ctx, proposerId, limit, offset)
return &MockIBlockByProposerCall{Call: call}
}
// MockIBlockByProposerCall wrap *gomock.Call
type MockIBlockByProposerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockByProposerCall) Return(arg0 []storage.Block, arg1 error) *MockIBlockByProposerCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockByProposerCall) Do(f func(context.Context, uint64, int, int) ([]storage.Block, error)) *MockIBlockByProposerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockByProposerCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Block, error)) *MockIBlockByProposerCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIBlock) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIBlockMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIBlockCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBlock)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIBlockCursorListCall{Call: call}
}
// MockIBlockCursorListCall wrap *gomock.Call
type MockIBlockCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockCursorListCall) Return(arg0 []*storage.Block, arg1 error) *MockIBlockCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Block, error)) *MockIBlockCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Block, error)) *MockIBlockCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIBlock) GetByID(ctx context.Context, id uint64) (*storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIBlockMockRecorder) GetByID(ctx, id any) *MockIBlockGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBlock)(nil).GetByID), ctx, id)
return &MockIBlockGetByIDCall{Call: call}
}
// MockIBlockGetByIDCall wrap *gomock.Call
type MockIBlockGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockGetByIDCall) Return(arg0 *storage.Block, arg1 error) *MockIBlockGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockGetByIDCall) Do(f func(context.Context, uint64) (*storage.Block, error)) *MockIBlockGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Block, error)) *MockIBlockGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIBlock) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIBlockMockRecorder) IsNoRows(err any) *MockIBlockIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBlock)(nil).IsNoRows), err)
return &MockIBlockIsNoRowsCall{Call: call}
}
// MockIBlockIsNoRowsCall wrap *gomock.Call
type MockIBlockIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockIsNoRowsCall) Return(arg0 bool) *MockIBlockIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockIsNoRowsCall) Do(f func(error) bool) *MockIBlockIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIBlockIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Last mocks base method.
func (m *MockIBlock) Last(ctx context.Context) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Last", ctx)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Last indicates an expected call of Last.
func (mr *MockIBlockMockRecorder) Last(ctx any) *MockIBlockLastCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Last", reflect.TypeOf((*MockIBlock)(nil).Last), ctx)
return &MockIBlockLastCall{Call: call}
}
// MockIBlockLastCall wrap *gomock.Call
type MockIBlockLastCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockLastCall) Return(arg0 storage.Block, arg1 error) *MockIBlockLastCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockLastCall) Do(f func(context.Context) (storage.Block, error)) *MockIBlockLastCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockLastCall) DoAndReturn(f func(context.Context) (storage.Block, error)) *MockIBlockLastCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIBlock) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIBlockMockRecorder) LastID(ctx any) *MockIBlockLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBlock)(nil).LastID), ctx)
return &MockIBlockLastIDCall{Call: call}
}
// MockIBlockLastIDCall wrap *gomock.Call
type MockIBlockLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockLastIDCall) Return(arg0 uint64, arg1 error) *MockIBlockLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIBlockLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIBlockLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIBlock) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIBlockMockRecorder) List(ctx, limit, offset, order any) *MockIBlockListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBlock)(nil).List), ctx, limit, offset, order)
return &MockIBlockListCall{Call: call}
}
// MockIBlockListCall wrap *gomock.Call
type MockIBlockListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockListCall) Return(arg0 []*storage.Block, arg1 error) *MockIBlockListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *MockIBlockListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *MockIBlockListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListWithStats mocks base method.
func (m *MockIBlock) ListWithStats(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListWithStats", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListWithStats indicates an expected call of ListWithStats.
func (mr *MockIBlockMockRecorder) ListWithStats(ctx, limit, offset, order any) *MockIBlockListWithStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithStats", reflect.TypeOf((*MockIBlock)(nil).ListWithStats), ctx, limit, offset, order)
return &MockIBlockListWithStatsCall{Call: call}
}
// MockIBlockListWithStatsCall wrap *gomock.Call
type MockIBlockListWithStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockListWithStatsCall) Return(arg0 []*storage.Block, arg1 error) *MockIBlockListWithStatsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockListWithStatsCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *MockIBlockListWithStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockListWithStatsCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *MockIBlockListWithStatsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIBlock) Save(ctx context.Context, m *storage.Block) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIBlockMockRecorder) Save(ctx, m any) *MockIBlockSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBlock)(nil).Save), ctx, m)
return &MockIBlockSaveCall{Call: call}
}
// MockIBlockSaveCall wrap *gomock.Call
type MockIBlockSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSaveCall) Return(arg0 error) *MockIBlockSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSaveCall) Do(f func(context.Context, *storage.Block) error) *MockIBlockSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSaveCall) DoAndReturn(f func(context.Context, *storage.Block) error) *MockIBlockSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Time mocks base method.
func (m *MockIBlock) Time(ctx context.Context, height types.Level) (time.Time, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Time", ctx, height)
ret0, _ := ret[0].(time.Time)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Time indicates an expected call of Time.
func (mr *MockIBlockMockRecorder) Time(ctx, height any) *MockIBlockTimeCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Time", reflect.TypeOf((*MockIBlock)(nil).Time), ctx, height)
return &MockIBlockTimeCall{Call: call}
}
// MockIBlockTimeCall wrap *gomock.Call
type MockIBlockTimeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockTimeCall) Return(arg0 time.Time, arg1 error) *MockIBlockTimeCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockTimeCall) Do(f func(context.Context, types.Level) (time.Time, error)) *MockIBlockTimeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockTimeCall) DoAndReturn(f func(context.Context, types.Level) (time.Time, error)) *MockIBlockTimeCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIBlock) Update(ctx context.Context, m *storage.Block) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIBlockMockRecorder) Update(ctx, m any) *MockIBlockUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBlock)(nil).Update), ctx, m)
return &MockIBlockUpdateCall{Call: call}
}
// MockIBlockUpdateCall wrap *gomock.Call
type MockIBlockUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockUpdateCall) Return(arg0 error) *MockIBlockUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockUpdateCall) Do(f func(context.Context, *storage.Block) error) *MockIBlockUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockUpdateCall) DoAndReturn(f func(context.Context, *storage.Block) error) *MockIBlockUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: block_signature.go
//
// Generated by this command:
//
// mockgen -source=block_signature.go -destination=mock/block_signature.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIBlockSignature is a mock of IBlockSignature interface.
type MockIBlockSignature struct {
ctrl *gomock.Controller
recorder *MockIBlockSignatureMockRecorder
}
// MockIBlockSignatureMockRecorder is the mock recorder for MockIBlockSignature.
type MockIBlockSignatureMockRecorder struct {
mock *MockIBlockSignature
}
// NewMockIBlockSignature creates a new mock instance.
func NewMockIBlockSignature(ctrl *gomock.Controller) *MockIBlockSignature {
mock := &MockIBlockSignature{ctrl: ctrl}
mock.recorder = &MockIBlockSignatureMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIBlockSignature) EXPECT() *MockIBlockSignatureMockRecorder {
return m.recorder
}
// CursorList mocks base method.
func (m *MockIBlockSignature) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.BlockSignature, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.BlockSignature)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIBlockSignatureMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIBlockSignatureCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBlockSignature)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIBlockSignatureCursorListCall{Call: call}
}
// MockIBlockSignatureCursorListCall wrap *gomock.Call
type MockIBlockSignatureCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureCursorListCall) Return(arg0 []*storage.BlockSignature, arg1 error) *MockIBlockSignatureCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.BlockSignature, error)) *MockIBlockSignatureCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.BlockSignature, error)) *MockIBlockSignatureCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIBlockSignature) GetByID(ctx context.Context, id uint64) (*storage.BlockSignature, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.BlockSignature)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIBlockSignatureMockRecorder) GetByID(ctx, id any) *MockIBlockSignatureGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBlockSignature)(nil).GetByID), ctx, id)
return &MockIBlockSignatureGetByIDCall{Call: call}
}
// MockIBlockSignatureGetByIDCall wrap *gomock.Call
type MockIBlockSignatureGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureGetByIDCall) Return(arg0 *storage.BlockSignature, arg1 error) *MockIBlockSignatureGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureGetByIDCall) Do(f func(context.Context, uint64) (*storage.BlockSignature, error)) *MockIBlockSignatureGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.BlockSignature, error)) *MockIBlockSignatureGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIBlockSignature) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIBlockSignatureMockRecorder) IsNoRows(err any) *MockIBlockSignatureIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBlockSignature)(nil).IsNoRows), err)
return &MockIBlockSignatureIsNoRowsCall{Call: call}
}
// MockIBlockSignatureIsNoRowsCall wrap *gomock.Call
type MockIBlockSignatureIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureIsNoRowsCall) Return(arg0 bool) *MockIBlockSignatureIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureIsNoRowsCall) Do(f func(error) bool) *MockIBlockSignatureIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIBlockSignatureIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIBlockSignature) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIBlockSignatureMockRecorder) LastID(ctx any) *MockIBlockSignatureLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBlockSignature)(nil).LastID), ctx)
return &MockIBlockSignatureLastIDCall{Call: call}
}
// MockIBlockSignatureLastIDCall wrap *gomock.Call
type MockIBlockSignatureLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureLastIDCall) Return(arg0 uint64, arg1 error) *MockIBlockSignatureLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIBlockSignatureLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIBlockSignatureLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LevelsByValidator mocks base method.
func (m *MockIBlockSignature) LevelsByValidator(ctx context.Context, validatorId uint64, startHeight types.Level) ([]types.Level, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LevelsByValidator", ctx, validatorId, startHeight)
ret0, _ := ret[0].([]types.Level)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LevelsByValidator indicates an expected call of LevelsByValidator.
func (mr *MockIBlockSignatureMockRecorder) LevelsByValidator(ctx, validatorId, startHeight any) *MockIBlockSignatureLevelsByValidatorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LevelsByValidator", reflect.TypeOf((*MockIBlockSignature)(nil).LevelsByValidator), ctx, validatorId, startHeight)
return &MockIBlockSignatureLevelsByValidatorCall{Call: call}
}
// MockIBlockSignatureLevelsByValidatorCall wrap *gomock.Call
type MockIBlockSignatureLevelsByValidatorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureLevelsByValidatorCall) Return(arg0 []types.Level, arg1 error) *MockIBlockSignatureLevelsByValidatorCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureLevelsByValidatorCall) Do(f func(context.Context, uint64, types.Level) ([]types.Level, error)) *MockIBlockSignatureLevelsByValidatorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureLevelsByValidatorCall) DoAndReturn(f func(context.Context, uint64, types.Level) ([]types.Level, error)) *MockIBlockSignatureLevelsByValidatorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIBlockSignature) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.BlockSignature, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.BlockSignature)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIBlockSignatureMockRecorder) List(ctx, limit, offset, order any) *MockIBlockSignatureListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBlockSignature)(nil).List), ctx, limit, offset, order)
return &MockIBlockSignatureListCall{Call: call}
}
// MockIBlockSignatureListCall wrap *gomock.Call
type MockIBlockSignatureListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureListCall) Return(arg0 []*storage.BlockSignature, arg1 error) *MockIBlockSignatureListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.BlockSignature, error)) *MockIBlockSignatureListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.BlockSignature, error)) *MockIBlockSignatureListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIBlockSignature) Save(ctx context.Context, m *storage.BlockSignature) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIBlockSignatureMockRecorder) Save(ctx, m any) *MockIBlockSignatureSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBlockSignature)(nil).Save), ctx, m)
return &MockIBlockSignatureSaveCall{Call: call}
}
// MockIBlockSignatureSaveCall wrap *gomock.Call
type MockIBlockSignatureSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureSaveCall) Return(arg0 error) *MockIBlockSignatureSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureSaveCall) Do(f func(context.Context, *storage.BlockSignature) error) *MockIBlockSignatureSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureSaveCall) DoAndReturn(f func(context.Context, *storage.BlockSignature) error) *MockIBlockSignatureSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIBlockSignature) Update(ctx context.Context, m *storage.BlockSignature) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIBlockSignatureMockRecorder) Update(ctx, m any) *MockIBlockSignatureUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBlockSignature)(nil).Update), ctx, m)
return &MockIBlockSignatureUpdateCall{Call: call}
}
// MockIBlockSignatureUpdateCall wrap *gomock.Call
type MockIBlockSignatureUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockSignatureUpdateCall) Return(arg0 error) *MockIBlockSignatureUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockSignatureUpdateCall) Do(f func(context.Context, *storage.BlockSignature) error) *MockIBlockSignatureUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockSignatureUpdateCall) DoAndReturn(f func(context.Context, *storage.BlockSignature) error) *MockIBlockSignatureUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: block_stats.go
//
// Generated by this command:
//
// mockgen -source=block_stats.go -destination=mock/block_stats.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
gomock "go.uber.org/mock/gomock"
)
// MockIBlockStats is a mock of IBlockStats interface.
type MockIBlockStats struct {
ctrl *gomock.Controller
recorder *MockIBlockStatsMockRecorder
}
// MockIBlockStatsMockRecorder is the mock recorder for MockIBlockStats.
type MockIBlockStatsMockRecorder struct {
mock *MockIBlockStats
}
// NewMockIBlockStats creates a new mock instance.
func NewMockIBlockStats(ctrl *gomock.Controller) *MockIBlockStats {
mock := &MockIBlockStats{ctrl: ctrl}
mock.recorder = &MockIBlockStatsMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIBlockStats) EXPECT() *MockIBlockStatsMockRecorder {
return m.recorder
}
// ByHeight mocks base method.
func (m *MockIBlockStats) ByHeight(ctx context.Context, height types.Level) (storage.BlockStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHeight", ctx, height)
ret0, _ := ret[0].(storage.BlockStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHeight indicates an expected call of ByHeight.
func (mr *MockIBlockStatsMockRecorder) ByHeight(ctx, height any) *MockIBlockStatsByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeight", reflect.TypeOf((*MockIBlockStats)(nil).ByHeight), ctx, height)
return &MockIBlockStatsByHeightCall{Call: call}
}
// MockIBlockStatsByHeightCall wrap *gomock.Call
type MockIBlockStatsByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockStatsByHeightCall) Return(arg0 storage.BlockStats, arg1 error) *MockIBlockStatsByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockStatsByHeightCall) Do(f func(context.Context, types.Level) (storage.BlockStats, error)) *MockIBlockStatsByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockStatsByHeightCall) DoAndReturn(f func(context.Context, types.Level) (storage.BlockStats, error)) *MockIBlockStatsByHeightCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastFrom mocks base method.
func (m *MockIBlockStats) LastFrom(ctx context.Context, head types.Level, limit int) ([]storage.BlockStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastFrom", ctx, head, limit)
ret0, _ := ret[0].([]storage.BlockStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastFrom indicates an expected call of LastFrom.
func (mr *MockIBlockStatsMockRecorder) LastFrom(ctx, head, limit any) *MockIBlockStatsLastFromCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastFrom", reflect.TypeOf((*MockIBlockStats)(nil).LastFrom), ctx, head, limit)
return &MockIBlockStatsLastFromCall{Call: call}
}
// MockIBlockStatsLastFromCall wrap *gomock.Call
type MockIBlockStatsLastFromCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIBlockStatsLastFromCall) Return(arg0 []storage.BlockStats, arg1 error) *MockIBlockStatsLastFromCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIBlockStatsLastFromCall) Do(f func(context.Context, types.Level, int) ([]storage.BlockStats, error)) *MockIBlockStatsLastFromCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIBlockStatsLastFromCall) DoAndReturn(f func(context.Context, types.Level, int) ([]storage.BlockStats, error)) *MockIBlockStatsLastFromCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: constant.go
//
// Generated by this command:
//
// mockgen -source=constant.go -destination=mock/constant.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/internal/storage/types"
gomock "go.uber.org/mock/gomock"
)
// MockIConstant is a mock of IConstant interface.
type MockIConstant struct {
ctrl *gomock.Controller
recorder *MockIConstantMockRecorder
}
// MockIConstantMockRecorder is the mock recorder for MockIConstant.
type MockIConstantMockRecorder struct {
mock *MockIConstant
}
// NewMockIConstant creates a new mock instance.
func NewMockIConstant(ctrl *gomock.Controller) *MockIConstant {
mock := &MockIConstant{ctrl: ctrl}
mock.recorder = &MockIConstantMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIConstant) EXPECT() *MockIConstantMockRecorder {
return m.recorder
}
// All mocks base method.
func (m *MockIConstant) All(ctx context.Context) ([]storage.Constant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "All", ctx)
ret0, _ := ret[0].([]storage.Constant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// All indicates an expected call of All.
func (mr *MockIConstantMockRecorder) All(ctx any) *MockIConstantAllCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "All", reflect.TypeOf((*MockIConstant)(nil).All), ctx)
return &MockIConstantAllCall{Call: call}
}
// MockIConstantAllCall wrap *gomock.Call
type MockIConstantAllCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIConstantAllCall) Return(arg0 []storage.Constant, arg1 error) *MockIConstantAllCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIConstantAllCall) Do(f func(context.Context) ([]storage.Constant, error)) *MockIConstantAllCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIConstantAllCall) DoAndReturn(f func(context.Context) ([]storage.Constant, error)) *MockIConstantAllCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByModule mocks base method.
func (m *MockIConstant) ByModule(ctx context.Context, module types.ModuleName) ([]storage.Constant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByModule", ctx, module)
ret0, _ := ret[0].([]storage.Constant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByModule indicates an expected call of ByModule.
func (mr *MockIConstantMockRecorder) ByModule(ctx, module any) *MockIConstantByModuleCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByModule", reflect.TypeOf((*MockIConstant)(nil).ByModule), ctx, module)
return &MockIConstantByModuleCall{Call: call}
}
// MockIConstantByModuleCall wrap *gomock.Call
type MockIConstantByModuleCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIConstantByModuleCall) Return(arg0 []storage.Constant, arg1 error) *MockIConstantByModuleCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIConstantByModuleCall) Do(f func(context.Context, types.ModuleName) ([]storage.Constant, error)) *MockIConstantByModuleCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIConstantByModuleCall) DoAndReturn(f func(context.Context, types.ModuleName) ([]storage.Constant, error)) *MockIConstantByModuleCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Get mocks base method.
func (m *MockIConstant) Get(ctx context.Context, module types.ModuleName, name string) (storage.Constant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", ctx, module, name)
ret0, _ := ret[0].(storage.Constant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockIConstantMockRecorder) Get(ctx, module, name any) *MockIConstantGetCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIConstant)(nil).Get), ctx, module, name)
return &MockIConstantGetCall{Call: call}
}
// MockIConstantGetCall wrap *gomock.Call
type MockIConstantGetCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIConstantGetCall) Return(arg0 storage.Constant, arg1 error) *MockIConstantGetCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIConstantGetCall) Do(f func(context.Context, types.ModuleName, string) (storage.Constant, error)) *MockIConstantGetCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIConstantGetCall) DoAndReturn(f func(context.Context, types.ModuleName, string) (storage.Constant, error)) *MockIConstantGetCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package mock
import (
models "github.com/celenium-io/celestia-indexer/internal/storage"
gomock "go.uber.org/mock/gomock"
)
type Storage struct {
Blocks models.IBlock
Tx models.ITx
Message models.IMessage
Event models.IEvent
Address models.IAddress
Namespace models.INamespace
State models.IState
ctrl *gomock.Controller
}
func Create(t gomock.TestReporter) Storage {
ctrl := gomock.NewController(t)
return Storage{
Blocks: NewMockIBlock(ctrl),
Tx: NewMockITx(ctrl),
Message: NewMockIMessage(ctrl),
Event: NewMockIEvent(ctrl),
Address: NewMockIAddress(ctrl),
Namespace: NewMockINamespace(ctrl),
State: NewMockIState(ctrl),
ctrl: ctrl,
}
}
func (s Storage) Close() error {
s.ctrl.Finish()
return nil
}
func (s Storage) Ctrl() *gomock.Controller {
return s.ctrl
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: delegation.go
//
// Generated by this command:
//
// mockgen -source=delegation.go -destination=mock/delegation.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIDelegation is a mock of IDelegation interface.
type MockIDelegation struct {
ctrl *gomock.Controller
recorder *MockIDelegationMockRecorder
}
// MockIDelegationMockRecorder is the mock recorder for MockIDelegation.
type MockIDelegationMockRecorder struct {
mock *MockIDelegation
}
// NewMockIDelegation creates a new mock instance.
func NewMockIDelegation(ctrl *gomock.Controller) *MockIDelegation {
mock := &MockIDelegation{ctrl: ctrl}
mock.recorder = &MockIDelegationMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIDelegation) EXPECT() *MockIDelegationMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIDelegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int, showZero bool) ([]storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, addressId, limit, offset, showZero)
ret0, _ := ret[0].([]storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIDelegationMockRecorder) ByAddress(ctx, addressId, limit, offset, showZero any) *MockIDelegationByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIDelegation)(nil).ByAddress), ctx, addressId, limit, offset, showZero)
return &MockIDelegationByAddressCall{Call: call}
}
// MockIDelegationByAddressCall wrap *gomock.Call
type MockIDelegationByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationByAddressCall) Return(arg0 []storage.Delegation, arg1 error) *MockIDelegationByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationByAddressCall) Do(f func(context.Context, uint64, int, int, bool) ([]storage.Delegation, error)) *MockIDelegationByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationByAddressCall) DoAndReturn(f func(context.Context, uint64, int, int, bool) ([]storage.Delegation, error)) *MockIDelegationByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByValidator mocks base method.
func (m *MockIDelegation) ByValidator(ctx context.Context, validatorId uint64, limit, offset int, showZero bool) ([]storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByValidator", ctx, validatorId, limit, offset, showZero)
ret0, _ := ret[0].([]storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByValidator indicates an expected call of ByValidator.
func (mr *MockIDelegationMockRecorder) ByValidator(ctx, validatorId, limit, offset, showZero any) *MockIDelegationByValidatorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByValidator", reflect.TypeOf((*MockIDelegation)(nil).ByValidator), ctx, validatorId, limit, offset, showZero)
return &MockIDelegationByValidatorCall{Call: call}
}
// MockIDelegationByValidatorCall wrap *gomock.Call
type MockIDelegationByValidatorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationByValidatorCall) Return(arg0 []storage.Delegation, arg1 error) *MockIDelegationByValidatorCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationByValidatorCall) Do(f func(context.Context, uint64, int, int, bool) ([]storage.Delegation, error)) *MockIDelegationByValidatorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationByValidatorCall) DoAndReturn(f func(context.Context, uint64, int, int, bool) ([]storage.Delegation, error)) *MockIDelegationByValidatorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIDelegation) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIDelegationMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIDelegationCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIDelegation)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIDelegationCursorListCall{Call: call}
}
// MockIDelegationCursorListCall wrap *gomock.Call
type MockIDelegationCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationCursorListCall) Return(arg0 []*storage.Delegation, arg1 error) *MockIDelegationCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Delegation, error)) *MockIDelegationCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Delegation, error)) *MockIDelegationCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIDelegation) GetByID(ctx context.Context, id uint64) (*storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIDelegationMockRecorder) GetByID(ctx, id any) *MockIDelegationGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIDelegation)(nil).GetByID), ctx, id)
return &MockIDelegationGetByIDCall{Call: call}
}
// MockIDelegationGetByIDCall wrap *gomock.Call
type MockIDelegationGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationGetByIDCall) Return(arg0 *storage.Delegation, arg1 error) *MockIDelegationGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationGetByIDCall) Do(f func(context.Context, uint64) (*storage.Delegation, error)) *MockIDelegationGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Delegation, error)) *MockIDelegationGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIDelegation) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIDelegationMockRecorder) IsNoRows(err any) *MockIDelegationIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIDelegation)(nil).IsNoRows), err)
return &MockIDelegationIsNoRowsCall{Call: call}
}
// MockIDelegationIsNoRowsCall wrap *gomock.Call
type MockIDelegationIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationIsNoRowsCall) Return(arg0 bool) *MockIDelegationIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationIsNoRowsCall) Do(f func(error) bool) *MockIDelegationIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIDelegationIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIDelegation) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIDelegationMockRecorder) LastID(ctx any) *MockIDelegationLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIDelegation)(nil).LastID), ctx)
return &MockIDelegationLastIDCall{Call: call}
}
// MockIDelegationLastIDCall wrap *gomock.Call
type MockIDelegationLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationLastIDCall) Return(arg0 uint64, arg1 error) *MockIDelegationLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIDelegationLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIDelegationLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIDelegation) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIDelegationMockRecorder) List(ctx, limit, offset, order any) *MockIDelegationListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIDelegation)(nil).List), ctx, limit, offset, order)
return &MockIDelegationListCall{Call: call}
}
// MockIDelegationListCall wrap *gomock.Call
type MockIDelegationListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationListCall) Return(arg0 []*storage.Delegation, arg1 error) *MockIDelegationListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Delegation, error)) *MockIDelegationListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Delegation, error)) *MockIDelegationListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIDelegation) Save(ctx context.Context, m *storage.Delegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIDelegationMockRecorder) Save(ctx, m any) *MockIDelegationSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIDelegation)(nil).Save), ctx, m)
return &MockIDelegationSaveCall{Call: call}
}
// MockIDelegationSaveCall wrap *gomock.Call
type MockIDelegationSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationSaveCall) Return(arg0 error) *MockIDelegationSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationSaveCall) Do(f func(context.Context, *storage.Delegation) error) *MockIDelegationSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationSaveCall) DoAndReturn(f func(context.Context, *storage.Delegation) error) *MockIDelegationSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIDelegation) Update(ctx context.Context, m *storage.Delegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIDelegationMockRecorder) Update(ctx, m any) *MockIDelegationUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIDelegation)(nil).Update), ctx, m)
return &MockIDelegationUpdateCall{Call: call}
}
// MockIDelegationUpdateCall wrap *gomock.Call
type MockIDelegationUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDelegationUpdateCall) Return(arg0 error) *MockIDelegationUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDelegationUpdateCall) Do(f func(context.Context, *storage.Delegation) error) *MockIDelegationUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDelegationUpdateCall) DoAndReturn(f func(context.Context, *storage.Delegation) error) *MockIDelegationUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: denom_metadata.go
//
// Generated by this command:
//
// mockgen -source=denom_metadata.go -destination=mock/denom_metadata.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIDenomMetadata is a mock of IDenomMetadata interface.
type MockIDenomMetadata struct {
ctrl *gomock.Controller
recorder *MockIDenomMetadataMockRecorder
}
// MockIDenomMetadataMockRecorder is the mock recorder for MockIDenomMetadata.
type MockIDenomMetadataMockRecorder struct {
mock *MockIDenomMetadata
}
// NewMockIDenomMetadata creates a new mock instance.
func NewMockIDenomMetadata(ctrl *gomock.Controller) *MockIDenomMetadata {
mock := &MockIDenomMetadata{ctrl: ctrl}
mock.recorder = &MockIDenomMetadataMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIDenomMetadata) EXPECT() *MockIDenomMetadataMockRecorder {
return m.recorder
}
// All mocks base method.
func (m *MockIDenomMetadata) All(ctx context.Context) ([]storage.DenomMetadata, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "All", ctx)
ret0, _ := ret[0].([]storage.DenomMetadata)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// All indicates an expected call of All.
func (mr *MockIDenomMetadataMockRecorder) All(ctx any) *MockIDenomMetadataAllCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "All", reflect.TypeOf((*MockIDenomMetadata)(nil).All), ctx)
return &MockIDenomMetadataAllCall{Call: call}
}
// MockIDenomMetadataAllCall wrap *gomock.Call
type MockIDenomMetadataAllCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIDenomMetadataAllCall) Return(arg0 []storage.DenomMetadata, arg1 error) *MockIDenomMetadataAllCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIDenomMetadataAllCall) Do(f func(context.Context) ([]storage.DenomMetadata, error)) *MockIDenomMetadataAllCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIDenomMetadataAllCall) DoAndReturn(f func(context.Context) ([]storage.DenomMetadata, error)) *MockIDenomMetadataAllCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: event.go
//
// Generated by this command:
//
// mockgen -source=event.go -destination=mock/event.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIEvent is a mock of IEvent interface.
type MockIEvent struct {
ctrl *gomock.Controller
recorder *MockIEventMockRecorder
}
// MockIEventMockRecorder is the mock recorder for MockIEvent.
type MockIEventMockRecorder struct {
mock *MockIEvent
}
// NewMockIEvent creates a new mock instance.
func NewMockIEvent(ctrl *gomock.Controller) *MockIEvent {
mock := &MockIEvent{ctrl: ctrl}
mock.recorder = &MockIEventMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIEvent) EXPECT() *MockIEventMockRecorder {
return m.recorder
}
// ByBlock mocks base method.
func (m *MockIEvent) ByBlock(ctx context.Context, height types.Level, fltrs storage.EventFilter) ([]storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByBlock", ctx, height, fltrs)
ret0, _ := ret[0].([]storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByBlock indicates an expected call of ByBlock.
func (mr *MockIEventMockRecorder) ByBlock(ctx, height, fltrs any) *MockIEventByBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByBlock", reflect.TypeOf((*MockIEvent)(nil).ByBlock), ctx, height, fltrs)
return &MockIEventByBlockCall{Call: call}
}
// MockIEventByBlockCall wrap *gomock.Call
type MockIEventByBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventByBlockCall) Return(arg0 []storage.Event, arg1 error) *MockIEventByBlockCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventByBlockCall) Do(f func(context.Context, types.Level, storage.EventFilter) ([]storage.Event, error)) *MockIEventByBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventByBlockCall) DoAndReturn(f func(context.Context, types.Level, storage.EventFilter) ([]storage.Event, error)) *MockIEventByBlockCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByTxId mocks base method.
func (m *MockIEvent) ByTxId(ctx context.Context, txId uint64, fltrs storage.EventFilter) ([]storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByTxId", ctx, txId, fltrs)
ret0, _ := ret[0].([]storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByTxId indicates an expected call of ByTxId.
func (mr *MockIEventMockRecorder) ByTxId(ctx, txId, fltrs any) *MockIEventByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByTxId", reflect.TypeOf((*MockIEvent)(nil).ByTxId), ctx, txId, fltrs)
return &MockIEventByTxIdCall{Call: call}
}
// MockIEventByTxIdCall wrap *gomock.Call
type MockIEventByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventByTxIdCall) Return(arg0 []storage.Event, arg1 error) *MockIEventByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventByTxIdCall) Do(f func(context.Context, uint64, storage.EventFilter) ([]storage.Event, error)) *MockIEventByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventByTxIdCall) DoAndReturn(f func(context.Context, uint64, storage.EventFilter) ([]storage.Event, error)) *MockIEventByTxIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIEvent) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIEventMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIEventCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIEvent)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIEventCursorListCall{Call: call}
}
// MockIEventCursorListCall wrap *gomock.Call
type MockIEventCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventCursorListCall) Return(arg0 []*storage.Event, arg1 error) *MockIEventCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Event, error)) *MockIEventCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Event, error)) *MockIEventCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIEvent) GetByID(ctx context.Context, id uint64) (*storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIEventMockRecorder) GetByID(ctx, id any) *MockIEventGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIEvent)(nil).GetByID), ctx, id)
return &MockIEventGetByIDCall{Call: call}
}
// MockIEventGetByIDCall wrap *gomock.Call
type MockIEventGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventGetByIDCall) Return(arg0 *storage.Event, arg1 error) *MockIEventGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventGetByIDCall) Do(f func(context.Context, uint64) (*storage.Event, error)) *MockIEventGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Event, error)) *MockIEventGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIEvent) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIEventMockRecorder) IsNoRows(err any) *MockIEventIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIEvent)(nil).IsNoRows), err)
return &MockIEventIsNoRowsCall{Call: call}
}
// MockIEventIsNoRowsCall wrap *gomock.Call
type MockIEventIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventIsNoRowsCall) Return(arg0 bool) *MockIEventIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventIsNoRowsCall) Do(f func(error) bool) *MockIEventIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIEventIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIEvent) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIEventMockRecorder) LastID(ctx any) *MockIEventLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIEvent)(nil).LastID), ctx)
return &MockIEventLastIDCall{Call: call}
}
// MockIEventLastIDCall wrap *gomock.Call
type MockIEventLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventLastIDCall) Return(arg0 uint64, arg1 error) *MockIEventLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIEventLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIEventLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIEvent) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIEventMockRecorder) List(ctx, limit, offset, order any) *MockIEventListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIEvent)(nil).List), ctx, limit, offset, order)
return &MockIEventListCall{Call: call}
}
// MockIEventListCall wrap *gomock.Call
type MockIEventListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventListCall) Return(arg0 []*storage.Event, arg1 error) *MockIEventListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Event, error)) *MockIEventListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Event, error)) *MockIEventListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIEvent) Save(ctx context.Context, m *storage.Event) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIEventMockRecorder) Save(ctx, m any) *MockIEventSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIEvent)(nil).Save), ctx, m)
return &MockIEventSaveCall{Call: call}
}
// MockIEventSaveCall wrap *gomock.Call
type MockIEventSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventSaveCall) Return(arg0 error) *MockIEventSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventSaveCall) Do(f func(context.Context, *storage.Event) error) *MockIEventSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventSaveCall) DoAndReturn(f func(context.Context, *storage.Event) error) *MockIEventSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIEvent) Update(ctx context.Context, m *storage.Event) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIEventMockRecorder) Update(ctx, m any) *MockIEventUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIEvent)(nil).Update), ctx, m)
return &MockIEventUpdateCall{Call: call}
}
// MockIEventUpdateCall wrap *gomock.Call
type MockIEventUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIEventUpdateCall) Return(arg0 error) *MockIEventUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIEventUpdateCall) Do(f func(context.Context, *storage.Event) error) *MockIEventUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIEventUpdateCall) DoAndReturn(f func(context.Context, *storage.Event) error) *MockIEventUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: generic.go
//
// Generated by this command:
//
// mockgen -source=generic.go -destination=mock/generic.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
io "io"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
pq "github.com/lib/pq"
decimal "github.com/shopspring/decimal"
bun "github.com/uptrace/bun"
gomock "go.uber.org/mock/gomock"
)
// MockNotificator is a mock of Notificator interface.
type MockNotificator struct {
ctrl *gomock.Controller
recorder *MockNotificatorMockRecorder
}
// MockNotificatorMockRecorder is the mock recorder for MockNotificator.
type MockNotificatorMockRecorder struct {
mock *MockNotificator
}
// NewMockNotificator creates a new mock instance.
func NewMockNotificator(ctrl *gomock.Controller) *MockNotificator {
mock := &MockNotificator{ctrl: ctrl}
mock.recorder = &MockNotificatorMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockNotificator) EXPECT() *MockNotificatorMockRecorder {
return m.recorder
}
// Notify mocks base method.
func (m *MockNotificator) Notify(ctx context.Context, channel, payload string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Notify", ctx, channel, payload)
ret0, _ := ret[0].(error)
return ret0
}
// Notify indicates an expected call of Notify.
func (mr *MockNotificatorMockRecorder) Notify(ctx, channel, payload any) *MockNotificatorNotifyCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Notify", reflect.TypeOf((*MockNotificator)(nil).Notify), ctx, channel, payload)
return &MockNotificatorNotifyCall{Call: call}
}
// MockNotificatorNotifyCall wrap *gomock.Call
type MockNotificatorNotifyCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockNotificatorNotifyCall) Return(arg0 error) *MockNotificatorNotifyCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockNotificatorNotifyCall) Do(f func(context.Context, string, string) error) *MockNotificatorNotifyCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockNotificatorNotifyCall) DoAndReturn(f func(context.Context, string, string) error) *MockNotificatorNotifyCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockListener is a mock of Listener interface.
type MockListener struct {
ctrl *gomock.Controller
recorder *MockListenerMockRecorder
}
// MockListenerMockRecorder is the mock recorder for MockListener.
type MockListenerMockRecorder struct {
mock *MockListener
}
// NewMockListener creates a new mock instance.
func NewMockListener(ctrl *gomock.Controller) *MockListener {
mock := &MockListener{ctrl: ctrl}
mock.recorder = &MockListenerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockListener) EXPECT() *MockListenerMockRecorder {
return m.recorder
}
// Close mocks base method.
func (m *MockListener) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *MockListenerMockRecorder) Close() *MockListenerCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockListener)(nil).Close))
return &MockListenerCloseCall{Call: call}
}
// MockListenerCloseCall wrap *gomock.Call
type MockListenerCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockListenerCloseCall) Return(arg0 error) *MockListenerCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockListenerCloseCall) Do(f func() error) *MockListenerCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockListenerCloseCall) DoAndReturn(f func() error) *MockListenerCloseCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Listen mocks base method.
func (m *MockListener) Listen() chan *pq.Notification {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Listen")
ret0, _ := ret[0].(chan *pq.Notification)
return ret0
}
// Listen indicates an expected call of Listen.
func (mr *MockListenerMockRecorder) Listen() *MockListenerListenCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Listen", reflect.TypeOf((*MockListener)(nil).Listen))
return &MockListenerListenCall{Call: call}
}
// MockListenerListenCall wrap *gomock.Call
type MockListenerListenCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockListenerListenCall) Return(arg0 chan *pq.Notification) *MockListenerListenCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockListenerListenCall) Do(f func() chan *pq.Notification) *MockListenerListenCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockListenerListenCall) DoAndReturn(f func() chan *pq.Notification) *MockListenerListenCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Subscribe mocks base method.
func (m *MockListener) Subscribe(ctx context.Context, channels ...string) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range channels {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Subscribe", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Subscribe indicates an expected call of Subscribe.
func (mr *MockListenerMockRecorder) Subscribe(ctx any, channels ...any) *MockListenerSubscribeCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, channels...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Subscribe", reflect.TypeOf((*MockListener)(nil).Subscribe), varargs...)
return &MockListenerSubscribeCall{Call: call}
}
// MockListenerSubscribeCall wrap *gomock.Call
type MockListenerSubscribeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockListenerSubscribeCall) Return(arg0 error) *MockListenerSubscribeCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockListenerSubscribeCall) Do(f func(context.Context, ...string) error) *MockListenerSubscribeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockListenerSubscribeCall) DoAndReturn(f func(context.Context, ...string) error) *MockListenerSubscribeCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockListenerFactory is a mock of ListenerFactory interface.
type MockListenerFactory struct {
ctrl *gomock.Controller
recorder *MockListenerFactoryMockRecorder
}
// MockListenerFactoryMockRecorder is the mock recorder for MockListenerFactory.
type MockListenerFactoryMockRecorder struct {
mock *MockListenerFactory
}
// NewMockListenerFactory creates a new mock instance.
func NewMockListenerFactory(ctrl *gomock.Controller) *MockListenerFactory {
mock := &MockListenerFactory{ctrl: ctrl}
mock.recorder = &MockListenerFactoryMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockListenerFactory) EXPECT() *MockListenerFactoryMockRecorder {
return m.recorder
}
// CreateListener mocks base method.
func (m *MockListenerFactory) CreateListener() storage.Listener {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateListener")
ret0, _ := ret[0].(storage.Listener)
return ret0
}
// CreateListener indicates an expected call of CreateListener.
func (mr *MockListenerFactoryMockRecorder) CreateListener() *MockListenerFactoryCreateListenerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateListener", reflect.TypeOf((*MockListenerFactory)(nil).CreateListener))
return &MockListenerFactoryCreateListenerCall{Call: call}
}
// MockListenerFactoryCreateListenerCall wrap *gomock.Call
type MockListenerFactoryCreateListenerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockListenerFactoryCreateListenerCall) Return(arg0 storage.Listener) *MockListenerFactoryCreateListenerCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockListenerFactoryCreateListenerCall) Do(f func() storage.Listener) *MockListenerFactoryCreateListenerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockListenerFactoryCreateListenerCall) DoAndReturn(f func() storage.Listener) *MockListenerFactoryCreateListenerCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockTransaction is a mock of Transaction interface.
type MockTransaction struct {
ctrl *gomock.Controller
recorder *MockTransactionMockRecorder
}
// MockTransactionMockRecorder is the mock recorder for MockTransaction.
type MockTransactionMockRecorder struct {
mock *MockTransaction
}
// NewMockTransaction creates a new mock instance.
func NewMockTransaction(ctrl *gomock.Controller) *MockTransaction {
mock := &MockTransaction{ctrl: ctrl}
mock.recorder = &MockTransactionMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockTransaction) EXPECT() *MockTransactionMockRecorder {
return m.recorder
}
// Add mocks base method.
func (m *MockTransaction) Add(ctx context.Context, model any) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Add", ctx, model)
ret0, _ := ret[0].(error)
return ret0
}
// Add indicates an expected call of Add.
func (mr *MockTransactionMockRecorder) Add(ctx, model any) *MockTransactionAddCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockTransaction)(nil).Add), ctx, model)
return &MockTransactionAddCall{Call: call}
}
// MockTransactionAddCall wrap *gomock.Call
type MockTransactionAddCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionAddCall) Return(arg0 error) *MockTransactionAddCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionAddCall) Do(f func(context.Context, any) error) *MockTransactionAddCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionAddCall) DoAndReturn(f func(context.Context, any) error) *MockTransactionAddCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BulkSave mocks base method.
func (m *MockTransaction) BulkSave(ctx context.Context, models []any) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BulkSave", ctx, models)
ret0, _ := ret[0].(error)
return ret0
}
// BulkSave indicates an expected call of BulkSave.
func (mr *MockTransactionMockRecorder) BulkSave(ctx, models any) *MockTransactionBulkSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BulkSave", reflect.TypeOf((*MockTransaction)(nil).BulkSave), ctx, models)
return &MockTransactionBulkSaveCall{Call: call}
}
// MockTransactionBulkSaveCall wrap *gomock.Call
type MockTransactionBulkSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionBulkSaveCall) Return(arg0 error) *MockTransactionBulkSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionBulkSaveCall) Do(f func(context.Context, []any) error) *MockTransactionBulkSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionBulkSaveCall) DoAndReturn(f func(context.Context, []any) error) *MockTransactionBulkSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CancelUnbondings mocks base method.
func (m *MockTransaction) CancelUnbondings(ctx context.Context, cancellations ...storage.Undelegation) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range cancellations {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "CancelUnbondings", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// CancelUnbondings indicates an expected call of CancelUnbondings.
func (mr *MockTransactionMockRecorder) CancelUnbondings(ctx any, cancellations ...any) *MockTransactionCancelUnbondingsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, cancellations...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CancelUnbondings", reflect.TypeOf((*MockTransaction)(nil).CancelUnbondings), varargs...)
return &MockTransactionCancelUnbondingsCall{Call: call}
}
// MockTransactionCancelUnbondingsCall wrap *gomock.Call
type MockTransactionCancelUnbondingsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionCancelUnbondingsCall) Return(arg0 error) *MockTransactionCancelUnbondingsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionCancelUnbondingsCall) Do(f func(context.Context, ...storage.Undelegation) error) *MockTransactionCancelUnbondingsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionCancelUnbondingsCall) DoAndReturn(f func(context.Context, ...storage.Undelegation) error) *MockTransactionCancelUnbondingsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Close mocks base method.
func (m *MockTransaction) Close(ctx context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close", ctx)
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *MockTransactionMockRecorder) Close(ctx any) *MockTransactionCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockTransaction)(nil).Close), ctx)
return &MockTransactionCloseCall{Call: call}
}
// MockTransactionCloseCall wrap *gomock.Call
type MockTransactionCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionCloseCall) Return(arg0 error) *MockTransactionCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionCloseCall) Do(f func(context.Context) error) *MockTransactionCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionCloseCall) DoAndReturn(f func(context.Context) error) *MockTransactionCloseCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CopyFrom mocks base method.
func (m *MockTransaction) CopyFrom(ctx context.Context, tableName string, data []storage0.Copiable) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CopyFrom", ctx, tableName, data)
ret0, _ := ret[0].(error)
return ret0
}
// CopyFrom indicates an expected call of CopyFrom.
func (mr *MockTransactionMockRecorder) CopyFrom(ctx, tableName, data any) *MockTransactionCopyFromCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CopyFrom", reflect.TypeOf((*MockTransaction)(nil).CopyFrom), ctx, tableName, data)
return &MockTransactionCopyFromCall{Call: call}
}
// MockTransactionCopyFromCall wrap *gomock.Call
type MockTransactionCopyFromCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionCopyFromCall) Return(arg0 error) *MockTransactionCopyFromCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionCopyFromCall) Do(f func(context.Context, string, []storage0.Copiable) error) *MockTransactionCopyFromCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionCopyFromCall) DoAndReturn(f func(context.Context, string, []storage0.Copiable) error) *MockTransactionCopyFromCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Delegation mocks base method.
func (m *MockTransaction) Delegation(ctx context.Context, validatorId, addressId uint64) (storage.Delegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Delegation", ctx, validatorId, addressId)
ret0, _ := ret[0].(storage.Delegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Delegation indicates an expected call of Delegation.
func (mr *MockTransactionMockRecorder) Delegation(ctx, validatorId, addressId any) *MockTransactionDelegationCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delegation", reflect.TypeOf((*MockTransaction)(nil).Delegation), ctx, validatorId, addressId)
return &MockTransactionDelegationCall{Call: call}
}
// MockTransactionDelegationCall wrap *gomock.Call
type MockTransactionDelegationCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionDelegationCall) Return(val storage.Delegation, err error) *MockTransactionDelegationCall {
c.Call = c.Call.Return(val, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionDelegationCall) Do(f func(context.Context, uint64, uint64) (storage.Delegation, error)) *MockTransactionDelegationCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionDelegationCall) DoAndReturn(f func(context.Context, uint64, uint64) (storage.Delegation, error)) *MockTransactionDelegationCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// DeleteBalances mocks base method.
func (m *MockTransaction) DeleteBalances(ctx context.Context, ids []uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteBalances", ctx, ids)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteBalances indicates an expected call of DeleteBalances.
func (mr *MockTransactionMockRecorder) DeleteBalances(ctx, ids any) *MockTransactionDeleteBalancesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBalances", reflect.TypeOf((*MockTransaction)(nil).DeleteBalances), ctx, ids)
return &MockTransactionDeleteBalancesCall{Call: call}
}
// MockTransactionDeleteBalancesCall wrap *gomock.Call
type MockTransactionDeleteBalancesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionDeleteBalancesCall) Return(arg0 error) *MockTransactionDeleteBalancesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionDeleteBalancesCall) Do(f func(context.Context, []uint64) error) *MockTransactionDeleteBalancesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionDeleteBalancesCall) DoAndReturn(f func(context.Context, []uint64) error) *MockTransactionDeleteBalancesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// DeleteDelegationsByValidator mocks base method.
func (m *MockTransaction) DeleteDelegationsByValidator(ctx context.Context, ids ...uint64) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range ids {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "DeleteDelegationsByValidator", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteDelegationsByValidator indicates an expected call of DeleteDelegationsByValidator.
func (mr *MockTransactionMockRecorder) DeleteDelegationsByValidator(ctx any, ids ...any) *MockTransactionDeleteDelegationsByValidatorCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, ids...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteDelegationsByValidator", reflect.TypeOf((*MockTransaction)(nil).DeleteDelegationsByValidator), varargs...)
return &MockTransactionDeleteDelegationsByValidatorCall{Call: call}
}
// MockTransactionDeleteDelegationsByValidatorCall wrap *gomock.Call
type MockTransactionDeleteDelegationsByValidatorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionDeleteDelegationsByValidatorCall) Return(arg0 error) *MockTransactionDeleteDelegationsByValidatorCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionDeleteDelegationsByValidatorCall) Do(f func(context.Context, ...uint64) error) *MockTransactionDeleteDelegationsByValidatorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionDeleteDelegationsByValidatorCall) DoAndReturn(f func(context.Context, ...uint64) error) *MockTransactionDeleteDelegationsByValidatorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// DeleteProviders mocks base method.
func (m *MockTransaction) DeleteProviders(ctx context.Context, rollupId uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteProviders", ctx, rollupId)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteProviders indicates an expected call of DeleteProviders.
func (mr *MockTransactionMockRecorder) DeleteProviders(ctx, rollupId any) *MockTransactionDeleteProvidersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProviders", reflect.TypeOf((*MockTransaction)(nil).DeleteProviders), ctx, rollupId)
return &MockTransactionDeleteProvidersCall{Call: call}
}
// MockTransactionDeleteProvidersCall wrap *gomock.Call
type MockTransactionDeleteProvidersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionDeleteProvidersCall) Return(arg0 error) *MockTransactionDeleteProvidersCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionDeleteProvidersCall) Do(f func(context.Context, uint64) error) *MockTransactionDeleteProvidersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionDeleteProvidersCall) DoAndReturn(f func(context.Context, uint64) error) *MockTransactionDeleteProvidersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// DeleteRollup mocks base method.
func (m *MockTransaction) DeleteRollup(ctx context.Context, rollupId uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteRollup", ctx, rollupId)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteRollup indicates an expected call of DeleteRollup.
func (mr *MockTransactionMockRecorder) DeleteRollup(ctx, rollupId any) *MockTransactionDeleteRollupCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRollup", reflect.TypeOf((*MockTransaction)(nil).DeleteRollup), ctx, rollupId)
return &MockTransactionDeleteRollupCall{Call: call}
}
// MockTransactionDeleteRollupCall wrap *gomock.Call
type MockTransactionDeleteRollupCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionDeleteRollupCall) Return(arg0 error) *MockTransactionDeleteRollupCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionDeleteRollupCall) Do(f func(context.Context, uint64) error) *MockTransactionDeleteRollupCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionDeleteRollupCall) DoAndReturn(f func(context.Context, uint64) error) *MockTransactionDeleteRollupCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Exec mocks base method.
func (m *MockTransaction) Exec(ctx context.Context, query string, params ...any) (int64, error) {
m.ctrl.T.Helper()
varargs := []any{ctx, query}
for _, a := range params {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Exec", varargs...)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Exec indicates an expected call of Exec.
func (mr *MockTransactionMockRecorder) Exec(ctx, query any, params ...any) *MockTransactionExecCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, query}, params...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exec", reflect.TypeOf((*MockTransaction)(nil).Exec), varargs...)
return &MockTransactionExecCall{Call: call}
}
// MockTransactionExecCall wrap *gomock.Call
type MockTransactionExecCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionExecCall) Return(arg0 int64, arg1 error) *MockTransactionExecCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionExecCall) Do(f func(context.Context, string, ...any) (int64, error)) *MockTransactionExecCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionExecCall) DoAndReturn(f func(context.Context, string, ...any) (int64, error)) *MockTransactionExecCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Flush mocks base method.
func (m *MockTransaction) Flush(ctx context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Flush", ctx)
ret0, _ := ret[0].(error)
return ret0
}
// Flush indicates an expected call of Flush.
func (mr *MockTransactionMockRecorder) Flush(ctx any) *MockTransactionFlushCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Flush", reflect.TypeOf((*MockTransaction)(nil).Flush), ctx)
return &MockTransactionFlushCall{Call: call}
}
// MockTransactionFlushCall wrap *gomock.Call
type MockTransactionFlushCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionFlushCall) Return(arg0 error) *MockTransactionFlushCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionFlushCall) Do(f func(context.Context) error) *MockTransactionFlushCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionFlushCall) DoAndReturn(f func(context.Context) error) *MockTransactionFlushCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetProposerId mocks base method.
func (m *MockTransaction) GetProposerId(ctx context.Context, address string) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetProposerId", ctx, address)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetProposerId indicates an expected call of GetProposerId.
func (mr *MockTransactionMockRecorder) GetProposerId(ctx, address any) *MockTransactionGetProposerIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProposerId", reflect.TypeOf((*MockTransaction)(nil).GetProposerId), ctx, address)
return &MockTransactionGetProposerIdCall{Call: call}
}
// MockTransactionGetProposerIdCall wrap *gomock.Call
type MockTransactionGetProposerIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionGetProposerIdCall) Return(arg0 uint64, arg1 error) *MockTransactionGetProposerIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionGetProposerIdCall) Do(f func(context.Context, string) (uint64, error)) *MockTransactionGetProposerIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionGetProposerIdCall) DoAndReturn(f func(context.Context, string) (uint64, error)) *MockTransactionGetProposerIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// HandleError mocks base method.
func (m *MockTransaction) HandleError(ctx context.Context, err error) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HandleError", ctx, err)
ret0, _ := ret[0].(error)
return ret0
}
// HandleError indicates an expected call of HandleError.
func (mr *MockTransactionMockRecorder) HandleError(ctx, err any) *MockTransactionHandleErrorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleError", reflect.TypeOf((*MockTransaction)(nil).HandleError), ctx, err)
return &MockTransactionHandleErrorCall{Call: call}
}
// MockTransactionHandleErrorCall wrap *gomock.Call
type MockTransactionHandleErrorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionHandleErrorCall) Return(arg0 error) *MockTransactionHandleErrorCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionHandleErrorCall) Do(f func(context.Context, error) error) *MockTransactionHandleErrorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionHandleErrorCall) DoAndReturn(f func(context.Context, error) error) *MockTransactionHandleErrorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Jail mocks base method.
func (m *MockTransaction) Jail(ctx context.Context, validators ...*storage.Validator) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range validators {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Jail", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Jail indicates an expected call of Jail.
func (mr *MockTransactionMockRecorder) Jail(ctx any, validators ...any) *MockTransactionJailCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, validators...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Jail", reflect.TypeOf((*MockTransaction)(nil).Jail), varargs...)
return &MockTransactionJailCall{Call: call}
}
// MockTransactionJailCall wrap *gomock.Call
type MockTransactionJailCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionJailCall) Return(arg0 error) *MockTransactionJailCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionJailCall) Do(f func(context.Context, ...*storage.Validator) error) *MockTransactionJailCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionJailCall) DoAndReturn(f func(context.Context, ...*storage.Validator) error) *MockTransactionJailCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastAddressAction mocks base method.
func (m *MockTransaction) LastAddressAction(ctx context.Context, address []byte) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastAddressAction", ctx, address)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastAddressAction indicates an expected call of LastAddressAction.
func (mr *MockTransactionMockRecorder) LastAddressAction(ctx, address any) *MockTransactionLastAddressActionCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAddressAction", reflect.TypeOf((*MockTransaction)(nil).LastAddressAction), ctx, address)
return &MockTransactionLastAddressActionCall{Call: call}
}
// MockTransactionLastAddressActionCall wrap *gomock.Call
type MockTransactionLastAddressActionCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionLastAddressActionCall) Return(arg0 uint64, arg1 error) *MockTransactionLastAddressActionCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionLastAddressActionCall) Do(f func(context.Context, []byte) (uint64, error)) *MockTransactionLastAddressActionCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionLastAddressActionCall) DoAndReturn(f func(context.Context, []byte) (uint64, error)) *MockTransactionLastAddressActionCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastBlock mocks base method.
func (m *MockTransaction) LastBlock(ctx context.Context) (storage.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastBlock", ctx)
ret0, _ := ret[0].(storage.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastBlock indicates an expected call of LastBlock.
func (mr *MockTransactionMockRecorder) LastBlock(ctx any) *MockTransactionLastBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastBlock", reflect.TypeOf((*MockTransaction)(nil).LastBlock), ctx)
return &MockTransactionLastBlockCall{Call: call}
}
// MockTransactionLastBlockCall wrap *gomock.Call
type MockTransactionLastBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionLastBlockCall) Return(block storage.Block, err error) *MockTransactionLastBlockCall {
c.Call = c.Call.Return(block, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionLastBlockCall) Do(f func(context.Context) (storage.Block, error)) *MockTransactionLastBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionLastBlockCall) DoAndReturn(f func(context.Context) (storage.Block, error)) *MockTransactionLastBlockCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastNamespaceMessage mocks base method.
func (m *MockTransaction) LastNamespaceMessage(ctx context.Context, nsId uint64) (storage.NamespaceMessage, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastNamespaceMessage", ctx, nsId)
ret0, _ := ret[0].(storage.NamespaceMessage)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastNamespaceMessage indicates an expected call of LastNamespaceMessage.
func (mr *MockTransactionMockRecorder) LastNamespaceMessage(ctx, nsId any) *MockTransactionLastNamespaceMessageCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastNamespaceMessage", reflect.TypeOf((*MockTransaction)(nil).LastNamespaceMessage), ctx, nsId)
return &MockTransactionLastNamespaceMessageCall{Call: call}
}
// MockTransactionLastNamespaceMessageCall wrap *gomock.Call
type MockTransactionLastNamespaceMessageCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionLastNamespaceMessageCall) Return(msg storage.NamespaceMessage, err error) *MockTransactionLastNamespaceMessageCall {
c.Call = c.Call.Return(msg, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionLastNamespaceMessageCall) Do(f func(context.Context, uint64) (storage.NamespaceMessage, error)) *MockTransactionLastNamespaceMessageCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionLastNamespaceMessageCall) DoAndReturn(f func(context.Context, uint64) (storage.NamespaceMessage, error)) *MockTransactionLastNamespaceMessageCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Namespace mocks base method.
func (m *MockTransaction) Namespace(ctx context.Context, id uint64) (storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Namespace", ctx, id)
ret0, _ := ret[0].(storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Namespace indicates an expected call of Namespace.
func (mr *MockTransactionMockRecorder) Namespace(ctx, id any) *MockTransactionNamespaceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Namespace", reflect.TypeOf((*MockTransaction)(nil).Namespace), ctx, id)
return &MockTransactionNamespaceCall{Call: call}
}
// MockTransactionNamespaceCall wrap *gomock.Call
type MockTransactionNamespaceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionNamespaceCall) Return(ns storage.Namespace, err error) *MockTransactionNamespaceCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionNamespaceCall) Do(f func(context.Context, uint64) (storage.Namespace, error)) *MockTransactionNamespaceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionNamespaceCall) DoAndReturn(f func(context.Context, uint64) (storage.Namespace, error)) *MockTransactionNamespaceCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RefreshLeaderboard mocks base method.
func (m *MockTransaction) RefreshLeaderboard(ctx context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RefreshLeaderboard", ctx)
ret0, _ := ret[0].(error)
return ret0
}
// RefreshLeaderboard indicates an expected call of RefreshLeaderboard.
func (mr *MockTransactionMockRecorder) RefreshLeaderboard(ctx any) *MockTransactionRefreshLeaderboardCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshLeaderboard", reflect.TypeOf((*MockTransaction)(nil).RefreshLeaderboard), ctx)
return &MockTransactionRefreshLeaderboardCall{Call: call}
}
// MockTransactionRefreshLeaderboardCall wrap *gomock.Call
type MockTransactionRefreshLeaderboardCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRefreshLeaderboardCall) Return(arg0 error) *MockTransactionRefreshLeaderboardCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRefreshLeaderboardCall) Do(f func(context.Context) error) *MockTransactionRefreshLeaderboardCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRefreshLeaderboardCall) DoAndReturn(f func(context.Context) error) *MockTransactionRefreshLeaderboardCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RetentionBlockSignatures mocks base method.
func (m *MockTransaction) RetentionBlockSignatures(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RetentionBlockSignatures", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RetentionBlockSignatures indicates an expected call of RetentionBlockSignatures.
func (mr *MockTransactionMockRecorder) RetentionBlockSignatures(ctx, height any) *MockTransactionRetentionBlockSignaturesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetentionBlockSignatures", reflect.TypeOf((*MockTransaction)(nil).RetentionBlockSignatures), ctx, height)
return &MockTransactionRetentionBlockSignaturesCall{Call: call}
}
// MockTransactionRetentionBlockSignaturesCall wrap *gomock.Call
type MockTransactionRetentionBlockSignaturesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRetentionBlockSignaturesCall) Return(arg0 error) *MockTransactionRetentionBlockSignaturesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRetentionBlockSignaturesCall) Do(f func(context.Context, types.Level) error) *MockTransactionRetentionBlockSignaturesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRetentionBlockSignaturesCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRetentionBlockSignaturesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RetentionCompletedRedelegations mocks base method.
func (m *MockTransaction) RetentionCompletedRedelegations(ctx context.Context, blockTime time.Time) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RetentionCompletedRedelegations", ctx, blockTime)
ret0, _ := ret[0].(error)
return ret0
}
// RetentionCompletedRedelegations indicates an expected call of RetentionCompletedRedelegations.
func (mr *MockTransactionMockRecorder) RetentionCompletedRedelegations(ctx, blockTime any) *MockTransactionRetentionCompletedRedelegationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetentionCompletedRedelegations", reflect.TypeOf((*MockTransaction)(nil).RetentionCompletedRedelegations), ctx, blockTime)
return &MockTransactionRetentionCompletedRedelegationsCall{Call: call}
}
// MockTransactionRetentionCompletedRedelegationsCall wrap *gomock.Call
type MockTransactionRetentionCompletedRedelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRetentionCompletedRedelegationsCall) Return(arg0 error) *MockTransactionRetentionCompletedRedelegationsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRetentionCompletedRedelegationsCall) Do(f func(context.Context, time.Time) error) *MockTransactionRetentionCompletedRedelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRetentionCompletedRedelegationsCall) DoAndReturn(f func(context.Context, time.Time) error) *MockTransactionRetentionCompletedRedelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RetentionCompletedUnbondings mocks base method.
func (m *MockTransaction) RetentionCompletedUnbondings(ctx context.Context, blockTime time.Time) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RetentionCompletedUnbondings", ctx, blockTime)
ret0, _ := ret[0].(error)
return ret0
}
// RetentionCompletedUnbondings indicates an expected call of RetentionCompletedUnbondings.
func (mr *MockTransactionMockRecorder) RetentionCompletedUnbondings(ctx, blockTime any) *MockTransactionRetentionCompletedUnbondingsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetentionCompletedUnbondings", reflect.TypeOf((*MockTransaction)(nil).RetentionCompletedUnbondings), ctx, blockTime)
return &MockTransactionRetentionCompletedUnbondingsCall{Call: call}
}
// MockTransactionRetentionCompletedUnbondingsCall wrap *gomock.Call
type MockTransactionRetentionCompletedUnbondingsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRetentionCompletedUnbondingsCall) Return(arg0 error) *MockTransactionRetentionCompletedUnbondingsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRetentionCompletedUnbondingsCall) Do(f func(context.Context, time.Time) error) *MockTransactionRetentionCompletedUnbondingsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRetentionCompletedUnbondingsCall) DoAndReturn(f func(context.Context, time.Time) error) *MockTransactionRetentionCompletedUnbondingsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Rollback mocks base method.
func (m *MockTransaction) Rollback(ctx context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Rollback", ctx)
ret0, _ := ret[0].(error)
return ret0
}
// Rollback indicates an expected call of Rollback.
func (mr *MockTransactionMockRecorder) Rollback(ctx any) *MockTransactionRollbackCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rollback", reflect.TypeOf((*MockTransaction)(nil).Rollback), ctx)
return &MockTransactionRollbackCall{Call: call}
}
// MockTransactionRollbackCall wrap *gomock.Call
type MockTransactionRollbackCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackCall) Return(arg0 error) *MockTransactionRollbackCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackCall) Do(f func(context.Context) error) *MockTransactionRollbackCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackCall) DoAndReturn(f func(context.Context) error) *MockTransactionRollbackCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackAddresses mocks base method.
func (m *MockTransaction) RollbackAddresses(ctx context.Context, height types.Level) ([]storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackAddresses", ctx, height)
ret0, _ := ret[0].([]storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackAddresses indicates an expected call of RollbackAddresses.
func (mr *MockTransactionMockRecorder) RollbackAddresses(ctx, height any) *MockTransactionRollbackAddressesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackAddresses", reflect.TypeOf((*MockTransaction)(nil).RollbackAddresses), ctx, height)
return &MockTransactionRollbackAddressesCall{Call: call}
}
// MockTransactionRollbackAddressesCall wrap *gomock.Call
type MockTransactionRollbackAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackAddressesCall) Return(address []storage.Address, err error) *MockTransactionRollbackAddressesCall {
c.Call = c.Call.Return(address, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackAddressesCall) Do(f func(context.Context, types.Level) ([]storage.Address, error)) *MockTransactionRollbackAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackAddressesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Address, error)) *MockTransactionRollbackAddressesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackBlobLog mocks base method.
func (m *MockTransaction) RollbackBlobLog(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackBlobLog", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackBlobLog indicates an expected call of RollbackBlobLog.
func (mr *MockTransactionMockRecorder) RollbackBlobLog(ctx, height any) *MockTransactionRollbackBlobLogCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlobLog", reflect.TypeOf((*MockTransaction)(nil).RollbackBlobLog), ctx, height)
return &MockTransactionRollbackBlobLogCall{Call: call}
}
// MockTransactionRollbackBlobLogCall wrap *gomock.Call
type MockTransactionRollbackBlobLogCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackBlobLogCall) Return(arg0 error) *MockTransactionRollbackBlobLogCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackBlobLogCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackBlobLogCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackBlobLogCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackBlobLogCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackBlock mocks base method.
func (m *MockTransaction) RollbackBlock(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackBlock", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackBlock indicates an expected call of RollbackBlock.
func (mr *MockTransactionMockRecorder) RollbackBlock(ctx, height any) *MockTransactionRollbackBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlock", reflect.TypeOf((*MockTransaction)(nil).RollbackBlock), ctx, height)
return &MockTransactionRollbackBlockCall{Call: call}
}
// MockTransactionRollbackBlockCall wrap *gomock.Call
type MockTransactionRollbackBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackBlockCall) Return(arg0 error) *MockTransactionRollbackBlockCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackBlockCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackBlockCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackBlockCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackBlockSignatures mocks base method.
func (m *MockTransaction) RollbackBlockSignatures(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackBlockSignatures", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackBlockSignatures indicates an expected call of RollbackBlockSignatures.
func (mr *MockTransactionMockRecorder) RollbackBlockSignatures(ctx, height any) *MockTransactionRollbackBlockSignaturesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlockSignatures", reflect.TypeOf((*MockTransaction)(nil).RollbackBlockSignatures), ctx, height)
return &MockTransactionRollbackBlockSignaturesCall{Call: call}
}
// MockTransactionRollbackBlockSignaturesCall wrap *gomock.Call
type MockTransactionRollbackBlockSignaturesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackBlockSignaturesCall) Return(err error) *MockTransactionRollbackBlockSignaturesCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackBlockSignaturesCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackBlockSignaturesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackBlockSignaturesCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackBlockSignaturesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackBlockStats mocks base method.
func (m *MockTransaction) RollbackBlockStats(ctx context.Context, height types.Level) (storage.BlockStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackBlockStats", ctx, height)
ret0, _ := ret[0].(storage.BlockStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackBlockStats indicates an expected call of RollbackBlockStats.
func (mr *MockTransactionMockRecorder) RollbackBlockStats(ctx, height any) *MockTransactionRollbackBlockStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlockStats", reflect.TypeOf((*MockTransaction)(nil).RollbackBlockStats), ctx, height)
return &MockTransactionRollbackBlockStatsCall{Call: call}
}
// MockTransactionRollbackBlockStatsCall wrap *gomock.Call
type MockTransactionRollbackBlockStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackBlockStatsCall) Return(stats storage.BlockStats, err error) *MockTransactionRollbackBlockStatsCall {
c.Call = c.Call.Return(stats, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackBlockStatsCall) Do(f func(context.Context, types.Level) (storage.BlockStats, error)) *MockTransactionRollbackBlockStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackBlockStatsCall) DoAndReturn(f func(context.Context, types.Level) (storage.BlockStats, error)) *MockTransactionRollbackBlockStatsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackEvents mocks base method.
func (m *MockTransaction) RollbackEvents(ctx context.Context, height types.Level) ([]storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackEvents", ctx, height)
ret0, _ := ret[0].([]storage.Event)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackEvents indicates an expected call of RollbackEvents.
func (mr *MockTransactionMockRecorder) RollbackEvents(ctx, height any) *MockTransactionRollbackEventsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackEvents", reflect.TypeOf((*MockTransaction)(nil).RollbackEvents), ctx, height)
return &MockTransactionRollbackEventsCall{Call: call}
}
// MockTransactionRollbackEventsCall wrap *gomock.Call
type MockTransactionRollbackEventsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackEventsCall) Return(events []storage.Event, err error) *MockTransactionRollbackEventsCall {
c.Call = c.Call.Return(events, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackEventsCall) Do(f func(context.Context, types.Level) ([]storage.Event, error)) *MockTransactionRollbackEventsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackEventsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Event, error)) *MockTransactionRollbackEventsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackGrants mocks base method.
func (m *MockTransaction) RollbackGrants(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackGrants", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackGrants indicates an expected call of RollbackGrants.
func (mr *MockTransactionMockRecorder) RollbackGrants(ctx, height any) *MockTransactionRollbackGrantsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackGrants", reflect.TypeOf((*MockTransaction)(nil).RollbackGrants), ctx, height)
return &MockTransactionRollbackGrantsCall{Call: call}
}
// MockTransactionRollbackGrantsCall wrap *gomock.Call
type MockTransactionRollbackGrantsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackGrantsCall) Return(arg0 error) *MockTransactionRollbackGrantsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackGrantsCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackGrantsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackGrantsCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackGrantsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackJails mocks base method.
func (m *MockTransaction) RollbackJails(ctx context.Context, height types.Level) ([]storage.Jail, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackJails", ctx, height)
ret0, _ := ret[0].([]storage.Jail)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackJails indicates an expected call of RollbackJails.
func (mr *MockTransactionMockRecorder) RollbackJails(ctx, height any) *MockTransactionRollbackJailsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackJails", reflect.TypeOf((*MockTransaction)(nil).RollbackJails), ctx, height)
return &MockTransactionRollbackJailsCall{Call: call}
}
// MockTransactionRollbackJailsCall wrap *gomock.Call
type MockTransactionRollbackJailsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackJailsCall) Return(arg0 []storage.Jail, arg1 error) *MockTransactionRollbackJailsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackJailsCall) Do(f func(context.Context, types.Level) ([]storage.Jail, error)) *MockTransactionRollbackJailsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackJailsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Jail, error)) *MockTransactionRollbackJailsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackMessageAddresses mocks base method.
func (m *MockTransaction) RollbackMessageAddresses(ctx context.Context, msgIds []uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackMessageAddresses", ctx, msgIds)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackMessageAddresses indicates an expected call of RollbackMessageAddresses.
func (mr *MockTransactionMockRecorder) RollbackMessageAddresses(ctx, msgIds any) *MockTransactionRollbackMessageAddressesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackMessageAddresses", reflect.TypeOf((*MockTransaction)(nil).RollbackMessageAddresses), ctx, msgIds)
return &MockTransactionRollbackMessageAddressesCall{Call: call}
}
// MockTransactionRollbackMessageAddressesCall wrap *gomock.Call
type MockTransactionRollbackMessageAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackMessageAddressesCall) Return(err error) *MockTransactionRollbackMessageAddressesCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackMessageAddressesCall) Do(f func(context.Context, []uint64) error) *MockTransactionRollbackMessageAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackMessageAddressesCall) DoAndReturn(f func(context.Context, []uint64) error) *MockTransactionRollbackMessageAddressesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackMessages mocks base method.
func (m *MockTransaction) RollbackMessages(ctx context.Context, height types.Level) ([]storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackMessages", ctx, height)
ret0, _ := ret[0].([]storage.Message)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackMessages indicates an expected call of RollbackMessages.
func (mr *MockTransactionMockRecorder) RollbackMessages(ctx, height any) *MockTransactionRollbackMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackMessages", reflect.TypeOf((*MockTransaction)(nil).RollbackMessages), ctx, height)
return &MockTransactionRollbackMessagesCall{Call: call}
}
// MockTransactionRollbackMessagesCall wrap *gomock.Call
type MockTransactionRollbackMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackMessagesCall) Return(msgs []storage.Message, err error) *MockTransactionRollbackMessagesCall {
c.Call = c.Call.Return(msgs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackMessagesCall) Do(f func(context.Context, types.Level) ([]storage.Message, error)) *MockTransactionRollbackMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackMessagesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Message, error)) *MockTransactionRollbackMessagesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackNamespaceMessages mocks base method.
func (m *MockTransaction) RollbackNamespaceMessages(ctx context.Context, height types.Level) ([]storage.NamespaceMessage, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackNamespaceMessages", ctx, height)
ret0, _ := ret[0].([]storage.NamespaceMessage)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackNamespaceMessages indicates an expected call of RollbackNamespaceMessages.
func (mr *MockTransactionMockRecorder) RollbackNamespaceMessages(ctx, height any) *MockTransactionRollbackNamespaceMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackNamespaceMessages", reflect.TypeOf((*MockTransaction)(nil).RollbackNamespaceMessages), ctx, height)
return &MockTransactionRollbackNamespaceMessagesCall{Call: call}
}
// MockTransactionRollbackNamespaceMessagesCall wrap *gomock.Call
type MockTransactionRollbackNamespaceMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackNamespaceMessagesCall) Return(msgs []storage.NamespaceMessage, err error) *MockTransactionRollbackNamespaceMessagesCall {
c.Call = c.Call.Return(msgs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackNamespaceMessagesCall) Do(f func(context.Context, types.Level) ([]storage.NamespaceMessage, error)) *MockTransactionRollbackNamespaceMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackNamespaceMessagesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.NamespaceMessage, error)) *MockTransactionRollbackNamespaceMessagesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackNamespaces mocks base method.
func (m *MockTransaction) RollbackNamespaces(ctx context.Context, height types.Level) ([]storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackNamespaces", ctx, height)
ret0, _ := ret[0].([]storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackNamespaces indicates an expected call of RollbackNamespaces.
func (mr *MockTransactionMockRecorder) RollbackNamespaces(ctx, height any) *MockTransactionRollbackNamespacesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackNamespaces", reflect.TypeOf((*MockTransaction)(nil).RollbackNamespaces), ctx, height)
return &MockTransactionRollbackNamespacesCall{Call: call}
}
// MockTransactionRollbackNamespacesCall wrap *gomock.Call
type MockTransactionRollbackNamespacesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackNamespacesCall) Return(ns []storage.Namespace, err error) *MockTransactionRollbackNamespacesCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackNamespacesCall) Do(f func(context.Context, types.Level) ([]storage.Namespace, error)) *MockTransactionRollbackNamespacesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackNamespacesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Namespace, error)) *MockTransactionRollbackNamespacesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackRedelegations mocks base method.
func (m *MockTransaction) RollbackRedelegations(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackRedelegations", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackRedelegations indicates an expected call of RollbackRedelegations.
func (mr *MockTransactionMockRecorder) RollbackRedelegations(ctx, height any) *MockTransactionRollbackRedelegationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackRedelegations", reflect.TypeOf((*MockTransaction)(nil).RollbackRedelegations), ctx, height)
return &MockTransactionRollbackRedelegationsCall{Call: call}
}
// MockTransactionRollbackRedelegationsCall wrap *gomock.Call
type MockTransactionRollbackRedelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackRedelegationsCall) Return(err error) *MockTransactionRollbackRedelegationsCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackRedelegationsCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackRedelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackRedelegationsCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackRedelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackSigners mocks base method.
func (m *MockTransaction) RollbackSigners(ctx context.Context, txIds []uint64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackSigners", ctx, txIds)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackSigners indicates an expected call of RollbackSigners.
func (mr *MockTransactionMockRecorder) RollbackSigners(ctx, txIds any) *MockTransactionRollbackSignersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackSigners", reflect.TypeOf((*MockTransaction)(nil).RollbackSigners), ctx, txIds)
return &MockTransactionRollbackSignersCall{Call: call}
}
// MockTransactionRollbackSignersCall wrap *gomock.Call
type MockTransactionRollbackSignersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackSignersCall) Return(err error) *MockTransactionRollbackSignersCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackSignersCall) Do(f func(context.Context, []uint64) error) *MockTransactionRollbackSignersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackSignersCall) DoAndReturn(f func(context.Context, []uint64) error) *MockTransactionRollbackSignersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackStakingLogs mocks base method.
func (m *MockTransaction) RollbackStakingLogs(ctx context.Context, height types.Level) ([]storage.StakingLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackStakingLogs", ctx, height)
ret0, _ := ret[0].([]storage.StakingLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackStakingLogs indicates an expected call of RollbackStakingLogs.
func (mr *MockTransactionMockRecorder) RollbackStakingLogs(ctx, height any) *MockTransactionRollbackStakingLogsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackStakingLogs", reflect.TypeOf((*MockTransaction)(nil).RollbackStakingLogs), ctx, height)
return &MockTransactionRollbackStakingLogsCall{Call: call}
}
// MockTransactionRollbackStakingLogsCall wrap *gomock.Call
type MockTransactionRollbackStakingLogsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackStakingLogsCall) Return(arg0 []storage.StakingLog, arg1 error) *MockTransactionRollbackStakingLogsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackStakingLogsCall) Do(f func(context.Context, types.Level) ([]storage.StakingLog, error)) *MockTransactionRollbackStakingLogsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackStakingLogsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.StakingLog, error)) *MockTransactionRollbackStakingLogsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackTxs mocks base method.
func (m *MockTransaction) RollbackTxs(ctx context.Context, height types.Level) ([]storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackTxs", ctx, height)
ret0, _ := ret[0].([]storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackTxs indicates an expected call of RollbackTxs.
func (mr *MockTransactionMockRecorder) RollbackTxs(ctx, height any) *MockTransactionRollbackTxsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackTxs", reflect.TypeOf((*MockTransaction)(nil).RollbackTxs), ctx, height)
return &MockTransactionRollbackTxsCall{Call: call}
}
// MockTransactionRollbackTxsCall wrap *gomock.Call
type MockTransactionRollbackTxsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackTxsCall) Return(txs []storage.Tx, err error) *MockTransactionRollbackTxsCall {
c.Call = c.Call.Return(txs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackTxsCall) Do(f func(context.Context, types.Level) ([]storage.Tx, error)) *MockTransactionRollbackTxsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackTxsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Tx, error)) *MockTransactionRollbackTxsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackUndelegations mocks base method.
func (m *MockTransaction) RollbackUndelegations(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackUndelegations", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackUndelegations indicates an expected call of RollbackUndelegations.
func (mr *MockTransactionMockRecorder) RollbackUndelegations(ctx, height any) *MockTransactionRollbackUndelegationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackUndelegations", reflect.TypeOf((*MockTransaction)(nil).RollbackUndelegations), ctx, height)
return &MockTransactionRollbackUndelegationsCall{Call: call}
}
// MockTransactionRollbackUndelegationsCall wrap *gomock.Call
type MockTransactionRollbackUndelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackUndelegationsCall) Return(err error) *MockTransactionRollbackUndelegationsCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackUndelegationsCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackUndelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackUndelegationsCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackUndelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackValidators mocks base method.
func (m *MockTransaction) RollbackValidators(ctx context.Context, height types.Level) ([]storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackValidators", ctx, height)
ret0, _ := ret[0].([]storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackValidators indicates an expected call of RollbackValidators.
func (mr *MockTransactionMockRecorder) RollbackValidators(ctx, height any) *MockTransactionRollbackValidatorsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackValidators", reflect.TypeOf((*MockTransaction)(nil).RollbackValidators), ctx, height)
return &MockTransactionRollbackValidatorsCall{Call: call}
}
// MockTransactionRollbackValidatorsCall wrap *gomock.Call
type MockTransactionRollbackValidatorsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackValidatorsCall) Return(arg0 []storage.Validator, arg1 error) *MockTransactionRollbackValidatorsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackValidatorsCall) Do(f func(context.Context, types.Level) ([]storage.Validator, error)) *MockTransactionRollbackValidatorsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackValidatorsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Validator, error)) *MockTransactionRollbackValidatorsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackVestingAccounts mocks base method.
func (m *MockTransaction) RollbackVestingAccounts(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackVestingAccounts", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackVestingAccounts indicates an expected call of RollbackVestingAccounts.
func (mr *MockTransactionMockRecorder) RollbackVestingAccounts(ctx, height any) *MockTransactionRollbackVestingAccountsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackVestingAccounts", reflect.TypeOf((*MockTransaction)(nil).RollbackVestingAccounts), ctx, height)
return &MockTransactionRollbackVestingAccountsCall{Call: call}
}
// MockTransactionRollbackVestingAccountsCall wrap *gomock.Call
type MockTransactionRollbackVestingAccountsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackVestingAccountsCall) Return(arg0 error) *MockTransactionRollbackVestingAccountsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackVestingAccountsCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackVestingAccountsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackVestingAccountsCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackVestingAccountsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackVestingPeriods mocks base method.
func (m *MockTransaction) RollbackVestingPeriods(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackVestingPeriods", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackVestingPeriods indicates an expected call of RollbackVestingPeriods.
func (mr *MockTransactionMockRecorder) RollbackVestingPeriods(ctx, height any) *MockTransactionRollbackVestingPeriodsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackVestingPeriods", reflect.TypeOf((*MockTransaction)(nil).RollbackVestingPeriods), ctx, height)
return &MockTransactionRollbackVestingPeriodsCall{Call: call}
}
// MockTransactionRollbackVestingPeriodsCall wrap *gomock.Call
type MockTransactionRollbackVestingPeriodsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionRollbackVestingPeriodsCall) Return(arg0 error) *MockTransactionRollbackVestingPeriodsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionRollbackVestingPeriodsCall) Do(f func(context.Context, types.Level) error) *MockTransactionRollbackVestingPeriodsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionRollbackVestingPeriodsCall) DoAndReturn(f func(context.Context, types.Level) error) *MockTransactionRollbackVestingPeriodsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveAddresses mocks base method.
func (m *MockTransaction) SaveAddresses(ctx context.Context, addresses ...*storage.Address) (int64, error) {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range addresses {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveAddresses", varargs...)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SaveAddresses indicates an expected call of SaveAddresses.
func (mr *MockTransactionMockRecorder) SaveAddresses(ctx any, addresses ...any) *MockTransactionSaveAddressesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, addresses...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveAddresses", reflect.TypeOf((*MockTransaction)(nil).SaveAddresses), varargs...)
return &MockTransactionSaveAddressesCall{Call: call}
}
// MockTransactionSaveAddressesCall wrap *gomock.Call
type MockTransactionSaveAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveAddressesCall) Return(arg0 int64, arg1 error) *MockTransactionSaveAddressesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveAddressesCall) Do(f func(context.Context, ...*storage.Address) (int64, error)) *MockTransactionSaveAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveAddressesCall) DoAndReturn(f func(context.Context, ...*storage.Address) (int64, error)) *MockTransactionSaveAddressesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveBalances mocks base method.
func (m *MockTransaction) SaveBalances(ctx context.Context, balances ...storage.Balance) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range balances {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveBalances", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveBalances indicates an expected call of SaveBalances.
func (mr *MockTransactionMockRecorder) SaveBalances(ctx any, balances ...any) *MockTransactionSaveBalancesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, balances...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveBalances", reflect.TypeOf((*MockTransaction)(nil).SaveBalances), varargs...)
return &MockTransactionSaveBalancesCall{Call: call}
}
// MockTransactionSaveBalancesCall wrap *gomock.Call
type MockTransactionSaveBalancesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveBalancesCall) Return(arg0 error) *MockTransactionSaveBalancesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveBalancesCall) Do(f func(context.Context, ...storage.Balance) error) *MockTransactionSaveBalancesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveBalancesCall) DoAndReturn(f func(context.Context, ...storage.Balance) error) *MockTransactionSaveBalancesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveBlobLogs mocks base method.
func (m *MockTransaction) SaveBlobLogs(ctx context.Context, logs ...storage.BlobLog) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range logs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveBlobLogs", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveBlobLogs indicates an expected call of SaveBlobLogs.
func (mr *MockTransactionMockRecorder) SaveBlobLogs(ctx any, logs ...any) *MockTransactionSaveBlobLogsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, logs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveBlobLogs", reflect.TypeOf((*MockTransaction)(nil).SaveBlobLogs), varargs...)
return &MockTransactionSaveBlobLogsCall{Call: call}
}
// MockTransactionSaveBlobLogsCall wrap *gomock.Call
type MockTransactionSaveBlobLogsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveBlobLogsCall) Return(arg0 error) *MockTransactionSaveBlobLogsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveBlobLogsCall) Do(f func(context.Context, ...storage.BlobLog) error) *MockTransactionSaveBlobLogsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveBlobLogsCall) DoAndReturn(f func(context.Context, ...storage.BlobLog) error) *MockTransactionSaveBlobLogsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveBlockSignatures mocks base method.
func (m *MockTransaction) SaveBlockSignatures(ctx context.Context, signs ...storage.BlockSignature) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range signs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveBlockSignatures", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveBlockSignatures indicates an expected call of SaveBlockSignatures.
func (mr *MockTransactionMockRecorder) SaveBlockSignatures(ctx any, signs ...any) *MockTransactionSaveBlockSignaturesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, signs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveBlockSignatures", reflect.TypeOf((*MockTransaction)(nil).SaveBlockSignatures), varargs...)
return &MockTransactionSaveBlockSignaturesCall{Call: call}
}
// MockTransactionSaveBlockSignaturesCall wrap *gomock.Call
type MockTransactionSaveBlockSignaturesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveBlockSignaturesCall) Return(arg0 error) *MockTransactionSaveBlockSignaturesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveBlockSignaturesCall) Do(f func(context.Context, ...storage.BlockSignature) error) *MockTransactionSaveBlockSignaturesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveBlockSignaturesCall) DoAndReturn(f func(context.Context, ...storage.BlockSignature) error) *MockTransactionSaveBlockSignaturesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveConstants mocks base method.
func (m *MockTransaction) SaveConstants(ctx context.Context, constants ...storage.Constant) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range constants {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveConstants", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveConstants indicates an expected call of SaveConstants.
func (mr *MockTransactionMockRecorder) SaveConstants(ctx any, constants ...any) *MockTransactionSaveConstantsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, constants...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveConstants", reflect.TypeOf((*MockTransaction)(nil).SaveConstants), varargs...)
return &MockTransactionSaveConstantsCall{Call: call}
}
// MockTransactionSaveConstantsCall wrap *gomock.Call
type MockTransactionSaveConstantsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveConstantsCall) Return(arg0 error) *MockTransactionSaveConstantsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveConstantsCall) Do(f func(context.Context, ...storage.Constant) error) *MockTransactionSaveConstantsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveConstantsCall) DoAndReturn(f func(context.Context, ...storage.Constant) error) *MockTransactionSaveConstantsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveDelegations mocks base method.
func (m *MockTransaction) SaveDelegations(ctx context.Context, delegations ...storage.Delegation) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range delegations {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveDelegations", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveDelegations indicates an expected call of SaveDelegations.
func (mr *MockTransactionMockRecorder) SaveDelegations(ctx any, delegations ...any) *MockTransactionSaveDelegationsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, delegations...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveDelegations", reflect.TypeOf((*MockTransaction)(nil).SaveDelegations), varargs...)
return &MockTransactionSaveDelegationsCall{Call: call}
}
// MockTransactionSaveDelegationsCall wrap *gomock.Call
type MockTransactionSaveDelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveDelegationsCall) Return(arg0 error) *MockTransactionSaveDelegationsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveDelegationsCall) Do(f func(context.Context, ...storage.Delegation) error) *MockTransactionSaveDelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveDelegationsCall) DoAndReturn(f func(context.Context, ...storage.Delegation) error) *MockTransactionSaveDelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveEvents mocks base method.
func (m *MockTransaction) SaveEvents(ctx context.Context, events ...storage.Event) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range events {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveEvents", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveEvents indicates an expected call of SaveEvents.
func (mr *MockTransactionMockRecorder) SaveEvents(ctx any, events ...any) *MockTransactionSaveEventsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, events...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveEvents", reflect.TypeOf((*MockTransaction)(nil).SaveEvents), varargs...)
return &MockTransactionSaveEventsCall{Call: call}
}
// MockTransactionSaveEventsCall wrap *gomock.Call
type MockTransactionSaveEventsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveEventsCall) Return(arg0 error) *MockTransactionSaveEventsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveEventsCall) Do(f func(context.Context, ...storage.Event) error) *MockTransactionSaveEventsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveEventsCall) DoAndReturn(f func(context.Context, ...storage.Event) error) *MockTransactionSaveEventsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveGrants mocks base method.
func (m *MockTransaction) SaveGrants(ctx context.Context, grants ...storage.Grant) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range grants {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveGrants", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveGrants indicates an expected call of SaveGrants.
func (mr *MockTransactionMockRecorder) SaveGrants(ctx any, grants ...any) *MockTransactionSaveGrantsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, grants...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveGrants", reflect.TypeOf((*MockTransaction)(nil).SaveGrants), varargs...)
return &MockTransactionSaveGrantsCall{Call: call}
}
// MockTransactionSaveGrantsCall wrap *gomock.Call
type MockTransactionSaveGrantsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveGrantsCall) Return(arg0 error) *MockTransactionSaveGrantsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveGrantsCall) Do(f func(context.Context, ...storage.Grant) error) *MockTransactionSaveGrantsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveGrantsCall) DoAndReturn(f func(context.Context, ...storage.Grant) error) *MockTransactionSaveGrantsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveJails mocks base method.
func (m *MockTransaction) SaveJails(ctx context.Context, jails ...storage.Jail) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range jails {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveJails", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveJails indicates an expected call of SaveJails.
func (mr *MockTransactionMockRecorder) SaveJails(ctx any, jails ...any) *MockTransactionSaveJailsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, jails...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveJails", reflect.TypeOf((*MockTransaction)(nil).SaveJails), varargs...)
return &MockTransactionSaveJailsCall{Call: call}
}
// MockTransactionSaveJailsCall wrap *gomock.Call
type MockTransactionSaveJailsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveJailsCall) Return(arg0 error) *MockTransactionSaveJailsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveJailsCall) Do(f func(context.Context, ...storage.Jail) error) *MockTransactionSaveJailsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveJailsCall) DoAndReturn(f func(context.Context, ...storage.Jail) error) *MockTransactionSaveJailsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveMessages mocks base method.
func (m *MockTransaction) SaveMessages(ctx context.Context, msgs ...*storage.Message) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range msgs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveMessages", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveMessages indicates an expected call of SaveMessages.
func (mr *MockTransactionMockRecorder) SaveMessages(ctx any, msgs ...any) *MockTransactionSaveMessagesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, msgs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveMessages", reflect.TypeOf((*MockTransaction)(nil).SaveMessages), varargs...)
return &MockTransactionSaveMessagesCall{Call: call}
}
// MockTransactionSaveMessagesCall wrap *gomock.Call
type MockTransactionSaveMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveMessagesCall) Return(arg0 error) *MockTransactionSaveMessagesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveMessagesCall) Do(f func(context.Context, ...*storage.Message) error) *MockTransactionSaveMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveMessagesCall) DoAndReturn(f func(context.Context, ...*storage.Message) error) *MockTransactionSaveMessagesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveMsgAddresses mocks base method.
func (m *MockTransaction) SaveMsgAddresses(ctx context.Context, addresses ...storage.MsgAddress) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range addresses {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveMsgAddresses", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveMsgAddresses indicates an expected call of SaveMsgAddresses.
func (mr *MockTransactionMockRecorder) SaveMsgAddresses(ctx any, addresses ...any) *MockTransactionSaveMsgAddressesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, addresses...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveMsgAddresses", reflect.TypeOf((*MockTransaction)(nil).SaveMsgAddresses), varargs...)
return &MockTransactionSaveMsgAddressesCall{Call: call}
}
// MockTransactionSaveMsgAddressesCall wrap *gomock.Call
type MockTransactionSaveMsgAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveMsgAddressesCall) Return(arg0 error) *MockTransactionSaveMsgAddressesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveMsgAddressesCall) Do(f func(context.Context, ...storage.MsgAddress) error) *MockTransactionSaveMsgAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveMsgAddressesCall) DoAndReturn(f func(context.Context, ...storage.MsgAddress) error) *MockTransactionSaveMsgAddressesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveNamespaceMessage mocks base method.
func (m *MockTransaction) SaveNamespaceMessage(ctx context.Context, nsMsgs ...storage.NamespaceMessage) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range nsMsgs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveNamespaceMessage", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveNamespaceMessage indicates an expected call of SaveNamespaceMessage.
func (mr *MockTransactionMockRecorder) SaveNamespaceMessage(ctx any, nsMsgs ...any) *MockTransactionSaveNamespaceMessageCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, nsMsgs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveNamespaceMessage", reflect.TypeOf((*MockTransaction)(nil).SaveNamespaceMessage), varargs...)
return &MockTransactionSaveNamespaceMessageCall{Call: call}
}
// MockTransactionSaveNamespaceMessageCall wrap *gomock.Call
type MockTransactionSaveNamespaceMessageCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveNamespaceMessageCall) Return(arg0 error) *MockTransactionSaveNamespaceMessageCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveNamespaceMessageCall) Do(f func(context.Context, ...storage.NamespaceMessage) error) *MockTransactionSaveNamespaceMessageCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveNamespaceMessageCall) DoAndReturn(f func(context.Context, ...storage.NamespaceMessage) error) *MockTransactionSaveNamespaceMessageCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveNamespaces mocks base method.
func (m *MockTransaction) SaveNamespaces(ctx context.Context, namespaces ...*storage.Namespace) (int64, error) {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range namespaces {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveNamespaces", varargs...)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SaveNamespaces indicates an expected call of SaveNamespaces.
func (mr *MockTransactionMockRecorder) SaveNamespaces(ctx any, namespaces ...any) *MockTransactionSaveNamespacesCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, namespaces...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveNamespaces", reflect.TypeOf((*MockTransaction)(nil).SaveNamespaces), varargs...)
return &MockTransactionSaveNamespacesCall{Call: call}
}
// MockTransactionSaveNamespacesCall wrap *gomock.Call
type MockTransactionSaveNamespacesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveNamespacesCall) Return(arg0 int64, arg1 error) *MockTransactionSaveNamespacesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveNamespacesCall) Do(f func(context.Context, ...*storage.Namespace) (int64, error)) *MockTransactionSaveNamespacesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveNamespacesCall) DoAndReturn(f func(context.Context, ...*storage.Namespace) (int64, error)) *MockTransactionSaveNamespacesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveProviders mocks base method.
func (m *MockTransaction) SaveProviders(ctx context.Context, providers ...storage.RollupProvider) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range providers {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveProviders", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveProviders indicates an expected call of SaveProviders.
func (mr *MockTransactionMockRecorder) SaveProviders(ctx any, providers ...any) *MockTransactionSaveProvidersCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, providers...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveProviders", reflect.TypeOf((*MockTransaction)(nil).SaveProviders), varargs...)
return &MockTransactionSaveProvidersCall{Call: call}
}
// MockTransactionSaveProvidersCall wrap *gomock.Call
type MockTransactionSaveProvidersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveProvidersCall) Return(arg0 error) *MockTransactionSaveProvidersCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveProvidersCall) Do(f func(context.Context, ...storage.RollupProvider) error) *MockTransactionSaveProvidersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveProvidersCall) DoAndReturn(f func(context.Context, ...storage.RollupProvider) error) *MockTransactionSaveProvidersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveRedelegations mocks base method.
func (m *MockTransaction) SaveRedelegations(ctx context.Context, redelegations ...storage.Redelegation) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range redelegations {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveRedelegations", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveRedelegations indicates an expected call of SaveRedelegations.
func (mr *MockTransactionMockRecorder) SaveRedelegations(ctx any, redelegations ...any) *MockTransactionSaveRedelegationsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, redelegations...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveRedelegations", reflect.TypeOf((*MockTransaction)(nil).SaveRedelegations), varargs...)
return &MockTransactionSaveRedelegationsCall{Call: call}
}
// MockTransactionSaveRedelegationsCall wrap *gomock.Call
type MockTransactionSaveRedelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveRedelegationsCall) Return(arg0 error) *MockTransactionSaveRedelegationsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveRedelegationsCall) Do(f func(context.Context, ...storage.Redelegation) error) *MockTransactionSaveRedelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveRedelegationsCall) DoAndReturn(f func(context.Context, ...storage.Redelegation) error) *MockTransactionSaveRedelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveRollup mocks base method.
func (m *MockTransaction) SaveRollup(ctx context.Context, rollup *storage.Rollup) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SaveRollup", ctx, rollup)
ret0, _ := ret[0].(error)
return ret0
}
// SaveRollup indicates an expected call of SaveRollup.
func (mr *MockTransactionMockRecorder) SaveRollup(ctx, rollup any) *MockTransactionSaveRollupCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveRollup", reflect.TypeOf((*MockTransaction)(nil).SaveRollup), ctx, rollup)
return &MockTransactionSaveRollupCall{Call: call}
}
// MockTransactionSaveRollupCall wrap *gomock.Call
type MockTransactionSaveRollupCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveRollupCall) Return(arg0 error) *MockTransactionSaveRollupCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveRollupCall) Do(f func(context.Context, *storage.Rollup) error) *MockTransactionSaveRollupCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveRollupCall) DoAndReturn(f func(context.Context, *storage.Rollup) error) *MockTransactionSaveRollupCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveSigners mocks base method.
func (m *MockTransaction) SaveSigners(ctx context.Context, addresses ...storage.Signer) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range addresses {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveSigners", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveSigners indicates an expected call of SaveSigners.
func (mr *MockTransactionMockRecorder) SaveSigners(ctx any, addresses ...any) *MockTransactionSaveSignersCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, addresses...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveSigners", reflect.TypeOf((*MockTransaction)(nil).SaveSigners), varargs...)
return &MockTransactionSaveSignersCall{Call: call}
}
// MockTransactionSaveSignersCall wrap *gomock.Call
type MockTransactionSaveSignersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveSignersCall) Return(arg0 error) *MockTransactionSaveSignersCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveSignersCall) Do(f func(context.Context, ...storage.Signer) error) *MockTransactionSaveSignersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveSignersCall) DoAndReturn(f func(context.Context, ...storage.Signer) error) *MockTransactionSaveSignersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveStakingLogs mocks base method.
func (m *MockTransaction) SaveStakingLogs(ctx context.Context, logs ...storage.StakingLog) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range logs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveStakingLogs", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveStakingLogs indicates an expected call of SaveStakingLogs.
func (mr *MockTransactionMockRecorder) SaveStakingLogs(ctx any, logs ...any) *MockTransactionSaveStakingLogsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, logs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveStakingLogs", reflect.TypeOf((*MockTransaction)(nil).SaveStakingLogs), varargs...)
return &MockTransactionSaveStakingLogsCall{Call: call}
}
// MockTransactionSaveStakingLogsCall wrap *gomock.Call
type MockTransactionSaveStakingLogsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveStakingLogsCall) Return(arg0 error) *MockTransactionSaveStakingLogsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveStakingLogsCall) Do(f func(context.Context, ...storage.StakingLog) error) *MockTransactionSaveStakingLogsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveStakingLogsCall) DoAndReturn(f func(context.Context, ...storage.StakingLog) error) *MockTransactionSaveStakingLogsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveTransactions mocks base method.
func (m *MockTransaction) SaveTransactions(ctx context.Context, txs ...storage.Tx) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range txs {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveTransactions", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveTransactions indicates an expected call of SaveTransactions.
func (mr *MockTransactionMockRecorder) SaveTransactions(ctx any, txs ...any) *MockTransactionSaveTransactionsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, txs...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveTransactions", reflect.TypeOf((*MockTransaction)(nil).SaveTransactions), varargs...)
return &MockTransactionSaveTransactionsCall{Call: call}
}
// MockTransactionSaveTransactionsCall wrap *gomock.Call
type MockTransactionSaveTransactionsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveTransactionsCall) Return(arg0 error) *MockTransactionSaveTransactionsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveTransactionsCall) Do(f func(context.Context, ...storage.Tx) error) *MockTransactionSaveTransactionsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveTransactionsCall) DoAndReturn(f func(context.Context, ...storage.Tx) error) *MockTransactionSaveTransactionsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveUndelegations mocks base method.
func (m *MockTransaction) SaveUndelegations(ctx context.Context, undelegations ...storage.Undelegation) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range undelegations {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveUndelegations", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveUndelegations indicates an expected call of SaveUndelegations.
func (mr *MockTransactionMockRecorder) SaveUndelegations(ctx any, undelegations ...any) *MockTransactionSaveUndelegationsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, undelegations...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveUndelegations", reflect.TypeOf((*MockTransaction)(nil).SaveUndelegations), varargs...)
return &MockTransactionSaveUndelegationsCall{Call: call}
}
// MockTransactionSaveUndelegationsCall wrap *gomock.Call
type MockTransactionSaveUndelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveUndelegationsCall) Return(arg0 error) *MockTransactionSaveUndelegationsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveUndelegationsCall) Do(f func(context.Context, ...storage.Undelegation) error) *MockTransactionSaveUndelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveUndelegationsCall) DoAndReturn(f func(context.Context, ...storage.Undelegation) error) *MockTransactionSaveUndelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveValidators mocks base method.
func (m *MockTransaction) SaveValidators(ctx context.Context, validators ...*storage.Validator) (int, error) {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range validators {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveValidators", varargs...)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SaveValidators indicates an expected call of SaveValidators.
func (mr *MockTransactionMockRecorder) SaveValidators(ctx any, validators ...any) *MockTransactionSaveValidatorsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, validators...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveValidators", reflect.TypeOf((*MockTransaction)(nil).SaveValidators), varargs...)
return &MockTransactionSaveValidatorsCall{Call: call}
}
// MockTransactionSaveValidatorsCall wrap *gomock.Call
type MockTransactionSaveValidatorsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveValidatorsCall) Return(arg0 int, arg1 error) *MockTransactionSaveValidatorsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveValidatorsCall) Do(f func(context.Context, ...*storage.Validator) (int, error)) *MockTransactionSaveValidatorsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveValidatorsCall) DoAndReturn(f func(context.Context, ...*storage.Validator) (int, error)) *MockTransactionSaveValidatorsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveVestingAccounts mocks base method.
func (m *MockTransaction) SaveVestingAccounts(ctx context.Context, accounts ...*storage.VestingAccount) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range accounts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveVestingAccounts", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveVestingAccounts indicates an expected call of SaveVestingAccounts.
func (mr *MockTransactionMockRecorder) SaveVestingAccounts(ctx any, accounts ...any) *MockTransactionSaveVestingAccountsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, accounts...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveVestingAccounts", reflect.TypeOf((*MockTransaction)(nil).SaveVestingAccounts), varargs...)
return &MockTransactionSaveVestingAccountsCall{Call: call}
}
// MockTransactionSaveVestingAccountsCall wrap *gomock.Call
type MockTransactionSaveVestingAccountsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveVestingAccountsCall) Return(arg0 error) *MockTransactionSaveVestingAccountsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveVestingAccountsCall) Do(f func(context.Context, ...*storage.VestingAccount) error) *MockTransactionSaveVestingAccountsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveVestingAccountsCall) DoAndReturn(f func(context.Context, ...*storage.VestingAccount) error) *MockTransactionSaveVestingAccountsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveVestingPeriods mocks base method.
func (m *MockTransaction) SaveVestingPeriods(ctx context.Context, periods ...storage.VestingPeriod) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range periods {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SaveVestingPeriods", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveVestingPeriods indicates an expected call of SaveVestingPeriods.
func (mr *MockTransactionMockRecorder) SaveVestingPeriods(ctx any, periods ...any) *MockTransactionSaveVestingPeriodsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, periods...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveVestingPeriods", reflect.TypeOf((*MockTransaction)(nil).SaveVestingPeriods), varargs...)
return &MockTransactionSaveVestingPeriodsCall{Call: call}
}
// MockTransactionSaveVestingPeriodsCall wrap *gomock.Call
type MockTransactionSaveVestingPeriodsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionSaveVestingPeriodsCall) Return(arg0 error) *MockTransactionSaveVestingPeriodsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionSaveVestingPeriodsCall) Do(f func(context.Context, ...storage.VestingPeriod) error) *MockTransactionSaveVestingPeriodsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionSaveVestingPeriodsCall) DoAndReturn(f func(context.Context, ...storage.VestingPeriod) error) *MockTransactionSaveVestingPeriodsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// State mocks base method.
func (m *MockTransaction) State(ctx context.Context, name string) (storage.State, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "State", ctx, name)
ret0, _ := ret[0].(storage.State)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// State indicates an expected call of State.
func (mr *MockTransactionMockRecorder) State(ctx, name any) *MockTransactionStateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "State", reflect.TypeOf((*MockTransaction)(nil).State), ctx, name)
return &MockTransactionStateCall{Call: call}
}
// MockTransactionStateCall wrap *gomock.Call
type MockTransactionStateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionStateCall) Return(state storage.State, err error) *MockTransactionStateCall {
c.Call = c.Call.Return(state, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionStateCall) Do(f func(context.Context, string) (storage.State, error)) *MockTransactionStateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionStateCall) DoAndReturn(f func(context.Context, string) (storage.State, error)) *MockTransactionStateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Tx mocks base method.
func (m *MockTransaction) Tx() *bun.Tx {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Tx")
ret0, _ := ret[0].(*bun.Tx)
return ret0
}
// Tx indicates an expected call of Tx.
func (mr *MockTransactionMockRecorder) Tx() *MockTransactionTxCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tx", reflect.TypeOf((*MockTransaction)(nil).Tx))
return &MockTransactionTxCall{Call: call}
}
// MockTransactionTxCall wrap *gomock.Call
type MockTransactionTxCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionTxCall) Return(arg0 *bun.Tx) *MockTransactionTxCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionTxCall) Do(f func() *bun.Tx) *MockTransactionTxCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionTxCall) DoAndReturn(f func() *bun.Tx) *MockTransactionTxCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m *MockTransaction) Update(ctx context.Context, model any) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Update", ctx, model)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockTransactionMockRecorder) Update(ctx, model any) *MockTransactionUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockTransaction)(nil).Update), ctx, model)
return &MockTransactionUpdateCall{Call: call}
}
// MockTransactionUpdateCall wrap *gomock.Call
type MockTransactionUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionUpdateCall) Return(arg0 error) *MockTransactionUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionUpdateCall) Do(f func(context.Context, any) error) *MockTransactionUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionUpdateCall) DoAndReturn(f func(context.Context, any) error) *MockTransactionUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// UpdateRollup mocks base method.
func (m *MockTransaction) UpdateRollup(ctx context.Context, rollup *storage.Rollup) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateRollup", ctx, rollup)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateRollup indicates an expected call of UpdateRollup.
func (mr *MockTransactionMockRecorder) UpdateRollup(ctx, rollup any) *MockTransactionUpdateRollupCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRollup", reflect.TypeOf((*MockTransaction)(nil).UpdateRollup), ctx, rollup)
return &MockTransactionUpdateRollupCall{Call: call}
}
// MockTransactionUpdateRollupCall wrap *gomock.Call
type MockTransactionUpdateRollupCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionUpdateRollupCall) Return(arg0 error) *MockTransactionUpdateRollupCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionUpdateRollupCall) Do(f func(context.Context, *storage.Rollup) error) *MockTransactionUpdateRollupCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionUpdateRollupCall) DoAndReturn(f func(context.Context, *storage.Rollup) error) *MockTransactionUpdateRollupCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// UpdateSlashedDelegations mocks base method.
func (m *MockTransaction) UpdateSlashedDelegations(ctx context.Context, validatorId uint64, fraction decimal.Decimal) ([]storage.Balance, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateSlashedDelegations", ctx, validatorId, fraction)
ret0, _ := ret[0].([]storage.Balance)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UpdateSlashedDelegations indicates an expected call of UpdateSlashedDelegations.
func (mr *MockTransactionMockRecorder) UpdateSlashedDelegations(ctx, validatorId, fraction any) *MockTransactionUpdateSlashedDelegationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSlashedDelegations", reflect.TypeOf((*MockTransaction)(nil).UpdateSlashedDelegations), ctx, validatorId, fraction)
return &MockTransactionUpdateSlashedDelegationsCall{Call: call}
}
// MockTransactionUpdateSlashedDelegationsCall wrap *gomock.Call
type MockTransactionUpdateSlashedDelegationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionUpdateSlashedDelegationsCall) Return(arg0 []storage.Balance, arg1 error) *MockTransactionUpdateSlashedDelegationsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionUpdateSlashedDelegationsCall) Do(f func(context.Context, uint64, decimal.Decimal) ([]storage.Balance, error)) *MockTransactionUpdateSlashedDelegationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionUpdateSlashedDelegationsCall) DoAndReturn(f func(context.Context, uint64, decimal.Decimal) ([]storage.Balance, error)) *MockTransactionUpdateSlashedDelegationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// UpdateValidators mocks base method.
func (m *MockTransaction) UpdateValidators(ctx context.Context, validators ...*storage.Validator) error {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range validators {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "UpdateValidators", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateValidators indicates an expected call of UpdateValidators.
func (mr *MockTransactionMockRecorder) UpdateValidators(ctx any, validators ...any) *MockTransactionUpdateValidatorsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, validators...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateValidators", reflect.TypeOf((*MockTransaction)(nil).UpdateValidators), varargs...)
return &MockTransactionUpdateValidatorsCall{Call: call}
}
// MockTransactionUpdateValidatorsCall wrap *gomock.Call
type MockTransactionUpdateValidatorsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionUpdateValidatorsCall) Return(arg0 error) *MockTransactionUpdateValidatorsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionUpdateValidatorsCall) Do(f func(context.Context, ...*storage.Validator) error) *MockTransactionUpdateValidatorsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionUpdateValidatorsCall) DoAndReturn(f func(context.Context, ...*storage.Validator) error) *MockTransactionUpdateValidatorsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Validator mocks base method.
func (m *MockTransaction) Validator(ctx context.Context, id uint64) (storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Validator", ctx, id)
ret0, _ := ret[0].(storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Validator indicates an expected call of Validator.
func (mr *MockTransactionMockRecorder) Validator(ctx, id any) *MockTransactionValidatorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Validator", reflect.TypeOf((*MockTransaction)(nil).Validator), ctx, id)
return &MockTransactionValidatorCall{Call: call}
}
// MockTransactionValidatorCall wrap *gomock.Call
type MockTransactionValidatorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockTransactionValidatorCall) Return(val storage.Validator, err error) *MockTransactionValidatorCall {
c.Call = c.Call.Return(val, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockTransactionValidatorCall) Do(f func(context.Context, uint64) (storage.Validator, error)) *MockTransactionValidatorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockTransactionValidatorCall) DoAndReturn(f func(context.Context, uint64) (storage.Validator, error)) *MockTransactionValidatorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockISearch is a mock of ISearch interface.
type MockISearch struct {
ctrl *gomock.Controller
recorder *MockISearchMockRecorder
}
// MockISearchMockRecorder is the mock recorder for MockISearch.
type MockISearchMockRecorder struct {
mock *MockISearch
}
// NewMockISearch creates a new mock instance.
func NewMockISearch(ctrl *gomock.Controller) *MockISearch {
mock := &MockISearch{ctrl: ctrl}
mock.recorder = &MockISearchMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockISearch) EXPECT() *MockISearchMockRecorder {
return m.recorder
}
// Search mocks base method.
func (m *MockISearch) Search(ctx context.Context, query []byte) ([]storage.SearchResult, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Search", ctx, query)
ret0, _ := ret[0].([]storage.SearchResult)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Search indicates an expected call of Search.
func (mr *MockISearchMockRecorder) Search(ctx, query any) *MockISearchSearchCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Search", reflect.TypeOf((*MockISearch)(nil).Search), ctx, query)
return &MockISearchSearchCall{Call: call}
}
// MockISearchSearchCall wrap *gomock.Call
type MockISearchSearchCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockISearchSearchCall) Return(arg0 []storage.SearchResult, arg1 error) *MockISearchSearchCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockISearchSearchCall) Do(f func(context.Context, []byte) ([]storage.SearchResult, error)) *MockISearchSearchCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockISearchSearchCall) DoAndReturn(f func(context.Context, []byte) ([]storage.SearchResult, error)) *MockISearchSearchCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SearchText mocks base method.
func (m *MockISearch) SearchText(ctx context.Context, text string) ([]storage.SearchResult, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SearchText", ctx, text)
ret0, _ := ret[0].([]storage.SearchResult)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SearchText indicates an expected call of SearchText.
func (mr *MockISearchMockRecorder) SearchText(ctx, text any) *MockISearchSearchTextCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SearchText", reflect.TypeOf((*MockISearch)(nil).SearchText), ctx, text)
return &MockISearchSearchTextCall{Call: call}
}
// MockISearchSearchTextCall wrap *gomock.Call
type MockISearchSearchTextCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockISearchSearchTextCall) Return(arg0 []storage.SearchResult, arg1 error) *MockISearchSearchTextCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockISearchSearchTextCall) Do(f func(context.Context, string) ([]storage.SearchResult, error)) *MockISearchSearchTextCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockISearchSearchTextCall) DoAndReturn(f func(context.Context, string) ([]storage.SearchResult, error)) *MockISearchSearchTextCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockExport is a mock of Export interface.
type MockExport struct {
ctrl *gomock.Controller
recorder *MockExportMockRecorder
}
// MockExportMockRecorder is the mock recorder for MockExport.
type MockExportMockRecorder struct {
mock *MockExport
}
// NewMockExport creates a new mock instance.
func NewMockExport(ctrl *gomock.Controller) *MockExport {
mock := &MockExport{ctrl: ctrl}
mock.recorder = &MockExportMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockExport) EXPECT() *MockExportMockRecorder {
return m.recorder
}
// Close mocks base method.
func (m *MockExport) Close() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Close")
ret0, _ := ret[0].(error)
return ret0
}
// Close indicates an expected call of Close.
func (mr *MockExportMockRecorder) Close() *MockExportCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockExport)(nil).Close))
return &MockExportCloseCall{Call: call}
}
// MockExportCloseCall wrap *gomock.Call
type MockExportCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockExportCloseCall) Return(arg0 error) *MockExportCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockExportCloseCall) Do(f func() error) *MockExportCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockExportCloseCall) DoAndReturn(f func() error) *MockExportCloseCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ToCsv mocks base method.
func (m *MockExport) ToCsv(ctx context.Context, writer io.Writer, query string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ToCsv", ctx, writer, query)
ret0, _ := ret[0].(error)
return ret0
}
// ToCsv indicates an expected call of ToCsv.
func (mr *MockExportMockRecorder) ToCsv(ctx, writer, query any) *MockExportToCsvCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ToCsv", reflect.TypeOf((*MockExport)(nil).ToCsv), ctx, writer, query)
return &MockExportToCsvCall{Call: call}
}
// MockExportToCsvCall wrap *gomock.Call
type MockExportToCsvCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockExportToCsvCall) Return(arg0 error) *MockExportToCsvCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockExportToCsvCall) Do(f func(context.Context, io.Writer, string) error) *MockExportToCsvCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockExportToCsvCall) DoAndReturn(f func(context.Context, io.Writer, string) error) *MockExportToCsvCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: grant.go
//
// Generated by this command:
//
// mockgen -source=grant.go -destination=mock/grant.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIGrant is a mock of IGrant interface.
type MockIGrant struct {
ctrl *gomock.Controller
recorder *MockIGrantMockRecorder
}
// MockIGrantMockRecorder is the mock recorder for MockIGrant.
type MockIGrantMockRecorder struct {
mock *MockIGrant
}
// NewMockIGrant creates a new mock instance.
func NewMockIGrant(ctrl *gomock.Controller) *MockIGrant {
mock := &MockIGrant{ctrl: ctrl}
mock.recorder = &MockIGrantMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIGrant) EXPECT() *MockIGrantMockRecorder {
return m.recorder
}
// ByGrantee mocks base method.
func (m *MockIGrant) ByGrantee(ctx context.Context, id uint64, limit, offset int) ([]storage.Grant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByGrantee", ctx, id, limit, offset)
ret0, _ := ret[0].([]storage.Grant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByGrantee indicates an expected call of ByGrantee.
func (mr *MockIGrantMockRecorder) ByGrantee(ctx, id, limit, offset any) *MockIGrantByGranteeCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByGrantee", reflect.TypeOf((*MockIGrant)(nil).ByGrantee), ctx, id, limit, offset)
return &MockIGrantByGranteeCall{Call: call}
}
// MockIGrantByGranteeCall wrap *gomock.Call
type MockIGrantByGranteeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantByGranteeCall) Return(arg0 []storage.Grant, arg1 error) *MockIGrantByGranteeCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantByGranteeCall) Do(f func(context.Context, uint64, int, int) ([]storage.Grant, error)) *MockIGrantByGranteeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantByGranteeCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Grant, error)) *MockIGrantByGranteeCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByGranter mocks base method.
func (m *MockIGrant) ByGranter(ctx context.Context, id uint64, limit, offset int) ([]storage.Grant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByGranter", ctx, id, limit, offset)
ret0, _ := ret[0].([]storage.Grant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByGranter indicates an expected call of ByGranter.
func (mr *MockIGrantMockRecorder) ByGranter(ctx, id, limit, offset any) *MockIGrantByGranterCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByGranter", reflect.TypeOf((*MockIGrant)(nil).ByGranter), ctx, id, limit, offset)
return &MockIGrantByGranterCall{Call: call}
}
// MockIGrantByGranterCall wrap *gomock.Call
type MockIGrantByGranterCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantByGranterCall) Return(arg0 []storage.Grant, arg1 error) *MockIGrantByGranterCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantByGranterCall) Do(f func(context.Context, uint64, int, int) ([]storage.Grant, error)) *MockIGrantByGranterCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantByGranterCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Grant, error)) *MockIGrantByGranterCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIGrant) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Grant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Grant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIGrantMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIGrantCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIGrant)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIGrantCursorListCall{Call: call}
}
// MockIGrantCursorListCall wrap *gomock.Call
type MockIGrantCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantCursorListCall) Return(arg0 []*storage.Grant, arg1 error) *MockIGrantCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Grant, error)) *MockIGrantCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Grant, error)) *MockIGrantCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIGrant) GetByID(ctx context.Context, id uint64) (*storage.Grant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Grant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIGrantMockRecorder) GetByID(ctx, id any) *MockIGrantGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIGrant)(nil).GetByID), ctx, id)
return &MockIGrantGetByIDCall{Call: call}
}
// MockIGrantGetByIDCall wrap *gomock.Call
type MockIGrantGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantGetByIDCall) Return(arg0 *storage.Grant, arg1 error) *MockIGrantGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantGetByIDCall) Do(f func(context.Context, uint64) (*storage.Grant, error)) *MockIGrantGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Grant, error)) *MockIGrantGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIGrant) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIGrantMockRecorder) IsNoRows(err any) *MockIGrantIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIGrant)(nil).IsNoRows), err)
return &MockIGrantIsNoRowsCall{Call: call}
}
// MockIGrantIsNoRowsCall wrap *gomock.Call
type MockIGrantIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantIsNoRowsCall) Return(arg0 bool) *MockIGrantIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantIsNoRowsCall) Do(f func(error) bool) *MockIGrantIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIGrantIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIGrant) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIGrantMockRecorder) LastID(ctx any) *MockIGrantLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIGrant)(nil).LastID), ctx)
return &MockIGrantLastIDCall{Call: call}
}
// MockIGrantLastIDCall wrap *gomock.Call
type MockIGrantLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantLastIDCall) Return(arg0 uint64, arg1 error) *MockIGrantLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIGrantLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIGrantLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIGrant) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Grant, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Grant)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIGrantMockRecorder) List(ctx, limit, offset, order any) *MockIGrantListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIGrant)(nil).List), ctx, limit, offset, order)
return &MockIGrantListCall{Call: call}
}
// MockIGrantListCall wrap *gomock.Call
type MockIGrantListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantListCall) Return(arg0 []*storage.Grant, arg1 error) *MockIGrantListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Grant, error)) *MockIGrantListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Grant, error)) *MockIGrantListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIGrant) Save(ctx context.Context, m *storage.Grant) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIGrantMockRecorder) Save(ctx, m any) *MockIGrantSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIGrant)(nil).Save), ctx, m)
return &MockIGrantSaveCall{Call: call}
}
// MockIGrantSaveCall wrap *gomock.Call
type MockIGrantSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantSaveCall) Return(arg0 error) *MockIGrantSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantSaveCall) Do(f func(context.Context, *storage.Grant) error) *MockIGrantSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantSaveCall) DoAndReturn(f func(context.Context, *storage.Grant) error) *MockIGrantSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIGrant) Update(ctx context.Context, m *storage.Grant) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIGrantMockRecorder) Update(ctx, m any) *MockIGrantUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIGrant)(nil).Update), ctx, m)
return &MockIGrantUpdateCall{Call: call}
}
// MockIGrantUpdateCall wrap *gomock.Call
type MockIGrantUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIGrantUpdateCall) Return(arg0 error) *MockIGrantUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIGrantUpdateCall) Do(f func(context.Context, *storage.Grant) error) *MockIGrantUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIGrantUpdateCall) DoAndReturn(f func(context.Context, *storage.Grant) error) *MockIGrantUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: jail.go
//
// Generated by this command:
//
// mockgen -source=jail.go -destination=mock/jail.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIJail is a mock of IJail interface.
type MockIJail struct {
ctrl *gomock.Controller
recorder *MockIJailMockRecorder
}
// MockIJailMockRecorder is the mock recorder for MockIJail.
type MockIJailMockRecorder struct {
mock *MockIJail
}
// NewMockIJail creates a new mock instance.
func NewMockIJail(ctrl *gomock.Controller) *MockIJail {
mock := &MockIJail{ctrl: ctrl}
mock.recorder = &MockIJailMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIJail) EXPECT() *MockIJailMockRecorder {
return m.recorder
}
// ByValidator mocks base method.
func (m *MockIJail) ByValidator(ctx context.Context, id uint64, limit, offset int) ([]storage.Jail, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByValidator", ctx, id, limit, offset)
ret0, _ := ret[0].([]storage.Jail)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByValidator indicates an expected call of ByValidator.
func (mr *MockIJailMockRecorder) ByValidator(ctx, id, limit, offset any) *MockIJailByValidatorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByValidator", reflect.TypeOf((*MockIJail)(nil).ByValidator), ctx, id, limit, offset)
return &MockIJailByValidatorCall{Call: call}
}
// MockIJailByValidatorCall wrap *gomock.Call
type MockIJailByValidatorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailByValidatorCall) Return(arg0 []storage.Jail, arg1 error) *MockIJailByValidatorCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailByValidatorCall) Do(f func(context.Context, uint64, int, int) ([]storage.Jail, error)) *MockIJailByValidatorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailByValidatorCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Jail, error)) *MockIJailByValidatorCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIJail) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Jail, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Jail)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIJailMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIJailCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIJail)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIJailCursorListCall{Call: call}
}
// MockIJailCursorListCall wrap *gomock.Call
type MockIJailCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailCursorListCall) Return(arg0 []*storage.Jail, arg1 error) *MockIJailCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Jail, error)) *MockIJailCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Jail, error)) *MockIJailCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIJail) GetByID(ctx context.Context, id uint64) (*storage.Jail, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Jail)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIJailMockRecorder) GetByID(ctx, id any) *MockIJailGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIJail)(nil).GetByID), ctx, id)
return &MockIJailGetByIDCall{Call: call}
}
// MockIJailGetByIDCall wrap *gomock.Call
type MockIJailGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailGetByIDCall) Return(arg0 *storage.Jail, arg1 error) *MockIJailGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailGetByIDCall) Do(f func(context.Context, uint64) (*storage.Jail, error)) *MockIJailGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Jail, error)) *MockIJailGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIJail) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIJailMockRecorder) IsNoRows(err any) *MockIJailIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIJail)(nil).IsNoRows), err)
return &MockIJailIsNoRowsCall{Call: call}
}
// MockIJailIsNoRowsCall wrap *gomock.Call
type MockIJailIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailIsNoRowsCall) Return(arg0 bool) *MockIJailIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailIsNoRowsCall) Do(f func(error) bool) *MockIJailIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIJailIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIJail) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIJailMockRecorder) LastID(ctx any) *MockIJailLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIJail)(nil).LastID), ctx)
return &MockIJailLastIDCall{Call: call}
}
// MockIJailLastIDCall wrap *gomock.Call
type MockIJailLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailLastIDCall) Return(arg0 uint64, arg1 error) *MockIJailLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIJailLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIJailLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIJail) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Jail, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Jail)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIJailMockRecorder) List(ctx, limit, offset, order any) *MockIJailListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIJail)(nil).List), ctx, limit, offset, order)
return &MockIJailListCall{Call: call}
}
// MockIJailListCall wrap *gomock.Call
type MockIJailListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailListCall) Return(arg0 []*storage.Jail, arg1 error) *MockIJailListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Jail, error)) *MockIJailListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Jail, error)) *MockIJailListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIJail) Save(ctx context.Context, m *storage.Jail) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIJailMockRecorder) Save(ctx, m any) *MockIJailSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIJail)(nil).Save), ctx, m)
return &MockIJailSaveCall{Call: call}
}
// MockIJailSaveCall wrap *gomock.Call
type MockIJailSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailSaveCall) Return(arg0 error) *MockIJailSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailSaveCall) Do(f func(context.Context, *storage.Jail) error) *MockIJailSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailSaveCall) DoAndReturn(f func(context.Context, *storage.Jail) error) *MockIJailSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIJail) Update(ctx context.Context, m *storage.Jail) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIJailMockRecorder) Update(ctx, m any) *MockIJailUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIJail)(nil).Update), ctx, m)
return &MockIJailUpdateCall{Call: call}
}
// MockIJailUpdateCall wrap *gomock.Call
type MockIJailUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIJailUpdateCall) Return(arg0 error) *MockIJailUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIJailUpdateCall) Do(f func(context.Context, *storage.Jail) error) *MockIJailUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIJailUpdateCall) DoAndReturn(f func(context.Context, *storage.Jail) error) *MockIJailUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: message.go
//
// Generated by this command:
//
// mockgen -source=message.go -destination=mock/message.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIMessage is a mock of IMessage interface.
type MockIMessage struct {
ctrl *gomock.Controller
recorder *MockIMessageMockRecorder
}
// MockIMessageMockRecorder is the mock recorder for MockIMessage.
type MockIMessageMockRecorder struct {
mock *MockIMessage
}
// NewMockIMessage creates a new mock instance.
func NewMockIMessage(ctrl *gomock.Controller) *MockIMessage {
mock := &MockIMessage{ctrl: ctrl}
mock.recorder = &MockIMessageMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIMessage) EXPECT() *MockIMessageMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIMessage) ByAddress(ctx context.Context, id uint64, filters storage.AddressMsgsFilter) ([]storage.AddressMessageWithTx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, id, filters)
ret0, _ := ret[0].([]storage.AddressMessageWithTx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIMessageMockRecorder) ByAddress(ctx, id, filters any) *MockIMessageByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIMessage)(nil).ByAddress), ctx, id, filters)
return &MockIMessageByAddressCall{Call: call}
}
// MockIMessageByAddressCall wrap *gomock.Call
type MockIMessageByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageByAddressCall) Return(arg0 []storage.AddressMessageWithTx, arg1 error) *MockIMessageByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageByAddressCall) Do(f func(context.Context, uint64, storage.AddressMsgsFilter) ([]storage.AddressMessageWithTx, error)) *MockIMessageByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageByAddressCall) DoAndReturn(f func(context.Context, uint64, storage.AddressMsgsFilter) ([]storage.AddressMessageWithTx, error)) *MockIMessageByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByTxId mocks base method.
func (m *MockIMessage) ByTxId(ctx context.Context, txId uint64, limit, offset int) ([]storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByTxId", ctx, txId, limit, offset)
ret0, _ := ret[0].([]storage.Message)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByTxId indicates an expected call of ByTxId.
func (mr *MockIMessageMockRecorder) ByTxId(ctx, txId, limit, offset any) *MockIMessageByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByTxId", reflect.TypeOf((*MockIMessage)(nil).ByTxId), ctx, txId, limit, offset)
return &MockIMessageByTxIdCall{Call: call}
}
// MockIMessageByTxIdCall wrap *gomock.Call
type MockIMessageByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageByTxIdCall) Return(arg0 []storage.Message, arg1 error) *MockIMessageByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageByTxIdCall) Do(f func(context.Context, uint64, int, int) ([]storage.Message, error)) *MockIMessageByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageByTxIdCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Message, error)) *MockIMessageByTxIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIMessage) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Message)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIMessageMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIMessageCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIMessage)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIMessageCursorListCall{Call: call}
}
// MockIMessageCursorListCall wrap *gomock.Call
type MockIMessageCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageCursorListCall) Return(arg0 []*storage.Message, arg1 error) *MockIMessageCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Message, error)) *MockIMessageCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Message, error)) *MockIMessageCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIMessage) GetByID(ctx context.Context, id uint64) (*storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Message)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIMessageMockRecorder) GetByID(ctx, id any) *MockIMessageGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIMessage)(nil).GetByID), ctx, id)
return &MockIMessageGetByIDCall{Call: call}
}
// MockIMessageGetByIDCall wrap *gomock.Call
type MockIMessageGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageGetByIDCall) Return(arg0 *storage.Message, arg1 error) *MockIMessageGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageGetByIDCall) Do(f func(context.Context, uint64) (*storage.Message, error)) *MockIMessageGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Message, error)) *MockIMessageGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIMessage) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIMessageMockRecorder) IsNoRows(err any) *MockIMessageIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIMessage)(nil).IsNoRows), err)
return &MockIMessageIsNoRowsCall{Call: call}
}
// MockIMessageIsNoRowsCall wrap *gomock.Call
type MockIMessageIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageIsNoRowsCall) Return(arg0 bool) *MockIMessageIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageIsNoRowsCall) Do(f func(error) bool) *MockIMessageIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIMessageIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIMessage) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIMessageMockRecorder) LastID(ctx any) *MockIMessageLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIMessage)(nil).LastID), ctx)
return &MockIMessageLastIDCall{Call: call}
}
// MockIMessageLastIDCall wrap *gomock.Call
type MockIMessageLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageLastIDCall) Return(arg0 uint64, arg1 error) *MockIMessageLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIMessageLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIMessageLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIMessage) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Message)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIMessageMockRecorder) List(ctx, limit, offset, order any) *MockIMessageListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIMessage)(nil).List), ctx, limit, offset, order)
return &MockIMessageListCall{Call: call}
}
// MockIMessageListCall wrap *gomock.Call
type MockIMessageListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageListCall) Return(arg0 []*storage.Message, arg1 error) *MockIMessageListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Message, error)) *MockIMessageListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Message, error)) *MockIMessageListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListWithTx mocks base method.
func (m *MockIMessage) ListWithTx(ctx context.Context, filters storage.MessageListWithTxFilters) ([]storage.MessageWithTx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListWithTx", ctx, filters)
ret0, _ := ret[0].([]storage.MessageWithTx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListWithTx indicates an expected call of ListWithTx.
func (mr *MockIMessageMockRecorder) ListWithTx(ctx, filters any) *MockIMessageListWithTxCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithTx", reflect.TypeOf((*MockIMessage)(nil).ListWithTx), ctx, filters)
return &MockIMessageListWithTxCall{Call: call}
}
// MockIMessageListWithTxCall wrap *gomock.Call
type MockIMessageListWithTxCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageListWithTxCall) Return(arg0 []storage.MessageWithTx, arg1 error) *MockIMessageListWithTxCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageListWithTxCall) Do(f func(context.Context, storage.MessageListWithTxFilters) ([]storage.MessageWithTx, error)) *MockIMessageListWithTxCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageListWithTxCall) DoAndReturn(f func(context.Context, storage.MessageListWithTxFilters) ([]storage.MessageWithTx, error)) *MockIMessageListWithTxCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIMessage) Save(ctx context.Context, m *storage.Message) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIMessageMockRecorder) Save(ctx, m any) *MockIMessageSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIMessage)(nil).Save), ctx, m)
return &MockIMessageSaveCall{Call: call}
}
// MockIMessageSaveCall wrap *gomock.Call
type MockIMessageSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageSaveCall) Return(arg0 error) *MockIMessageSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageSaveCall) Do(f func(context.Context, *storage.Message) error) *MockIMessageSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageSaveCall) DoAndReturn(f func(context.Context, *storage.Message) error) *MockIMessageSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIMessage) Update(ctx context.Context, m *storage.Message) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIMessageMockRecorder) Update(ctx, m any) *MockIMessageUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIMessage)(nil).Update), ctx, m)
return &MockIMessageUpdateCall{Call: call}
}
// MockIMessageUpdateCall wrap *gomock.Call
type MockIMessageUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIMessageUpdateCall) Return(arg0 error) *MockIMessageUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIMessageUpdateCall) Do(f func(context.Context, *storage.Message) error) *MockIMessageUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIMessageUpdateCall) DoAndReturn(f func(context.Context, *storage.Message) error) *MockIMessageUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: namespace.go
//
// Generated by this command:
//
// mockgen -source=namespace.go -destination=mock/namespace.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockINamespace is a mock of INamespace interface.
type MockINamespace struct {
ctrl *gomock.Controller
recorder *MockINamespaceMockRecorder
}
// MockINamespaceMockRecorder is the mock recorder for MockINamespace.
type MockINamespaceMockRecorder struct {
mock *MockINamespace
}
// NewMockINamespace creates a new mock instance.
func NewMockINamespace(ctrl *gomock.Controller) *MockINamespace {
mock := &MockINamespace{ctrl: ctrl}
mock.recorder = &MockINamespaceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockINamespace) EXPECT() *MockINamespaceMockRecorder {
return m.recorder
}
// ByNamespaceId mocks base method.
func (m *MockINamespace) ByNamespaceId(ctx context.Context, namespaceId []byte) ([]storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByNamespaceId", ctx, namespaceId)
ret0, _ := ret[0].([]storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByNamespaceId indicates an expected call of ByNamespaceId.
func (mr *MockINamespaceMockRecorder) ByNamespaceId(ctx, namespaceId any) *MockINamespaceByNamespaceIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByNamespaceId", reflect.TypeOf((*MockINamespace)(nil).ByNamespaceId), ctx, namespaceId)
return &MockINamespaceByNamespaceIdCall{Call: call}
}
// MockINamespaceByNamespaceIdCall wrap *gomock.Call
type MockINamespaceByNamespaceIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceByNamespaceIdCall) Return(arg0 []storage.Namespace, arg1 error) *MockINamespaceByNamespaceIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceByNamespaceIdCall) Do(f func(context.Context, []byte) ([]storage.Namespace, error)) *MockINamespaceByNamespaceIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceByNamespaceIdCall) DoAndReturn(f func(context.Context, []byte) ([]storage.Namespace, error)) *MockINamespaceByNamespaceIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByNamespaceIdAndVersion mocks base method.
func (m *MockINamespace) ByNamespaceIdAndVersion(ctx context.Context, namespaceId []byte, version byte) (storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByNamespaceIdAndVersion", ctx, namespaceId, version)
ret0, _ := ret[0].(storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByNamespaceIdAndVersion indicates an expected call of ByNamespaceIdAndVersion.
func (mr *MockINamespaceMockRecorder) ByNamespaceIdAndVersion(ctx, namespaceId, version any) *MockINamespaceByNamespaceIdAndVersionCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByNamespaceIdAndVersion", reflect.TypeOf((*MockINamespace)(nil).ByNamespaceIdAndVersion), ctx, namespaceId, version)
return &MockINamespaceByNamespaceIdAndVersionCall{Call: call}
}
// MockINamespaceByNamespaceIdAndVersionCall wrap *gomock.Call
type MockINamespaceByNamespaceIdAndVersionCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceByNamespaceIdAndVersionCall) Return(arg0 storage.Namespace, arg1 error) *MockINamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceByNamespaceIdAndVersionCall) Do(f func(context.Context, []byte, byte) (storage.Namespace, error)) *MockINamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceByNamespaceIdAndVersionCall) DoAndReturn(f func(context.Context, []byte, byte) (storage.Namespace, error)) *MockINamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockINamespace) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockINamespaceMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockINamespaceCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockINamespace)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockINamespaceCursorListCall{Call: call}
}
// MockINamespaceCursorListCall wrap *gomock.Call
type MockINamespaceCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceCursorListCall) Return(arg0 []*storage.Namespace, arg1 error) *MockINamespaceCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Namespace, error)) *MockINamespaceCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Namespace, error)) *MockINamespaceCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockINamespace) GetByID(ctx context.Context, id uint64) (*storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockINamespaceMockRecorder) GetByID(ctx, id any) *MockINamespaceGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockINamespace)(nil).GetByID), ctx, id)
return &MockINamespaceGetByIDCall{Call: call}
}
// MockINamespaceGetByIDCall wrap *gomock.Call
type MockINamespaceGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceGetByIDCall) Return(arg0 *storage.Namespace, arg1 error) *MockINamespaceGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceGetByIDCall) Do(f func(context.Context, uint64) (*storage.Namespace, error)) *MockINamespaceGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Namespace, error)) *MockINamespaceGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByIds mocks base method.
func (m *MockINamespace) GetByIds(ctx context.Context, ids ...uint64) ([]storage.Namespace, error) {
m.ctrl.T.Helper()
varargs := []any{ctx}
for _, a := range ids {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetByIds", varargs...)
ret0, _ := ret[0].([]storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByIds indicates an expected call of GetByIds.
func (mr *MockINamespaceMockRecorder) GetByIds(ctx any, ids ...any) *MockINamespaceGetByIdsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx}, ids...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByIds", reflect.TypeOf((*MockINamespace)(nil).GetByIds), varargs...)
return &MockINamespaceGetByIdsCall{Call: call}
}
// MockINamespaceGetByIdsCall wrap *gomock.Call
type MockINamespaceGetByIdsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceGetByIdsCall) Return(ns []storage.Namespace, err error) *MockINamespaceGetByIdsCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceGetByIdsCall) Do(f func(context.Context, ...uint64) ([]storage.Namespace, error)) *MockINamespaceGetByIdsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceGetByIdsCall) DoAndReturn(f func(context.Context, ...uint64) ([]storage.Namespace, error)) *MockINamespaceGetByIdsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockINamespace) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockINamespaceMockRecorder) IsNoRows(err any) *MockINamespaceIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockINamespace)(nil).IsNoRows), err)
return &MockINamespaceIsNoRowsCall{Call: call}
}
// MockINamespaceIsNoRowsCall wrap *gomock.Call
type MockINamespaceIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceIsNoRowsCall) Return(arg0 bool) *MockINamespaceIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceIsNoRowsCall) Do(f func(error) bool) *MockINamespaceIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceIsNoRowsCall) DoAndReturn(f func(error) bool) *MockINamespaceIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockINamespace) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockINamespaceMockRecorder) LastID(ctx any) *MockINamespaceLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockINamespace)(nil).LastID), ctx)
return &MockINamespaceLastIDCall{Call: call}
}
// MockINamespaceLastIDCall wrap *gomock.Call
type MockINamespaceLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceLastIDCall) Return(arg0 uint64, arg1 error) *MockINamespaceLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceLastIDCall) Do(f func(context.Context) (uint64, error)) *MockINamespaceLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockINamespaceLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockINamespace) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockINamespaceMockRecorder) List(ctx, limit, offset, order any) *MockINamespaceListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockINamespace)(nil).List), ctx, limit, offset, order)
return &MockINamespaceListCall{Call: call}
}
// MockINamespaceListCall wrap *gomock.Call
type MockINamespaceListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceListCall) Return(arg0 []*storage.Namespace, arg1 error) *MockINamespaceListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Namespace, error)) *MockINamespaceListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Namespace, error)) *MockINamespaceListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListWithSort mocks base method.
func (m *MockINamespace) ListWithSort(ctx context.Context, sortField string, sort storage0.SortOrder, limit, offset int) ([]storage.Namespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListWithSort", ctx, sortField, sort, limit, offset)
ret0, _ := ret[0].([]storage.Namespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListWithSort indicates an expected call of ListWithSort.
func (mr *MockINamespaceMockRecorder) ListWithSort(ctx, sortField, sort, limit, offset any) *MockINamespaceListWithSortCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithSort", reflect.TypeOf((*MockINamespace)(nil).ListWithSort), ctx, sortField, sort, limit, offset)
return &MockINamespaceListWithSortCall{Call: call}
}
// MockINamespaceListWithSortCall wrap *gomock.Call
type MockINamespaceListWithSortCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceListWithSortCall) Return(ns []storage.Namespace, err error) *MockINamespaceListWithSortCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceListWithSortCall) Do(f func(context.Context, string, storage0.SortOrder, int, int) ([]storage.Namespace, error)) *MockINamespaceListWithSortCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceListWithSortCall) DoAndReturn(f func(context.Context, string, storage0.SortOrder, int, int) ([]storage.Namespace, error)) *MockINamespaceListWithSortCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Messages mocks base method.
func (m *MockINamespace) Messages(ctx context.Context, id uint64, limit, offset int) ([]storage.NamespaceMessage, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Messages", ctx, id, limit, offset)
ret0, _ := ret[0].([]storage.NamespaceMessage)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Messages indicates an expected call of Messages.
func (mr *MockINamespaceMockRecorder) Messages(ctx, id, limit, offset any) *MockINamespaceMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Messages", reflect.TypeOf((*MockINamespace)(nil).Messages), ctx, id, limit, offset)
return &MockINamespaceMessagesCall{Call: call}
}
// MockINamespaceMessagesCall wrap *gomock.Call
type MockINamespaceMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceMessagesCall) Return(arg0 []storage.NamespaceMessage, arg1 error) *MockINamespaceMessagesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceMessagesCall) Do(f func(context.Context, uint64, int, int) ([]storage.NamespaceMessage, error)) *MockINamespaceMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceMessagesCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.NamespaceMessage, error)) *MockINamespaceMessagesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockINamespace) Save(ctx context.Context, m *storage.Namespace) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockINamespaceMockRecorder) Save(ctx, m any) *MockINamespaceSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockINamespace)(nil).Save), ctx, m)
return &MockINamespaceSaveCall{Call: call}
}
// MockINamespaceSaveCall wrap *gomock.Call
type MockINamespaceSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceSaveCall) Return(arg0 error) *MockINamespaceSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceSaveCall) Do(f func(context.Context, *storage.Namespace) error) *MockINamespaceSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceSaveCall) DoAndReturn(f func(context.Context, *storage.Namespace) error) *MockINamespaceSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockINamespace) Update(ctx context.Context, m *storage.Namespace) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockINamespaceMockRecorder) Update(ctx, m any) *MockINamespaceUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockINamespace)(nil).Update), ctx, m)
return &MockINamespaceUpdateCall{Call: call}
}
// MockINamespaceUpdateCall wrap *gomock.Call
type MockINamespaceUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockINamespaceUpdateCall) Return(arg0 error) *MockINamespaceUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockINamespaceUpdateCall) Do(f func(context.Context, *storage.Namespace) error) *MockINamespaceUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockINamespaceUpdateCall) DoAndReturn(f func(context.Context, *storage.Namespace) error) *MockINamespaceUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: price.go
//
// Generated by this command:
//
// mockgen -source=price.go -destination=mock/price.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIPrice is a mock of IPrice interface.
type MockIPrice struct {
ctrl *gomock.Controller
recorder *MockIPriceMockRecorder
}
// MockIPriceMockRecorder is the mock recorder for MockIPrice.
type MockIPriceMockRecorder struct {
mock *MockIPrice
}
// NewMockIPrice creates a new mock instance.
func NewMockIPrice(ctrl *gomock.Controller) *MockIPrice {
mock := &MockIPrice{ctrl: ctrl}
mock.recorder = &MockIPriceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIPrice) EXPECT() *MockIPriceMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockIPrice) Get(ctx context.Context, timeframe string, start, end time.Time, limit int) ([]storage.Price, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", ctx, timeframe, start, end, limit)
ret0, _ := ret[0].([]storage.Price)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockIPriceMockRecorder) Get(ctx, timeframe, start, end, limit any) *MockIPriceGetCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIPrice)(nil).Get), ctx, timeframe, start, end, limit)
return &MockIPriceGetCall{Call: call}
}
// MockIPriceGetCall wrap *gomock.Call
type MockIPriceGetCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIPriceGetCall) Return(arg0 []storage.Price, arg1 error) *MockIPriceGetCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIPriceGetCall) Do(f func(context.Context, string, time.Time, time.Time, int) ([]storage.Price, error)) *MockIPriceGetCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIPriceGetCall) DoAndReturn(f func(context.Context, string, time.Time, time.Time, int) ([]storage.Price, error)) *MockIPriceGetCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Last mocks base method.
func (m *MockIPrice) Last(ctx context.Context) (storage.Price, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Last", ctx)
ret0, _ := ret[0].(storage.Price)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Last indicates an expected call of Last.
func (mr *MockIPriceMockRecorder) Last(ctx any) *MockIPriceLastCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Last", reflect.TypeOf((*MockIPrice)(nil).Last), ctx)
return &MockIPriceLastCall{Call: call}
}
// MockIPriceLastCall wrap *gomock.Call
type MockIPriceLastCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIPriceLastCall) Return(arg0 storage.Price, arg1 error) *MockIPriceLastCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIPriceLastCall) Do(f func(context.Context) (storage.Price, error)) *MockIPriceLastCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIPriceLastCall) DoAndReturn(f func(context.Context) (storage.Price, error)) *MockIPriceLastCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m *MockIPrice) Save(ctx context.Context, price *storage.Price) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Save", ctx, price)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIPriceMockRecorder) Save(ctx, price any) *MockIPriceSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIPrice)(nil).Save), ctx, price)
return &MockIPriceSaveCall{Call: call}
}
// MockIPriceSaveCall wrap *gomock.Call
type MockIPriceSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIPriceSaveCall) Return(arg0 error) *MockIPriceSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIPriceSaveCall) Do(f func(context.Context, *storage.Price) error) *MockIPriceSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIPriceSaveCall) DoAndReturn(f func(context.Context, *storage.Price) error) *MockIPriceSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: redelegation.go
//
// Generated by this command:
//
// mockgen -source=redelegation.go -destination=mock/redelegation.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIRedelegation is a mock of IRedelegation interface.
type MockIRedelegation struct {
ctrl *gomock.Controller
recorder *MockIRedelegationMockRecorder
}
// MockIRedelegationMockRecorder is the mock recorder for MockIRedelegation.
type MockIRedelegationMockRecorder struct {
mock *MockIRedelegation
}
// NewMockIRedelegation creates a new mock instance.
func NewMockIRedelegation(ctrl *gomock.Controller) *MockIRedelegation {
mock := &MockIRedelegation{ctrl: ctrl}
mock.recorder = &MockIRedelegationMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIRedelegation) EXPECT() *MockIRedelegationMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIRedelegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int) ([]storage.Redelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, addressId, limit, offset)
ret0, _ := ret[0].([]storage.Redelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIRedelegationMockRecorder) ByAddress(ctx, addressId, limit, offset any) *MockIRedelegationByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIRedelegation)(nil).ByAddress), ctx, addressId, limit, offset)
return &MockIRedelegationByAddressCall{Call: call}
}
// MockIRedelegationByAddressCall wrap *gomock.Call
type MockIRedelegationByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationByAddressCall) Return(arg0 []storage.Redelegation, arg1 error) *MockIRedelegationByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationByAddressCall) Do(f func(context.Context, uint64, int, int) ([]storage.Redelegation, error)) *MockIRedelegationByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationByAddressCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Redelegation, error)) *MockIRedelegationByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIRedelegation) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Redelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Redelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIRedelegationMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIRedelegationCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIRedelegation)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIRedelegationCursorListCall{Call: call}
}
// MockIRedelegationCursorListCall wrap *gomock.Call
type MockIRedelegationCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationCursorListCall) Return(arg0 []*storage.Redelegation, arg1 error) *MockIRedelegationCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Redelegation, error)) *MockIRedelegationCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Redelegation, error)) *MockIRedelegationCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIRedelegation) GetByID(ctx context.Context, id uint64) (*storage.Redelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Redelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIRedelegationMockRecorder) GetByID(ctx, id any) *MockIRedelegationGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIRedelegation)(nil).GetByID), ctx, id)
return &MockIRedelegationGetByIDCall{Call: call}
}
// MockIRedelegationGetByIDCall wrap *gomock.Call
type MockIRedelegationGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationGetByIDCall) Return(arg0 *storage.Redelegation, arg1 error) *MockIRedelegationGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationGetByIDCall) Do(f func(context.Context, uint64) (*storage.Redelegation, error)) *MockIRedelegationGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Redelegation, error)) *MockIRedelegationGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIRedelegation) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIRedelegationMockRecorder) IsNoRows(err any) *MockIRedelegationIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIRedelegation)(nil).IsNoRows), err)
return &MockIRedelegationIsNoRowsCall{Call: call}
}
// MockIRedelegationIsNoRowsCall wrap *gomock.Call
type MockIRedelegationIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationIsNoRowsCall) Return(arg0 bool) *MockIRedelegationIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationIsNoRowsCall) Do(f func(error) bool) *MockIRedelegationIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIRedelegationIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIRedelegation) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIRedelegationMockRecorder) LastID(ctx any) *MockIRedelegationLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIRedelegation)(nil).LastID), ctx)
return &MockIRedelegationLastIDCall{Call: call}
}
// MockIRedelegationLastIDCall wrap *gomock.Call
type MockIRedelegationLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationLastIDCall) Return(arg0 uint64, arg1 error) *MockIRedelegationLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIRedelegationLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIRedelegationLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIRedelegation) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Redelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Redelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIRedelegationMockRecorder) List(ctx, limit, offset, order any) *MockIRedelegationListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIRedelegation)(nil).List), ctx, limit, offset, order)
return &MockIRedelegationListCall{Call: call}
}
// MockIRedelegationListCall wrap *gomock.Call
type MockIRedelegationListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationListCall) Return(arg0 []*storage.Redelegation, arg1 error) *MockIRedelegationListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Redelegation, error)) *MockIRedelegationListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Redelegation, error)) *MockIRedelegationListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIRedelegation) Save(ctx context.Context, m *storage.Redelegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIRedelegationMockRecorder) Save(ctx, m any) *MockIRedelegationSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIRedelegation)(nil).Save), ctx, m)
return &MockIRedelegationSaveCall{Call: call}
}
// MockIRedelegationSaveCall wrap *gomock.Call
type MockIRedelegationSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationSaveCall) Return(arg0 error) *MockIRedelegationSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationSaveCall) Do(f func(context.Context, *storage.Redelegation) error) *MockIRedelegationSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationSaveCall) DoAndReturn(f func(context.Context, *storage.Redelegation) error) *MockIRedelegationSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIRedelegation) Update(ctx context.Context, m *storage.Redelegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIRedelegationMockRecorder) Update(ctx, m any) *MockIRedelegationUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIRedelegation)(nil).Update), ctx, m)
return &MockIRedelegationUpdateCall{Call: call}
}
// MockIRedelegationUpdateCall wrap *gomock.Call
type MockIRedelegationUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRedelegationUpdateCall) Return(arg0 error) *MockIRedelegationUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRedelegationUpdateCall) Do(f func(context.Context, *storage.Redelegation) error) *MockIRedelegationUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRedelegationUpdateCall) DoAndReturn(f func(context.Context, *storage.Redelegation) error) *MockIRedelegationUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: rollup.go
//
// Generated by this command:
//
// mockgen -source=rollup.go -destination=mock/rollup.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIRollup is a mock of IRollup interface.
type MockIRollup struct {
ctrl *gomock.Controller
recorder *MockIRollupMockRecorder
}
// MockIRollupMockRecorder is the mock recorder for MockIRollup.
type MockIRollupMockRecorder struct {
mock *MockIRollup
}
// NewMockIRollup creates a new mock instance.
func NewMockIRollup(ctrl *gomock.Controller) *MockIRollup {
mock := &MockIRollup{ctrl: ctrl}
mock.recorder = &MockIRollupMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIRollup) EXPECT() *MockIRollupMockRecorder {
return m.recorder
}
// AllSeries mocks base method.
func (m *MockIRollup) AllSeries(ctx context.Context, timeframe storage.Timeframe) ([]storage.RollupHistogramItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AllSeries", ctx, timeframe)
ret0, _ := ret[0].([]storage.RollupHistogramItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AllSeries indicates an expected call of AllSeries.
func (mr *MockIRollupMockRecorder) AllSeries(ctx, timeframe any) *MockIRollupAllSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllSeries", reflect.TypeOf((*MockIRollup)(nil).AllSeries), ctx, timeframe)
return &MockIRollupAllSeriesCall{Call: call}
}
// MockIRollupAllSeriesCall wrap *gomock.Call
type MockIRollupAllSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupAllSeriesCall) Return(arg0 []storage.RollupHistogramItem, arg1 error) *MockIRollupAllSeriesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupAllSeriesCall) Do(f func(context.Context, storage.Timeframe) ([]storage.RollupHistogramItem, error)) *MockIRollupAllSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupAllSeriesCall) DoAndReturn(f func(context.Context, storage.Timeframe) ([]storage.RollupHistogramItem, error)) *MockIRollupAllSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ById mocks base method.
func (m *MockIRollup) ById(ctx context.Context, rollupId uint64) (storage.RollupWithStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ById", ctx, rollupId)
ret0, _ := ret[0].(storage.RollupWithStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ById indicates an expected call of ById.
func (mr *MockIRollupMockRecorder) ById(ctx, rollupId any) *MockIRollupByIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ById", reflect.TypeOf((*MockIRollup)(nil).ById), ctx, rollupId)
return &MockIRollupByIdCall{Call: call}
}
// MockIRollupByIdCall wrap *gomock.Call
type MockIRollupByIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupByIdCall) Return(arg0 storage.RollupWithStats, arg1 error) *MockIRollupByIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupByIdCall) Do(f func(context.Context, uint64) (storage.RollupWithStats, error)) *MockIRollupByIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupByIdCall) DoAndReturn(f func(context.Context, uint64) (storage.RollupWithStats, error)) *MockIRollupByIdCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BySlug mocks base method.
func (m *MockIRollup) BySlug(ctx context.Context, slug string) (storage.RollupWithStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BySlug", ctx, slug)
ret0, _ := ret[0].(storage.RollupWithStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BySlug indicates an expected call of BySlug.
func (mr *MockIRollupMockRecorder) BySlug(ctx, slug any) *MockIRollupBySlugCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BySlug", reflect.TypeOf((*MockIRollup)(nil).BySlug), ctx, slug)
return &MockIRollupBySlugCall{Call: call}
}
// MockIRollupBySlugCall wrap *gomock.Call
type MockIRollupBySlugCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupBySlugCall) Return(arg0 storage.RollupWithStats, arg1 error) *MockIRollupBySlugCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupBySlugCall) Do(f func(context.Context, string) (storage.RollupWithStats, error)) *MockIRollupBySlugCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupBySlugCall) DoAndReturn(f func(context.Context, string) (storage.RollupWithStats, error)) *MockIRollupBySlugCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Count mocks base method.
func (m *MockIRollup) Count(ctx context.Context) (int64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Count", ctx)
ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Count indicates an expected call of Count.
func (mr *MockIRollupMockRecorder) Count(ctx any) *MockIRollupCountCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Count", reflect.TypeOf((*MockIRollup)(nil).Count), ctx)
return &MockIRollupCountCall{Call: call}
}
// MockIRollupCountCall wrap *gomock.Call
type MockIRollupCountCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupCountCall) Return(arg0 int64, arg1 error) *MockIRollupCountCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupCountCall) Do(f func(context.Context) (int64, error)) *MockIRollupCountCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupCountCall) DoAndReturn(f func(context.Context) (int64, error)) *MockIRollupCountCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIRollup) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Rollup, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Rollup)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIRollupMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIRollupCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIRollup)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIRollupCursorListCall{Call: call}
}
// MockIRollupCursorListCall wrap *gomock.Call
type MockIRollupCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupCursorListCall) Return(arg0 []*storage.Rollup, arg1 error) *MockIRollupCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Rollup, error)) *MockIRollupCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Rollup, error)) *MockIRollupCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Distribution mocks base method.
func (m *MockIRollup) Distribution(ctx context.Context, rollupId uint64, series string, groupBy storage.Timeframe) ([]storage.DistributionItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Distribution", ctx, rollupId, series, groupBy)
ret0, _ := ret[0].([]storage.DistributionItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Distribution indicates an expected call of Distribution.
func (mr *MockIRollupMockRecorder) Distribution(ctx, rollupId, series, groupBy any) *MockIRollupDistributionCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Distribution", reflect.TypeOf((*MockIRollup)(nil).Distribution), ctx, rollupId, series, groupBy)
return &MockIRollupDistributionCall{Call: call}
}
// MockIRollupDistributionCall wrap *gomock.Call
type MockIRollupDistributionCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupDistributionCall) Return(items []storage.DistributionItem, err error) *MockIRollupDistributionCall {
c.Call = c.Call.Return(items, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupDistributionCall) Do(f func(context.Context, uint64, string, storage.Timeframe) ([]storage.DistributionItem, error)) *MockIRollupDistributionCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupDistributionCall) DoAndReturn(f func(context.Context, uint64, string, storage.Timeframe) ([]storage.DistributionItem, error)) *MockIRollupDistributionCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIRollup) GetByID(ctx context.Context, id uint64) (*storage.Rollup, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Rollup)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIRollupMockRecorder) GetByID(ctx, id any) *MockIRollupGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIRollup)(nil).GetByID), ctx, id)
return &MockIRollupGetByIDCall{Call: call}
}
// MockIRollupGetByIDCall wrap *gomock.Call
type MockIRollupGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupGetByIDCall) Return(arg0 *storage.Rollup, arg1 error) *MockIRollupGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupGetByIDCall) Do(f func(context.Context, uint64) (*storage.Rollup, error)) *MockIRollupGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Rollup, error)) *MockIRollupGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIRollup) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIRollupMockRecorder) IsNoRows(err any) *MockIRollupIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIRollup)(nil).IsNoRows), err)
return &MockIRollupIsNoRowsCall{Call: call}
}
// MockIRollupIsNoRowsCall wrap *gomock.Call
type MockIRollupIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupIsNoRowsCall) Return(arg0 bool) *MockIRollupIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupIsNoRowsCall) Do(f func(error) bool) *MockIRollupIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIRollupIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIRollup) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIRollupMockRecorder) LastID(ctx any) *MockIRollupLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIRollup)(nil).LastID), ctx)
return &MockIRollupLastIDCall{Call: call}
}
// MockIRollupLastIDCall wrap *gomock.Call
type MockIRollupLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupLastIDCall) Return(arg0 uint64, arg1 error) *MockIRollupLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIRollupLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIRollupLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Leaderboard mocks base method.
func (m *MockIRollup) Leaderboard(ctx context.Context, fltrs storage.LeaderboardFilters) ([]storage.RollupWithStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Leaderboard", ctx, fltrs)
ret0, _ := ret[0].([]storage.RollupWithStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Leaderboard indicates an expected call of Leaderboard.
func (mr *MockIRollupMockRecorder) Leaderboard(ctx, fltrs any) *MockIRollupLeaderboardCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Leaderboard", reflect.TypeOf((*MockIRollup)(nil).Leaderboard), ctx, fltrs)
return &MockIRollupLeaderboardCall{Call: call}
}
// MockIRollupLeaderboardCall wrap *gomock.Call
type MockIRollupLeaderboardCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupLeaderboardCall) Return(arg0 []storage.RollupWithStats, arg1 error) *MockIRollupLeaderboardCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupLeaderboardCall) Do(f func(context.Context, storage.LeaderboardFilters) ([]storage.RollupWithStats, error)) *MockIRollupLeaderboardCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupLeaderboardCall) DoAndReturn(f func(context.Context, storage.LeaderboardFilters) ([]storage.RollupWithStats, error)) *MockIRollupLeaderboardCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LeaderboardDay mocks base method.
func (m *MockIRollup) LeaderboardDay(ctx context.Context, fltrs storage.LeaderboardFilters) ([]storage.RollupWithDayStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LeaderboardDay", ctx, fltrs)
ret0, _ := ret[0].([]storage.RollupWithDayStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LeaderboardDay indicates an expected call of LeaderboardDay.
func (mr *MockIRollupMockRecorder) LeaderboardDay(ctx, fltrs any) *MockIRollupLeaderboardDayCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LeaderboardDay", reflect.TypeOf((*MockIRollup)(nil).LeaderboardDay), ctx, fltrs)
return &MockIRollupLeaderboardDayCall{Call: call}
}
// MockIRollupLeaderboardDayCall wrap *gomock.Call
type MockIRollupLeaderboardDayCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupLeaderboardDayCall) Return(arg0 []storage.RollupWithDayStats, arg1 error) *MockIRollupLeaderboardDayCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupLeaderboardDayCall) Do(f func(context.Context, storage.LeaderboardFilters) ([]storage.RollupWithDayStats, error)) *MockIRollupLeaderboardDayCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupLeaderboardDayCall) DoAndReturn(f func(context.Context, storage.LeaderboardFilters) ([]storage.RollupWithDayStats, error)) *MockIRollupLeaderboardDayCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIRollup) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Rollup, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Rollup)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIRollupMockRecorder) List(ctx, limit, offset, order any) *MockIRollupListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIRollup)(nil).List), ctx, limit, offset, order)
return &MockIRollupListCall{Call: call}
}
// MockIRollupListCall wrap *gomock.Call
type MockIRollupListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupListCall) Return(arg0 []*storage.Rollup, arg1 error) *MockIRollupListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Rollup, error)) *MockIRollupListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Rollup, error)) *MockIRollupListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Namespaces mocks base method.
func (m *MockIRollup) Namespaces(ctx context.Context, rollupId uint64, limit, offset int) ([]uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Namespaces", ctx, rollupId, limit, offset)
ret0, _ := ret[0].([]uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Namespaces indicates an expected call of Namespaces.
func (mr *MockIRollupMockRecorder) Namespaces(ctx, rollupId, limit, offset any) *MockIRollupNamespacesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Namespaces", reflect.TypeOf((*MockIRollup)(nil).Namespaces), ctx, rollupId, limit, offset)
return &MockIRollupNamespacesCall{Call: call}
}
// MockIRollupNamespacesCall wrap *gomock.Call
type MockIRollupNamespacesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupNamespacesCall) Return(namespaceIds []uint64, err error) *MockIRollupNamespacesCall {
c.Call = c.Call.Return(namespaceIds, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupNamespacesCall) Do(f func(context.Context, uint64, int, int) ([]uint64, error)) *MockIRollupNamespacesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupNamespacesCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]uint64, error)) *MockIRollupNamespacesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Providers mocks base method.
func (m *MockIRollup) Providers(ctx context.Context, rollupId uint64) ([]storage.RollupProvider, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Providers", ctx, rollupId)
ret0, _ := ret[0].([]storage.RollupProvider)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Providers indicates an expected call of Providers.
func (mr *MockIRollupMockRecorder) Providers(ctx, rollupId any) *MockIRollupProvidersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Providers", reflect.TypeOf((*MockIRollup)(nil).Providers), ctx, rollupId)
return &MockIRollupProvidersCall{Call: call}
}
// MockIRollupProvidersCall wrap *gomock.Call
type MockIRollupProvidersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProvidersCall) Return(providers []storage.RollupProvider, err error) *MockIRollupProvidersCall {
c.Call = c.Call.Return(providers, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProvidersCall) Do(f func(context.Context, uint64) ([]storage.RollupProvider, error)) *MockIRollupProvidersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProvidersCall) DoAndReturn(f func(context.Context, uint64) ([]storage.RollupProvider, error)) *MockIRollupProvidersCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollupStatsGrouping mocks base method.
func (m *MockIRollup) RollupStatsGrouping(ctx context.Context, fltrs storage.RollupGroupStatsFilters) ([]storage.RollupGroupedStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollupStatsGrouping", ctx, fltrs)
ret0, _ := ret[0].([]storage.RollupGroupedStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollupStatsGrouping indicates an expected call of RollupStatsGrouping.
func (mr *MockIRollupMockRecorder) RollupStatsGrouping(ctx, fltrs any) *MockIRollupRollupStatsGroupingCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollupStatsGrouping", reflect.TypeOf((*MockIRollup)(nil).RollupStatsGrouping), ctx, fltrs)
return &MockIRollupRollupStatsGroupingCall{Call: call}
}
// MockIRollupRollupStatsGroupingCall wrap *gomock.Call
type MockIRollupRollupStatsGroupingCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupRollupStatsGroupingCall) Return(arg0 []storage.RollupGroupedStats, arg1 error) *MockIRollupRollupStatsGroupingCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupRollupStatsGroupingCall) Do(f func(context.Context, storage.RollupGroupStatsFilters) ([]storage.RollupGroupedStats, error)) *MockIRollupRollupStatsGroupingCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupRollupStatsGroupingCall) DoAndReturn(f func(context.Context, storage.RollupGroupStatsFilters) ([]storage.RollupGroupedStats, error)) *MockIRollupRollupStatsGroupingCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollupsByNamespace mocks base method.
func (m *MockIRollup) RollupsByNamespace(ctx context.Context, namespaceId uint64, limit, offset int) ([]storage.Rollup, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollupsByNamespace", ctx, namespaceId, limit, offset)
ret0, _ := ret[0].([]storage.Rollup)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollupsByNamespace indicates an expected call of RollupsByNamespace.
func (mr *MockIRollupMockRecorder) RollupsByNamespace(ctx, namespaceId, limit, offset any) *MockIRollupRollupsByNamespaceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollupsByNamespace", reflect.TypeOf((*MockIRollup)(nil).RollupsByNamespace), ctx, namespaceId, limit, offset)
return &MockIRollupRollupsByNamespaceCall{Call: call}
}
// MockIRollupRollupsByNamespaceCall wrap *gomock.Call
type MockIRollupRollupsByNamespaceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupRollupsByNamespaceCall) Return(rollups []storage.Rollup, err error) *MockIRollupRollupsByNamespaceCall {
c.Call = c.Call.Return(rollups, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupRollupsByNamespaceCall) Do(f func(context.Context, uint64, int, int) ([]storage.Rollup, error)) *MockIRollupRollupsByNamespaceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupRollupsByNamespaceCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Rollup, error)) *MockIRollupRollupsByNamespaceCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIRollup) Save(ctx context.Context, m *storage.Rollup) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIRollupMockRecorder) Save(ctx, m any) *MockIRollupSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIRollup)(nil).Save), ctx, m)
return &MockIRollupSaveCall{Call: call}
}
// MockIRollupSaveCall wrap *gomock.Call
type MockIRollupSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupSaveCall) Return(arg0 error) *MockIRollupSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupSaveCall) Do(f func(context.Context, *storage.Rollup) error) *MockIRollupSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupSaveCall) DoAndReturn(f func(context.Context, *storage.Rollup) error) *MockIRollupSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Series mocks base method.
func (m *MockIRollup) Series(ctx context.Context, rollupId uint64, timeframe storage.Timeframe, column string, req storage.SeriesRequest) ([]storage.HistogramItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Series", ctx, rollupId, timeframe, column, req)
ret0, _ := ret[0].([]storage.HistogramItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Series indicates an expected call of Series.
func (mr *MockIRollupMockRecorder) Series(ctx, rollupId, timeframe, column, req any) *MockIRollupSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Series", reflect.TypeOf((*MockIRollup)(nil).Series), ctx, rollupId, timeframe, column, req)
return &MockIRollupSeriesCall{Call: call}
}
// MockIRollupSeriesCall wrap *gomock.Call
type MockIRollupSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupSeriesCall) Return(items []storage.HistogramItem, err error) *MockIRollupSeriesCall {
c.Call = c.Call.Return(items, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupSeriesCall) Do(f func(context.Context, uint64, storage.Timeframe, string, storage.SeriesRequest) ([]storage.HistogramItem, error)) *MockIRollupSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupSeriesCall) DoAndReturn(f func(context.Context, uint64, storage.Timeframe, string, storage.SeriesRequest) ([]storage.HistogramItem, error)) *MockIRollupSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Tags mocks base method.
func (m *MockIRollup) Tags(ctx context.Context) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Tags", ctx)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Tags indicates an expected call of Tags.
func (mr *MockIRollupMockRecorder) Tags(ctx any) *MockIRollupTagsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tags", reflect.TypeOf((*MockIRollup)(nil).Tags), ctx)
return &MockIRollupTagsCall{Call: call}
}
// MockIRollupTagsCall wrap *gomock.Call
type MockIRollupTagsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupTagsCall) Return(arg0 []string, arg1 error) *MockIRollupTagsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupTagsCall) Do(f func(context.Context) ([]string, error)) *MockIRollupTagsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupTagsCall) DoAndReturn(f func(context.Context) ([]string, error)) *MockIRollupTagsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Unverified mocks base method.
func (m *MockIRollup) Unverified(ctx context.Context) ([]storage.Rollup, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Unverified", ctx)
ret0, _ := ret[0].([]storage.Rollup)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Unverified indicates an expected call of Unverified.
func (mr *MockIRollupMockRecorder) Unverified(ctx any) *MockIRollupUnverifiedCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unverified", reflect.TypeOf((*MockIRollup)(nil).Unverified), ctx)
return &MockIRollupUnverifiedCall{Call: call}
}
// MockIRollupUnverifiedCall wrap *gomock.Call
type MockIRollupUnverifiedCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupUnverifiedCall) Return(rollups []storage.Rollup, err error) *MockIRollupUnverifiedCall {
c.Call = c.Call.Return(rollups, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupUnverifiedCall) Do(f func(context.Context) ([]storage.Rollup, error)) *MockIRollupUnverifiedCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupUnverifiedCall) DoAndReturn(f func(context.Context) ([]storage.Rollup, error)) *MockIRollupUnverifiedCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIRollup) Update(ctx context.Context, m *storage.Rollup) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIRollupMockRecorder) Update(ctx, m any) *MockIRollupUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIRollup)(nil).Update), ctx, m)
return &MockIRollupUpdateCall{Call: call}
}
// MockIRollupUpdateCall wrap *gomock.Call
type MockIRollupUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupUpdateCall) Return(arg0 error) *MockIRollupUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupUpdateCall) Do(f func(context.Context, *storage.Rollup) error) *MockIRollupUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupUpdateCall) DoAndReturn(f func(context.Context, *storage.Rollup) error) *MockIRollupUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: rollup_provider.go
//
// Generated by this command:
//
// mockgen -source=rollup_provider.go -destination=mock/rollup_provider.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIRollupProvider is a mock of IRollupProvider interface.
type MockIRollupProvider struct {
ctrl *gomock.Controller
recorder *MockIRollupProviderMockRecorder
}
// MockIRollupProviderMockRecorder is the mock recorder for MockIRollupProvider.
type MockIRollupProviderMockRecorder struct {
mock *MockIRollupProvider
}
// NewMockIRollupProvider creates a new mock instance.
func NewMockIRollupProvider(ctrl *gomock.Controller) *MockIRollupProvider {
mock := &MockIRollupProvider{ctrl: ctrl}
mock.recorder = &MockIRollupProviderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIRollupProvider) EXPECT() *MockIRollupProviderMockRecorder {
return m.recorder
}
// CursorList mocks base method.
func (m *MockIRollupProvider) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.RollupProvider, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.RollupProvider)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIRollupProviderMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIRollupProviderCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIRollupProvider)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIRollupProviderCursorListCall{Call: call}
}
// MockIRollupProviderCursorListCall wrap *gomock.Call
type MockIRollupProviderCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderCursorListCall) Return(arg0 []*storage.RollupProvider, arg1 error) *MockIRollupProviderCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.RollupProvider, error)) *MockIRollupProviderCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.RollupProvider, error)) *MockIRollupProviderCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIRollupProvider) GetByID(ctx context.Context, id uint64) (*storage.RollupProvider, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.RollupProvider)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIRollupProviderMockRecorder) GetByID(ctx, id any) *MockIRollupProviderGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIRollupProvider)(nil).GetByID), ctx, id)
return &MockIRollupProviderGetByIDCall{Call: call}
}
// MockIRollupProviderGetByIDCall wrap *gomock.Call
type MockIRollupProviderGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderGetByIDCall) Return(arg0 *storage.RollupProvider, arg1 error) *MockIRollupProviderGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderGetByIDCall) Do(f func(context.Context, uint64) (*storage.RollupProvider, error)) *MockIRollupProviderGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.RollupProvider, error)) *MockIRollupProviderGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIRollupProvider) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIRollupProviderMockRecorder) IsNoRows(err any) *MockIRollupProviderIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIRollupProvider)(nil).IsNoRows), err)
return &MockIRollupProviderIsNoRowsCall{Call: call}
}
// MockIRollupProviderIsNoRowsCall wrap *gomock.Call
type MockIRollupProviderIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderIsNoRowsCall) Return(arg0 bool) *MockIRollupProviderIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderIsNoRowsCall) Do(f func(error) bool) *MockIRollupProviderIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIRollupProviderIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIRollupProvider) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIRollupProviderMockRecorder) LastID(ctx any) *MockIRollupProviderLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIRollupProvider)(nil).LastID), ctx)
return &MockIRollupProviderLastIDCall{Call: call}
}
// MockIRollupProviderLastIDCall wrap *gomock.Call
type MockIRollupProviderLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderLastIDCall) Return(arg0 uint64, arg1 error) *MockIRollupProviderLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIRollupProviderLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIRollupProviderLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIRollupProvider) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.RollupProvider, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.RollupProvider)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIRollupProviderMockRecorder) List(ctx, limit, offset, order any) *MockIRollupProviderListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIRollupProvider)(nil).List), ctx, limit, offset, order)
return &MockIRollupProviderListCall{Call: call}
}
// MockIRollupProviderListCall wrap *gomock.Call
type MockIRollupProviderListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderListCall) Return(arg0 []*storage.RollupProvider, arg1 error) *MockIRollupProviderListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.RollupProvider, error)) *MockIRollupProviderListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.RollupProvider, error)) *MockIRollupProviderListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIRollupProvider) Save(ctx context.Context, m *storage.RollupProvider) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIRollupProviderMockRecorder) Save(ctx, m any) *MockIRollupProviderSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIRollupProvider)(nil).Save), ctx, m)
return &MockIRollupProviderSaveCall{Call: call}
}
// MockIRollupProviderSaveCall wrap *gomock.Call
type MockIRollupProviderSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderSaveCall) Return(arg0 error) *MockIRollupProviderSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderSaveCall) Do(f func(context.Context, *storage.RollupProvider) error) *MockIRollupProviderSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderSaveCall) DoAndReturn(f func(context.Context, *storage.RollupProvider) error) *MockIRollupProviderSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIRollupProvider) Update(ctx context.Context, m *storage.RollupProvider) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIRollupProviderMockRecorder) Update(ctx, m any) *MockIRollupProviderUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIRollupProvider)(nil).Update), ctx, m)
return &MockIRollupProviderUpdateCall{Call: call}
}
// MockIRollupProviderUpdateCall wrap *gomock.Call
type MockIRollupProviderUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIRollupProviderUpdateCall) Return(arg0 error) *MockIRollupProviderUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIRollupProviderUpdateCall) Do(f func(context.Context, *storage.RollupProvider) error) *MockIRollupProviderUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIRollupProviderUpdateCall) DoAndReturn(f func(context.Context, *storage.RollupProvider) error) *MockIRollupProviderUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: staking_log.go
//
// Generated by this command:
//
// mockgen -source=staking_log.go -destination=mock/staking_log.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIStakingLog is a mock of IStakingLog interface.
type MockIStakingLog struct {
ctrl *gomock.Controller
recorder *MockIStakingLogMockRecorder
}
// MockIStakingLogMockRecorder is the mock recorder for MockIStakingLog.
type MockIStakingLogMockRecorder struct {
mock *MockIStakingLog
}
// NewMockIStakingLog creates a new mock instance.
func NewMockIStakingLog(ctrl *gomock.Controller) *MockIStakingLog {
mock := &MockIStakingLog{ctrl: ctrl}
mock.recorder = &MockIStakingLogMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIStakingLog) EXPECT() *MockIStakingLogMockRecorder {
return m.recorder
}
// CursorList mocks base method.
func (m *MockIStakingLog) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.StakingLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.StakingLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIStakingLogMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIStakingLogCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIStakingLog)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIStakingLogCursorListCall{Call: call}
}
// MockIStakingLogCursorListCall wrap *gomock.Call
type MockIStakingLogCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogCursorListCall) Return(arg0 []*storage.StakingLog, arg1 error) *MockIStakingLogCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.StakingLog, error)) *MockIStakingLogCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.StakingLog, error)) *MockIStakingLogCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIStakingLog) GetByID(ctx context.Context, id uint64) (*storage.StakingLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.StakingLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIStakingLogMockRecorder) GetByID(ctx, id any) *MockIStakingLogGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIStakingLog)(nil).GetByID), ctx, id)
return &MockIStakingLogGetByIDCall{Call: call}
}
// MockIStakingLogGetByIDCall wrap *gomock.Call
type MockIStakingLogGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogGetByIDCall) Return(arg0 *storage.StakingLog, arg1 error) *MockIStakingLogGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogGetByIDCall) Do(f func(context.Context, uint64) (*storage.StakingLog, error)) *MockIStakingLogGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.StakingLog, error)) *MockIStakingLogGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIStakingLog) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIStakingLogMockRecorder) IsNoRows(err any) *MockIStakingLogIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIStakingLog)(nil).IsNoRows), err)
return &MockIStakingLogIsNoRowsCall{Call: call}
}
// MockIStakingLogIsNoRowsCall wrap *gomock.Call
type MockIStakingLogIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogIsNoRowsCall) Return(arg0 bool) *MockIStakingLogIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogIsNoRowsCall) Do(f func(error) bool) *MockIStakingLogIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIStakingLogIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIStakingLog) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIStakingLogMockRecorder) LastID(ctx any) *MockIStakingLogLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIStakingLog)(nil).LastID), ctx)
return &MockIStakingLogLastIDCall{Call: call}
}
// MockIStakingLogLastIDCall wrap *gomock.Call
type MockIStakingLogLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogLastIDCall) Return(arg0 uint64, arg1 error) *MockIStakingLogLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIStakingLogLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIStakingLogLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIStakingLog) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.StakingLog, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.StakingLog)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIStakingLogMockRecorder) List(ctx, limit, offset, order any) *MockIStakingLogListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIStakingLog)(nil).List), ctx, limit, offset, order)
return &MockIStakingLogListCall{Call: call}
}
// MockIStakingLogListCall wrap *gomock.Call
type MockIStakingLogListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogListCall) Return(arg0 []*storage.StakingLog, arg1 error) *MockIStakingLogListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.StakingLog, error)) *MockIStakingLogListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.StakingLog, error)) *MockIStakingLogListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIStakingLog) Save(ctx context.Context, m *storage.StakingLog) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIStakingLogMockRecorder) Save(ctx, m any) *MockIStakingLogSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIStakingLog)(nil).Save), ctx, m)
return &MockIStakingLogSaveCall{Call: call}
}
// MockIStakingLogSaveCall wrap *gomock.Call
type MockIStakingLogSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogSaveCall) Return(arg0 error) *MockIStakingLogSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogSaveCall) Do(f func(context.Context, *storage.StakingLog) error) *MockIStakingLogSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogSaveCall) DoAndReturn(f func(context.Context, *storage.StakingLog) error) *MockIStakingLogSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIStakingLog) Update(ctx context.Context, m *storage.StakingLog) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIStakingLogMockRecorder) Update(ctx, m any) *MockIStakingLogUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIStakingLog)(nil).Update), ctx, m)
return &MockIStakingLogUpdateCall{Call: call}
}
// MockIStakingLogUpdateCall wrap *gomock.Call
type MockIStakingLogUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStakingLogUpdateCall) Return(arg0 error) *MockIStakingLogUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStakingLogUpdateCall) Do(f func(context.Context, *storage.StakingLog) error) *MockIStakingLogUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStakingLogUpdateCall) DoAndReturn(f func(context.Context, *storage.StakingLog) error) *MockIStakingLogUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: state.go
//
// Generated by this command:
//
// mockgen -source=state.go -destination=mock/state.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIState is a mock of IState interface.
type MockIState struct {
ctrl *gomock.Controller
recorder *MockIStateMockRecorder
}
// MockIStateMockRecorder is the mock recorder for MockIState.
type MockIStateMockRecorder struct {
mock *MockIState
}
// NewMockIState creates a new mock instance.
func NewMockIState(ctrl *gomock.Controller) *MockIState {
mock := &MockIState{ctrl: ctrl}
mock.recorder = &MockIStateMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIState) EXPECT() *MockIStateMockRecorder {
return m.recorder
}
// ByName mocks base method.
func (m *MockIState) ByName(ctx context.Context, name string) (storage.State, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByName", ctx, name)
ret0, _ := ret[0].(storage.State)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByName indicates an expected call of ByName.
func (mr *MockIStateMockRecorder) ByName(ctx, name any) *MockIStateByNameCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByName", reflect.TypeOf((*MockIState)(nil).ByName), ctx, name)
return &MockIStateByNameCall{Call: call}
}
// MockIStateByNameCall wrap *gomock.Call
type MockIStateByNameCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateByNameCall) Return(arg0 storage.State, arg1 error) *MockIStateByNameCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateByNameCall) Do(f func(context.Context, string) (storage.State, error)) *MockIStateByNameCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateByNameCall) DoAndReturn(f func(context.Context, string) (storage.State, error)) *MockIStateByNameCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIState) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.State, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.State)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIStateMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIStateCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIState)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIStateCursorListCall{Call: call}
}
// MockIStateCursorListCall wrap *gomock.Call
type MockIStateCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateCursorListCall) Return(arg0 []*storage.State, arg1 error) *MockIStateCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.State, error)) *MockIStateCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.State, error)) *MockIStateCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIState) GetByID(ctx context.Context, id uint64) (*storage.State, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.State)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIStateMockRecorder) GetByID(ctx, id any) *MockIStateGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIState)(nil).GetByID), ctx, id)
return &MockIStateGetByIDCall{Call: call}
}
// MockIStateGetByIDCall wrap *gomock.Call
type MockIStateGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateGetByIDCall) Return(arg0 *storage.State, arg1 error) *MockIStateGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateGetByIDCall) Do(f func(context.Context, uint64) (*storage.State, error)) *MockIStateGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.State, error)) *MockIStateGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIState) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIStateMockRecorder) IsNoRows(err any) *MockIStateIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIState)(nil).IsNoRows), err)
return &MockIStateIsNoRowsCall{Call: call}
}
// MockIStateIsNoRowsCall wrap *gomock.Call
type MockIStateIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateIsNoRowsCall) Return(arg0 bool) *MockIStateIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateIsNoRowsCall) Do(f func(error) bool) *MockIStateIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIStateIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIState) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIStateMockRecorder) LastID(ctx any) *MockIStateLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIState)(nil).LastID), ctx)
return &MockIStateLastIDCall{Call: call}
}
// MockIStateLastIDCall wrap *gomock.Call
type MockIStateLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateLastIDCall) Return(arg0 uint64, arg1 error) *MockIStateLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIStateLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIStateLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIState) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.State, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.State)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIStateMockRecorder) List(ctx, limit, offset, order any) *MockIStateListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIState)(nil).List), ctx, limit, offset, order)
return &MockIStateListCall{Call: call}
}
// MockIStateListCall wrap *gomock.Call
type MockIStateListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateListCall) Return(arg0 []*storage.State, arg1 error) *MockIStateListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.State, error)) *MockIStateListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.State, error)) *MockIStateListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIState) Save(ctx context.Context, m *storage.State) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIStateMockRecorder) Save(ctx, m any) *MockIStateSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIState)(nil).Save), ctx, m)
return &MockIStateSaveCall{Call: call}
}
// MockIStateSaveCall wrap *gomock.Call
type MockIStateSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateSaveCall) Return(arg0 error) *MockIStateSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateSaveCall) Do(f func(context.Context, *storage.State) error) *MockIStateSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateSaveCall) DoAndReturn(f func(context.Context, *storage.State) error) *MockIStateSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIState) Update(ctx context.Context, m *storage.State) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIStateMockRecorder) Update(ctx, m any) *MockIStateUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIState)(nil).Update), ctx, m)
return &MockIStateUpdateCall{Call: call}
}
// MockIStateUpdateCall wrap *gomock.Call
type MockIStateUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStateUpdateCall) Return(arg0 error) *MockIStateUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStateUpdateCall) Do(f func(context.Context, *storage.State) error) *MockIStateUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStateUpdateCall) DoAndReturn(f func(context.Context, *storage.State) error) *MockIStateUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: stats.go
//
// Generated by this command:
//
// mockgen -source=stats.go -destination=mock/stats.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIStats is a mock of IStats interface.
type MockIStats struct {
ctrl *gomock.Controller
recorder *MockIStatsMockRecorder
}
// MockIStatsMockRecorder is the mock recorder for MockIStats.
type MockIStatsMockRecorder struct {
mock *MockIStats
}
// NewMockIStats creates a new mock instance.
func NewMockIStats(ctrl *gomock.Controller) *MockIStats {
mock := &MockIStats{ctrl: ctrl}
mock.recorder = &MockIStatsMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIStats) EXPECT() *MockIStatsMockRecorder {
return m.recorder
}
// Change24hBlockStats mocks base method.
func (m *MockIStats) Change24hBlockStats(ctx context.Context) (storage.Change24hBlockStats, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Change24hBlockStats", ctx)
ret0, _ := ret[0].(storage.Change24hBlockStats)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Change24hBlockStats indicates an expected call of Change24hBlockStats.
func (mr *MockIStatsMockRecorder) Change24hBlockStats(ctx any) *MockIStatsChange24hBlockStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Change24hBlockStats", reflect.TypeOf((*MockIStats)(nil).Change24hBlockStats), ctx)
return &MockIStatsChange24hBlockStatsCall{Call: call}
}
// MockIStatsChange24hBlockStatsCall wrap *gomock.Call
type MockIStatsChange24hBlockStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsChange24hBlockStatsCall) Return(response storage.Change24hBlockStats, err error) *MockIStatsChange24hBlockStatsCall {
c.Call = c.Call.Return(response, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsChange24hBlockStatsCall) Do(f func(context.Context) (storage.Change24hBlockStats, error)) *MockIStatsChange24hBlockStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsChange24hBlockStatsCall) DoAndReturn(f func(context.Context) (storage.Change24hBlockStats, error)) *MockIStatsChange24hBlockStatsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Count mocks base method.
func (m *MockIStats) Count(ctx context.Context, req storage.CountRequest) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Count", ctx, req)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Count indicates an expected call of Count.
func (mr *MockIStatsMockRecorder) Count(ctx, req any) *MockIStatsCountCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Count", reflect.TypeOf((*MockIStats)(nil).Count), ctx, req)
return &MockIStatsCountCall{Call: call}
}
// MockIStatsCountCall wrap *gomock.Call
type MockIStatsCountCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsCountCall) Return(arg0 string, arg1 error) *MockIStatsCountCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsCountCall) Do(f func(context.Context, storage.CountRequest) (string, error)) *MockIStatsCountCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsCountCall) DoAndReturn(f func(context.Context, storage.CountRequest) (string, error)) *MockIStatsCountCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CumulativeSeries mocks base method.
func (m *MockIStats) CumulativeSeries(ctx context.Context, timeframe storage.Timeframe, name string, req storage.SeriesRequest) ([]storage.SeriesItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CumulativeSeries", ctx, timeframe, name, req)
ret0, _ := ret[0].([]storage.SeriesItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CumulativeSeries indicates an expected call of CumulativeSeries.
func (mr *MockIStatsMockRecorder) CumulativeSeries(ctx, timeframe, name, req any) *MockIStatsCumulativeSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CumulativeSeries", reflect.TypeOf((*MockIStats)(nil).CumulativeSeries), ctx, timeframe, name, req)
return &MockIStatsCumulativeSeriesCall{Call: call}
}
// MockIStatsCumulativeSeriesCall wrap *gomock.Call
type MockIStatsCumulativeSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsCumulativeSeriesCall) Return(arg0 []storage.SeriesItem, arg1 error) *MockIStatsCumulativeSeriesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsCumulativeSeriesCall) Do(f func(context.Context, storage.Timeframe, string, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsCumulativeSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsCumulativeSeriesCall) DoAndReturn(f func(context.Context, storage.Timeframe, string, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsCumulativeSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MessagesCount24h mocks base method.
func (m *MockIStats) MessagesCount24h(ctx context.Context) ([]storage.CountItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MessagesCount24h", ctx)
ret0, _ := ret[0].([]storage.CountItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// MessagesCount24h indicates an expected call of MessagesCount24h.
func (mr *MockIStatsMockRecorder) MessagesCount24h(ctx any) *MockIStatsMessagesCount24hCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MessagesCount24h", reflect.TypeOf((*MockIStats)(nil).MessagesCount24h), ctx)
return &MockIStatsMessagesCount24hCall{Call: call}
}
// MockIStatsMessagesCount24hCall wrap *gomock.Call
type MockIStatsMessagesCount24hCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsMessagesCount24hCall) Return(arg0 []storage.CountItem, arg1 error) *MockIStatsMessagesCount24hCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsMessagesCount24hCall) Do(f func(context.Context) ([]storage.CountItem, error)) *MockIStatsMessagesCount24hCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsMessagesCount24hCall) DoAndReturn(f func(context.Context) ([]storage.CountItem, error)) *MockIStatsMessagesCount24hCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// NamespaceSeries mocks base method.
func (m *MockIStats) NamespaceSeries(ctx context.Context, timeframe storage.Timeframe, name string, nsId uint64, req storage.SeriesRequest) ([]storage.SeriesItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NamespaceSeries", ctx, timeframe, name, nsId, req)
ret0, _ := ret[0].([]storage.SeriesItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NamespaceSeries indicates an expected call of NamespaceSeries.
func (mr *MockIStatsMockRecorder) NamespaceSeries(ctx, timeframe, name, nsId, req any) *MockIStatsNamespaceSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NamespaceSeries", reflect.TypeOf((*MockIStats)(nil).NamespaceSeries), ctx, timeframe, name, nsId, req)
return &MockIStatsNamespaceSeriesCall{Call: call}
}
// MockIStatsNamespaceSeriesCall wrap *gomock.Call
type MockIStatsNamespaceSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsNamespaceSeriesCall) Return(response []storage.SeriesItem, err error) *MockIStatsNamespaceSeriesCall {
c.Call = c.Call.Return(response, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsNamespaceSeriesCall) Do(f func(context.Context, storage.Timeframe, string, uint64, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsNamespaceSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsNamespaceSeriesCall) DoAndReturn(f func(context.Context, storage.Timeframe, string, uint64, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsNamespaceSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollupStats24h mocks base method.
func (m *MockIStats) RollupStats24h(ctx context.Context) ([]storage.RollupStats24h, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollupStats24h", ctx)
ret0, _ := ret[0].([]storage.RollupStats24h)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollupStats24h indicates an expected call of RollupStats24h.
func (mr *MockIStatsMockRecorder) RollupStats24h(ctx any) *MockIStatsRollupStats24hCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollupStats24h", reflect.TypeOf((*MockIStats)(nil).RollupStats24h), ctx)
return &MockIStatsRollupStats24hCall{Call: call}
}
// MockIStatsRollupStats24hCall wrap *gomock.Call
type MockIStatsRollupStats24hCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsRollupStats24hCall) Return(arg0 []storage.RollupStats24h, arg1 error) *MockIStatsRollupStats24hCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsRollupStats24hCall) Do(f func(context.Context) ([]storage.RollupStats24h, error)) *MockIStatsRollupStats24hCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsRollupStats24hCall) DoAndReturn(f func(context.Context) ([]storage.RollupStats24h, error)) *MockIStatsRollupStats24hCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Series mocks base method.
func (m *MockIStats) Series(ctx context.Context, timeframe storage.Timeframe, name string, req storage.SeriesRequest) ([]storage.SeriesItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Series", ctx, timeframe, name, req)
ret0, _ := ret[0].([]storage.SeriesItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Series indicates an expected call of Series.
func (mr *MockIStatsMockRecorder) Series(ctx, timeframe, name, req any) *MockIStatsSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Series", reflect.TypeOf((*MockIStats)(nil).Series), ctx, timeframe, name, req)
return &MockIStatsSeriesCall{Call: call}
}
// MockIStatsSeriesCall wrap *gomock.Call
type MockIStatsSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsSeriesCall) Return(arg0 []storage.SeriesItem, arg1 error) *MockIStatsSeriesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsSeriesCall) Do(f func(context.Context, storage.Timeframe, string, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsSeriesCall) DoAndReturn(f func(context.Context, storage.Timeframe, string, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SquareSize mocks base method.
func (m *MockIStats) SquareSize(ctx context.Context, from, to *time.Time) (map[int][]storage.SeriesItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SquareSize", ctx, from, to)
ret0, _ := ret[0].(map[int][]storage.SeriesItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SquareSize indicates an expected call of SquareSize.
func (mr *MockIStatsMockRecorder) SquareSize(ctx, from, to any) *MockIStatsSquareSizeCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SquareSize", reflect.TypeOf((*MockIStats)(nil).SquareSize), ctx, from, to)
return &MockIStatsSquareSizeCall{Call: call}
}
// MockIStatsSquareSizeCall wrap *gomock.Call
type MockIStatsSquareSizeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsSquareSizeCall) Return(arg0 map[int][]storage.SeriesItem, arg1 error) *MockIStatsSquareSizeCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsSquareSizeCall) Do(f func(context.Context, *time.Time, *time.Time) (map[int][]storage.SeriesItem, error)) *MockIStatsSquareSizeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsSquareSizeCall) DoAndReturn(f func(context.Context, *time.Time, *time.Time) (map[int][]storage.SeriesItem, error)) *MockIStatsSquareSizeCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// StakingSeries mocks base method.
func (m *MockIStats) StakingSeries(ctx context.Context, timeframe storage.Timeframe, name string, validatorId uint64, req storage.SeriesRequest) ([]storage.SeriesItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StakingSeries", ctx, timeframe, name, validatorId, req)
ret0, _ := ret[0].([]storage.SeriesItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StakingSeries indicates an expected call of StakingSeries.
func (mr *MockIStatsMockRecorder) StakingSeries(ctx, timeframe, name, validatorId, req any) *MockIStatsStakingSeriesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StakingSeries", reflect.TypeOf((*MockIStats)(nil).StakingSeries), ctx, timeframe, name, validatorId, req)
return &MockIStatsStakingSeriesCall{Call: call}
}
// MockIStatsStakingSeriesCall wrap *gomock.Call
type MockIStatsStakingSeriesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsStakingSeriesCall) Return(response []storage.SeriesItem, err error) *MockIStatsStakingSeriesCall {
c.Call = c.Call.Return(response, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsStakingSeriesCall) Do(f func(context.Context, storage.Timeframe, string, uint64, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsStakingSeriesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsStakingSeriesCall) DoAndReturn(f func(context.Context, storage.Timeframe, string, uint64, storage.SeriesRequest) ([]storage.SeriesItem, error)) *MockIStatsStakingSeriesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Summary mocks base method.
func (m *MockIStats) Summary(ctx context.Context, req storage.SummaryRequest) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Summary", ctx, req)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Summary indicates an expected call of Summary.
func (mr *MockIStatsMockRecorder) Summary(ctx, req any) *MockIStatsSummaryCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockIStats)(nil).Summary), ctx, req)
return &MockIStatsSummaryCall{Call: call}
}
// MockIStatsSummaryCall wrap *gomock.Call
type MockIStatsSummaryCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsSummaryCall) Return(arg0 string, arg1 error) *MockIStatsSummaryCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsSummaryCall) Do(f func(context.Context, storage.SummaryRequest) (string, error)) *MockIStatsSummaryCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsSummaryCall) DoAndReturn(f func(context.Context, storage.SummaryRequest) (string, error)) *MockIStatsSummaryCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// TPS mocks base method.
func (m *MockIStats) TPS(ctx context.Context) (storage.TPS, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TPS", ctx)
ret0, _ := ret[0].(storage.TPS)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TPS indicates an expected call of TPS.
func (mr *MockIStatsMockRecorder) TPS(ctx any) *MockIStatsTPSCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TPS", reflect.TypeOf((*MockIStats)(nil).TPS), ctx)
return &MockIStatsTPSCall{Call: call}
}
// MockIStatsTPSCall wrap *gomock.Call
type MockIStatsTPSCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIStatsTPSCall) Return(arg0 storage.TPS, arg1 error) *MockIStatsTPSCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIStatsTPSCall) Do(f func(context.Context) (storage.TPS, error)) *MockIStatsTPSCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIStatsTPSCall) DoAndReturn(f func(context.Context) (storage.TPS, error)) *MockIStatsTPSCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: tx.go
//
// Generated by this command:
//
// mockgen -source=tx.go -destination=mock/tx.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
time "time"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
types "github.com/celenium-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockITx is a mock of ITx interface.
type MockITx struct {
ctrl *gomock.Controller
recorder *MockITxMockRecorder
}
// MockITxMockRecorder is the mock recorder for MockITx.
type MockITxMockRecorder struct {
mock *MockITx
}
// NewMockITx creates a new mock instance.
func NewMockITx(ctrl *gomock.Controller) *MockITx {
mock := &MockITx{ctrl: ctrl}
mock.recorder = &MockITxMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockITx) EXPECT() *MockITxMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockITx) ByAddress(ctx context.Context, addressId uint64, fltrs storage.TxFilter) ([]storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, addressId, fltrs)
ret0, _ := ret[0].([]storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockITxMockRecorder) ByAddress(ctx, addressId, fltrs any) *MockITxByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockITx)(nil).ByAddress), ctx, addressId, fltrs)
return &MockITxByAddressCall{Call: call}
}
// MockITxByAddressCall wrap *gomock.Call
type MockITxByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxByAddressCall) Return(arg0 []storage.Tx, arg1 error) *MockITxByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxByAddressCall) Do(f func(context.Context, uint64, storage.TxFilter) ([]storage.Tx, error)) *MockITxByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxByAddressCall) DoAndReturn(f func(context.Context, uint64, storage.TxFilter) ([]storage.Tx, error)) *MockITxByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByHash mocks base method.
func (m *MockITx) ByHash(ctx context.Context, hash []byte) (storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByHash", ctx, hash)
ret0, _ := ret[0].(storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByHash indicates an expected call of ByHash.
func (mr *MockITxMockRecorder) ByHash(ctx, hash any) *MockITxByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockITx)(nil).ByHash), ctx, hash)
return &MockITxByHashCall{Call: call}
}
// MockITxByHashCall wrap *gomock.Call
type MockITxByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxByHashCall) Return(arg0 storage.Tx, arg1 error) *MockITxByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxByHashCall) Do(f func(context.Context, []byte) (storage.Tx, error)) *MockITxByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Tx, error)) *MockITxByHashCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByIdWithRelations mocks base method.
func (m *MockITx) ByIdWithRelations(ctx context.Context, id uint64) (storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByIdWithRelations", ctx, id)
ret0, _ := ret[0].(storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByIdWithRelations indicates an expected call of ByIdWithRelations.
func (mr *MockITxMockRecorder) ByIdWithRelations(ctx, id any) *MockITxByIdWithRelationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByIdWithRelations", reflect.TypeOf((*MockITx)(nil).ByIdWithRelations), ctx, id)
return &MockITxByIdWithRelationsCall{Call: call}
}
// MockITxByIdWithRelationsCall wrap *gomock.Call
type MockITxByIdWithRelationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxByIdWithRelationsCall) Return(arg0 storage.Tx, arg1 error) *MockITxByIdWithRelationsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxByIdWithRelationsCall) Do(f func(context.Context, uint64) (storage.Tx, error)) *MockITxByIdWithRelationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxByIdWithRelationsCall) DoAndReturn(f func(context.Context, uint64) (storage.Tx, error)) *MockITxByIdWithRelationsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockITx) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockITxMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockITxCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockITx)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockITxCursorListCall{Call: call}
}
// MockITxCursorListCall wrap *gomock.Call
type MockITxCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxCursorListCall) Return(arg0 []*storage.Tx, arg1 error) *MockITxCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Tx, error)) *MockITxCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Tx, error)) *MockITxCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Filter mocks base method.
func (m *MockITx) Filter(ctx context.Context, fltrs storage.TxFilter) ([]storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Filter", ctx, fltrs)
ret0, _ := ret[0].([]storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Filter indicates an expected call of Filter.
func (mr *MockITxMockRecorder) Filter(ctx, fltrs any) *MockITxFilterCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Filter", reflect.TypeOf((*MockITx)(nil).Filter), ctx, fltrs)
return &MockITxFilterCall{Call: call}
}
// MockITxFilterCall wrap *gomock.Call
type MockITxFilterCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxFilterCall) Return(arg0 []storage.Tx, arg1 error) *MockITxFilterCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxFilterCall) Do(f func(context.Context, storage.TxFilter) ([]storage.Tx, error)) *MockITxFilterCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxFilterCall) DoAndReturn(f func(context.Context, storage.TxFilter) ([]storage.Tx, error)) *MockITxFilterCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Gas mocks base method.
func (m *MockITx) Gas(ctx context.Context, height types.Level, ts time.Time) ([]storage.Gas, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Gas", ctx, height, ts)
ret0, _ := ret[0].([]storage.Gas)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Gas indicates an expected call of Gas.
func (mr *MockITxMockRecorder) Gas(ctx, height, ts any) *MockITxGasCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Gas", reflect.TypeOf((*MockITx)(nil).Gas), ctx, height, ts)
return &MockITxGasCall{Call: call}
}
// MockITxGasCall wrap *gomock.Call
type MockITxGasCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxGasCall) Return(arg0 []storage.Gas, arg1 error) *MockITxGasCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxGasCall) Do(f func(context.Context, types.Level, time.Time) ([]storage.Gas, error)) *MockITxGasCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxGasCall) DoAndReturn(f func(context.Context, types.Level, time.Time) ([]storage.Gas, error)) *MockITxGasCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Genesis mocks base method.
func (m *MockITx) Genesis(ctx context.Context, limit, offset int, sortOrder storage0.SortOrder) ([]storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Genesis", ctx, limit, offset, sortOrder)
ret0, _ := ret[0].([]storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Genesis indicates an expected call of Genesis.
func (mr *MockITxMockRecorder) Genesis(ctx, limit, offset, sortOrder any) *MockITxGenesisCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockITx)(nil).Genesis), ctx, limit, offset, sortOrder)
return &MockITxGenesisCall{Call: call}
}
// MockITxGenesisCall wrap *gomock.Call
type MockITxGenesisCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxGenesisCall) Return(arg0 []storage.Tx, arg1 error) *MockITxGenesisCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxGenesisCall) Do(f func(context.Context, int, int, storage0.SortOrder) ([]storage.Tx, error)) *MockITxGenesisCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxGenesisCall) DoAndReturn(f func(context.Context, int, int, storage0.SortOrder) ([]storage.Tx, error)) *MockITxGenesisCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockITx) GetByID(ctx context.Context, id uint64) (*storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockITxMockRecorder) GetByID(ctx, id any) *MockITxGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockITx)(nil).GetByID), ctx, id)
return &MockITxGetByIDCall{Call: call}
}
// MockITxGetByIDCall wrap *gomock.Call
type MockITxGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxGetByIDCall) Return(arg0 *storage.Tx, arg1 error) *MockITxGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxGetByIDCall) Do(f func(context.Context, uint64) (*storage.Tx, error)) *MockITxGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Tx, error)) *MockITxGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IdAndTimeByHash mocks base method.
func (m *MockITx) IdAndTimeByHash(ctx context.Context, hash []byte) (uint64, time.Time, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IdAndTimeByHash", ctx, hash)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(time.Time)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// IdAndTimeByHash indicates an expected call of IdAndTimeByHash.
func (mr *MockITxMockRecorder) IdAndTimeByHash(ctx, hash any) *MockITxIdAndTimeByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdAndTimeByHash", reflect.TypeOf((*MockITx)(nil).IdAndTimeByHash), ctx, hash)
return &MockITxIdAndTimeByHashCall{Call: call}
}
// MockITxIdAndTimeByHashCall wrap *gomock.Call
type MockITxIdAndTimeByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxIdAndTimeByHashCall) Return(arg0 uint64, arg1 time.Time, arg2 error) *MockITxIdAndTimeByHashCall {
c.Call = c.Call.Return(arg0, arg1, arg2)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxIdAndTimeByHashCall) Do(f func(context.Context, []byte) (uint64, time.Time, error)) *MockITxIdAndTimeByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxIdAndTimeByHashCall) DoAndReturn(f func(context.Context, []byte) (uint64, time.Time, error)) *MockITxIdAndTimeByHashCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockITx) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockITxMockRecorder) IsNoRows(err any) *MockITxIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockITx)(nil).IsNoRows), err)
return &MockITxIsNoRowsCall{Call: call}
}
// MockITxIsNoRowsCall wrap *gomock.Call
type MockITxIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxIsNoRowsCall) Return(arg0 bool) *MockITxIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxIsNoRowsCall) Do(f func(error) bool) *MockITxIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxIsNoRowsCall) DoAndReturn(f func(error) bool) *MockITxIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockITx) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockITxMockRecorder) LastID(ctx any) *MockITxLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockITx)(nil).LastID), ctx)
return &MockITxLastIDCall{Call: call}
}
// MockITxLastIDCall wrap *gomock.Call
type MockITxLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxLastIDCall) Return(arg0 uint64, arg1 error) *MockITxLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxLastIDCall) Do(f func(context.Context) (uint64, error)) *MockITxLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockITxLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockITx) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Tx, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Tx)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockITxMockRecorder) List(ctx, limit, offset, order any) *MockITxListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockITx)(nil).List), ctx, limit, offset, order)
return &MockITxListCall{Call: call}
}
// MockITxListCall wrap *gomock.Call
type MockITxListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxListCall) Return(arg0 []*storage.Tx, arg1 error) *MockITxListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Tx, error)) *MockITxListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Tx, error)) *MockITxListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockITx) Save(ctx context.Context, m *storage.Tx) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockITxMockRecorder) Save(ctx, m any) *MockITxSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockITx)(nil).Save), ctx, m)
return &MockITxSaveCall{Call: call}
}
// MockITxSaveCall wrap *gomock.Call
type MockITxSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxSaveCall) Return(arg0 error) *MockITxSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxSaveCall) Do(f func(context.Context, *storage.Tx) error) *MockITxSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxSaveCall) DoAndReturn(f func(context.Context, *storage.Tx) error) *MockITxSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockITx) Update(ctx context.Context, m *storage.Tx) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockITxMockRecorder) Update(ctx, m any) *MockITxUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockITx)(nil).Update), ctx, m)
return &MockITxUpdateCall{Call: call}
}
// MockITxUpdateCall wrap *gomock.Call
type MockITxUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockITxUpdateCall) Return(arg0 error) *MockITxUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockITxUpdateCall) Do(f func(context.Context, *storage.Tx) error) *MockITxUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockITxUpdateCall) DoAndReturn(f func(context.Context, *storage.Tx) error) *MockITxUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: undelegation.go
//
// Generated by this command:
//
// mockgen -source=undelegation.go -destination=mock/undelegation.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIUndelegation is a mock of IUndelegation interface.
type MockIUndelegation struct {
ctrl *gomock.Controller
recorder *MockIUndelegationMockRecorder
}
// MockIUndelegationMockRecorder is the mock recorder for MockIUndelegation.
type MockIUndelegationMockRecorder struct {
mock *MockIUndelegation
}
// NewMockIUndelegation creates a new mock instance.
func NewMockIUndelegation(ctrl *gomock.Controller) *MockIUndelegation {
mock := &MockIUndelegation{ctrl: ctrl}
mock.recorder = &MockIUndelegationMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIUndelegation) EXPECT() *MockIUndelegationMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIUndelegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int) ([]storage.Undelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, addressId, limit, offset)
ret0, _ := ret[0].([]storage.Undelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIUndelegationMockRecorder) ByAddress(ctx, addressId, limit, offset any) *MockIUndelegationByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIUndelegation)(nil).ByAddress), ctx, addressId, limit, offset)
return &MockIUndelegationByAddressCall{Call: call}
}
// MockIUndelegationByAddressCall wrap *gomock.Call
type MockIUndelegationByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationByAddressCall) Return(arg0 []storage.Undelegation, arg1 error) *MockIUndelegationByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationByAddressCall) Do(f func(context.Context, uint64, int, int) ([]storage.Undelegation, error)) *MockIUndelegationByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationByAddressCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.Undelegation, error)) *MockIUndelegationByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIUndelegation) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Undelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Undelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIUndelegationMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIUndelegationCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIUndelegation)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIUndelegationCursorListCall{Call: call}
}
// MockIUndelegationCursorListCall wrap *gomock.Call
type MockIUndelegationCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationCursorListCall) Return(arg0 []*storage.Undelegation, arg1 error) *MockIUndelegationCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Undelegation, error)) *MockIUndelegationCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Undelegation, error)) *MockIUndelegationCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIUndelegation) GetByID(ctx context.Context, id uint64) (*storage.Undelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Undelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIUndelegationMockRecorder) GetByID(ctx, id any) *MockIUndelegationGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIUndelegation)(nil).GetByID), ctx, id)
return &MockIUndelegationGetByIDCall{Call: call}
}
// MockIUndelegationGetByIDCall wrap *gomock.Call
type MockIUndelegationGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationGetByIDCall) Return(arg0 *storage.Undelegation, arg1 error) *MockIUndelegationGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationGetByIDCall) Do(f func(context.Context, uint64) (*storage.Undelegation, error)) *MockIUndelegationGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Undelegation, error)) *MockIUndelegationGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIUndelegation) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIUndelegationMockRecorder) IsNoRows(err any) *MockIUndelegationIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIUndelegation)(nil).IsNoRows), err)
return &MockIUndelegationIsNoRowsCall{Call: call}
}
// MockIUndelegationIsNoRowsCall wrap *gomock.Call
type MockIUndelegationIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationIsNoRowsCall) Return(arg0 bool) *MockIUndelegationIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationIsNoRowsCall) Do(f func(error) bool) *MockIUndelegationIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIUndelegationIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIUndelegation) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIUndelegationMockRecorder) LastID(ctx any) *MockIUndelegationLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIUndelegation)(nil).LastID), ctx)
return &MockIUndelegationLastIDCall{Call: call}
}
// MockIUndelegationLastIDCall wrap *gomock.Call
type MockIUndelegationLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationLastIDCall) Return(arg0 uint64, arg1 error) *MockIUndelegationLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIUndelegationLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIUndelegationLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIUndelegation) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Undelegation, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Undelegation)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIUndelegationMockRecorder) List(ctx, limit, offset, order any) *MockIUndelegationListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIUndelegation)(nil).List), ctx, limit, offset, order)
return &MockIUndelegationListCall{Call: call}
}
// MockIUndelegationListCall wrap *gomock.Call
type MockIUndelegationListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationListCall) Return(arg0 []*storage.Undelegation, arg1 error) *MockIUndelegationListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Undelegation, error)) *MockIUndelegationListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Undelegation, error)) *MockIUndelegationListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIUndelegation) Save(ctx context.Context, m *storage.Undelegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIUndelegationMockRecorder) Save(ctx, m any) *MockIUndelegationSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIUndelegation)(nil).Save), ctx, m)
return &MockIUndelegationSaveCall{Call: call}
}
// MockIUndelegationSaveCall wrap *gomock.Call
type MockIUndelegationSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationSaveCall) Return(arg0 error) *MockIUndelegationSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationSaveCall) Do(f func(context.Context, *storage.Undelegation) error) *MockIUndelegationSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationSaveCall) DoAndReturn(f func(context.Context, *storage.Undelegation) error) *MockIUndelegationSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIUndelegation) Update(ctx context.Context, m *storage.Undelegation) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIUndelegationMockRecorder) Update(ctx, m any) *MockIUndelegationUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIUndelegation)(nil).Update), ctx, m)
return &MockIUndelegationUpdateCall{Call: call}
}
// MockIUndelegationUpdateCall wrap *gomock.Call
type MockIUndelegationUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIUndelegationUpdateCall) Return(arg0 error) *MockIUndelegationUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIUndelegationUpdateCall) Do(f func(context.Context, *storage.Undelegation) error) *MockIUndelegationUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIUndelegationUpdateCall) DoAndReturn(f func(context.Context, *storage.Undelegation) error) *MockIUndelegationUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: validator.go
//
// Generated by this command:
//
// mockgen -source=validator.go -destination=mock/validator.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
decimal "github.com/shopspring/decimal"
gomock "go.uber.org/mock/gomock"
)
// MockIValidator is a mock of IValidator interface.
type MockIValidator struct {
ctrl *gomock.Controller
recorder *MockIValidatorMockRecorder
}
// MockIValidatorMockRecorder is the mock recorder for MockIValidator.
type MockIValidatorMockRecorder struct {
mock *MockIValidator
}
// NewMockIValidator creates a new mock instance.
func NewMockIValidator(ctrl *gomock.Controller) *MockIValidator {
mock := &MockIValidator{ctrl: ctrl}
mock.recorder = &MockIValidatorMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIValidator) EXPECT() *MockIValidatorMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIValidator) ByAddress(ctx context.Context, address string) (storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, address)
ret0, _ := ret[0].(storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIValidatorMockRecorder) ByAddress(ctx, address any) *MockIValidatorByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIValidator)(nil).ByAddress), ctx, address)
return &MockIValidatorByAddressCall{Call: call}
}
// MockIValidatorByAddressCall wrap *gomock.Call
type MockIValidatorByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorByAddressCall) Return(arg0 storage.Validator, arg1 error) *MockIValidatorByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorByAddressCall) Do(f func(context.Context, string) (storage.Validator, error)) *MockIValidatorByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorByAddressCall) DoAndReturn(f func(context.Context, string) (storage.Validator, error)) *MockIValidatorByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIValidator) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIValidatorMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIValidatorCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIValidator)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIValidatorCursorListCall{Call: call}
}
// MockIValidatorCursorListCall wrap *gomock.Call
type MockIValidatorCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorCursorListCall) Return(arg0 []*storage.Validator, arg1 error) *MockIValidatorCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Validator, error)) *MockIValidatorCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Validator, error)) *MockIValidatorCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIValidator) GetByID(ctx context.Context, id uint64) (*storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIValidatorMockRecorder) GetByID(ctx, id any) *MockIValidatorGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIValidator)(nil).GetByID), ctx, id)
return &MockIValidatorGetByIDCall{Call: call}
}
// MockIValidatorGetByIDCall wrap *gomock.Call
type MockIValidatorGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorGetByIDCall) Return(arg0 *storage.Validator, arg1 error) *MockIValidatorGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorGetByIDCall) Do(f func(context.Context, uint64) (*storage.Validator, error)) *MockIValidatorGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Validator, error)) *MockIValidatorGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIValidator) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIValidatorMockRecorder) IsNoRows(err any) *MockIValidatorIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIValidator)(nil).IsNoRows), err)
return &MockIValidatorIsNoRowsCall{Call: call}
}
// MockIValidatorIsNoRowsCall wrap *gomock.Call
type MockIValidatorIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorIsNoRowsCall) Return(arg0 bool) *MockIValidatorIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorIsNoRowsCall) Do(f func(error) bool) *MockIValidatorIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIValidatorIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// JailedCount mocks base method.
func (m *MockIValidator) JailedCount(ctx context.Context) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "JailedCount", ctx)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// JailedCount indicates an expected call of JailedCount.
func (mr *MockIValidatorMockRecorder) JailedCount(ctx any) *MockIValidatorJailedCountCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JailedCount", reflect.TypeOf((*MockIValidator)(nil).JailedCount), ctx)
return &MockIValidatorJailedCountCall{Call: call}
}
// MockIValidatorJailedCountCall wrap *gomock.Call
type MockIValidatorJailedCountCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorJailedCountCall) Return(arg0 int, arg1 error) *MockIValidatorJailedCountCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorJailedCountCall) Do(f func(context.Context) (int, error)) *MockIValidatorJailedCountCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorJailedCountCall) DoAndReturn(f func(context.Context) (int, error)) *MockIValidatorJailedCountCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIValidator) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIValidatorMockRecorder) LastID(ctx any) *MockIValidatorLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIValidator)(nil).LastID), ctx)
return &MockIValidatorLastIDCall{Call: call}
}
// MockIValidatorLastIDCall wrap *gomock.Call
type MockIValidatorLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorLastIDCall) Return(arg0 uint64, arg1 error) *MockIValidatorLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIValidatorLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIValidatorLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIValidator) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIValidatorMockRecorder) List(ctx, limit, offset, order any) *MockIValidatorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIValidator)(nil).List), ctx, limit, offset, order)
return &MockIValidatorListCall{Call: call}
}
// MockIValidatorListCall wrap *gomock.Call
type MockIValidatorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorListCall) Return(arg0 []*storage.Validator, arg1 error) *MockIValidatorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Validator, error)) *MockIValidatorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Validator, error)) *MockIValidatorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListByPower mocks base method.
func (m *MockIValidator) ListByPower(ctx context.Context, fltrs storage.ValidatorFilters) ([]storage.Validator, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListByPower", ctx, fltrs)
ret0, _ := ret[0].([]storage.Validator)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListByPower indicates an expected call of ListByPower.
func (mr *MockIValidatorMockRecorder) ListByPower(ctx, fltrs any) *MockIValidatorListByPowerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListByPower", reflect.TypeOf((*MockIValidator)(nil).ListByPower), ctx, fltrs)
return &MockIValidatorListByPowerCall{Call: call}
}
// MockIValidatorListByPowerCall wrap *gomock.Call
type MockIValidatorListByPowerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorListByPowerCall) Return(arg0 []storage.Validator, arg1 error) *MockIValidatorListByPowerCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorListByPowerCall) Do(f func(context.Context, storage.ValidatorFilters) ([]storage.Validator, error)) *MockIValidatorListByPowerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorListByPowerCall) DoAndReturn(f func(context.Context, storage.ValidatorFilters) ([]storage.Validator, error)) *MockIValidatorListByPowerCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIValidator) Save(ctx context.Context, m *storage.Validator) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIValidatorMockRecorder) Save(ctx, m any) *MockIValidatorSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIValidator)(nil).Save), ctx, m)
return &MockIValidatorSaveCall{Call: call}
}
// MockIValidatorSaveCall wrap *gomock.Call
type MockIValidatorSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorSaveCall) Return(arg0 error) *MockIValidatorSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorSaveCall) Do(f func(context.Context, *storage.Validator) error) *MockIValidatorSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorSaveCall) DoAndReturn(f func(context.Context, *storage.Validator) error) *MockIValidatorSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// TotalVotingPower mocks base method.
func (m *MockIValidator) TotalVotingPower(ctx context.Context) (decimal.Decimal, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TotalVotingPower", ctx)
ret0, _ := ret[0].(decimal.Decimal)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TotalVotingPower indicates an expected call of TotalVotingPower.
func (mr *MockIValidatorMockRecorder) TotalVotingPower(ctx any) *MockIValidatorTotalVotingPowerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TotalVotingPower", reflect.TypeOf((*MockIValidator)(nil).TotalVotingPower), ctx)
return &MockIValidatorTotalVotingPowerCall{Call: call}
}
// MockIValidatorTotalVotingPowerCall wrap *gomock.Call
type MockIValidatorTotalVotingPowerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorTotalVotingPowerCall) Return(arg0 decimal.Decimal, arg1 error) *MockIValidatorTotalVotingPowerCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorTotalVotingPowerCall) Do(f func(context.Context) (decimal.Decimal, error)) *MockIValidatorTotalVotingPowerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorTotalVotingPowerCall) DoAndReturn(f func(context.Context) (decimal.Decimal, error)) *MockIValidatorTotalVotingPowerCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIValidator) Update(ctx context.Context, m *storage.Validator) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIValidatorMockRecorder) Update(ctx, m any) *MockIValidatorUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIValidator)(nil).Update), ctx, m)
return &MockIValidatorUpdateCall{Call: call}
}
// MockIValidatorUpdateCall wrap *gomock.Call
type MockIValidatorUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIValidatorUpdateCall) Return(arg0 error) *MockIValidatorUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIValidatorUpdateCall) Do(f func(context.Context, *storage.Validator) error) *MockIValidatorUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIValidatorUpdateCall) DoAndReturn(f func(context.Context, *storage.Validator) error) *MockIValidatorUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: vesting_account.go
//
// Generated by this command:
//
// mockgen -source=vesting_account.go -destination=mock/vesting_account.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIVestingAccount is a mock of IVestingAccount interface.
type MockIVestingAccount struct {
ctrl *gomock.Controller
recorder *MockIVestingAccountMockRecorder
}
// MockIVestingAccountMockRecorder is the mock recorder for MockIVestingAccount.
type MockIVestingAccountMockRecorder struct {
mock *MockIVestingAccount
}
// NewMockIVestingAccount creates a new mock instance.
func NewMockIVestingAccount(ctrl *gomock.Controller) *MockIVestingAccount {
mock := &MockIVestingAccount{ctrl: ctrl}
mock.recorder = &MockIVestingAccountMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIVestingAccount) EXPECT() *MockIVestingAccountMockRecorder {
return m.recorder
}
// ByAddress mocks base method.
func (m *MockIVestingAccount) ByAddress(ctx context.Context, addressId uint64, limit, offset int, showEnded bool) ([]storage.VestingAccount, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByAddress", ctx, addressId, limit, offset, showEnded)
ret0, _ := ret[0].([]storage.VestingAccount)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByAddress indicates an expected call of ByAddress.
func (mr *MockIVestingAccountMockRecorder) ByAddress(ctx, addressId, limit, offset, showEnded any) *MockIVestingAccountByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIVestingAccount)(nil).ByAddress), ctx, addressId, limit, offset, showEnded)
return &MockIVestingAccountByAddressCall{Call: call}
}
// MockIVestingAccountByAddressCall wrap *gomock.Call
type MockIVestingAccountByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountByAddressCall) Return(arg0 []storage.VestingAccount, arg1 error) *MockIVestingAccountByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountByAddressCall) Do(f func(context.Context, uint64, int, int, bool) ([]storage.VestingAccount, error)) *MockIVestingAccountByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountByAddressCall) DoAndReturn(f func(context.Context, uint64, int, int, bool) ([]storage.VestingAccount, error)) *MockIVestingAccountByAddressCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIVestingAccount) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.VestingAccount, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.VestingAccount)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIVestingAccountMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIVestingAccountCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIVestingAccount)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIVestingAccountCursorListCall{Call: call}
}
// MockIVestingAccountCursorListCall wrap *gomock.Call
type MockIVestingAccountCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountCursorListCall) Return(arg0 []*storage.VestingAccount, arg1 error) *MockIVestingAccountCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.VestingAccount, error)) *MockIVestingAccountCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.VestingAccount, error)) *MockIVestingAccountCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIVestingAccount) GetByID(ctx context.Context, id uint64) (*storage.VestingAccount, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.VestingAccount)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIVestingAccountMockRecorder) GetByID(ctx, id any) *MockIVestingAccountGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIVestingAccount)(nil).GetByID), ctx, id)
return &MockIVestingAccountGetByIDCall{Call: call}
}
// MockIVestingAccountGetByIDCall wrap *gomock.Call
type MockIVestingAccountGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountGetByIDCall) Return(arg0 *storage.VestingAccount, arg1 error) *MockIVestingAccountGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountGetByIDCall) Do(f func(context.Context, uint64) (*storage.VestingAccount, error)) *MockIVestingAccountGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.VestingAccount, error)) *MockIVestingAccountGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIVestingAccount) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIVestingAccountMockRecorder) IsNoRows(err any) *MockIVestingAccountIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIVestingAccount)(nil).IsNoRows), err)
return &MockIVestingAccountIsNoRowsCall{Call: call}
}
// MockIVestingAccountIsNoRowsCall wrap *gomock.Call
type MockIVestingAccountIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountIsNoRowsCall) Return(arg0 bool) *MockIVestingAccountIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountIsNoRowsCall) Do(f func(error) bool) *MockIVestingAccountIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIVestingAccountIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIVestingAccount) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIVestingAccountMockRecorder) LastID(ctx any) *MockIVestingAccountLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIVestingAccount)(nil).LastID), ctx)
return &MockIVestingAccountLastIDCall{Call: call}
}
// MockIVestingAccountLastIDCall wrap *gomock.Call
type MockIVestingAccountLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountLastIDCall) Return(arg0 uint64, arg1 error) *MockIVestingAccountLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIVestingAccountLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIVestingAccountLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIVestingAccount) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.VestingAccount, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.VestingAccount)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIVestingAccountMockRecorder) List(ctx, limit, offset, order any) *MockIVestingAccountListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIVestingAccount)(nil).List), ctx, limit, offset, order)
return &MockIVestingAccountListCall{Call: call}
}
// MockIVestingAccountListCall wrap *gomock.Call
type MockIVestingAccountListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountListCall) Return(arg0 []*storage.VestingAccount, arg1 error) *MockIVestingAccountListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.VestingAccount, error)) *MockIVestingAccountListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.VestingAccount, error)) *MockIVestingAccountListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIVestingAccount) Save(ctx context.Context, m *storage.VestingAccount) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIVestingAccountMockRecorder) Save(ctx, m any) *MockIVestingAccountSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIVestingAccount)(nil).Save), ctx, m)
return &MockIVestingAccountSaveCall{Call: call}
}
// MockIVestingAccountSaveCall wrap *gomock.Call
type MockIVestingAccountSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountSaveCall) Return(arg0 error) *MockIVestingAccountSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountSaveCall) Do(f func(context.Context, *storage.VestingAccount) error) *MockIVestingAccountSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountSaveCall) DoAndReturn(f func(context.Context, *storage.VestingAccount) error) *MockIVestingAccountSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIVestingAccount) Update(ctx context.Context, m *storage.VestingAccount) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIVestingAccountMockRecorder) Update(ctx, m any) *MockIVestingAccountUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIVestingAccount)(nil).Update), ctx, m)
return &MockIVestingAccountUpdateCall{Call: call}
}
// MockIVestingAccountUpdateCall wrap *gomock.Call
type MockIVestingAccountUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingAccountUpdateCall) Return(arg0 error) *MockIVestingAccountUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingAccountUpdateCall) Do(f func(context.Context, *storage.VestingAccount) error) *MockIVestingAccountUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingAccountUpdateCall) DoAndReturn(f func(context.Context, *storage.VestingAccount) error) *MockIVestingAccountUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: vesting_period.go
//
// Generated by this command:
//
// mockgen -source=vesting_period.go -destination=mock/vesting_period.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
storage "github.com/celenium-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
gomock "go.uber.org/mock/gomock"
)
// MockIVestingPeriod is a mock of IVestingPeriod interface.
type MockIVestingPeriod struct {
ctrl *gomock.Controller
recorder *MockIVestingPeriodMockRecorder
}
// MockIVestingPeriodMockRecorder is the mock recorder for MockIVestingPeriod.
type MockIVestingPeriodMockRecorder struct {
mock *MockIVestingPeriod
}
// NewMockIVestingPeriod creates a new mock instance.
func NewMockIVestingPeriod(ctrl *gomock.Controller) *MockIVestingPeriod {
mock := &MockIVestingPeriod{ctrl: ctrl}
mock.recorder = &MockIVestingPeriodMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockIVestingPeriod) EXPECT() *MockIVestingPeriodMockRecorder {
return m.recorder
}
// ByVesting mocks base method.
func (m *MockIVestingPeriod) ByVesting(ctx context.Context, id uint64, limit, offset int) ([]storage.VestingPeriod, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByVesting", ctx, id, limit, offset)
ret0, _ := ret[0].([]storage.VestingPeriod)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ByVesting indicates an expected call of ByVesting.
func (mr *MockIVestingPeriodMockRecorder) ByVesting(ctx, id, limit, offset any) *MockIVestingPeriodByVestingCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByVesting", reflect.TypeOf((*MockIVestingPeriod)(nil).ByVesting), ctx, id, limit, offset)
return &MockIVestingPeriodByVestingCall{Call: call}
}
// MockIVestingPeriodByVestingCall wrap *gomock.Call
type MockIVestingPeriodByVestingCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodByVestingCall) Return(arg0 []storage.VestingPeriod, arg1 error) *MockIVestingPeriodByVestingCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodByVestingCall) Do(f func(context.Context, uint64, int, int) ([]storage.VestingPeriod, error)) *MockIVestingPeriodByVestingCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodByVestingCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.VestingPeriod, error)) *MockIVestingPeriodByVestingCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CursorList mocks base method.
func (m *MockIVestingPeriod) CursorList(ctx context.Context, id, limit uint64, order storage0.SortOrder, cmp storage0.Comparator) ([]*storage.VestingPeriod, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CursorList", ctx, id, limit, order, cmp)
ret0, _ := ret[0].([]*storage.VestingPeriod)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CursorList indicates an expected call of CursorList.
func (mr *MockIVestingPeriodMockRecorder) CursorList(ctx, id, limit, order, cmp any) *MockIVestingPeriodCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIVestingPeriod)(nil).CursorList), ctx, id, limit, order, cmp)
return &MockIVestingPeriodCursorListCall{Call: call}
}
// MockIVestingPeriodCursorListCall wrap *gomock.Call
type MockIVestingPeriodCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodCursorListCall) Return(arg0 []*storage.VestingPeriod, arg1 error) *MockIVestingPeriodCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.VestingPeriod, error)) *MockIVestingPeriodCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.VestingPeriod, error)) *MockIVestingPeriodCursorListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// GetByID mocks base method.
func (m *MockIVestingPeriod) GetByID(ctx context.Context, id uint64) (*storage.VestingPeriod, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetByID", ctx, id)
ret0, _ := ret[0].(*storage.VestingPeriod)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetByID indicates an expected call of GetByID.
func (mr *MockIVestingPeriodMockRecorder) GetByID(ctx, id any) *MockIVestingPeriodGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIVestingPeriod)(nil).GetByID), ctx, id)
return &MockIVestingPeriodGetByIDCall{Call: call}
}
// MockIVestingPeriodGetByIDCall wrap *gomock.Call
type MockIVestingPeriodGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodGetByIDCall) Return(arg0 *storage.VestingPeriod, arg1 error) *MockIVestingPeriodGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodGetByIDCall) Do(f func(context.Context, uint64) (*storage.VestingPeriod, error)) *MockIVestingPeriodGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.VestingPeriod, error)) *MockIVestingPeriodGetByIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// IsNoRows mocks base method.
func (m *MockIVestingPeriod) IsNoRows(err error) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsNoRows", err)
ret0, _ := ret[0].(bool)
return ret0
}
// IsNoRows indicates an expected call of IsNoRows.
func (mr *MockIVestingPeriodMockRecorder) IsNoRows(err any) *MockIVestingPeriodIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIVestingPeriod)(nil).IsNoRows), err)
return &MockIVestingPeriodIsNoRowsCall{Call: call}
}
// MockIVestingPeriodIsNoRowsCall wrap *gomock.Call
type MockIVestingPeriodIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodIsNoRowsCall) Return(arg0 bool) *MockIVestingPeriodIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodIsNoRowsCall) Do(f func(error) bool) *MockIVestingPeriodIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodIsNoRowsCall) DoAndReturn(f func(error) bool) *MockIVestingPeriodIsNoRowsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// LastID mocks base method.
func (m *MockIVestingPeriod) LastID(ctx context.Context) (uint64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LastID", ctx)
ret0, _ := ret[0].(uint64)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LastID indicates an expected call of LastID.
func (mr *MockIVestingPeriodMockRecorder) LastID(ctx any) *MockIVestingPeriodLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIVestingPeriod)(nil).LastID), ctx)
return &MockIVestingPeriodLastIDCall{Call: call}
}
// MockIVestingPeriodLastIDCall wrap *gomock.Call
type MockIVestingPeriodLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodLastIDCall) Return(arg0 uint64, arg1 error) *MockIVestingPeriodLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodLastIDCall) Do(f func(context.Context) (uint64, error)) *MockIVestingPeriodLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *MockIVestingPeriodLastIDCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// List mocks base method.
func (m *MockIVestingPeriod) List(ctx context.Context, limit, offset uint64, order storage0.SortOrder) ([]*storage.VestingPeriod, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "List", ctx, limit, offset, order)
ret0, _ := ret[0].([]*storage.VestingPeriod)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// List indicates an expected call of List.
func (mr *MockIVestingPeriodMockRecorder) List(ctx, limit, offset, order any) *MockIVestingPeriodListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIVestingPeriod)(nil).List), ctx, limit, offset, order)
return &MockIVestingPeriodListCall{Call: call}
}
// MockIVestingPeriodListCall wrap *gomock.Call
type MockIVestingPeriodListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodListCall) Return(arg0 []*storage.VestingPeriod, arg1 error) *MockIVestingPeriodListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.VestingPeriod, error)) *MockIVestingPeriodListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.VestingPeriod, error)) *MockIVestingPeriodListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Save mocks base method.
func (m_2 *MockIVestingPeriod) Save(ctx context.Context, m *storage.VestingPeriod) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Save", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Save indicates an expected call of Save.
func (mr *MockIVestingPeriodMockRecorder) Save(ctx, m any) *MockIVestingPeriodSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIVestingPeriod)(nil).Save), ctx, m)
return &MockIVestingPeriodSaveCall{Call: call}
}
// MockIVestingPeriodSaveCall wrap *gomock.Call
type MockIVestingPeriodSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodSaveCall) Return(arg0 error) *MockIVestingPeriodSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodSaveCall) Do(f func(context.Context, *storage.VestingPeriod) error) *MockIVestingPeriodSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodSaveCall) DoAndReturn(f func(context.Context, *storage.VestingPeriod) error) *MockIVestingPeriodSaveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Update mocks base method.
func (m_2 *MockIVestingPeriod) Update(ctx context.Context, m *storage.VestingPeriod) error {
m_2.ctrl.T.Helper()
ret := m_2.ctrl.Call(m_2, "Update", ctx, m)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockIVestingPeriodMockRecorder) Update(ctx, m any) *MockIVestingPeriodUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIVestingPeriod)(nil).Update), ctx, m)
return &MockIVestingPeriodUpdateCall{Call: call}
}
// MockIVestingPeriodUpdateCall wrap *gomock.Call
type MockIVestingPeriodUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockIVestingPeriodUpdateCall) Return(arg0 error) *MockIVestingPeriodUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockIVestingPeriodUpdateCall) Do(f func(context.Context, *storage.VestingPeriod) error) *MockIVestingPeriodUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockIVestingPeriodUpdateCall) DoAndReturn(f func(context.Context, *storage.VestingPeriod) error) *MockIVestingPeriodUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"encoding/base64"
"fmt"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type INamespace interface {
sdk.Table[*Namespace]
ByNamespaceId(ctx context.Context, namespaceId []byte) ([]Namespace, error)
ByNamespaceIdAndVersion(ctx context.Context, namespaceId []byte, version byte) (Namespace, error)
Messages(ctx context.Context, id uint64, limit, offset int) ([]NamespaceMessage, error)
ListWithSort(ctx context.Context, sortField string, sort sdk.SortOrder, limit, offset int) (ns []Namespace, err error)
GetByIds(ctx context.Context, ids ...uint64) (ns []Namespace, err error)
}
// Namespace -
type Namespace struct {
bun.BaseModel `bun:"namespace" comment:"Table with celestia namespaces."`
Id uint64 `bun:"id,pk,autoincrement" comment:"Unique internal identity"`
FirstHeight types.Level `bun:"first_height,notnull" comment:"Block height of the first message changing the namespace"`
LastHeight types.Level `bun:"last_height,notnull" comment:"Block height of the last message changing the namespace"`
Version byte `bun:"version,unique:namespace_id_version_idx" comment:"Namespace version"`
NamespaceID []byte `bun:"namespace_id,unique:namespace_id_version_idx" comment:"Namespace identity"`
Size int64 `bun:"size" comment:"Blobs size"`
PfbCount int64 `bun:"pfb_count" comment:"Count of pay for blobs messages for the namespace"`
BlobsCount int64 `bun:"blobs_count" comment:"Count of blobs sent to namespace"`
Reserved bool `bun:"reserved,default:false" comment:"If namespace is reserved flag is true"`
LastMessageTime time.Time `bun:"last_message_time" comment:"Time when last pay for blob was sent"`
}
// TableName -
func (Namespace) TableName() string {
return "namespace"
}
func (ns Namespace) String() string {
return fmt.Sprintf("%x%x", ns.Version, ns.NamespaceID)
}
func (ns Namespace) Hash() string {
return base64.StdEncoding.EncodeToString(append([]byte{ns.Version}, ns.NamespaceID...))
}
func (ns Namespace) Copy() *Namespace {
return &Namespace{
Id: ns.Id,
FirstHeight: ns.FirstHeight,
LastHeight: ns.LastHeight,
Version: ns.Version,
NamespaceID: ns.NamespaceID,
Size: ns.Size,
PfbCount: ns.PfbCount,
BlobsCount: ns.BlobsCount,
Reserved: ns.Reserved,
LastMessageTime: ns.LastMessageTime,
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/uptrace/bun"
)
type NamespaceMessage struct {
bun.BaseModel `bun:"namespace_message" comment:"Table with relation messages to namespace."`
NamespaceId uint64 `bun:"namespace_id,pk" comment:"Namespace internal id"`
MsgId uint64 `bun:"msg_id,pk" comment:"Message id"`
TxId uint64 `bun:"tx_id" comment:"Transaction id"`
Time time.Time `bun:"time,notnull,pk" comment:"Message time"`
Height types.Level `bun:"height" comment:"Message block height"`
Size uint64 `bun:"size" comment:"Total namespace size change due to message"`
Message *Message `bun:"rel:belongs-to,join:msg_id=id"`
Namespace *Namespace `bun:"rel:belongs-to,join:namespace_id=id"`
Tx *Tx `bun:"rel:belongs-to,join:tx_id=id"`
}
func (NamespaceMessage) TableName() string {
return "namespace_message"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
// Address -
type Address struct {
*postgres.Table[*storage.Address]
}
// NewAddress -
func NewAddress(db *database.Bun) *Address {
return &Address{
Table: postgres.NewTable[*storage.Address](db),
}
}
// ByHash -
func (a *Address) ByHash(ctx context.Context, hash []byte) (address storage.Address, err error) {
addressQuery := a.DB().NewSelect().
Model((*storage.Address)(nil)).
Where("hash = ?", hash)
err = a.DB().NewSelect().TableExpr("(?) as address", addressQuery).
ColumnExpr("address.*").
ColumnExpr("celestial.id as celestials__id, celestial.image_url as celestials__image_url").
ColumnExpr("balance.currency as balance__currency, balance.spendable as balance__spendable, balance.delegated as balance__delegated, balance.unbonding as balance__unbonding").
Join("left join balance on balance.id = address.id").
Join("left join celestial on celestial.address_id = address.id and celestial.status = 'PRIMARY'").
Scan(ctx, &address)
return
}
func (a *Address) ListWithBalance(ctx context.Context, filters storage.AddressListFilter) (result []storage.Address, err error) {
if filters.SortField == "last_height" || filters.SortField == "first_height" {
addressQuery := a.DB().NewSelect().
Model((*storage.Address)(nil))
addressQuery = addressListFilter(addressQuery, filters)
err = a.DB().NewSelect().
TableExpr("(?) as address", addressQuery).
ColumnExpr("address.*").
ColumnExpr("celestial.id as celestials__id, celestial.image_url as celestials__image_url").
ColumnExpr("balance.currency as balance__currency, balance.spendable as balance__spendable, balance.delegated as balance__delegated, balance.unbonding as balance__unbonding").
Join("left join balance on balance.id = address.id").
Join("left join celestial on celestial.address_id = address.id and celestial.status = 'PRIMARY'").
Scan(ctx, &result)
} else {
addressQuery := a.DB().NewSelect().
Model((*storage.Balance)(nil))
addressQuery = addressListFilter(addressQuery, filters)
err = a.DB().NewSelect().
TableExpr("(?) as balance", addressQuery).
ColumnExpr("address.*").
ColumnExpr("celestial.id as celestials__id, celestial.image_url as celestials__image_url").
ColumnExpr("balance.currency as balance__currency, balance.spendable as balance__spendable, balance.delegated as balance__delegated, balance.unbonding as balance__unbonding").
Join("left join address on balance.id = address.id").
Join("left join celestial on celestial.address_id = address.id and celestial.status = 'PRIMARY'").
Scan(ctx, &result)
}
return
}
func (a *Address) Series(ctx context.Context, addressId uint64, timeframe storage.Timeframe, column string, req storage.SeriesRequest) (items []storage.HistogramItem, err error) {
query := a.DB().NewSelect().
Where("address_id = ?", addressId).
Order("time desc")
switch timeframe {
case storage.TimeframeHour:
query = query.Table("accounts_tx_by_hour")
case storage.TimeframeDay:
query = query.Table("accounts_tx_by_day")
case storage.TimeframeMonth:
query = query.Table("accounts_tx_by_month")
default:
return nil, errors.Errorf("invalid timeframe: %s", timeframe)
}
switch column {
case "gas_used":
query = query.ColumnExpr("gas_used as value, time as bucket")
case "gas_wanted":
query = query.ColumnExpr("gas_wanted as value, time as bucket")
case "tx_count":
query = query.ColumnExpr("count as value, time as bucket")
case "fee":
query = query.ColumnExpr("fee as value, time as bucket")
default:
return nil, errors.Errorf("invalid column: %s", column)
}
if !req.From.IsZero() {
query = query.Where("time >= ?", req.From)
}
if !req.To.IsZero() {
query = query.Where("time < ?", req.To)
}
err = query.Scan(ctx, &items)
return
}
// IdByHash -
func (a *Address) IdByHash(ctx context.Context, hash ...[]byte) (id []uint64, err error) {
err = a.DB().NewSelect().
Model((*storage.Address)(nil)).
Column("id").
Where("hash IN (?)", bun.In(hash)).
Scan(ctx, &id)
return
}
// IdByAddress -
func (a *Address) IdByAddress(ctx context.Context, address string, ids ...uint64) (id uint64, err error) {
query := a.DB().NewSelect().
Model((*storage.Address)(nil)).
Column("id").
Where("address = ?", address)
if len(ids) > 0 {
query = query.Where("id IN (?)", bun.In(ids))
}
err = query.Scan(ctx, &id)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
)
// ApiKey -
type ApiKey struct {
db *database.Bun
}
// NewApiKey -
func NewApiKey(db *database.Bun) *ApiKey {
return &ApiKey{
db: db,
}
}
func (ak *ApiKey) Get(ctx context.Context, key string) (apikey storage.ApiKey, err error) {
apikey.Key = key
err = ak.db.DB().NewSelect().Model(&apikey).WherePK().Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"io"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/uptrace/bun"
)
// BlobLog -
type BlobLog struct {
*postgres.Table[*storage.BlobLog]
export *Export
}
// NewBlobLog -
func NewBlobLog(db *database.Bun, export *Export) *BlobLog {
return &BlobLog{
Table: postgres.NewTable[*storage.BlobLog](db),
export: export,
}
}
func (bl *BlobLog) ByNamespace(ctx context.Context, nsId uint64, fltrs storage.BlobLogFilters) (logs []storage.BlobLog, err error) {
blobsQuery := bl.DB().NewSelect().Model((*storage.BlobLog)(nil)).
Where("blob_log.namespace_id = ?", nsId)
blobsQuery = blobLogFilters(blobsQuery, fltrs)
var query *bun.SelectQuery
if fltrs.Joins {
query = bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("signer.address as signer__address").
ColumnExpr("celestial.id as signer__celestials__id, celestial.image_url as signer__celestials__image_url").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
ColumnExpr("rollup.id as rollup__id, rollup.name as rollup__name, rollup.logo as rollup__logo, rollup.slug as rollup__slug").
TableExpr("(?) as blob_log", blobsQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join celestial on celestial.address_id = signer.id and celestial.status = 'PRIMARY'").
Join("left join tx on tx.id = blob_log.tx_id").
Join("left join rollup_provider as p on blob_log.signer_id = p.address_id and blob_log.namespace_id = p.namespace_id").
Join("left join rollup on rollup.id = p.rollup_id")
query = blobLogSort(query, fltrs.SortBy, fltrs.Sort)
} else {
query = blobsQuery
}
err = query.Scan(ctx, &logs)
return
}
func (bl *BlobLog) ByProviders(ctx context.Context, providers []storage.RollupProvider, fltrs storage.BlobLogFilters) (logs []storage.BlobLog, err error) {
if len(providers) == 0 {
return nil, nil
}
blobQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil))
for i := range providers {
blobQuery = blobQuery.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
sq.Where("blob_log.signer_id = ?", providers[i].AddressId)
if providers[i].NamespaceId > 0 {
sq.Where("blob_log.namespace_id = ?", providers[i].NamespaceId)
}
return sq
})
}
blobQuery = blobLogFilters(blobQuery, fltrs)
query := bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("ns.id as namespace__id, ns.size as namespace__size, ns.blobs_count as namespace__blobs_count, ns.version as namespace__version, ns.namespace_id as namespace__namespace_id, ns.reserved as namespace__reserved, ns.pfb_count as namespace__pfb_count, ns.last_height as namespace__last_height, ns.last_message_time as namespace__last_message_time").
TableExpr("(?) as blob_log", blobQuery).
Join("left join namespace as ns on ns.id = blob_log.namespace_id")
if fltrs.Joins {
query = query.
ColumnExpr("signer.address as signer__address").
ColumnExpr("celestial.id as signer__celestials__id, celestial.image_url as signer__celestials__image_url").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join celestial on celestial.address_id = signer.id and celestial.status = 'PRIMARY'").
Join("left join tx on tx.id = blob_log.tx_id")
}
query = blobLogSort(query, fltrs.SortBy, fltrs.Sort)
err = query.Scan(ctx, &logs)
return
}
const (
maxExportPeriodInMonth = 1
)
func (bl *BlobLog) ExportByProviders(ctx context.Context, providers []storage.RollupProvider, from, to time.Time, stream io.Writer) (err error) {
if len(providers) == 0 {
return nil
}
blobQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil))
switch {
case from.IsZero() && to.IsZero():
blobQuery = blobQuery.
Where("time >= ?", time.Now().AddDate(0, -maxExportPeriodInMonth, 0).UTC())
case !from.IsZero() && to.IsZero():
blobQuery = blobQuery.
Where("time >= ?", from).
Where("time < ?", from.AddDate(0, maxExportPeriodInMonth, 0).UTC())
case from.IsZero() && !to.IsZero():
blobQuery = blobQuery.
Where("time < ?", to).
Where("time >= ?", to.AddDate(0, -maxExportPeriodInMonth, 0).UTC())
case !from.IsZero() && !to.IsZero():
if to.Sub(from) > time.Hour*24*30 {
blobQuery = blobQuery.
Where("time >= ?", from).
Where("time < ?", from.AddDate(0, maxExportPeriodInMonth, 0).UTC())
} else {
blobQuery = blobQuery.
Where("time >= ?", from).
Where("time < ?", to)
}
}
blobQuery = blobQuery.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
for i := range providers {
q = q.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
sq.Where("blob_log.signer_id = ?", providers[i].AddressId)
if providers[i].NamespaceId > 0 {
sq.Where("blob_log.namespace_id = ?", providers[i].NamespaceId)
}
return sq
})
}
return q
})
query := bl.DB().NewSelect().
ColumnExpr("blob_log.time, blob_log.height, blob_log.size, blob_log.commitment, blob_log.content_type").
ColumnExpr("signer.address as signer").
ColumnExpr("ns.version as namespace_version, ns.namespace_id as namespace_namespace_id").
ColumnExpr("tx.hash as tx_hash").
TableExpr("(?) as blob_log", blobQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join namespace as ns on ns.id = blob_log.namespace_id").
Join("left join tx on tx.id = blob_log.tx_id").
Order("blob_log.time desc").
String()
err = bl.export.ToCsv(ctx, stream, query)
return
}
func (bl *BlobLog) BySigner(ctx context.Context, signerId uint64, fltrs storage.BlobLogFilters) (logs []storage.BlobLog, err error) {
blobQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil)).
Where("signer_id = ?", signerId)
blobQuery = blobLogFilters(blobQuery, fltrs)
query := bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("ns.id as namespace__id, ns.size as namespace__size, ns.blobs_count as namespace__blobs_count, ns.version as namespace__version, ns.namespace_id as namespace__namespace_id, ns.reserved as namespace__reserved, ns.pfb_count as namespace__pfb_count, ns.last_height as namespace__last_height, ns.last_message_time as namespace__last_message_time").
TableExpr("(?) as blob_log", blobQuery).
Join("left join namespace as ns on ns.id = blob_log.namespace_id")
if fltrs.Joins {
query = query.
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
Join("left join tx on tx.id = blob_log.tx_id")
}
query = blobLogSort(query, fltrs.SortBy, fltrs.Sort)
err = query.Scan(ctx, &logs)
return
}
func (bl *BlobLog) ByTxId(ctx context.Context, txId uint64, fltrs storage.BlobLogFilters) (logs []storage.BlobLog, err error) {
blobLogQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil)).
Where("tx_id = ?", txId)
blobLogQuery = blobLogFilters(blobLogQuery, fltrs)
err = bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("rollup.id as rollup__id, rollup.name as rollup__name, rollup.logo as rollup__logo, rollup.slug as rollup__slug").
ColumnExpr("signer.address as signer__address").
ColumnExpr("celestial.id as signer__celestials__id, celestial.image_url as signer__celestials__image_url").
ColumnExpr("ns.id as namespace__id, ns.size as namespace__size, ns.blobs_count as namespace__blobs_count, ns.version as namespace__version, ns.namespace_id as namespace__namespace_id, ns.reserved as namespace__reserved, ns.pfb_count as namespace__pfb_count, ns.last_height as namespace__last_height, ns.last_message_time as namespace__last_message_time").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
TableExpr("(?) as blob_log", blobLogQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join celestial on celestial.address_id = signer.id and celestial.status = 'PRIMARY'").
Join("left join namespace as ns on ns.id = blob_log.namespace_id").
Join("left join tx on tx.id = blob_log.tx_id").
Join("left join rollup_provider as p on blob_log.signer_id = p.address_id and blob_log.namespace_id = p.namespace_id").
Join("left join rollup on rollup.id = p.rollup_id").
Scan(ctx, &logs)
return
}
func (bl *BlobLog) ByHeight(ctx context.Context, height types.Level, fltrs storage.BlobLogFilters) (logs []storage.BlobLog, err error) {
blobLogQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil)).
Where("blob_log.height = ?", height)
blobLogQuery = blobLogFilters(blobLogQuery, fltrs)
err = bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("rollup.id as rollup__id, rollup.name as rollup__name, rollup.logo as rollup__logo, rollup.slug as rollup__slug").
ColumnExpr("signer.address as signer__address").
ColumnExpr("celestial.id as signer__celestials__id, celestial.image_url as signer__celestials__image_url").
ColumnExpr("ns.id as namespace__id, ns.size as namespace__size, ns.blobs_count as namespace__blobs_count, ns.version as namespace__version, ns.namespace_id as namespace__namespace_id, ns.reserved as namespace__reserved, ns.pfb_count as namespace__pfb_count, ns.last_height as namespace__last_height, ns.last_message_time as namespace__last_message_time").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
TableExpr("(?) as blob_log", blobLogQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join celestial on celestial.address_id = signer.id and celestial.status = 'PRIMARY'").
Join("left join namespace as ns on ns.id = blob_log.namespace_id").
Join("left join tx on tx.id = blob_log.tx_id").
Join("left join rollup_provider as p on blob_log.signer_id = p.address_id and blob_log.namespace_id = p.namespace_id").
Join("left join rollup on rollup.id = p.rollup_id").
Scan(ctx, &logs)
return
}
func (bl *BlobLog) CountByTxId(ctx context.Context, txId uint64) (int, error) {
return bl.DB().NewSelect().Model((*storage.BlobLog)(nil)).
Where("tx_id = ?", txId).
Count(ctx)
}
func (bl *BlobLog) Blob(ctx context.Context, height types.Level, nsId uint64, commitment string) (l storage.BlobLog, err error) {
blobLogQuery := bl.DB().NewSelect().
Model((*storage.BlobLog)(nil)).
Where("blob_log.height = ?", height).
Where("blob_log.namespace_id = ?", nsId).
Where("blob_log.commitment = ?", commitment)
err = bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("rollup.id as rollup__id, rollup.name as rollup__name, rollup.logo as rollup__logo, rollup.slug as rollup__slug").
ColumnExpr("signer.address as signer__address").
ColumnExpr("celestial.id as signer__celestials__id, celestial.image_url as signer__celestials__image_url").
ColumnExpr("ns.id as namespace__id, ns.size as namespace__size, ns.blobs_count as namespace__blobs_count, ns.version as namespace__version, ns.namespace_id as namespace__namespace_id, ns.reserved as namespace__reserved, ns.pfb_count as namespace__pfb_count, ns.last_height as namespace__last_height, ns.last_message_time as namespace__last_message_time").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
TableExpr("(?) as blob_log", blobLogQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join celestial on celestial.address_id = signer.id and celestial.status = 'PRIMARY'").
Join("left join namespace as ns on ns.id = blob_log.namespace_id").
Join("left join tx on tx.id = blob_log.tx_id").
Join("left join rollup_provider as p on blob_log.signer_id = p.address_id and blob_log.namespace_id = p.namespace_id").
Join("left join rollup on rollup.id = p.rollup_id").
Scan(ctx, &l)
return
}
func (bl *BlobLog) ListBlobs(ctx context.Context, fltrs storage.ListBlobLogFilters) (logs []storage.BlobLog, err error) {
blobLogQuery := bl.DB().NewSelect().Model((*storage.BlobLog)(nil))
blobLogQuery = listBlobLogFilters(blobLogQuery, fltrs)
query := bl.DB().NewSelect().
ColumnExpr("blob_log.*").
ColumnExpr("signer.address as signer__address").
ColumnExpr("ns.version as namespace__version, ns.namespace_id as namespace__namespace_id").
ColumnExpr("tx.hash as tx__hash, tx.id as tx__id").
TableExpr("(?) as blob_log", blobLogQuery).
Join("left join address as signer on signer.id = blob_log.signer_id").
Join("left join namespace as ns on ns.id = blob_log.namespace_id").
Join("left join tx on tx.id = blob_log.tx_id")
query = blobLogSort(query, fltrs.SortBy, fltrs.Sort)
err = query.Scan(ctx, &logs)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/go-lib/database"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/uptrace/bun"
)
// Blocks -
type Blocks struct {
*postgres.Table[*storage.Block]
}
// NewBlocks -
func NewBlocks(db *database.Bun) *Blocks {
return &Blocks{
Table: postgres.NewTable[*storage.Block](db),
}
}
// ByHeight -
func (b *Blocks) ByHeight(ctx context.Context, height types.Level) (block storage.Block, err error) {
err = b.DB().NewSelect().Model(&block).
Where("block.height = ?", height).
Relation("Proposer", func(sq *bun.SelectQuery) *bun.SelectQuery {
return sq.Column("id", "cons_address", "moniker")
}).
Limit(1).
Scan(ctx)
return
}
// ByHeightWithStats -
func (b *Blocks) ByHeightWithStats(ctx context.Context, height types.Level) (block storage.Block, err error) {
subQuery := b.DB().NewSelect().Model(&block).
Where("block.height = ?", height).
Limit(1)
err = b.DB().NewSelect().
ColumnExpr("block.id, block.height, block.time, block.version_block, block.version_app, block.message_types, block.hash, block.parent_hash, block.last_commit_hash, block.data_hash, block.validators_hash, block.next_validators_hash, block.consensus_hash, block.app_hash, block.last_results_hash, block.evidence_hash, block.proposer_id").
ColumnExpr("stats.id AS stats__id, stats.height AS stats__height, stats.time AS stats__time, stats.tx_count AS stats__tx_count, stats.events_count AS stats__events_count, stats.blobs_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.gas_limit AS stats__gas_limit, stats.gas_used AS stats__gas_used, stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee, stats.bytes_in_block AS stats__bytes_in_block, stats.blobs_count AS stats__blobs_count, stats.rewards AS stats__rewards, stats.commissions AS stats__commissions, stats.square_size AS stats__square_size").
ColumnExpr("proposer.id AS proposer__id, proposer.cons_address AS proposer__cons_address, proposer.moniker AS proposer__moniker").
With("q", subQuery).
TableExpr("q as block").
Join("LEFT JOIN block_stats AS stats ON (stats.height = block.height) AND (stats.time = block.time)").
Join("LEFT JOIN validator AS proposer ON (proposer.id = block.proposer_id)").
Scan(ctx, &block)
return
}
// ByIdWithRelations -
func (b *Blocks) ByIdWithRelations(ctx context.Context, id uint64) (block storage.Block, err error) {
subQuery := b.DB().NewSelect().Model(&block).
Where("block.id = ?", id).
Limit(1)
err = b.DB().NewSelect().
ColumnExpr("block.id, block.height, block.time, block.version_block, block.version_app, block.message_types, block.hash, block.parent_hash, block.last_commit_hash, block.data_hash, block.validators_hash, block.next_validators_hash, block.consensus_hash, block.app_hash, block.last_results_hash, block.evidence_hash, block.proposer_id").
ColumnExpr("stats.id AS stats__id, stats.height AS stats__height, stats.time AS stats__time, stats.tx_count AS stats__tx_count, stats.events_count AS stats__events_count, stats.blobs_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.gas_limit AS stats__gas_limit, stats.gas_used AS stats__gas_used, stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee, stats.bytes_in_block AS stats__bytes_in_block, stats.blobs_count AS stats__blobs_count, stats.rewards AS stats__rewards, stats.commissions AS stats__commissions, stats.square_size AS stats__square_size").
ColumnExpr("proposer.id AS proposer__id, proposer.cons_address AS proposer__cons_address, proposer.moniker AS proposer__moniker").
With("q", subQuery).
TableExpr("q as block").
Join("LEFT JOIN block_stats AS stats ON (stats.height = block.height) AND (stats.time = block.time)").
Join("LEFT JOIN validator AS proposer ON (proposer.id = block.proposer_id)").
Scan(ctx, &block)
return
}
// Last -
func (b *Blocks) Last(ctx context.Context) (block storage.Block, err error) {
err = b.DB().NewSelect().Model(&block).
Relation("Proposer", func(sq *bun.SelectQuery) *bun.SelectQuery {
return sq.Column("id", "cons_address", "moniker")
}).
Order("id desc").
Limit(1).
Scan(ctx)
return
}
// ByHash -
func (b *Blocks) ByHash(ctx context.Context, hash []byte) (block storage.Block, err error) {
subQuery := b.DB().NewSelect().Model(&block).
Where("hash = ?", hash).
Limit(1)
err = b.DB().NewSelect().
ColumnExpr("block.id, block.height, block.time, block.version_block, block.version_app, block.message_types, block.hash, block.parent_hash, block.last_commit_hash, block.data_hash, block.validators_hash, block.next_validators_hash, block.consensus_hash, block.app_hash, block.last_results_hash, block.evidence_hash, block.proposer_id").
ColumnExpr("stats.id AS stats__id, stats.height AS stats__height, stats.time AS stats__time, stats.tx_count AS stats__tx_count, stats.events_count AS stats__events_count, stats.blobs_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.gas_limit AS stats__gas_limit, stats.gas_used AS stats__gas_used, stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee, stats.bytes_in_block AS stats__bytes_in_block, stats.blobs_count AS stats__blobs_count, stats.rewards AS stats__rewards, stats.commissions AS stats__commissions, stats.square_size AS stats__square_size").
ColumnExpr("proposer.id AS proposer__id, proposer.cons_address AS proposer__cons_address, proposer.moniker AS proposer__moniker").
With("q", subQuery).
TableExpr("q as block").
Join("LEFT JOIN block_stats AS stats ON (stats.height = block.height) AND (stats.time = block.time)").
Join("LEFT JOIN validator AS proposer ON (proposer.id = block.proposer_id)").
Scan(ctx, &block)
return
}
// ListWithStats -
func (b *Blocks) ListWithStats(ctx context.Context, limit, offset uint64, order sdk.SortOrder) (blocks []*storage.Block, err error) {
subQuery := b.DB().NewSelect().
Model(&blocks)
//nolint:gosec
subQuery = limitScope(subQuery, int(limit))
if offset > 0 {
//nolint:gosec
subQuery = subQuery.Offset(int(offset))
}
subQuery = sortScope(subQuery, "time", order)
query := b.DB().NewSelect().
ColumnExpr("block.*").
ColumnExpr("v.id AS proposer__id, v.cons_address as proposer__cons_address, v.moniker as proposer__moniker").
ColumnExpr("stats.id AS stats__id, stats.height AS stats__height, stats.time AS stats__time, stats.tx_count AS stats__tx_count, stats.events_count AS stats__events_count, stats.blobs_count as stats__blobs_count").
ColumnExpr("stats.blobs_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.bytes_in_block AS stats__bytes_in_block, stats.rewards AS stats__rewards, stats.commissions AS stats__commissions").
ColumnExpr("stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee, stats.gas_used AS stats__gas_used, stats.gas_limit AS stats__gas_limit, stats.square_size AS stats__square_size").
TableExpr("(?) as block", subQuery).
Join("LEFT JOIN block_stats as stats ON (stats.height = block.height) AND (stats.time = block.time)").
Join("LEFT JOIN validator as v ON v.id = block.proposer_id")
query = sortScope(query, "block.id", order)
err = query.Scan(ctx, &blocks)
return
}
func (b *Blocks) ByProposer(ctx context.Context, proposerId uint64, limit, offset int) (blocks []storage.Block, err error) {
blocksQuery := b.DB().NewSelect().Model(&blocks).
Where("proposer_id = ?", proposerId).
Order("time desc")
blocksQuery = limitScope(blocksQuery, limit)
if offset > 0 {
blocksQuery = blocksQuery.Offset(offset)
}
err = b.DB().NewSelect().
ColumnExpr("block.*").
ColumnExpr("stats.id AS stats__id, stats.height AS stats__height, stats.time AS stats__time, stats.tx_count AS stats__tx_count, stats.events_count AS stats__events_count, stats.blobs_count as stats__blobs_count").
ColumnExpr("stats.blobs_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.bytes_in_block AS stats__bytes_in_block, stats.rewards AS stats__rewards, stats.commissions AS stats__commissions").
ColumnExpr("stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee, stats.gas_used AS stats__gas_used, stats.gas_limit AS stats__gas_limit, stats.square_size AS stats__square_size").
TableExpr("(?) as block", blocksQuery).
Join("LEFT JOIN block_stats as stats ON (stats.height = block.height) AND (stats.time = block.time)").
Order("time desc").
Scan(ctx, &blocks)
return
}
func (b *Blocks) Time(ctx context.Context, height types.Level) (response time.Time, err error) {
err = b.DB().NewSelect().Model((*storage.Block)(nil)).
Column("time").
Where("height = ?", height).
Scan(ctx, &response)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// BlockSignature -
type BlockSignature struct {
*postgres.Table[*storage.BlockSignature]
}
// NewBlockSignature -
func NewBlockSignature(db *database.Bun) *BlockSignature {
return &BlockSignature{
Table: postgres.NewTable[*storage.BlockSignature](db),
}
}
func (bs *BlockSignature) LevelsByValidator(ctx context.Context, validatorId uint64, startHeight types.Level) (levels []types.Level, err error) {
err = bs.DB().NewSelect().
Model((*storage.BlockSignature)(nil)).
Column("height").
Where("validator_id = ?", validatorId).
Where("height > ?", startHeight).
Order("id desc").
Scan(ctx, &levels)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
)
// BlockStats -
type BlockStats struct {
db *database.Bun
}
// NewBlockStats -
func NewBlockStats(db *database.Bun) *BlockStats {
return &BlockStats{
db: db,
}
}
// ByHeight -
func (b *BlockStats) ByHeight(ctx context.Context, height pkgTypes.Level) (stats storage.BlockStats, err error) {
err = b.db.DB().NewSelect().Model(&stats).
Where("height = ?", height).
Limit(1).
Scan(ctx)
return
}
func (b *BlockStats) LastFrom(ctx context.Context, head pkgTypes.Level, limit int) (stats []storage.BlockStats, err error) {
err = b.db.DB().NewSelect().Model(&stats).
Where("height <= ?", head).
Limit(limit).
Order("id desc").
Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/go-lib/database"
)
// Constant -
type Constant struct {
db *database.Bun
}
// NewConstant -
func NewConstant(db *database.Bun) *Constant {
return &Constant{
db: db,
}
}
func (constant *Constant) Get(ctx context.Context, module types.ModuleName, name string) (c storage.Constant, err error) {
err = constant.db.DB().NewSelect().Model(&c).
Where("module = ?", module).
Where("name = ?", name).
Scan(ctx)
return
}
func (constant *Constant) ByModule(ctx context.Context, module types.ModuleName) (c []storage.Constant, err error) {
err = constant.db.DB().NewSelect().Model(&c).
Where("module = ?", module).
Scan(ctx)
return
}
func (constant *Constant) All(ctx context.Context) (c []storage.Constant, err error) {
err = constant.db.DB().NewSelect().Model(&c).Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/stats"
models "github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres/migrations"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
celestialsPg "github.com/celenium-io/celestial-module/pkg/storage/postgres"
"github.com/dipdup-net/go-lib/config"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/pkg/errors"
"github.com/uptrace/bun"
"github.com/uptrace/bun/migrate"
)
// Storage -
type Storage struct {
*postgres.Storage
cfg config.Database
scriptsDir string
Blocks models.IBlock
BlockStats models.IBlockStats
BlockSignatures models.IBlockSignature
BlobLogs models.IBlobLog
Constants models.IConstant
DenomMetadata models.IDenomMetadata
Tx models.ITx
Message models.IMessage
Event models.IEvent
Address models.IAddress
VestingAccounts models.IVestingAccount
VestingPeriods models.IVestingPeriod
Namespace models.INamespace
Price models.IPrice
State models.IState
Stats models.IStats
Search models.ISearch
Validator models.IValidator
StakingLogs models.IStakingLog
Delegation models.IDelegation
Redelegation models.IRedelegation
Undelegation models.IUndelegation
Jails models.IJail
Rollup models.IRollup
Grants models.IGrant
ApiKeys models.IApiKey
Celestials celestials.ICelestial
CelestialState celestials.ICelestialState
Notificator *Notificator
export models.Export
}
// Create -
func Create(ctx context.Context, cfg config.Database, scriptsDir string, withMigrations bool) (Storage, error) {
init := initDatabase
if withMigrations {
init = initDatabaseWithMigrations
}
strg, err := postgres.Create(ctx, cfg, init)
if err != nil {
return Storage{}, err
}
export := NewExport(cfg)
s := Storage{
cfg: cfg,
scriptsDir: scriptsDir,
Storage: strg,
Blocks: NewBlocks(strg.Connection()),
BlockStats: NewBlockStats(strg.Connection()),
BlockSignatures: NewBlockSignature(strg.Connection()),
BlobLogs: NewBlobLog(strg.Connection(), export),
Constants: NewConstant(strg.Connection()),
DenomMetadata: NewDenomMetadata(strg.Connection()),
Message: NewMessage(strg.Connection()),
Event: NewEvent(strg.Connection()),
Address: NewAddress(strg.Connection()),
VestingAccounts: NewVestingAccount(strg.Connection()),
VestingPeriods: NewVestingPeriod(strg.Connection()),
Price: NewPrice(strg.Connection()),
Tx: NewTx(strg.Connection()),
State: NewState(strg.Connection()),
Namespace: NewNamespace(strg.Connection()),
Stats: NewStats(strg.Connection()),
Search: NewSearch(strg.Connection()),
Validator: NewValidator(strg.Connection()),
StakingLogs: NewStakingLog(strg.Connection()),
Delegation: NewDelegation(strg.Connection()),
Redelegation: NewRedelegation(strg.Connection()),
Undelegation: NewUndelegation(strg.Connection()),
Jails: NewJail(strg.Connection()),
Rollup: NewRollup(strg.Connection()),
Grants: NewGrant(strg.Connection()),
ApiKeys: NewApiKey(strg.Connection()),
Celestials: celestialsPg.NewCelestials(strg.Connection()),
CelestialState: celestialsPg.NewCelestialState(strg.Connection()),
Notificator: NewNotificator(cfg, strg.Connection().DB()),
export: export,
}
if err := s.createScripts(ctx, "functions", false); err != nil {
return s, errors.Wrap(err, "creating views")
}
if err := s.createScripts(ctx, "views", true); err != nil {
return s, errors.Wrap(err, "creating views")
}
return s, nil
}
func initDatabase(ctx context.Context, conn *database.Bun) error {
if err := createExtensions(ctx, conn); err != nil {
return errors.Wrap(err, "create extensions")
}
if err := createTypes(ctx, conn); err != nil {
return errors.Wrap(err, "creating custom types")
}
// register many-to-many relationships
conn.DB().RegisterModel(
(*models.NamespaceMessage)(nil),
(*models.MsgAddress)(nil),
(*models.RollupProvider)(nil),
)
if err := database.CreateTables(ctx, conn, models.Models...); err != nil {
if err := conn.Close(); err != nil {
return err
}
return err
}
if err := database.MakeComments(ctx, conn, models.Models...); err != nil {
if err := conn.Close(); err != nil {
return err
}
return errors.Wrap(err, "make comments")
}
if err := createHypertables(ctx, conn); err != nil {
if err := conn.Close(); err != nil {
return err
}
return errors.Wrap(err, "create hypertables")
}
return createIndices(ctx, conn)
}
func initDatabaseWithMigrations(ctx context.Context, conn *database.Bun) error {
exists, err := checkTablesExists(ctx, conn)
if err != nil {
return errors.Wrap(err, "check table exists")
}
if exists {
if err := migrateDatabase(ctx, conn); err != nil {
return errors.Wrap(err, "migrate database")
}
}
return initDatabase(ctx, conn)
}
func (s Storage) CreateListener() models.Listener {
return NewNotificator(s.cfg, s.Notificator.db)
}
func createHypertables(ctx context.Context, conn *database.Bun) error {
return conn.DB().RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
for _, model := range []storage.Model{
&models.Block{},
&models.BlockStats{},
&models.Tx{},
&models.Message{},
&models.Event{},
&models.NamespaceMessage{},
&models.BlobLog{},
&models.Jail{},
&models.StakingLog{},
&models.Price{},
} {
if _, err := tx.ExecContext(ctx,
`SELECT create_hypertable(?, 'time', chunk_time_interval => INTERVAL '1 month', if_not_exists => TRUE);`,
model.TableName(),
); err != nil {
return err
}
if err := stats.InitModel(model); err != nil {
return err
}
}
if err := stats.InitModel(&models.Validator{}); err != nil {
return err
}
return nil
})
}
func createExtensions(ctx context.Context, conn *database.Bun) error {
return conn.DB().RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
_, err := tx.ExecContext(ctx, "CREATE EXTENSION IF NOT EXISTS pg_trgm;")
return err
})
}
func migrateDatabase(ctx context.Context, db *database.Bun) error {
migrator := migrate.NewMigrator(db.DB(), migrations.Migrations)
if err := migrator.Init(ctx); err != nil {
return err
}
if err := migrator.Lock(ctx); err != nil {
return err
}
defer migrator.Unlock(ctx) //nolint:errcheck
_, err := migrator.Migrate(ctx)
return err
}
func (s Storage) Close() error {
if err := s.export.Close(); err != nil {
return err
}
if err := s.Storage.Close(); err != nil {
return err
}
return nil
}
func checkTablesExists(ctx context.Context, db *database.Bun) (bool, error) {
var exists bool
err := db.DB().NewRaw(`SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'state'
)`).Scan(ctx, &exists)
return exists, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestial-module/pkg/storage/postgres"
"github.com/dipdup-net/go-lib/database"
"github.com/rs/zerolog/log"
"github.com/uptrace/bun"
)
const (
createTypeQuery = `DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = ?) THEN
CREATE TYPE ? AS ENUM (?);
END IF;
END$$;`
)
func createTypes(ctx context.Context, conn *database.Bun) error {
if err := postgres.CreateTypes(ctx, conn); err != nil {
return err
}
log.Info().Msg("creating custom types...")
return conn.DB().RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"event_type",
bun.Safe("event_type"),
bun.In(types.EventTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"msg_type",
bun.Safe("msg_type"),
bun.In(types.MsgTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"status",
bun.Safe("status"),
bun.In(types.StatusValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"msg_address_type",
bun.Safe("msg_address_type"),
bun.In(types.MsgAddressTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"module_name",
bun.Safe("module_name"),
bun.In(types.ModuleNameValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"staking_log_type",
bun.Safe("staking_log_type"),
bun.In(types.StakingLogTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"vesting_type",
bun.Safe("vesting_type"),
bun.In(types.VestingTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"rollup_type",
bun.Safe("rollup_type"),
bun.In(types.RollupTypeValues()),
); err != nil {
return err
}
if _, err := tx.ExecContext(
ctx,
createTypeQuery,
"rollup_category",
bun.Safe("rollup_category"),
bun.In(types.RollupCategoryValues()),
); err != nil {
return err
}
return nil
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Delegation -
type Delegation struct {
*postgres.Table[*storage.Delegation]
}
// NewDelegation -
func NewDelegation(db *database.Bun) *Delegation {
return &Delegation{
Table: postgres.NewTable[*storage.Delegation](db),
}
}
func (d *Delegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int, showZero bool) (delegations []storage.Delegation, err error) {
subQuery := d.DB().NewSelect().Model((*storage.Delegation)(nil)).
Where("address_id = ?", addressId).
Order("amount desc")
subQuery = limitScope(subQuery, limit)
if offset > 0 {
subQuery = subQuery.Offset(offset)
}
if !showZero {
subQuery = subQuery.Where("amount > 0")
}
err = d.DB().NewSelect().
TableExpr("(?) as delegation", subQuery).
ColumnExpr("delegation.*").
ColumnExpr("validator.id as validator__id, validator.moniker as validator__moniker, validator.cons_address as validator__cons_address").
Join("left join validator on validator.id = validator_id").
Scan(ctx, &delegations)
return
}
func (d *Delegation) ByValidator(ctx context.Context, validatorId uint64, limit, offset int, showZero bool) (delegations []storage.Delegation, err error) {
subQuery := d.DB().NewSelect().Model((*storage.Delegation)(nil)).
Where("validator_id = ?", validatorId).
Order("amount desc")
subQuery = limitScope(subQuery, limit)
if offset > 0 {
subQuery = subQuery.Offset(offset)
}
if !showZero {
subQuery = subQuery.Where("amount > 0")
}
err = d.DB().NewSelect().
TableExpr("(?) as delegation", subQuery).
ColumnExpr("delegation.*").
ColumnExpr("celestial.id as address__celestials__id, celestial.image_url as address__celestials__image_url").
ColumnExpr("address.id as address__id, address.address as address__address").
Join("left join address on address.id = delegation.address_id").
Join("left join celestial on celestial.address_id = delegation.address_id and celestial.status = 'PRIMARY'").
Scan(ctx, &delegations)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
)
// DenomMetadata -
type DenomMetadata struct {
db *database.Bun
}
// NewDenomMetadata -
func NewDenomMetadata(db *database.Bun) *DenomMetadata {
return &DenomMetadata{
db: db,
}
}
func (dm *DenomMetadata) All(ctx context.Context) (metadata []storage.DenomMetadata, err error) {
err = dm.db.DB().NewSelect().Model(&metadata).Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Event -
type Event struct {
*postgres.Table[*storage.Event]
}
// NewEvent -
func NewEvent(db *database.Bun) *Event {
return &Event{
Table: postgres.NewTable[*storage.Event](db),
}
}
// ByTxId -
func (e *Event) ByTxId(ctx context.Context, txId uint64, fltrs storage.EventFilter) (events []storage.Event, err error) {
query := e.DB().NewSelect().Model(&events).
Where("tx_id = ?", txId)
query = limitScope(query, fltrs.Limit)
query = sortScope(query, "id", sdk.SortOrderAsc)
if fltrs.Offset > 0 {
query = query.Offset(fltrs.Offset)
}
if !fltrs.Time.IsZero() {
query = query.
Where("time >= ?", fltrs.Time).
Where("time < ?", fltrs.Time.Add(time.Second))
}
err = query.Scan(ctx)
return
}
// ByBlock -
func (e *Event) ByBlock(ctx context.Context, height pkgTypes.Level, fltrs storage.EventFilter) (events []storage.Event, err error) {
query := e.DB().NewSelect().Model(&events).
Where("height = ?", height).
Where("tx_id IS NULL")
query = limitScope(query, fltrs.Limit)
query = sortScope(query, "id", sdk.SortOrderAsc)
if fltrs.Offset > 0 {
query = query.Offset(fltrs.Offset)
}
if !fltrs.Time.IsZero() {
query = query.
Where("time >= ?", fltrs.Time).
Where("time < ?", fltrs.Time.Add(time.Second))
}
err = query.Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"fmt"
"io"
"github.com/dipdup-net/go-lib/config"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
type Export struct {
*bun.DB
}
func NewExport(cfg config.Database) *Export {
dsn := fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=disable&application_name=export",
cfg.User,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.Database,
)
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
db := bun.NewDB(sqldb, pgdialect.New())
return &Export{db}
}
func (e *Export) ToCsv(ctx context.Context, writer io.Writer, query string) error {
conn, err := e.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
rawQuery := fmt.Sprintf("COPY (%s) TO STDOUT WITH CSV HEADER", bun.Safe(query))
_, err = pgdriver.CopyTo(ctx, conn, writer, rawQuery)
return err
}
func (e *Export) Close() error {
if err := e.DB.Close(); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Grant -
type Grant struct {
*postgres.Table[*storage.Grant]
}
// NewGrant -
func NewGrant(db *database.Bun) *Grant {
return &Grant{
Table: postgres.NewTable[*storage.Grant](db),
}
}
func (g *Grant) ByGrantee(ctx context.Context, id uint64, limit, offset int) (grants []storage.Grant, err error) {
query := g.DB().NewSelect().
Model((*storage.Grant)(nil)).
Where("grantee_id = ?", id).
Order("id desc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = g.DB().NewSelect().
TableExpr("(?) as g", query).
ColumnExpr("g.*").
ColumnExpr("address.address as granter__address").
ColumnExpr("celestial.id as granter__celestials__id, celestial.image_url as granter__celestials__image_url").
Join("left join address on address.id = g.granter_id").
Join("left join celestial on celestial.address_id = g.granter_id and celestial.status = 'PRIMARY'").
Scan(ctx, &grants)
return
}
func (g *Grant) ByGranter(ctx context.Context, id uint64, limit, offset int) (grants []storage.Grant, err error) {
query := g.DB().NewSelect().
Model((*storage.Grant)(nil)).
Where("granter_id = ?", id).
Order("id desc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = g.DB().NewSelect().
TableExpr("(?) as g", query).
ColumnExpr("g.*").
ColumnExpr("address.address as grantee__address").
ColumnExpr("celestial.id as grantee__celestials__id, celestial.image_url as grantee__celestials__image_url").
Join("left join address on address.id = g.grantee_id").
Join("left join celestial on celestial.address_id = g.grantee_id and celestial.status = 'PRIMARY'").
Scan(ctx, &grants)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"github.com/celenium-io/celestia-indexer/internal/storage"
celestialPg "github.com/celenium-io/celestial-module/pkg/storage/postgres"
"github.com/dipdup-net/go-lib/database"
"github.com/rs/zerolog/log"
"github.com/uptrace/bun"
)
func createIndices(ctx context.Context, conn *database.Bun) error {
log.Info().Msg("creating indexes...")
return conn.DB().RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
// Address
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Address)(nil)).
Index("address_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Address)(nil)).
Index("address_hash_idx").
Column("hash").
Exec(ctx); err != nil {
return err
}
// Block
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Block)(nil)).
Index("block_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Block)(nil)).
Index("block_proposer_id_idx").
Column("proposer_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Block)(nil)).
Index("block_hash_idx").
Column("hash").
Using("HASH").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Block)(nil)).
Index("block_data_hash_idx").
Column("data_hash").
Using("HASH").
Exec(ctx); err != nil {
return err
}
// BlockStats
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlockStats)(nil)).
Index("block_stats_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
// Tx
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Tx)(nil)).
Index("tx_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Tx)(nil)).
Index("tx_hash_idx").
Column("hash").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Tx)(nil)).
Index("tx_status_idx").
Column("status").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Tx)(nil)).
Index("tx_message_types_idx").
Column("message_types").
Exec(ctx); err != nil {
return err
}
// Signer
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Signer)(nil)).
Index("signer_tx_id_idx").
Column("tx_id").
Exec(ctx); err != nil {
return err
}
// Event
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Event)(nil)).
Index("event_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Event)(nil)).
Index("event_tx_id_idx").
Column("tx_id").
Where("tx_id IS NOT NULL").
Exec(ctx); err != nil {
return err
}
// Message
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Message)(nil)).
Index("message_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Message)(nil)).
Index("message_tx_id_idx").
Column("tx_id").
Where("tx_id IS NOT NULL").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Message)(nil)).
Index("message_type_idx").
Column("type").
Exec(ctx); err != nil {
return err
}
// Namespace
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Namespace)(nil)).
Index("namespace_idx").
Column("namespace_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Namespace)(nil)).
Index("namespace_version_idx").
Column("version").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Namespace)(nil)).
Index("namespace_last_action_idx").
Column("last_message_time").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Namespace)(nil)).
Index("namespace_pfb_count_idx").
Column("pfb_count").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Namespace)(nil)).
Index("namespace_size_idx").
Column("size").
Exec(ctx); err != nil {
return err
}
// Validator
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Validator)(nil)).
Index("validator_cons_address_idx").
Column("cons_address").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Validator)(nil)).
Index("validator_moniker_idx").
ColumnExpr("moniker gin_trgm_ops").
Using("GIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Validator)(nil)).
Index("validator_jailed_idx").
ColumnExpr("(1)").
Where("NOT jailed").
Exec(ctx); err != nil {
return err
}
// Blob log
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlobLog)(nil)).
Index("blob_log_namespace_id_idx").
Column("namespace_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlobLog)(nil)).
Index("blob_log_signer_id_idx").
Column("signer_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlobLog)(nil)).
Index("blob_log_tx_id_idx").
Column("tx_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlobLog)(nil)).
Index("blob_log_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlobLog)(nil)).
Index("blob_log_commitment_idx").
Column("commitment").
Using("HASH").
Exec(ctx); err != nil {
return err
}
// Rollup
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Rollup)(nil)).
Index("rollup_name_idx").
ColumnExpr("name gin_trgm_ops").
Using("GIN").
Exec(ctx); err != nil {
return err
}
// RollupProvider
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.RollupProvider)(nil)).
Index("rollup_provider_rollup_id_idx").
Column("rollup_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.RollupProvider)(nil)).
Index("rollup_provider_namespace_id_idx").
Column("namespace_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.RollupProvider)(nil)).
Index("rollup_provider_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
// BlockSignature
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlockSignature)(nil)).
Index("block_signature_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.BlockSignature)(nil)).
Index("block_signature_validator_id_idx").
Column("validator_id").
Exec(ctx); err != nil {
return err
}
// StakingLog
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.StakingLog)(nil)).
Index("staking_log_validator_id_idx").
Column("validator_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.StakingLog)(nil)).
Index("staking_log_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.StakingLog)(nil)).
Index("staking_log_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
// Delegation
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Delegation)(nil)).
Index("delegation_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Delegation)(nil)).
Index("delegation_validator_id_idx").
Column("validator_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Delegation)(nil)).
Index("delegation_amount_idx").
Column("amount").
Exec(ctx); err != nil {
return err
}
// Redelegation
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Redelegation)(nil)).
Index("redelegation_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Redelegation)(nil)).
Index("redelegation_amount_idx").
Column("amount").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Redelegation)(nil)).
Index("redelegation_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
// Undelegation
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Undelegation)(nil)).
Index("undelegation_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Undelegation)(nil)).
Index("undelegation_validator_id_idx").
Column("validator_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Undelegation)(nil)).
Index("undelegation_amount_idx").
Column("amount").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Undelegation)(nil)).
Index("undelegation_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
// Jail
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Jail)(nil)).
Index("jail_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Jail)(nil)).
Index("jail_validator_id_idx").
Column("validator_id").
Exec(ctx); err != nil {
return err
}
// Vesting account
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.VestingAccount)(nil)).
Index("vesting_account_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.VestingAccount)(nil)).
Index("vesting_account_address_id_idx").
Column("address_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.VestingAccount)(nil)).
Index("vesting_account_end_time_idx").
Column("end_time").
Exec(ctx); err != nil {
return err
}
// Grant
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Grant)(nil)).
Index("grant_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Grant)(nil)).
Index("grant_granter_id_idx").
Column("granter_id").
Exec(ctx); err != nil {
return err
}
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Grant)(nil)).
Index("grant_grantee_id_idx").
Column("grantee_id").
Exec(ctx); err != nil {
return err
}
// Celestial
if err := celestialPg.CreateIndex(ctx, tx); err != nil {
return err
}
return nil
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"bytes"
"context"
"os"
"path/filepath"
"github.com/pkg/errors"
)
func (s Storage) createScripts(ctx context.Context, subFolder string, split bool) error {
scriptsDir := filepath.Join(s.scriptsDir, subFolder)
files, err := os.ReadDir(scriptsDir)
if err != nil {
return err
}
for i := range files {
if files[i].IsDir() {
continue
}
path := filepath.Join(scriptsDir, files[i].Name())
raw, err := os.ReadFile(path)
if err != nil {
return err
}
if split {
queries := bytes.Split(raw, []byte{';'})
if len(queries) == 0 {
continue
}
for _, query := range queries {
query = bytes.TrimLeft(query, "\n ")
if len(query) == 0 {
continue
}
if _, err := s.Connection().DB().NewRaw(string(query)).Exec(ctx); err != nil {
return errors.Wrapf(err, "creating %s '%s'", subFolder, files[i].Name())
}
}
} else {
if _, err := s.Connection().DB().NewRaw(string(raw)).Exec(ctx); err != nil {
return errors.Wrapf(err, "creating %s '%s'", subFolder, files[i].Name())
}
}
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Jail -
type Jail struct {
*postgres.Table[*storage.Jail]
}
// NewJail -
func NewJail(db *database.Bun) *Jail {
return &Jail{
Table: postgres.NewTable[*storage.Jail](db),
}
}
func (j *Jail) ByValidator(ctx context.Context, id uint64, limit, offset int) (jails []storage.Jail, err error) {
query := j.DB().NewSelect().Model(&jails).
Where("validator_id = ?", id).
Order("time desc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = query.Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/uptrace/bun"
)
// Message -
type Message struct {
*postgres.Table[*storage.Message]
}
// NewMessage -
func NewMessage(db *database.Bun) *Message {
return &Message{
Table: postgres.NewTable[*storage.Message](db),
}
}
// ByTxId -
func (m *Message) ByTxId(ctx context.Context, txId uint64, limit, offset int) (messages []storage.Message, err error) {
query := m.DB().NewSelect().Model(&messages).
Where("tx_id = ?", txId).
Order("id asc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = query.Scan(ctx)
return
}
func (m *Message) ListWithTx(ctx context.Context, filters storage.MessageListWithTxFilters) (msgs []storage.MessageWithTx, err error) {
query := m.DB().NewSelect().Model(&msgs).Offset(filters.Offset)
query = messagesFilter(query, filters)
err = query.Relation("Tx").Scan(ctx)
return
}
func (m *Message) ByAddress(ctx context.Context, addressId uint64, filters storage.AddressMsgsFilter) (msgs []storage.AddressMessageWithTx, err error) {
query := m.DB().NewSelect().Model((*storage.MsgAddress)(nil)).
Where("address_id = ?", addressId).
Offset(filters.Offset)
query = limitScope(query, filters.Limit)
query = sortScope(query, "msg_id", filters.Sort)
wrapQuery := m.DB().NewSelect().TableExpr("(?) as msg_address", query).
ColumnExpr(`msg_address.address_id, msg_address.msg_id, msg_address.type, msg.id AS msg__id, msg.height AS msg__height, msg.time AS msg__time, msg.position AS msg__position, msg.type AS msg__type, msg.tx_id AS msg__tx_id, msg.size AS msg__size, msg.data AS msg__data`).
ColumnExpr("tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.hash as tx__hash, tx.message_types as tx__message_types").
Join("left join message as msg on msg_address.msg_id = msg.id").
Join("left join tx on tx.id = msg.tx_id and tx.time = msg.time")
if len(filters.MessageTypes) > 0 {
wrapQuery = wrapQuery.Where("msg.type IN (?)", bun.In(filters.MessageTypes))
}
wrapQuery = sortScope(wrapQuery, "msg_id", filters.Sort)
err = wrapQuery.Scan(ctx, &msgs)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package migrations
import (
"embed"
"github.com/uptrace/bun/migrate"
)
var Migrations = migrate.NewMigrations()
//go:embed *.sql
var sqlMigrations embed.FS
func init() {
if err := Migrations.Discover(sqlMigrations); err != nil {
panic(err)
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/uptrace/bun"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Namespace -
type Namespace struct {
*postgres.Table[*storage.Namespace]
}
// NewNamespace -
func NewNamespace(db *database.Bun) *Namespace {
return &Namespace{
Table: postgres.NewTable[*storage.Namespace](db),
}
}
// ByNamespaceId -
func (n *Namespace) ByNamespaceId(ctx context.Context, namespaceId []byte) (namespace []storage.Namespace, err error) {
err = n.DB().NewSelect().Model(&namespace).
Where("namespace_id = ?", namespaceId).
Scan(ctx)
return
}
// ByNamespaceIdAndVersion -
func (n *Namespace) ByNamespaceIdAndVersion(ctx context.Context, namespaceId []byte, version byte) (namespace storage.Namespace, err error) {
err = n.DB().NewSelect().Model(&namespace).
Where("namespace_id = ?", namespaceId).
Where("version = ?", version).
Scan(ctx)
return
}
// Messages -
func (n *Namespace) Messages(ctx context.Context, id uint64, limit, offset int) (msgs []storage.NamespaceMessage, err error) {
subQuery := n.DB().NewSelect().Model(&msgs).
Where("namespace_id = ?", id).
Order("time desc")
subQuery = limitScope(subQuery, limit)
if offset > 0 {
subQuery = subQuery.Offset(offset)
}
query := n.DB().NewSelect().
TableExpr("(?) as msgs", subQuery).
ColumnExpr("msgs.*").
ColumnExpr("namespace.id as namespace__id, namespace.first_height as namespace__first_height, namespace.last_height as namespace__last_height, namespace.version as namespace__version, namespace.namespace_id as namespace__namespace_id, namespace.size as namespace__size, namespace.pfb_count as namespace__pfb_count, namespace.reserved as namespace__reserved, namespace.last_message_time as namespace__last_message_time").
ColumnExpr("message.id as message__id, message.height as message__height, message.time as message__time, message.position as message__position, message.type as message__type, message.tx_id as message__tx_id, message.size AS message__size, message.data as message__data").
ColumnExpr("tx.id as tx__id, tx.height as tx__height, tx.time as tx__time, tx.position as tx__position, tx.gas_wanted as tx__gas_wanted, tx.gas_used as tx__gas_used, tx.timeout_height as tx__timeout_height, tx.events_count as tx__events_count, tx.messages_count as tx__messages_count, tx.fee as tx__fee, tx.status as tx__status, tx.error as tx__error, tx.codespace as tx__codespace, tx.hash as tx__hash, tx.memo as tx__memo, tx.message_types as tx__message_types").
Join("LEFT JOIN namespace ON namespace.id = msgs.namespace_id").
Join("LEFT JOIN message ON message.id = msgs.msg_id").
Join("LEFT JOIN tx ON tx.id = msgs.tx_id").
Order("msgs.time desc")
err = query.Scan(ctx, &msgs)
return
}
func (n *Namespace) ListWithSort(ctx context.Context, sortField string, sort sdk.SortOrder, limit, offset int) (ns []storage.Namespace, err error) {
var field string
switch sortField {
case timeColumn:
field = "last_message_time"
case pfbCountColumn:
field = pfbCountColumn
case sizeColumn:
field = sizeColumn
default:
field = "id"
}
if offset < 0 {
offset = 0
}
query := n.DB().NewSelect().Model(&ns)
limitScope(query, limit)
sortScope(query, field, sort)
err = query.Offset(offset).Scan(ctx)
return
}
func (n *Namespace) GetByIds(ctx context.Context, ids ...uint64) (ns []storage.Namespace, err error) {
if len(ids) == 0 {
return nil, nil
}
err = n.DB().NewSelect().Model(&ns).Where("id IN (?)", bun.In(ids)).Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"fmt"
"time"
"github.com/dipdup-net/go-lib/config"
"github.com/lib/pq"
"github.com/uptrace/bun"
)
const (
connectionName = "celestia_notifications"
minReconnectInterval = 10 * time.Second
maxReconnectInterval = time.Minute
)
type Notificator struct {
db *bun.DB
l *pq.Listener
}
func NewNotificator(cfg config.Database, db *bun.DB) *Notificator {
connStr := fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=disable",
cfg.User,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.Database,
)
return &Notificator{
l: pq.NewListener(
connStr,
minReconnectInterval,
maxReconnectInterval,
nil,
),
db: db,
}
}
func (n *Notificator) Notify(ctx context.Context, channel string, payload string) error {
_, err := n.db.ExecContext(ctx, "NOTIFY ?, ?", bun.Ident(channel), payload)
return err
}
func (n *Notificator) Listen() chan *pq.Notification {
return n.l.Notify
}
func (n *Notificator) Subscribe(ctx context.Context, channels ...string) error {
for i := range channels {
if err := n.l.Listen(channels[i]); err != nil {
return err
}
}
return nil
}
func (n *Notificator) Close() error {
return n.l.Close()
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/pkg/errors"
)
// Price -
type Price struct {
db *database.Bun
}
// NewPrice -
func NewPrice(db *database.Bun) *Price {
return &Price{
db: db,
}
}
func (p *Price) Get(ctx context.Context, timeframe string, start, end time.Time, limit int) (price []storage.Price, err error) {
query := p.db.DB().NewSelect()
switch timeframe {
case storage.PriceTimeframeDay:
query = query.Table("price_by_day")
case storage.PriceTimeframeHour:
query = query.Table("price_by_hour")
case storage.PriceTimeframeMinute:
query = query.Table("price")
default:
return nil, errors.Errorf("unknown price timeframe: %s", timeframe)
}
if !start.IsZero() {
query = query.Where("time >= ?", start)
}
if !end.IsZero() {
query = query.Where("time < ?", end)
}
limitScope(query, limit)
err = query.Order("time desc").Scan(ctx, &price)
return
}
func (p *Price) Save(ctx context.Context, price *storage.Price) error {
if price == nil {
return nil
}
_, err := p.db.DB().NewInsert().Model(price).Exec(ctx)
return err
}
func (p *Price) Last(ctx context.Context) (price storage.Price, err error) {
err = p.db.DB().NewSelect().Model(&price).Order("time desc").Limit(1).Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Redelegation -
type Redelegation struct {
*postgres.Table[*storage.Redelegation]
}
// NewRedelegation -
func NewRedelegation(db *database.Bun) *Redelegation {
return &Redelegation{
Table: postgres.NewTable[*storage.Redelegation](db),
}
}
func (d *Redelegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int) (redelegations []storage.Redelegation, err error) {
subQuery := d.DB().NewSelect().Model((*storage.Redelegation)(nil)).
Where("address_id = ?", addressId).
Order("amount desc")
subQuery = limitScope(subQuery, limit)
if offset > 0 {
subQuery = subQuery.Offset(offset)
}
err = d.DB().NewSelect().
TableExpr("(?) as redelegation", subQuery).
ColumnExpr("redelegation.*").
ColumnExpr("source.id as source__id, source.moniker as source__moniker, source.cons_address as source__cons_address").
ColumnExpr("dest.id as destination__id, dest.moniker as destination__moniker, dest.cons_address as destination__cons_address").
Join("left join validator as source on source.id = src_id").
Join("left join validator as dest on dest.id = dest_id").
Scan(ctx, &redelegations)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
// Rollup -
type Rollup struct {
*postgres.Table[*storage.Rollup]
}
// NewRollup -
func NewRollup(db *database.Bun) *Rollup {
return &Rollup{
Table: postgres.NewTable[*storage.Rollup](db),
}
}
func (r *Rollup) Leaderboard(ctx context.Context, fltrs storage.LeaderboardFilters) (rollups []storage.RollupWithStats, err error) {
switch fltrs.SortField {
case timeColumn:
fltrs.SortField = "last_time"
case sizeColumn, blobsCountColumn, feeColumn:
case "":
fltrs.SortField = sizeColumn
default:
return nil, errors.Errorf("unknown sort field: %s", fltrs.SortField)
}
query := r.DB().NewSelect().
Table(storage.ViewLeaderboard).
ColumnExpr("leaderboard.*").
ColumnExpr("da_change.da_pct as da_pct").
Offset(fltrs.Offset).
Join("left join da_change on da_change.rollup_id = leaderboard.id")
if len(fltrs.Category) > 0 {
query = query.Where("category IN (?)", bun.In(fltrs.Category))
}
if len(fltrs.Tags) > 0 {
query = query.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
for i := range fltrs.Tags {
q.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
return sq.Where("? = ANY(tags)", fltrs.Tags[i])
})
}
return q
})
}
if len(fltrs.Stack) > 0 {
query = query.Where("stack IN (?)", bun.In(fltrs.Stack))
}
if len(fltrs.Provider) > 0 {
query = query.Where("provider IN (?)", bun.In(fltrs.Provider))
}
if len(fltrs.Type) > 0 {
query = query.Where("type IN (?)", bun.In(fltrs.Type))
}
query = sortScope(query, fltrs.SortField, fltrs.Sort)
query = limitScope(query, fltrs.Limit)
err = query.Scan(ctx, &rollups)
return
}
func (r *Rollup) LeaderboardDay(ctx context.Context, fltrs storage.LeaderboardFilters) (rollups []storage.RollupWithDayStats, err error) {
switch fltrs.SortField {
case "avg_size", blobsCountColumn, "total_size", "total_fee", "throughput", "namespace_count", "pfb_count", "mb_price":
case "":
fltrs.SortField = "throughput"
default:
return nil, errors.Errorf("unknown sort field: %s", fltrs.SortField)
}
query := r.DB().NewSelect().
Table(storage.ViewLeaderboardDay).
Column("avg_size", blobsCountColumn, "total_size", "total_fee", "throughput", "namespace_count", "pfb_count", "mb_price").
ColumnExpr("rollup.*").
Offset(fltrs.Offset).
Join("left join rollup on rollup.id = rollup_id AND rollup.verified = true")
if len(fltrs.Category) > 0 {
query = query.Where("category IN (?)", bun.In(fltrs.Category))
}
if len(fltrs.Tags) > 0 {
query = query.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
for i := range fltrs.Tags {
q.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
return sq.Where("? = ANY(tags)", fltrs.Tags[i])
})
}
return q
})
}
if len(fltrs.Stack) > 0 {
query = query.Where("stack IN (?)", bun.In(fltrs.Stack))
}
if len(fltrs.Provider) > 0 {
query = query.Where("provider IN (?)", bun.In(fltrs.Provider))
}
if len(fltrs.Type) > 0 {
query = query.Where("type IN (?)", bun.In(fltrs.Type))
}
query = sortScope(query, fltrs.SortField, fltrs.Sort)
query = limitScope(query, fltrs.Limit)
err = query.Scan(ctx, &rollups)
return
}
func (r *Rollup) Namespaces(ctx context.Context, rollupId uint64, limit, offset int) (namespaceIds []uint64, err error) {
query := r.DB().NewSelect().
TableExpr("rollup_stats_by_month as r").
ColumnExpr("distinct r.namespace_id").
Join("inner join rollup_provider as rp on rp.address_id = r.signer_id AND (rp.namespace_id = r.namespace_id OR rp.namespace_id = 0)").
Where("rollup_id = ?", rollupId)
if offset > 0 {
query = query.Offset(offset)
}
query = limitScope(query, limit)
err = query.Scan(ctx, &namespaceIds)
return
}
func (r *Rollup) Providers(ctx context.Context, rollupId uint64) (providers []storage.RollupProvider, err error) {
err = r.DB().NewSelect().Model(&providers).
Where("rollup_id = ?", rollupId).
Scan(ctx)
return
}
func (r *Rollup) RollupsByNamespace(ctx context.Context, namespaceId uint64, limit, offset int) (rollups []storage.Rollup, err error) {
subQuery := r.DB().NewSelect().
Model((*storage.RollupProvider)(nil)).
Column("rollup_id").
Where("namespace_id = ?", namespaceId).
Group("rollup_id").
Offset(offset)
subQuery = limitScope(subQuery, limit)
err = r.DB().NewSelect().
With("rollups", subQuery).
Table("rollups").
ColumnExpr("rollup.*").
Join("left join rollup on rollup.id = rollups.rollup_id and rollup.verified = true").
Scan(ctx, &rollups)
return
}
func (r *Rollup) Series(ctx context.Context, rollupId uint64, timeframe storage.Timeframe, column string, req storage.SeriesRequest) (items []storage.HistogramItem, err error) {
providers, err := r.Providers(ctx, rollupId)
if err != nil {
return nil, err
}
if len(providers) == 0 {
return nil, nil
}
query := r.DB().NewSelect().Order("time desc").Group("time")
switch timeframe {
case storage.TimeframeHour:
query = query.Table("rollup_stats_by_hour")
case storage.TimeframeDay:
query = query.Table("rollup_stats_by_day")
case storage.TimeframeMonth:
query = query.Table("rollup_stats_by_month")
default:
return nil, errors.Errorf("invalid timeframe: %s", timeframe)
}
switch column {
case "blobs_count":
query = query.ColumnExpr("sum(blobs_count) as value, time as bucket")
case "size":
query = query.ColumnExpr("sum(size) as value, time as bucket")
case "size_per_blob":
query = query.ColumnExpr("(sum(size) / sum(blobs_count)) as value, time as bucket")
case "fee":
query = query.ColumnExpr("sum(fee) as value, time as bucket")
default:
return nil, errors.Errorf("invalid column: %s", column)
}
if !req.From.IsZero() {
query = query.Where("time >= ?", req.From)
}
if !req.To.IsZero() {
query = query.Where("time < ?", req.To)
}
if len(providers) > 0 {
query.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
for i := range providers {
q.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
sq = sq.Where("signer_id = ?", providers[i].AddressId)
if providers[i].NamespaceId > 0 {
sq = sq.Where("namespace_id = ?", providers[i].NamespaceId)
}
return sq
})
}
return q
})
}
err = query.Scan(ctx, &items)
return
}
func (r *Rollup) Count(ctx context.Context) (int64, error) {
count, err := r.DB().NewSelect().Model((*storage.Rollup)(nil)).Where("verified = TRUE").Count(ctx)
return int64(count), err
}
func (r *Rollup) Stats(ctx context.Context, rollupId uint64) (stats storage.RollupStats, err error) {
err = r.DB().NewSelect().Table(storage.ViewLeaderboard).
Column("blobs_count", "size", "last_time", "first_time", "fee", "size_pct", "fee_pct", "blobs_count_pct").
Where("id = ?", rollupId).Scan(ctx, &stats)
return
}
func (r *Rollup) BySlug(ctx context.Context, slug string) (rollup storage.RollupWithStats, err error) {
err = r.DB().NewSelect().
Table(storage.ViewLeaderboard).
ColumnExpr("leaderboard.*").
ColumnExpr("da_change.da_pct as da_pct").
Where("slug = ?", slug).
Limit(1).
Join("left join da_change on da_change.rollup_id = leaderboard.id").
Scan(ctx, &rollup)
return
}
func (r *Rollup) ById(ctx context.Context, rollupId uint64) (rollup storage.RollupWithStats, err error) {
err = r.DB().NewSelect().
Table(storage.ViewLeaderboard).
Where("id = ?", rollupId).
ColumnExpr("leaderboard.*").
ColumnExpr("da_change.da_pct as da_pct").
Limit(1).
Join("left join da_change on da_change.rollup_id = leaderboard.id").
Scan(ctx, &rollup)
return
}
func (r *Rollup) Distribution(ctx context.Context, rollupId uint64, series string, groupBy storage.Timeframe) (items []storage.DistributionItem, err error) {
providers, err := r.Providers(ctx, rollupId)
if err != nil {
return
}
if len(providers) == 0 {
return
}
cte := r.DB().NewSelect()
for i := range providers {
cte.WhereGroup(" OR ", func(sq *bun.SelectQuery) *bun.SelectQuery {
if providers[i].NamespaceId > 0 {
return sq.
Where("namespace_id = ?", providers[i].NamespaceId).
Where("signer_id = ?", providers[i].AddressId)
}
return sq.Where("signer_id = ?", providers[i].AddressId)
})
}
switch groupBy {
case storage.TimeframeDay:
cte = cte.Table("rollup_stats_by_day").
ColumnExpr("extract(isodow from time) as name").
Where("time >= ?", time.Now().AddDate(0, -3, 0).UTC())
case storage.TimeframeHour:
cte = cte.Table("rollup_stats_by_hour").
ColumnExpr("extract(hour from time) as name").
Where("time >= ?", time.Now().AddDate(0, -1, 0).UTC())
default:
err = errors.Errorf("invalid distribution rollup groupBy: %s", groupBy)
return
}
switch series {
case "size":
cte = cte.ColumnExpr("size as value")
case "blobs_count":
cte = cte.ColumnExpr("blobs_count as value")
case "size_per_blob":
cte = cte.ColumnExpr("(size / blobs_count) as value")
case "fee_per_blob":
cte = cte.ColumnExpr("(fee / blobs_count) as value")
default:
err = errors.Errorf("invalid distribution rollup series: %s", groupBy)
return
}
err = r.DB().NewSelect().
TableExpr("(?) as cte", cte).
ColumnExpr("name, avg(value) as value").
Group("name").
Order("name asc").
Scan(ctx, &items)
return
}
func (r *Rollup) AllSeries(ctx context.Context, timeframe storage.Timeframe) (items []storage.RollupHistogramItem, err error) {
subQuery := r.DB().NewSelect().
ColumnExpr("rp.rollup_id, sum(size) as size, sum(blobs_count) as blobs_count, sum(fee) as fee, time").
Join("inner join rollup_provider rp on (rp.namespace_id = 0 or rp.namespace_id = stats.namespace_id) and rp.address_id = signer_id").
Group("rollup_id", "time")
switch timeframe {
case storage.TimeframeHour:
subQuery = subQuery.TableExpr("? as stats", bun.Safe(storage.ViewRollupStatsByHour)).Where("time > now() - '24 hours'::interval")
case storage.TimeframeDay:
subQuery = subQuery.TableExpr("? as stats", bun.Safe(storage.ViewRollupStatsByDay)).Where("time > now() - '30 days'::interval")
case storage.TimeframeMonth:
subQuery = subQuery.TableExpr("? as stats", bun.Safe(storage.ViewRollupStatsByMonth)).Where("time > now() - '1 year'::interval")
}
err = r.DB().NewSelect().
TableExpr("(?) as series", subQuery).
ColumnExpr("series.time as time, series.size as size, series.blobs_count as blobs_count, series.fee as fee, rollup.name as name, rollup.logo as logo").
Join("left join rollup on rollup.id = series.rollup_id").
Where("rollup.verified = true").
OrderExpr("time desc").
Scan(ctx, &items)
return
}
func (r *Rollup) RollupStatsGrouping(ctx context.Context, fltrs storage.RollupGroupStatsFilters) (results []storage.RollupGroupedStats, err error) {
query := r.DB().NewSelect().Table(storage.ViewLeaderboard)
switch fltrs.Func {
case "sum":
query = query.
ColumnExpr("sum(fee) as fee").
ColumnExpr("sum(size) as size").
ColumnExpr("sum(blobs_count) as blobs_count")
case "avg":
query = query.
ColumnExpr("avg(fee) as fee").
ColumnExpr("avg(size) as size").
ColumnExpr("avg(blobs_count) as blobs_count")
default:
return nil, errors.Errorf("unknown func field: %s", fltrs.Column)
}
switch fltrs.Column {
case "stack", "type", "category", "vm", "provider":
query = query.ColumnExpr(fltrs.Column + " as group").Group(fltrs.Column)
default:
return nil, errors.Errorf("unknown column field: %s", fltrs.Column)
}
err = query.Scan(ctx, &results)
return
}
func (r *Rollup) Tags(ctx context.Context) (arr []string, err error) {
err = r.DB().NewSelect().
Model((*storage.Rollup)(nil)).
Distinct().
ColumnExpr("unnest(tags)").
Where("verified = true").
Scan(ctx, &arr)
return
}
func (r *Rollup) Unverified(ctx context.Context) (rollups []storage.Rollup, err error) {
err = r.DB().NewSelect().
Model(&rollups).
Where("verified = false").
Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"fmt"
"github.com/celenium-io/celestia-indexer/internal/storage"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
const (
sizeColumn = "size"
timeColumn = "time"
pfbCountColumn = "pfb_count"
blobsCountColumn = "blobs_count"
feeColumn = "fee"
)
func limitScope(q *bun.SelectQuery, limit int) *bun.SelectQuery {
if limit < 1 || limit > 100 {
limit = 10
}
return q.Limit(limit)
}
func sortScope(q *bun.SelectQuery, field string, sort sdk.SortOrder) *bun.SelectQuery {
if sort != sdk.SortOrderAsc && sort != sdk.SortOrderDesc {
sort = sdk.SortOrderAsc
}
return q.OrderExpr("? ?", bun.Ident(field), bun.Safe(sort))
}
func txFilter(query *bun.SelectQuery, fltrs storage.TxFilter) *bun.SelectQuery {
query = limitScope(query, fltrs.Limit)
query = sortScope(query, "id", fltrs.Sort)
if !fltrs.MessageTypes.Empty() {
query = query.Where("bit_count(message_types & ?::bit(76)) > 0", fltrs.MessageTypes)
}
if !fltrs.ExcludedMessageTypes.Empty() {
query = query.Where("bit_count(message_types & ~(?::bit(76))) > 0", fltrs.ExcludedMessageTypes)
}
if len(fltrs.Status) > 0 {
query = query.WhereGroup(" AND ", func(sq *bun.SelectQuery) *bun.SelectQuery {
for i := range fltrs.Status {
sq = sq.WhereOr("status = ?", fltrs.Status[i])
}
return sq
})
}
if fltrs.Height != nil {
query = query.Where("height = ?", *fltrs.Height)
}
if !fltrs.TimeFrom.IsZero() {
query = query.Where("time >= ?", fltrs.TimeFrom)
}
if !fltrs.TimeTo.IsZero() {
query = query.Where("time < ?", fltrs.TimeTo)
}
if fltrs.WithMessages {
query = query.Relation("Messages")
}
return query
}
func addressListFilter(query *bun.SelectQuery, fltrs storage.AddressListFilter) *bun.SelectQuery {
query = limitScope(query, fltrs.Limit)
query = query.Offset(fltrs.Offset)
switch fltrs.SortField {
case "id", "spendable", "unbonding", "delegated", "last_height":
query = sortScope(query, fltrs.SortField, fltrs.Sort)
case "first_height":
query = sortScope(query, "height", fltrs.Sort)
default:
query = sortScope(query, "id", fltrs.Sort)
}
return query
}
func messagesFilter(query *bun.SelectQuery, fltrs storage.MessageListWithTxFilters) *bun.SelectQuery {
query = limitScope(query, fltrs.Limit)
if len(fltrs.MessageTypes) > 0 {
query = query.Where("type IN (?)", bun.In(fltrs.MessageTypes))
}
if len(fltrs.ExcludedMessageTypes) > 0 {
query = query.Where("type NOT IN (?)", bun.In(fltrs.ExcludedMessageTypes))
}
if fltrs.Height > 0 {
query = query.Where("message.height = ?", fltrs.Height)
}
return query
}
func blobLogFilters(query *bun.SelectQuery, fltrs storage.BlobLogFilters) *bun.SelectQuery {
if fltrs.Offset > 0 {
query = query.Offset(fltrs.Offset)
}
if !fltrs.From.IsZero() {
query = query.Where("time >= ?", fltrs.From)
}
if !fltrs.To.IsZero() {
query = query.Where("time < ?", fltrs.To)
}
if fltrs.Commitment != "" {
query = query.Where("commitment = ?", fltrs.Commitment)
}
if len(fltrs.Signers) > 0 {
query = query.Where("signer_id IN (?)", bun.In(fltrs.Signers))
}
if fltrs.Cursor > 0 {
switch fltrs.Sort {
case sdk.SortOrderAsc:
query = query.Where("id > ?", fltrs.Cursor)
case sdk.SortOrderDesc:
query = query.Where("id < ?", fltrs.Cursor)
}
}
query = limitScope(query, fltrs.Limit)
return blobLogSort(query, fltrs.SortBy, fltrs.Sort)
}
func listBlobLogFilters(query *bun.SelectQuery, fltrs storage.ListBlobLogFilters) *bun.SelectQuery {
if fltrs.Offset > 0 {
query = query.Offset(fltrs.Offset)
}
if !fltrs.From.IsZero() {
query = query.Where("time >= ?", fltrs.From)
}
if !fltrs.To.IsZero() {
query = query.Where("time < ?", fltrs.To)
}
if fltrs.Commitment != "" {
query = query.Where("commitment = ?", fltrs.Commitment)
}
if len(fltrs.Signers) > 0 {
query = query.Where("signer_id IN (?)", bun.In(fltrs.Signers))
}
if len(fltrs.Namespaces) > 0 {
query = query.Where("namespace_id IN (?)", bun.In(fltrs.Namespaces))
}
if fltrs.Cursor > 0 {
switch fltrs.Sort {
case sdk.SortOrderAsc:
query = query.Where("id > ?", fltrs.Cursor)
case sdk.SortOrderDesc:
query = query.Where("id < ?", fltrs.Cursor)
}
}
query = limitScope(query, fltrs.Limit)
return blobLogSort(query, fltrs.SortBy, fltrs.Sort)
}
func blobLogSort(query *bun.SelectQuery, sortBy string, sort sdk.SortOrder) *bun.SelectQuery {
switch sortBy {
case sizeColumn, timeColumn:
query = sortScope(query, fmt.Sprintf("blob_log.%s", sortBy), sort)
case "":
if sort != sdk.SortOrderAsc && sort != sdk.SortOrderDesc {
sort = sdk.SortOrderAsc
}
query = query.OrderExpr("blob_log.time ?0, blob_log.id ?0", bun.Safe(sort))
default:
return query
}
return query
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"encoding/hex"
"strings"
"github.com/celenium-io/celestia-indexer/internal/storage"
celestials "github.com/celenium-io/celestial-module/pkg/storage"
"github.com/dipdup-net/go-lib/database"
)
// Search -
type Search struct {
db *database.Bun
}
// NewSearch -
func NewSearch(db *database.Bun) *Search {
return &Search{
db: db,
}
}
func (s *Search) Search(ctx context.Context, query []byte) (results []storage.SearchResult, err error) {
blockQuery := s.db.DB().NewSelect().
Model((*storage.Block)(nil)).
ColumnExpr("id, ? as value, 'block' as type", hex.EncodeToString(query)).
Where("hash = ?", query).
WhereOr("data_hash = ?", query)
txQuery := s.db.DB().NewSelect().
Model((*storage.Tx)(nil)).
ColumnExpr("id, encode(hash, 'hex') as value, 'tx' as type").
Where("hash = ?", query)
union := blockQuery.UnionAll(txQuery)
err = s.db.DB().NewSelect().
TableExpr("(?) as search", union).
Limit(10).
Offset(0).
Scan(ctx, &results)
return
}
func (s *Search) SearchText(ctx context.Context, text string) (results []storage.SearchResult, err error) {
text = strings.ToUpper(text)
text = "%" + text + "%"
validatorQuery := s.db.DB().NewSelect().
Model((*storage.Validator)(nil)).
ColumnExpr("id, moniker as value, 'validator' as type").
Where("moniker ILIKE ?", text)
rollupQuery := s.db.DB().NewSelect().
Model((*storage.Rollup)(nil)).
ColumnExpr("id, name as value, 'rollup' as type").
Where("name ILIKE ?", text)
namespaceQuery := s.db.DB().NewSelect().
Model((*storage.Namespace)(nil)).
ColumnExpr("id, encode(namespace_id, 'hex') as value, 'namespace' as type").
Where("encode(namespace_id, 'hex') ILIKE ?", text)
celestialsQuery := s.db.DB().NewSelect().
Model((*celestials.Celestial)(nil)).
ColumnExpr("address_id as id, id as value, 'celestial' as type").
Where("id ILIKE ?", text)
union := rollupQuery.
UnionAll(namespaceQuery).
UnionAll(validatorQuery).
UnionAll(celestialsQuery)
err = s.db.DB().NewSelect().
TableExpr("(?) as search", union).
Limit(10).
Offset(0).
Scan(ctx, &results)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"fmt"
"strconv"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.20.0"
"go.opentelemetry.io/otel/trace"
"github.com/getsentry/sentry-go"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/schema"
)
type SentryHook struct {
dbName string
formatQueries bool
tracer trace.Tracer
}
var _ bun.QueryHook = (*SentryHook)(nil)
func NewSentryHook(dbName string, tracer trace.Tracer, formatQueries bool) *SentryHook {
h := new(SentryHook)
h.dbName = dbName
h.formatQueries = formatQueries
h.tracer = tracer
return h
}
func (h *SentryHook) Init(db *bun.DB) {}
func (h *SentryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context {
ctx, _ = h.tracer.Start(ctx, "db", trace.WithSpanKind(trace.SpanKindClient))
return ctx
}
func (h *SentryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
operation := event.Operation()
root := sentry.TransactionFromContext(ctx)
if root == nil {
return
}
span := root.StartChild(operation, sentry.WithOpName("db"))
defer span.Finish()
query := h.eventQuery(event)
span.Description = query
span.SetData("db.statement", query)
span.SetTag("db.operation", operation)
span.SetTag("db.name", h.dbName)
if event.IQuery != nil {
if tableName := event.IQuery.GetTableName(); tableName != "" {
span.SetTag("db.sql.table", tableName)
}
}
if sys := dbSystem(event.DB); sys.Valid() {
span.SetTag(string(sys.Key), sys.Value.AsString())
}
if event.Result != nil {
if n, _ := event.Result.RowsAffected(); n > 0 {
span.SetData("db.rows_affected", strconv.Itoa(int(n)))
}
}
switch event.Err {
case nil, sql.ErrNoRows, sql.ErrTxDone:
// ignore
default:
span.SetTag("exception.message", event.Err.Error())
span.SetTag("exception.type", fmt.Sprintf("%T", event.Err))
// span.SetStatus(codes.Error, event.Err.Error())
}
}
func (h *SentryHook) eventQuery(event *bun.QueryEvent) string {
const softQueryLimit = 8000
const hardQueryLimit = 16000
var query string
if h.formatQueries && len(event.Query) <= softQueryLimit {
query = event.Query
} else {
query = unformattedQuery(event)
}
if len(query) > hardQueryLimit {
query = query[:hardQueryLimit]
}
return query
}
func unformattedQuery(event *bun.QueryEvent) string {
if event.IQuery != nil {
if b, err := event.IQuery.AppendQuery(schema.NewNopFormatter(), nil); err == nil {
return string(b)
}
}
return event.QueryTemplate
}
func dbSystem(db *bun.DB) attribute.KeyValue {
switch db.Dialect().Name() {
case dialect.PG:
return semconv.DBSystemPostgreSQL
case dialect.MySQL:
return semconv.DBSystemMySQL
case dialect.SQLite:
return semconv.DBSystemSqlite
case dialect.MSSQL:
return semconv.DBSystemMSSQL
default:
return attribute.KeyValue{}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// StakingLog -
type StakingLog struct {
*postgres.Table[*storage.StakingLog]
}
// NewStakingLog -
func NewStakingLog(db *database.Bun) *StakingLog {
return &StakingLog{
Table: postgres.NewTable[*storage.StakingLog](db),
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// State -
type State struct {
*postgres.Table[*storage.State]
}
// NewState -
func NewState(db *database.Bun) *State {
return &State{
Table: postgres.NewTable[*storage.State](db),
}
}
// ByName -
func (s *State) ByName(ctx context.Context, name string) (state storage.State, err error) {
err = s.DB().NewSelect().Model(&state).Where("name = ?", name).Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
type Stats struct {
db *database.Bun
}
func NewStats(conn *database.Bun) Stats {
return Stats{conn}
}
func (s Stats) Count(ctx context.Context, req storage.CountRequest) (string, error) {
if err := req.Validate(); err != nil {
return "", err
}
query := s.db.DB().NewSelect().Table(req.Table).
ColumnExpr("COUNT(*)")
if req.From > 0 {
query = query.Where("time >= to_timestamp(?)", req.From)
}
if req.To > 0 {
query = query.Where("time < to_timestamp(?)", req.To)
}
var count string
err := query.Scan(ctx, &count)
return count, err
}
func (s Stats) Summary(ctx context.Context, req storage.SummaryRequest) (string, error) {
if err := req.Validate(); err != nil {
return "", err
}
query := s.db.DB().NewSelect().Table(req.Table).
ColumnExpr(`? (?)`, bun.Safe(req.Function), bun.Safe(req.Column))
if req.From > 0 {
query = query.Where("time >= to_timestamp(?)", req.From)
}
if req.To > 0 {
query = query.Where("time < to_timestamp(?)", req.To)
}
var value string
err := query.Scan(ctx, &value)
return value, err
}
func (s Stats) TPS(ctx context.Context) (response storage.TPS, err error) {
if err = s.db.DB().NewSelect().Table(storage.ViewBlockStatsByHour).
ColumnExpr("max(tps) as high, min(tps) as low").
Where("ts > date_trunc('hour', now()) - '1 week'::interval").
Where("ts < date_trunc('hour', now())").
Scan(ctx, &response.High, &response.Low); err != nil {
return
}
if err = s.db.DB().NewSelect().Model((*storage.BlockStats)(nil)).
ColumnExpr("sum(tx_count)/3600.0").
Where("time > now() - '1 hour'::interval").
Scan(ctx, &response.Current); err != nil {
return
}
var prev float64
if err = s.db.DB().NewSelect().Model((*storage.BlockStats)(nil)).
ColumnExpr("sum(tx_count)/3600.0").
Where("time > now() - '2 hour'::interval").
Where("time <= now() - '1 hour'::interval").
Scan(ctx, &prev); err != nil {
return
}
switch {
case prev == 0 && response.Current == 0:
response.ChangeLastHourPct = 0
case prev == 0 && response.Current > 0:
response.ChangeLastHourPct = 1
default:
response.ChangeLastHourPct = (response.Current - prev) / prev
}
return
}
func (s Stats) Change24hBlockStats(ctx context.Context) (response storage.Change24hBlockStats, err error) {
first := s.db.DB().NewSelect().
Table(storage.ViewBlockStatsByHour).
ColumnExpr(`
sum(tx_count) as tx_count,
sum(bytes_in_block) as bytes_in_block,
sum(blobs_size) as blobs_size,
sum(fee) as fee`).
Where("ts > NOW() - '1 day':: interval")
second := s.db.DB().NewSelect().
Table(storage.ViewBlockStatsByHour).
ColumnExpr(`
sum(tx_count) as tx_count,
sum(bytes_in_block) as bytes_in_block,
sum(blobs_size) as blobs_size,
sum(fee) as fee`).
Where("ts <= NOW() - '1 day':: interval").
Where("ts > NOW() - '2 days':: interval")
err = s.db.DB().NewSelect().
With("f", first).
With("s", second).
TableExpr("f, s").
ColumnExpr(`
case when s.tx_count > 0 then (f.tx_count - s.tx_count)/s.tx_count when f.tx_count > 0 then 1 else 0 end as tx_count_24h,
case when s.bytes_in_block > 0 then (f.bytes_in_block - s.bytes_in_block)/s.bytes_in_block when f.bytes_in_block > 0 then 1 else 0 end as bytes_in_block_24h,
case when s.blobs_size > 0 then (f.blobs_size - s.blobs_size)/s.blobs_size when f.blobs_size > 0 then 1 else 0 end as blobs_size_24h,
case when s.fee > 0 then (f.fee - s.fee)/s.fee when f.fee > 0 then 1 else 0 end as fee_24h
`).
Scan(ctx, &response)
return
}
func (s Stats) Series(ctx context.Context, timeframe storage.Timeframe, name string, req storage.SeriesRequest) (response []storage.SeriesItem, err error) {
var view string
switch timeframe {
case storage.TimeframeHour:
view = storage.ViewBlockStatsByHour
case storage.TimeframeDay:
view = storage.ViewBlockStatsByDay
case storage.TimeframeWeek:
view = storage.ViewBlockStatsByWeek
case storage.TimeframeMonth:
view = storage.ViewBlockStatsByMonth
case storage.TimeframeYear:
view = storage.ViewBlockStatsByYear
default:
return nil, errors.Errorf("unexpected timeframe %s", timeframe)
}
query := s.db.DB().NewSelect().Table(view)
switch name {
case storage.SeriesBlobsSize:
query.ColumnExpr("ts, blobs_size as value")
case storage.SeriesTPS:
query.ColumnExpr("ts, tps as value, tps_max as max, tps_min as min")
case storage.SeriesBPS:
query.ColumnExpr("ts, bps as value, bps_max as max, bps_min as min")
case storage.SeriesFee:
query.ColumnExpr("ts, fee as value")
case storage.SeriesSupplyChange:
query.ColumnExpr("ts, supply_change as value")
case storage.SeriesBlockTime:
query.ColumnExpr("ts, block_time as value")
case storage.SeriesTxCount:
query.ColumnExpr("ts, tx_count as value")
case storage.SeriesEventsCount:
query.ColumnExpr("ts, events_count as value")
case storage.SeriesGasPrice:
query.ColumnExpr("ts, gas_price as value")
case storage.SeriesGasEfficiency:
query.ColumnExpr("ts, gas_efficiency as value")
case storage.SeriesGasLimit:
query.ColumnExpr("ts, gas_limit as value")
case storage.SeriesGasUsed:
query.ColumnExpr("ts, gas_used as value")
case storage.SeriesBytesInBlock:
query.ColumnExpr("ts, bytes_in_block as value")
case storage.SeriesBlobsCount:
query.ColumnExpr("ts, blobs_count as value")
case storage.SeriesCommissions:
query.ColumnExpr("ts, commissions as value")
case storage.SeriesRewards:
query.ColumnExpr("ts, rewards as value")
default:
return nil, errors.Errorf("unexpected series name: %s", name)
}
if !req.From.IsZero() {
query = query.Where("ts >= ?", req.From)
}
if !req.To.IsZero() {
query = query.Where("ts < ?", req.To)
}
err = query.Scan(ctx, &response)
return
}
func (s Stats) NamespaceSeries(ctx context.Context, timeframe storage.Timeframe, name string, nsId uint64, req storage.SeriesRequest) (response []storage.SeriesItem, err error) {
var view string
switch timeframe {
case storage.TimeframeHour:
view = storage.ViewNamespaceStatsByHour
case storage.TimeframeDay:
view = storage.ViewNamespaceStatsByDay
case storage.TimeframeWeek:
view = storage.ViewNamespaceStatsByWeek
case storage.TimeframeMonth:
view = storage.ViewNamespaceStatsByMonth
case storage.TimeframeYear:
view = storage.ViewNamespaceStatsByYear
default:
return nil, errors.Errorf("unexpected timeframe %s", timeframe)
}
query := s.db.DB().NewSelect().Table(view).Where("namespace_id = ?", nsId)
switch name {
case storage.SeriesNsPfbCount:
query.ColumnExpr("ts, pfb_count as value")
case storage.SeriesNsSize:
query.ColumnExpr("ts, size as value")
default:
return nil, errors.Errorf("unexpected series name: %s", name)
}
if !req.From.IsZero() {
query = query.Where("ts >= ?", req.From)
}
if !req.To.IsZero() {
query = query.Where("ts < ?", req.To)
}
err = query.Scan(ctx, &response)
return
}
func (s Stats) CumulativeSeries(ctx context.Context, timeframe storage.Timeframe, name string, req storage.SeriesRequest) (response []storage.SeriesItem, err error) {
query := s.db.DB().NewSelect()
switch timeframe {
case storage.TimeframeHour:
query.Table(storage.ViewBlockStatsByHour)
case storage.TimeframeDay:
query.Table(storage.ViewBlockStatsByDay)
case storage.TimeframeWeek:
query.Table(storage.ViewBlockStatsByWeek)
case storage.TimeframeMonth:
query.Table(storage.ViewBlockStatsByMonth)
case storage.TimeframeYear:
query.Table(storage.ViewBlockStatsByYear)
default:
return nil, errors.Errorf("unexpected timeframe %s", timeframe)
}
switch name {
case storage.SeriesBlobsSize:
query.ColumnExpr("ts, sum(sum(blobs_size)) OVER(ORDER BY ts) as value")
case storage.SeriesFee:
query.ColumnExpr("ts, sum(sum(fee)) OVER(ORDER BY ts) as value")
case storage.SeriesTxCount:
query.ColumnExpr("ts, sum(sum(tx_count)) OVER(ORDER BY ts) as value")
case storage.SeriesGasLimit:
query.ColumnExpr("ts, sum(sum(gas_limit)) OVER(ORDER BY ts) as value")
case storage.SeriesGasUsed:
query.ColumnExpr("ts, sum(sum(gas_used)) OVER(ORDER BY ts) as value")
case storage.SeriesBytesInBlock:
query.ColumnExpr("ts, sum(sum(bytes_in_block)) OVER(ORDER BY ts) as value")
case storage.SeriesBlobsCount:
query.ColumnExpr("ts, sum(sum(blobs_count)) OVER(ORDER BY ts) as value")
case storage.SeriesSupplyChange:
query.ColumnExpr("ts, sum(sum(supply_change)) OVER(ORDER BY ts) as value")
default:
return nil, errors.Errorf("unexpected series name: %s", name)
}
withQuery := query.Group("ts")
q := s.db.DB().
NewSelect().
With("q", withQuery).
Table("q")
if !req.From.IsZero() {
q = q.Where("ts >= ?", req.From)
}
if !req.To.IsZero() {
q = q.Where("ts < ?", req.To)
}
err = q.Scan(ctx, &response)
return
}
func (s Stats) StakingSeries(ctx context.Context, timeframe storage.Timeframe, name string, validatorId uint64, req storage.SeriesRequest) (response []storage.SeriesItem, err error) {
var view string
switch timeframe {
case storage.TimeframeHour:
view = storage.ViewStakingByHour
case storage.TimeframeDay:
view = storage.ViewStakingByDay
case storage.TimeframeMonth:
view = storage.ViewStakingByMonth
default:
return nil, errors.Errorf("unexpected timeframe %s", timeframe)
}
query := s.db.DB().NewSelect().Table(view).Where("validator_id = ?", validatorId)
switch name {
case storage.SeriesRewards:
query.ColumnExpr("time as ts, rewards as value")
case storage.SeriesCommissions:
query.ColumnExpr("time as ts, commissions as value")
case storage.SeriesFlow:
query.ColumnExpr("time as ts, flow as value")
default:
return nil, errors.Errorf("unexpected series name: %s", name)
}
if !req.From.IsZero() {
query = query.Where("time >= ?", req.From)
}
if !req.To.IsZero() {
query = query.Where("time < ?", req.To)
}
err = query.Scan(ctx, &response)
return
}
type squareSize struct {
SquareSize int `bun:"square_size"`
Time time.Time `bun:"ts"`
CountBlocks string `bun:"count_blocks"`
}
func (s Stats) SquareSize(ctx context.Context, from, to *time.Time) (result map[int][]storage.SeriesItem, err error) {
query := s.db.DB().NewSelect().
Table(storage.ViewSquareSize).
OrderExpr("ts desc, square_size desc")
switch {
case from == nil && to == nil:
query.
Where("ts >= ?", time.Now().AddDate(0, -1, 0).UTC())
case from != nil && to == nil:
query.
Where("ts >= ?", from.UTC()).
Where("ts < ?", from.AddDate(0, 1, 0).UTC())
case from == nil && to != nil:
query.
Where("ts >= ?", to.AddDate(0, -1, 0).UTC()).
Where("ts < ?", to.UTC())
case from != nil && to != nil:
query.
Where("ts >= ?", from.UTC()).
Where("ts < ?", to.UTC())
}
var response []squareSize
if err := query.Scan(ctx, &response); err != nil {
return result, err
}
result = make(map[int][]storage.SeriesItem)
for _, item := range response {
seriesItem := storage.SeriesItem{
Value: item.CountBlocks,
Time: item.Time,
}
if _, ok := result[item.SquareSize]; !ok {
result[item.SquareSize] = make([]storage.SeriesItem, 0)
}
result[item.SquareSize] = append(result[item.SquareSize], seriesItem)
}
return
}
func (s Stats) RollupStats24h(ctx context.Context) (response []storage.RollupStats24h, err error) {
inner := s.db.DB().NewSelect().
Table(storage.ViewRollupStatsByHour).
Column("namespace_id", "signer_id", "size", "fee", "blobs_count").
Where("time > now() - '1 day'::interval")
joined := s.db.DB().NewSelect().
TableExpr("(?) as data", inner).
ColumnExpr("rollup_id, sum(data.size) as size, sum(data.fee) as fee, sum(data.blobs_count) as blobs_count").
Join("left join rollup_provider as rp on rp.address_id = data.signer_id AND (rp.namespace_id = data.namespace_id OR rp.namespace_id = 0)").
Group("rollup_id")
err = s.db.DB().NewSelect().
TableExpr("(?) as grouped", joined).
ColumnExpr("grouped.*, r.name, r.logo").
Join("left join rollup as r on r.id = grouped.rollup_id").
Order("blobs_count desc").
Scan(ctx, &response)
return
}
func (s Stats) MessagesCount24h(ctx context.Context) (response []storage.CountItem, err error) {
err = s.db.DB().NewSelect().
Model((*storage.Message)(nil)).
ColumnExpr("count(*) as value, type as name").
Where("time > now() - '1 day'::interval").
Group("type").
Order("value desc").
Scan(ctx, &response)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/lib/pq"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
"github.com/vmihailenco/msgpack/v5"
models "github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
)
type Transaction struct {
storage.Transaction
}
func BeginTransaction(ctx context.Context, tx storage.Transactable) (models.Transaction, error) {
t, err := tx.BeginTransaction(ctx)
return Transaction{t}, err
}
func (tx Transaction) SaveConstants(ctx context.Context, constants ...models.Constant) error {
if len(constants) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&constants).Exec(ctx)
return err
}
func (tx Transaction) SaveTransactions(ctx context.Context, txs ...models.Tx) error {
switch len(txs) {
case 0:
return nil
case 1:
return tx.Add(ctx, &txs[0])
default:
arr := make([]any, len(txs))
for i := range txs {
arr[i] = &txs[i]
}
return tx.BulkSave(ctx, arr)
}
}
type addedNamespace struct {
bun.BaseModel `bun:"namespace"`
*models.Namespace
Xmax uint64 `bun:"xmax"`
}
func (tx Transaction) SaveNamespaces(ctx context.Context, namespaces ...*models.Namespace) (int64, error) {
if len(namespaces) == 0 {
return 0, nil
}
addedNamespaces := make([]addedNamespace, len(namespaces))
for i := range namespaces {
addedNamespaces[i].Namespace = namespaces[i]
}
_, err := tx.Tx().NewInsert().Model(&addedNamespaces).
Column("version", "namespace_id", "pfb_count", "size", "first_height", "last_height", "last_message_time", "blobs_count").
On("CONFLICT ON CONSTRAINT namespace_id_version_idx DO UPDATE").
Set("size = EXCLUDED.size + added_namespace.size").
Set("pfb_count = EXCLUDED.pfb_count + added_namespace.pfb_count").
Set("last_height = EXCLUDED.last_height").
Set("last_message_time = EXCLUDED.last_message_time").
Set("blobs_count = EXCLUDED.blobs_count + added_namespace.blobs_count").
Returning("xmax, id").
Exec(ctx)
if err != nil {
return 0, err
}
var count int64
for i := range addedNamespaces {
if addedNamespaces[i].Xmax == 0 {
count++
}
}
return count, err
}
type addedAddress struct {
bun.BaseModel `bun:"address"`
*models.Address
Xmax uint64 `bun:"xmax"`
}
func (tx Transaction) SaveAddresses(ctx context.Context, addresses ...*models.Address) (int64, error) {
if len(addresses) == 0 {
return 0, nil
}
addr := make([]addedAddress, len(addresses))
for i := range addresses {
addr[i].Address = addresses[i]
}
_, err := tx.Tx().NewInsert().Model(&addr).
Column("address", "height", "last_height", "hash").
On("CONFLICT ON CONSTRAINT address_idx DO UPDATE").
Set("last_height = EXCLUDED.last_height").
Returning("xmax, id").
Exec(ctx)
if err != nil {
return 0, err
}
var count int64
for i := range addr {
if addr[i].Xmax == 0 {
count++
}
}
return count, err
}
func (tx Transaction) SaveBalances(ctx context.Context, balances ...models.Balance) error {
if len(balances) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&balances).
Column("id", "currency", "spendable", "delegated", "unbonding").
On("CONFLICT (id, currency) DO UPDATE").
Set("spendable = EXCLUDED.spendable + balance.spendable").
Set("delegated = EXCLUDED.delegated + balance.delegated").
Set("unbonding = EXCLUDED.unbonding + balance.unbonding").
Exec(ctx)
return err
}
func (tx Transaction) SaveEvents(ctx context.Context, events ...models.Event) error {
switch {
case len(events) == 0:
return nil
case len(events) < 20:
_, err := tx.Tx().NewInsert().Model(&events).Exec(ctx)
return err
default:
stmt, err := tx.Tx().PrepareContext(ctx,
pq.CopyIn("event", "height", "time", "position", "type", "tx_id", "data"),
)
if err != nil {
return err
}
for i := range events {
var s []byte
if len(events[i].Data) > 0 {
if raw, err := msgpack.Marshal(events[i].Data); err == nil {
s = raw
}
}
if _, err := stmt.ExecContext(ctx, events[i].Height, events[i].Time, events[i].Position, events[i].Type, events[i].TxId, s); err != nil {
return err
}
}
if _, err := stmt.ExecContext(ctx); err != nil {
return err
}
return stmt.Close()
}
}
func (tx Transaction) SaveMessages(ctx context.Context, msgs ...*models.Message) error {
if len(msgs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&msgs).Returning("id").Exec(ctx)
return err
}
func (tx Transaction) SaveSigners(ctx context.Context, addresses ...models.Signer) error {
if len(addresses) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&addresses).Exec(ctx)
return err
}
func (tx Transaction) SaveBlobLogs(ctx context.Context, logs ...models.BlobLog) error {
if len(logs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&logs).Exec(ctx)
return err
}
func (tx Transaction) SaveMsgAddresses(ctx context.Context, addresses ...models.MsgAddress) error {
if len(addresses) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&addresses).Exec(ctx)
return err
}
func (tx Transaction) SaveNamespaceMessage(ctx context.Context, nsMsgs ...models.NamespaceMessage) error {
if len(nsMsgs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&nsMsgs).Exec(ctx)
return err
}
func (tx Transaction) SaveBlockSignatures(ctx context.Context, signs ...models.BlockSignature) error {
if len(signs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&signs).Exec(ctx)
return err
}
func (tx Transaction) SaveVestingAccounts(ctx context.Context, accs ...*models.VestingAccount) error {
if len(accs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&accs).Returning("id").Exec(ctx)
return err
}
func (tx Transaction) SaveVestingPeriods(ctx context.Context, periods ...models.VestingPeriod) error {
if len(periods) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&periods).Returning("id").Exec(ctx)
return err
}
func (tx Transaction) SaveGrants(ctx context.Context, grants ...models.Grant) error {
if len(grants) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().
Model(&grants).
Column("height", "time", "granter_id", "grantee_id", "authorization", "expiration", "revoked", "revoke_height", "params").
On("CONFLICT ON CONSTRAINT grant_key DO UPDATE").
Set("revoked = EXCLUDED.revoked").
Set("revoke_height = EXCLUDED.revoke_height").
Exec(ctx)
return err
}
type addedValidator struct {
bun.BaseModel `bun:"validator"`
*models.Validator
Xmax uint64 `bun:"xmax"`
}
func (tx Transaction) SaveValidators(ctx context.Context, validators ...*models.Validator) (int, error) {
if len(validators) == 0 {
return 0, nil
}
arr := make([]addedValidator, len(validators))
for i := range validators {
arr[i].Validator = validators[i]
}
query := tx.Tx().NewInsert().Model(&arr).
Column("id", "delegator", "address", "cons_address", "moniker", "website", "identity", "contacts", "details", "rate", "max_rate", "max_change_rate", "min_self_delegation", "stake", "jailed", "commissions", "rewards", "height").
On("CONFLICT ON CONSTRAINT address_validator DO UPDATE").
Set("rate = CASE WHEN EXCLUDED.rate > 0 THEN EXCLUDED.rate ELSE added_validator.rate END").
Set("min_self_delegation = CASE WHEN EXCLUDED.min_self_delegation > 0 THEN EXCLUDED.min_self_delegation ELSE added_validator.min_self_delegation END").
Set("stake = added_validator.stake + EXCLUDED.stake").
Set("commissions = added_validator.commissions + EXCLUDED.commissions").
Set("rewards = added_validator.rewards + EXCLUDED.rewards").
Set("moniker = CASE WHEN EXCLUDED.moniker != '[do-not-modify]' THEN EXCLUDED.moniker ELSE added_validator.moniker END").
Set("website = CASE WHEN EXCLUDED.website != '[do-not-modify]' THEN EXCLUDED.website ELSE added_validator.website END").
Set("identity = CASE WHEN EXCLUDED.identity != '[do-not-modify]' THEN EXCLUDED.identity ELSE added_validator.identity END").
Set("contacts = CASE WHEN EXCLUDED.contacts != '[do-not-modify]' THEN EXCLUDED.contacts ELSE added_validator.contacts END").
Set("details = CASE WHEN EXCLUDED.details != '[do-not-modify]' THEN EXCLUDED.details ELSE added_validator.details END").
Set("jailed = CASE WHEN EXCLUDED.jailed IS NOT NULL THEN EXCLUDED.jailed ELSE added_validator.jailed END").
Returning("xmax, id")
if _, err := query.Exec(ctx); err != nil {
return 0, err
}
var count int
for i := range arr {
if arr[i].Xmax == 0 {
count++
}
}
return count, nil
}
func (tx Transaction) SaveUndelegations(ctx context.Context, undelegations ...models.Undelegation) error {
if len(undelegations) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&undelegations).Exec(ctx)
return err
}
func (tx Transaction) SaveRedelegations(ctx context.Context, redelegations ...models.Redelegation) error {
if len(redelegations) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&redelegations).Exec(ctx)
return err
}
func (tx Transaction) SaveStakingLogs(ctx context.Context, logs ...models.StakingLog) error {
if len(logs) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&logs).Exec(ctx)
return err
}
func (tx Transaction) SaveDelegations(ctx context.Context, delegations ...models.Delegation) error {
if len(delegations) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&delegations).
Column("id", "address_id", "validator_id", "amount").
On("CONFLICT ON CONSTRAINT delegation_pair DO UPDATE").
Set("amount = delegation.amount + EXCLUDED.amount").
Exec(ctx)
return err
}
func (tx Transaction) SaveJails(ctx context.Context, jails ...models.Jail) error {
if len(jails) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&jails).Exec(ctx)
return err
}
func (tx Transaction) Jail(ctx context.Context, validators ...*models.Validator) error {
if len(validators) == 0 {
return nil
}
values := tx.Tx().NewValues(&validators)
_, err := tx.Tx().NewUpdate().
With("_data", values).
Model((*models.Validator)(nil)).
TableExpr("_data").
Set("jailed = true").
Set("stake = _data.stake + validator.stake").
Where("validator.id = _data.id").
Exec(ctx)
return err
}
func (tx Transaction) UpdateSlashedDelegations(ctx context.Context, validatorId uint64, fraction decimal.Decimal) (balances []models.Balance, err error) {
if validatorId == 0 || !fraction.IsPositive() {
return nil, nil
}
fr, _ := fraction.Float64()
_, err = tx.Tx().NewUpdate().
Model((*models.Delegation)(nil)).
Set("amount = amount * (1 - ?)", fr).
Where("validator_id = ?", validatorId).
Returning("address_id as id, 'utia' as currency, -(amount / (1 - ?) - amount) as delegated", fr).
Exec(ctx, &balances)
return
}
func (tx Transaction) LastBlock(ctx context.Context) (block models.Block, err error) {
err = tx.Tx().NewSelect().Model(&block).Order("id desc").Limit(1).Scan(ctx)
return
}
func (tx Transaction) State(ctx context.Context, name string) (state models.State, err error) {
err = tx.Tx().NewSelect().Model(&state).Where("name = ?", name).Scan(ctx)
return
}
func (tx Transaction) Namespace(ctx context.Context, id uint64) (ns models.Namespace, err error) {
err = tx.Tx().NewSelect().Model(&ns).Where("id = ?", id).Scan(ctx)
return
}
func (tx Transaction) RollbackBlock(ctx context.Context, height types.Level) error {
_, err := tx.Tx().NewDelete().
Model((*models.Block)(nil)).
Where("height = ?", height).
Exec(ctx)
return err
}
func (tx Transaction) RollbackBlockStats(ctx context.Context, height types.Level) (stats models.BlockStats, err error) {
_, err = tx.Tx().NewDelete().Model(&stats).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackAddresses(ctx context.Context, height types.Level) (address []models.Address, err error) {
_, err = tx.Tx().NewDelete().Model(&address).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackTxs(ctx context.Context, height types.Level) (txs []models.Tx, err error) {
_, err = tx.Tx().NewDelete().Model(&txs).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackEvents(ctx context.Context, height types.Level) (events []models.Event, err error) {
_, err = tx.Tx().NewDelete().Model(&events).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackMessages(ctx context.Context, height types.Level) (msgs []models.Message, err error) {
_, err = tx.Tx().NewDelete().Model(&msgs).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackNamespaceMessages(ctx context.Context, height types.Level) (msgs []models.NamespaceMessage, err error) {
_, err = tx.Tx().NewDelete().Model(&msgs).Where("height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackNamespaces(ctx context.Context, height types.Level) (ns []models.Namespace, err error) {
_, err = tx.Tx().NewDelete().Model(&ns).Where("first_height = ?", height).Returning("*").Exec(ctx)
return
}
func (tx Transaction) RollbackValidators(ctx context.Context, height types.Level) (validators []models.Validator, err error) {
_, err = tx.Tx().NewDelete().Model(&validators).Where("height = ?", height).Returning("id").Exec(ctx)
return
}
func (tx Transaction) RollbackBlobLog(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.BlobLog)(nil)).Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackGrants(ctx context.Context, height types.Level) (err error) {
if _, err = tx.Tx().NewDelete().
Model((*models.Grant)(nil)).
Where("height = ?", height).
Exec(ctx); err != nil {
return err
}
_, err = tx.Tx().NewUpdate().
Model((*models.Grant)(nil)).
Where("revoke_height = ?", height).
Set("revoked = false").
Set("revoke_height = null").
Exec(ctx)
return
}
func (tx Transaction) RollbackUndelegations(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.Undelegation)(nil)).Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackRedelegations(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.Redelegation)(nil)).Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackVestingAccounts(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.VestingAccount)(nil)).Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackVestingPeriods(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.VestingPeriod)(nil)).Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackSigners(ctx context.Context, txIds []uint64) (err error) {
_, err = tx.Tx().NewDelete().
Model((*models.Signer)(nil)).
Where("tx_id IN (?)", bun.In(txIds)).
Exec(ctx)
return
}
func (tx Transaction) RollbackMessageAddresses(ctx context.Context, msgIds []uint64) (err error) {
_, err = tx.Tx().NewDelete().
Model((*models.MsgAddress)(nil)).
Where("msg_id IN (?)", bun.In(msgIds)).
Exec(ctx)
return
}
func (tx Transaction) RollbackBlockSignatures(ctx context.Context, height types.Level) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.BlockSignature)(nil)).
Where("height = ?", height).Exec(ctx)
return
}
func (tx Transaction) RollbackJails(ctx context.Context, height types.Level) (jails []models.Jail, err error) {
_, err = tx.Tx().NewDelete().Model(&jails).
Where("height = ?", height).
Returning("id, validator_id").
Exec(ctx)
return
}
func (tx Transaction) RollbackStakingLogs(ctx context.Context, height types.Level) (logs []models.StakingLog, err error) {
_, err = tx.Tx().NewDelete().Model(&logs).
Where("height = ?", height).
Returning("*").
Exec(ctx)
return
}
func (tx Transaction) DeleteBalances(ctx context.Context, ids []uint64) error {
if len(ids) == 0 {
return nil
}
_, err := tx.Tx().NewDelete().
Model((*models.Balance)(nil)).
Where("id IN (?)", bun.In(ids)).
Exec(ctx)
return err
}
func (tx Transaction) DeleteDelegationsByValidator(ctx context.Context, ids ...uint64) error {
if len(ids) == 0 {
return nil
}
_, err := tx.Tx().NewDelete().
Model((*models.Delegation)(nil)).
Where("validator_id IN (?)", bun.In(ids)).
Exec(ctx)
return err
}
func (tx Transaction) LastAddressAction(ctx context.Context, address []byte) (uint64, error) {
var height uint64
err := tx.Tx().NewSelect().
Model((*models.MsgAddress)(nil)).
ExcludeColumn("msg_id", "address_id", "type").
Where("address.hash = ?", address).
Order("msg_id desc").
Relation("Msg", func(q *bun.SelectQuery) *bun.SelectQuery {
return q.Column("height")
}).
Relation("Address", func(q *bun.SelectQuery) *bun.SelectQuery {
return q.ExcludeColumn("*")
}).
Scan(ctx, &height)
return height, err
}
func (tx Transaction) LastNamespaceMessage(ctx context.Context, nsId uint64) (msg models.NamespaceMessage, err error) {
err = tx.Tx().NewSelect().
Model(&msg).
Where("namespace_id = ?", nsId).
Order("msg_id desc").
Limit(1).
Scan(ctx)
return
}
func (tx Transaction) GetProposerId(ctx context.Context, address string) (id uint64, err error) {
err = tx.Tx().NewSelect().
Model((*models.Validator)(nil)).
Column("id").
Where("cons_address = ?", address).
Order("id desc").
Limit(1).
Scan(ctx, &id)
return
}
func (tx Transaction) SaveRollup(ctx context.Context, rollup *models.Rollup) error {
if rollup == nil {
return nil
}
_, err := tx.Tx().NewInsert().Model(rollup).Exec(ctx)
return err
}
func (tx Transaction) UpdateRollup(ctx context.Context, rollup *models.Rollup) error {
if rollup == nil || (rollup.IsEmpty() && !rollup.Verified) {
return nil
}
query := tx.Tx().NewUpdate().Model(rollup).WherePK()
if rollup.Name != "" {
query = query.Set("name = ?", rollup.Name)
}
if rollup.Slug != "" {
query = query.Set("slug = ?", rollup.Slug)
}
if rollup.Description != "" {
query = query.Set("description = ?", rollup.Description)
}
if rollup.Twitter != "" {
query = query.Set("twitter = ?", rollup.Twitter)
}
if rollup.GitHub != "" {
query = query.Set("github = ?", rollup.GitHub)
}
if rollup.Website != "" {
query = query.Set("website = ?", rollup.Website)
}
if rollup.Logo != "" {
query = query.Set("logo = ?", rollup.Logo)
}
if rollup.L2Beat != "" {
query = query.Set("l2_beat = ?", rollup.L2Beat)
}
if rollup.Explorer != "" {
query = query.Set("explorer = ?", rollup.Explorer)
}
if rollup.BridgeContract != "" {
query = query.Set("bridge_contract = ?", rollup.BridgeContract)
}
if rollup.Stack != "" {
query = query.Set("stack = ?", rollup.Stack)
}
if rollup.Links != nil {
query = query.Set("links = ?", pq.Array(rollup.Links))
}
if rollup.Type != "" {
query = query.Set("type = ?", rollup.Type)
}
if rollup.Category != "" {
query = query.Set("category = ?", rollup.Category)
}
if rollup.Tags != nil {
query = query.Set("tags = ?", pq.Array(rollup.Tags))
}
if rollup.Provider != "" {
query = query.Set("provider = ?", rollup.Provider)
}
if rollup.Compression != "" {
query = query.Set("compression = ?", rollup.Compression)
}
if rollup.VM != "" {
query = query.Set("vm = ?", rollup.VM)
}
if rollup.DeFiLama != "" {
query = query.Set("defi_lama = ?", rollup.DeFiLama)
}
query = query.Set("verified = ?", rollup.Verified)
_, err := query.Exec(ctx)
return err
}
func (tx Transaction) SaveProviders(ctx context.Context, providers ...models.RollupProvider) error {
if len(providers) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&providers).Exec(ctx)
return err
}
func (tx Transaction) DeleteProviders(ctx context.Context, rollupId uint64) error {
if rollupId == 0 {
return nil
}
_, err := tx.Tx().NewDelete().
Model((*models.RollupProvider)(nil)).
Where("rollup_id = ?", rollupId).
Exec(ctx)
return err
}
func (tx Transaction) DeleteRollup(ctx context.Context, rollupId uint64) error {
if rollupId == 0 {
return nil
}
_, err := tx.Tx().NewDelete().
Model((*models.Rollup)(nil)).
Where("id = ?", rollupId).
Exec(ctx)
return err
}
func (tx Transaction) RetentionBlockSignatures(ctx context.Context, height types.Level) error {
_, err := tx.Tx().NewDelete().Model((*models.BlockSignature)(nil)).
Where("height <= ?", height).
Exec(ctx)
return err
}
func (tx Transaction) CancelUnbondings(ctx context.Context, cancellations ...models.Undelegation) error {
if len(cancellations) == 0 {
return nil
}
for i := range cancellations {
if _, err := tx.Tx().NewDelete().
Model(&cancellations[i]).
Where("height = ?height").
Where("amount = ?amount").
Where("validator_id = ?validator_id").
Where("address_id = ?address_id").
Exec(ctx); err != nil {
return err
}
}
return nil
}
func (tx Transaction) RetentionCompletedUnbondings(ctx context.Context, blockTime time.Time) error {
_, err := tx.Tx().NewDelete().Model((*models.Undelegation)(nil)).
Where("completion_time < ?", blockTime).
Exec(ctx)
return err
}
func (tx Transaction) RetentionCompletedRedelegations(ctx context.Context, blockTime time.Time) error {
_, err := tx.Tx().NewDelete().Model((*models.Redelegation)(nil)).
Where("completion_time < ?", blockTime).
Exec(ctx)
return err
}
func (tx Transaction) UpdateValidators(ctx context.Context, validators ...*models.Validator) error {
if len(validators) == 0 {
return nil
}
values := tx.Tx().NewValues(&validators)
_, err := tx.Tx().NewUpdate().
With("_data", values).
Model((*models.Validator)(nil)).
TableExpr("_data").
Set("stake = validator.stake + _data.stake").
Set("jailed = _data.jailed").
Set("commissions = validator.commissions + _data.commissions").
Set("rewards = validator.rewards + _data.rewards").
Where("validator.id = _data.id").
Exec(ctx)
return err
}
func (tx Transaction) Validator(ctx context.Context, id uint64) (val models.Validator, err error) {
err = tx.Tx().NewSelect().Model(&val).Where("id = ?", id).Scan(ctx)
return
}
func (tx Transaction) Delegation(ctx context.Context, validatorId, addressId uint64) (val models.Delegation, err error) {
err = tx.Tx().NewSelect().Model(&val).
Where("validator_id = ?", validatorId).
Where("address_id = ?", addressId).
Scan(ctx)
return
}
func (tx Transaction) RefreshLeaderboard(ctx context.Context) error {
_, err := tx.Tx().ExecContext(ctx, "REFRESH MATERIALIZED VIEW leaderboard;")
return err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/go-lib/database"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/uptrace/bun"
)
// Tx -
type Tx struct {
*postgres.Table[*storage.Tx]
}
// NewTx -
func NewTx(db *database.Bun) *Tx {
return &Tx{
Table: postgres.NewTable[*storage.Tx](db),
}
}
func (tx *Tx) getSigners(ctx context.Context, txId ...uint64) (signers []storage.Signer, err error) {
subQuery := tx.DB().NewSelect().
Model((*storage.Signer)(nil)).
Where("tx_id IN (?)", bun.In(txId))
err = tx.DB().NewSelect().TableExpr("(?) as signer", subQuery).
ColumnExpr("address.address as address__address").
ColumnExpr("celestial.id as address__celestials__id, celestial.image_url as address__celestials__image_url").
ColumnExpr("signer.*").
Join("left join address on address.id = signer.address_id").
Join("left join celestial on celestial.address_id = signer.address_id and celestial.status = 'PRIMARY'").
Scan(ctx, &signers)
return
}
func (tx *Tx) setSigners(ctx context.Context, txs []storage.Tx) error {
ids := make([]uint64, len(txs))
for i := range ids {
ids[i] = txs[i].Id
}
signers, err := tx.getSigners(ctx, ids...)
if err != nil {
return err
}
for i := range signers {
for j := range txs {
if txs[j].Id == signers[i].TxId && signers[i].Address != nil {
txs[j].Signers = append(txs[j].Signers, *signers[i].Address)
break
}
}
}
return nil
}
func (tx *Tx) ByHash(ctx context.Context, hash []byte) (transaction storage.Tx, err error) {
if err = tx.DB().NewSelect().Model(&transaction).
Where("hash = ?", hash).
Scan(ctx); err != nil {
return
}
signers, err := tx.getSigners(ctx, transaction.Id)
if err != nil {
return
}
transaction.Signers = make([]storage.Address, len(signers))
for i := range signers {
if signers[i].Address != nil {
transaction.Signers[i] = *signers[i].Address
}
}
return
}
func (tx *Tx) Filter(ctx context.Context, fltrs storage.TxFilter) (txs []storage.Tx, err error) {
query := tx.DB().NewSelect().Model(&txs).Offset(fltrs.Offset)
query = txFilter(query, fltrs)
if err = query.Scan(ctx); err != nil {
return
}
err = tx.setSigners(ctx, txs)
return
}
func (tx *Tx) ByIdWithRelations(ctx context.Context, id uint64) (transaction storage.Tx, err error) {
if err = tx.DB().NewSelect().Model(&transaction).
Where("id = ?", id).
Relation("Messages").
Scan(ctx); err != nil {
return
}
signers, err := tx.getSigners(ctx, transaction.Id)
if err != nil {
return
}
transaction.Signers = make([]storage.Address, len(signers))
for i := range signers {
if signers[i].Address != nil {
transaction.Signers[i] = *signers[i].Address
}
}
return
}
func (tx *Tx) ByAddress(ctx context.Context, addressId uint64, fltrs storage.TxFilter) ([]storage.Tx, error) {
var relations []storage.Signer
query := tx.DB().NewSelect().
Model(&relations).
Where("address_id = ?", addressId).
Relation("Tx").
Offset(fltrs.Offset)
query = txFilter(query, fltrs)
if err := query.Scan(ctx); err != nil {
return nil, err
}
transactions := make([]storage.Tx, len(relations))
for i := range relations {
transactions[i] = *relations[i].Tx
}
return transactions, nil
}
func (tx *Tx) Genesis(ctx context.Context, limit, offset int, sortOrder sdk.SortOrder) (txs []storage.Tx, err error) {
query := tx.DB().NewSelect().Model(&txs).Offset(offset).Where("hash IS NULL")
query = limitScope(query, limit)
query = sortScope(query, "id", sortOrder)
err = query.Scan(ctx)
return
}
func (tx *Tx) Gas(ctx context.Context, height types.Level, ts time.Time) (response []storage.Gas, err error) {
err = tx.DB().NewSelect().
Model((*storage.Tx)(nil)).
ColumnExpr("gas_wanted, gas_used, fee, (CASE WHEN gas_wanted > 0 THEN fee / gas_wanted ELSE 0 END) as gas_price").
Where("height = ?", height).
Where("gas_used <= gas_wanted").
Where("fee > 0").
Where("time = ?", ts).
Scan(ctx, &response)
return
}
func (tx *Tx) IdAndTimeByHash(ctx context.Context, hash []byte) (id uint64, t time.Time, err error) {
err = tx.DB().NewSelect().
Model((*storage.Tx)(nil)).
Column("id", "time").
Where("hash = ?", hash).
Scan(ctx, &id, &t)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// Undelegation -
type Undelegation struct {
*postgres.Table[*storage.Undelegation]
}
// NewUndelegation -
func NewUndelegation(db *database.Bun) *Undelegation {
return &Undelegation{
Table: postgres.NewTable[*storage.Undelegation](db),
}
}
func (d *Undelegation) ByAddress(ctx context.Context, addressId uint64, limit, offset int) (undelegations []storage.Undelegation, err error) {
subQuery := d.DB().NewSelect().Model((*storage.Undelegation)(nil)).
Where("address_id = ?", addressId).
Order("amount desc")
subQuery = limitScope(subQuery, limit)
if offset > 0 {
subQuery = subQuery.Offset(offset)
}
err = d.DB().NewSelect().
TableExpr("(?) as undelegation", subQuery).
ColumnExpr("undelegation.*").
ColumnExpr("validator.id as validator__id, validator.moniker as validator__moniker, validator.cons_address as validator__cons_address").
Join("left join validator on validator.id = validator_id").
Scan(ctx, &undelegations)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
"github.com/shopspring/decimal"
)
// Validator -
type Validator struct {
*postgres.Table[*storage.Validator]
}
// NewValidator -
func NewValidator(db *database.Bun) *Validator {
return &Validator{
Table: postgres.NewTable[*storage.Validator](db),
}
}
func (v *Validator) ByAddress(ctx context.Context, address string) (validator storage.Validator, err error) {
err = v.DB().NewSelect().Model(&validator).
Where("address = ?", address).
Scan(ctx)
return
}
func (v *Validator) TotalVotingPower(ctx context.Context) (decimal.Decimal, error) {
q := v.DB().NewSelect().
Model((*storage.Validator)(nil)).
Column("stake").
Where("jailed = false").
Order("stake desc").
Limit(100)
var power decimal.Decimal
err := v.DB().NewSelect().
With("q", q).
Table("q").
ColumnExpr("sum(floor(stake / 1000000))").
Scan(ctx, &power)
return power, err
}
func (v *Validator) ListByPower(ctx context.Context, fltrs storage.ValidatorFilters) (validators []storage.Validator, err error) {
query := v.DB().NewSelect().Model(&validators).
OrderExpr("(not jailed)::int * stake desc")
query = limitScope(query, fltrs.Limit)
if fltrs.Offset > 0 {
query = query.Offset(fltrs.Offset)
}
if fltrs.Jailed != nil {
if *fltrs.Jailed {
query = query.Where("jailed = true")
} else {
query = query.Where("jailed = false")
}
}
err = query.Scan(ctx)
return
}
func (v *Validator) JailedCount(ctx context.Context) (int, error) {
return v.DB().NewSelect().
Model((*storage.Validator)(nil)).
Where("jailed = true").
Count(ctx)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// VestingAccount -
type VestingAccount struct {
*postgres.Table[*storage.VestingAccount]
}
// NewVestingAccount -
func NewVestingAccount(db *database.Bun) *VestingAccount {
return &VestingAccount{
Table: postgres.NewTable[*storage.VestingAccount](db),
}
}
func (v *VestingAccount) ByAddress(ctx context.Context, addressId uint64, limit, offset int, showEnded bool) (accs []storage.VestingAccount, err error) {
query := v.DB().NewSelect().
Model((*storage.VestingAccount)(nil)).
Where("address_id = ?", addressId).
Order("end_time desc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
if !showEnded {
query = query.Where("end_time >= ?", time.Now().UTC())
}
err = v.DB().NewSelect().
TableExpr("(?) as vesting_account", query).
ColumnExpr("vesting_account.*").
ColumnExpr("tx.hash as tx__hash").
Join("left join tx on tx.id = tx_id").
Scan(ctx, &accs)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// VestingPeriod -
type VestingPeriod struct {
*postgres.Table[*storage.VestingPeriod]
}
// NewVestingPeriod -
func NewVestingPeriod(db *database.Bun) *VestingPeriod {
return &VestingPeriod{
Table: postgres.NewTable[*storage.VestingPeriod](db),
}
}
func (v *VestingPeriod) ByVesting(ctx context.Context, id uint64, limit, offset int) (periods []storage.VestingPeriod, err error) {
query := v.DB().NewSelect().
Model(&periods).
Where("vesting_account_id = ?", id).
Order("id desc")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = query.Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
const (
PriceTimeframeMinute = "1m"
PriceTimeframeHour = "1h"
PriceTimeframeDay = "1d"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IPrice interface {
Save(ctx context.Context, price *Price) error
Last(ctx context.Context) (Price, error)
Get(ctx context.Context, timeframe string, start, end time.Time, limit int) ([]Price, error)
}
type Price struct {
bun.BaseModel `bun:"price" comment:"Table with TIA price"`
Time time.Time `bun:"time,pk" comment:"Time of candles"`
Open decimal.Decimal `bun:"open,,type:numeric" comment:"Open price"`
High decimal.Decimal `bun:"high,,type:numeric" comment:"High price"`
Low decimal.Decimal `bun:"low,,type:numeric" comment:"Low price"`
Close decimal.Decimal `bun:"close,,type:numeric" comment:"Close price"`
}
// TableName -
func (Price) TableName() string {
return "price"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IRedelegation interface {
storage.Table[*Redelegation]
ByAddress(ctx context.Context, addressId uint64, limit, offset int) ([]Redelegation, error)
}
// Redelegation -
type Redelegation struct {
bun.BaseModel `bun:"redelegation" comment:"Table with redelegations"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Time time.Time `bun:"time,notnull" comment:"The time of block"`
Height pkgTypes.Level `bun:",notnull" comment:"The number (height) of this block"`
AddressId uint64 `bun:"address_id" comment:"Internal address id"`
SrcId uint64 `bun:"src_id" comment:"Internal source validator id"`
DestId uint64 `bun:"dest_id" comment:"Internal destination validator id"`
Amount decimal.Decimal `bun:"amount,type:numeric" comment:"Delegated amount"`
CompletionTime time.Time `bun:"completion_time" comment:"Time when redelegation will be completed"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Source *Validator `bun:"rel:belongs-to,join:src_id=id"`
Destination *Validator `bun:"rel:belongs-to,join:dest_id=id"`
}
// TableName -
func (Redelegation) TableName() string {
return "redelegation"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
type LeaderboardFilters struct {
SortField string
Sort sdk.SortOrder
Limit int
Offset int
Category []types.RollupCategory
Tags []string
Type []types.RollupType
Stack []string
Provider []string
}
type RollupGroupStatsFilters struct {
Func string
Column string
}
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IRollup interface {
sdk.Table[*Rollup]
Leaderboard(ctx context.Context, fltrs LeaderboardFilters) ([]RollupWithStats, error)
LeaderboardDay(ctx context.Context, fltrs LeaderboardFilters) ([]RollupWithDayStats, error)
Namespaces(ctx context.Context, rollupId uint64, limit, offset int) (namespaceIds []uint64, err error)
Providers(ctx context.Context, rollupId uint64) (providers []RollupProvider, err error)
RollupsByNamespace(ctx context.Context, namespaceId uint64, limit, offset int) (rollups []Rollup, err error)
ById(ctx context.Context, rollupId uint64) (RollupWithStats, error)
Series(ctx context.Context, rollupId uint64, timeframe Timeframe, column string, req SeriesRequest) (items []HistogramItem, err error)
AllSeries(ctx context.Context, timeframe Timeframe) ([]RollupHistogramItem, error)
Count(ctx context.Context) (int64, error)
Distribution(ctx context.Context, rollupId uint64, series string, groupBy Timeframe) (items []DistributionItem, err error)
BySlug(ctx context.Context, slug string) (RollupWithStats, error)
RollupStatsGrouping(ctx context.Context, fltrs RollupGroupStatsFilters) ([]RollupGroupedStats, error)
Tags(ctx context.Context) ([]string, error)
Unverified(ctx context.Context) (rollups []Rollup, err error)
}
// Rollup -
type Rollup struct {
bun.BaseModel `bun:"rollup" comment:"Table with rollups."`
Id uint64 `bun:"id,pk,autoincrement" comment:"Unique internal identity"`
Name string `bun:"name" comment:"Rollup's name"`
Description string `bun:"description" comment:"Rollup's description"`
Website string `bun:"website" comment:"Website"`
GitHub string `bun:"github" comment:"Github repository"`
Twitter string `bun:"twitter" comment:"Twitter account"`
Logo string `bun:"logo" comment:"Link to rollup logo"`
Slug string `bun:"slug,unique:rollup_slug" comment:"Rollup slug"`
BridgeContract string `bun:"bridge_contract" comment:"Link to bridge contract"`
L2Beat string `bun:"l2_beat" comment:"Link to L2 Beat"`
DeFiLama string `bun:"defi_lama" comment:"DeFi Lama chain name"`
Explorer string `bun:"explorer" comment:"Link to chain explorer"`
Stack string `bun:"stack" comment:"Underlaying stack"`
Compression string `bun:"compression" comment:"Compression"`
Provider string `bun:"provider" comment:"RaaS provider"`
Type types.RollupType `bun:"type,type:rollup_type" comment:"Type of rollup: settled or sovereign"`
Category types.RollupCategory `bun:"category,type:rollup_category" comment:"Category of rollup"`
Tags []string `bun:"tags,array"`
VM string `bun:"vm" comment:"Virtual machine"`
Links []string `bun:"links,array" comment:"Other links to rollup related sites"`
Verified bool `bun:"verified"`
Providers []*RollupProvider `bun:"rel:has-many,join:id=rollup_id"`
}
// TableName -
func (Rollup) TableName() string {
return "rollup"
}
func (r Rollup) IsEmpty() bool {
return r.Description == "" &&
r.GitHub == "" &&
r.Name == "" &&
r.Twitter == "" &&
r.Website == "" &&
r.Logo == "" &&
r.L2Beat == "" &&
r.BridgeContract == "" &&
r.Explorer == "" &&
r.Stack == "" &&
r.Links == nil &&
r.Category == "" &&
r.Tags == nil &&
r.Compression == "" &&
r.Provider == "" &&
r.Type == "" &&
r.VM == "" &&
r.DeFiLama == ""
}
type RollupWithStats struct {
Rollup
RollupStats
DAChange
}
type DAChange struct {
DAPct float64 `bun:"da_pct"`
}
type RollupStats struct {
Size int64 `bun:"size"`
BlobsCount int64 `bun:"blobs_count"`
LastActionTime time.Time `bun:"last_time"`
FirstActionTime time.Time `bun:"first_time"`
Fee decimal.Decimal `bun:"fee"`
SizePct float64 `bun:"size_pct"`
FeePct float64 `bun:"fee_pct"`
BlobsCountPct float64 `bun:"blobs_count_pct"`
}
type RollupWithDayStats struct {
Rollup
RolluDayStats
}
type RolluDayStats struct {
AvgSize float64 `bun:"avg_size"`
BlobsCount int64 `bun:"blobs_count"`
TotalSize int64 `bun:"total_size"`
Throghput int64 `bun:"throughput"`
TotalFee decimal.Decimal `bun:"total_fee"`
NamespaceCount int64 `bun:"namespace_count"`
PfbCount int64 `bun:"pfb_count"`
MBPrice decimal.Decimal `bun:"mb_price"`
}
type RollupHistogramItem struct {
Fee string `bun:"fee"`
BlobsCount int64 `bun:"blobs_count"`
Size int64 `bun:"size"`
Name string `bun:"name"`
Logo string `bun:"logo"`
Time time.Time `bun:"time"`
}
type RollupGroupedStats struct {
Fee float64 `bun:"fee"`
Size float64 `bun:"size"`
BlobsCount int64 `bun:"blobs_count"`
Group string `bun:"group"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IRollupProvider interface {
storage.Table[*RollupProvider]
}
// RollupProvider -
type RollupProvider struct {
bun.BaseModel `bun:"rollup_provider" comment:"Table with data providers for rollups."`
RollupId uint64 `bun:"rollup_id,pk" comment:"Unique internal rollup identity"`
NamespaceId uint64 `bun:"namespace_id,pk" comment:"Namespace identity. May be NULL"`
AddressId uint64 `bun:"address_id,pk" comment:"Celestia address of data provider"`
}
// TableName -
func (RollupProvider) TableName() string {
return "rollup_provider"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/uptrace/bun"
)
type Signer struct {
bun.BaseModel `bun:"signer" comment:"Table with signers tx"`
AddressId uint64 `bun:"address_id,pk" comment:"Address internal id"`
TxId uint64 `bun:"tx_id,pk" comment:"Transaction internal id"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Tx *Tx `bun:"rel:belongs-to,join:tx_id=id"`
}
func (Signer) TableName() string {
return "signer"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IStakingLog interface {
storage.Table[*StakingLog]
}
// Delegation -
type StakingLog struct {
bun.BaseModel `bun:"staking_log" comment:"Table with staking events log"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
Height pkgTypes.Level `bun:"height,notnull" comment:"The number (height) of this block" stats:"func:min max,filterable"`
AddressId *uint64 `bun:"address_id" comment:"Internal address id"`
ValidatorId uint64 `bun:"validator_id" comment:"Internal validator id"`
Change decimal.Decimal `bun:"change,type:numeric" comment:"Change amount"`
Type types.StakingLogType `bun:"type,type:staking_log_type" comment:"Staking log type"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Validator *Validator `bun:"rel:belongs-to,join:validator_id=id"`
}
// TableName -
func (StakingLog) TableName() string {
return "staking_log"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IState interface {
storage.Table[*State]
ByName(ctx context.Context, name string) (State, error)
}
// State -
type State struct {
bun.BaseModel `bun:"state" comment:"Current indexer state"`
Id uint64 `bun:",pk,autoincrement" comment:"Unique internal identity"`
Name string `bun:",unique:state_name" comment:"Indexer name"`
LastHeight types.Level `bun:"last_height" comment:"Last block height"`
LastHash []byte `bun:"last_hash" comment:"Last block hash"`
LastTime time.Time `bun:"last_time" comment:"Time of last block"`
ChainId string `bun:"chain_id" comment:"Celestia chain id"`
TotalTx int64 `bun:"total_tx" comment:"Transactions count in celestia"`
TotalAccounts int64 `bun:"total_accounts" comment:"Accounts count in celestia"`
TotalNamespaces int64 `bun:"total_namespaces" comment:"Namespaces count in celestia"`
TotalBlobsSize int64 `bun:"total_blobs_size" comment:"Total blobs size"`
TotalValidators int `bun:"total_validators" comment:"Total validator's count"`
TotalSupply decimal.Decimal `bun:"total_supply,type:numeric" comment:"Total supply in celestia"`
TotalFee decimal.Decimal `bun:"total_fee,type:numeric" comment:"Total paid fee"`
TotalStake decimal.Decimal `bun:"total_stake,type:numeric" comment:"Total stake"`
TotalVotingPower decimal.Decimal `bun:"-"`
}
// TableName -
func (State) TableName() string {
return "state"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/stats"
"github.com/pkg/errors"
)
type CountRequest struct {
Table string
From uint64
To uint64
}
func (req CountRequest) Validate() error {
if _, ok := stats.Tables[req.Table]; !ok {
return errors.Wrapf(ErrValidation, "unknown table '%s' for stats computing", req.Table)
}
return nil
}
type SummaryRequest struct {
CountRequest
Column string
Function string
}
func (req SummaryRequest) Validate() error {
table, ok := stats.Tables[req.Table]
if !ok {
return errors.Wrapf(ErrValidation, "unknown table '%s' for stats computing", req.Table)
}
column, ok := table.Columns[req.Column]
if !ok {
return errors.Wrapf(ErrValidation, "unknown column '%s' in table '%s' for stats computing", req.Column, req.Table)
}
if _, ok := column.Functions[req.Function]; !ok {
return errors.Wrapf(ErrValidation, "unknown function '%s' for '%s'.'%s'", req.Function, req.Table, req.Column)
}
return nil
}
type Timeframe string
const (
TimeframeHour Timeframe = "hour"
TimeframeDay Timeframe = "day"
TimeframeWeek Timeframe = "week"
TimeframeMonth Timeframe = "month"
TimeframeYear Timeframe = "year"
)
type HistogramRequest struct {
SummaryRequest
Timeframe Timeframe
}
func (req HistogramRequest) Validate() error {
if err := req.SummaryRequest.Validate(); err != nil {
return err
}
return nil
}
type HistogramCountRequest struct {
CountRequest
Timeframe Timeframe
}
func (req HistogramCountRequest) Validate() error {
if err := req.CountRequest.Validate(); err != nil {
return err
}
return nil
}
type HistogramItem struct {
Time time.Time `bun:"bucket"`
Value string `bun:"value"`
}
type TPS struct {
Low float64
High float64
Current float64
ChangeLastHourPct float64
}
type Change24hBlockStats struct {
TxCount float64 `bun:"tx_count_24h"`
Fee float64 `bun:"fee_24h"`
BlobsSize float64 `bun:"blobs_size_24h"`
BytesInBlock float64 `bun:"bytes_in_block_24h"`
}
type SeriesRequest struct {
From time.Time
To time.Time
}
type DistributionItem struct {
Name int `bun:"name"`
Value string `bun:"value"`
}
type CountItem struct {
Name string `bun:"name"`
Value int64 `bun:"value"`
}
func NewSeriesRequest(from, to int64) SeriesRequest {
var seriesRequest SeriesRequest
if from > 0 {
seriesRequest.From = time.Unix(from, 0).UTC()
}
if to > 0 {
seriesRequest.To = time.Unix(to, 0).UTC()
}
return seriesRequest
}
type RollupStats24h struct {
RollupId int64 `bun:"rollup_id"`
Name string `bun:"name"`
Logo string `bun:"logo"`
Size int64 `bun:"size"`
Fee float64 `bun:"fee"`
BlobsCount int64 `bun:"blobs_count"`
}
type SeriesItem struct {
Time time.Time `bun:"ts"`
Value string `bun:"value"`
Max string `bun:"max"`
Min string `bun:"min"`
}
const (
SeriesBlobsSize = "blobs_size"
SeriesBlobsCount = "blobs_count"
SeriesBlobsFee = "blobs_fee"
SeriesTPS = "tps"
SeriesBPS = "bps"
SeriesFee = "fee"
SeriesSupplyChange = "supply_change"
SeriesBlockTime = "block_time"
SeriesTxCount = "tx_count"
SeriesEventsCount = "events_count"
SeriesGasPrice = "gas_price"
SeriesGasUsed = "gas_used"
SeriesGasLimit = "gas_limit"
SeriesGasEfficiency = "gas_efficiency"
SeriesNsPfbCount = "pfb_count"
SeriesNsSize = "size"
SeriesBytesInBlock = "bytes_in_block"
SeriesRewards = "rewards"
SeriesCommissions = "commissions"
SeriesFlow = "flow"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IStats interface {
Count(ctx context.Context, req CountRequest) (string, error)
Summary(ctx context.Context, req SummaryRequest) (string, error)
TPS(ctx context.Context) (TPS, error)
Series(ctx context.Context, timeframe Timeframe, name string, req SeriesRequest) ([]SeriesItem, error)
CumulativeSeries(ctx context.Context, timeframe Timeframe, name string, req SeriesRequest) ([]SeriesItem, error)
NamespaceSeries(ctx context.Context, timeframe Timeframe, name string, nsId uint64, req SeriesRequest) (response []SeriesItem, err error)
StakingSeries(ctx context.Context, timeframe Timeframe, name string, validatorId uint64, req SeriesRequest) (response []SeriesItem, err error)
RollupStats24h(ctx context.Context) ([]RollupStats24h, error)
SquareSize(ctx context.Context, from, to *time.Time) (map[int][]SeriesItem, error)
Change24hBlockStats(ctx context.Context) (response Change24hBlockStats, err error)
MessagesCount24h(ctx context.Context) ([]CountItem, error)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type ITx interface {
storage.Table[*Tx]
ByHash(ctx context.Context, hash []byte) (Tx, error)
IdAndTimeByHash(ctx context.Context, hash []byte) (uint64, time.Time, error)
Filter(ctx context.Context, fltrs TxFilter) ([]Tx, error)
ByIdWithRelations(ctx context.Context, id uint64) (Tx, error)
ByAddress(ctx context.Context, addressId uint64, fltrs TxFilter) ([]Tx, error)
Genesis(ctx context.Context, limit, offset int, sortOrder storage.SortOrder) ([]Tx, error)
Gas(ctx context.Context, height pkgTypes.Level, ts time.Time) ([]Gas, error)
}
type Gas struct {
GasWanted int64 `bun:"gas_wanted"`
GasUsed int64 `bun:"gas_used"`
Fee decimal.Decimal `bun:"fee"`
GasPrice decimal.Decimal `bun:"gas_price"`
}
type ByGasPrice []Gas
func (gp ByGasPrice) Len() int { return len(gp) }
func (gp ByGasPrice) Less(i, j int) bool { return gp[j].GasPrice.GreaterThan(gp[i].GasPrice) }
func (gp ByGasPrice) Swap(i, j int) { gp[i], gp[j] = gp[j], gp[i] }
type TxFilter struct {
Limit int
Offset int
Sort storage.SortOrder
Status []string
MessageTypes types.MsgTypeBits
ExcludedMessageTypes types.MsgTypeBits
Height *uint64
TimeFrom time.Time
TimeTo time.Time
WithMessages bool
}
// Tx -
type Tx struct {
bun.BaseModel `bun:"tx" comment:"Table with celestia transactions."`
Id uint64 `bun:"id,autoincrement,pk,notnull" comment:"Unique internal id"`
Height pkgTypes.Level `bun:",notnull" comment:"The number (height) of this block" stats:"func:min max,filterable"`
Time time.Time `bun:"time,pk,notnull" comment:"The time of block" stats:"func:min max,filterable"`
Position int64 `bun:"position" comment:"Position in block"`
GasWanted int64 `bun:"gas_wanted" comment:"Gas wanted" stats:"func:min max sum avg"`
GasUsed int64 `bun:"gas_used" comment:"Gas used" stats:"func:min max sum avg"`
TimeoutHeight uint64 `bun:"timeout_height" comment:"Block height until which the transaction is valid" stats:"func:min max avg"`
EventsCount int64 `bun:"events_count" comment:"Events count in transaction" stats:"func:min max sum avg"`
MessagesCount int64 `bun:"messages_count" comment:"Messages count in transaction" stats:"func:min max sum avg"`
Fee decimal.Decimal `bun:"fee,type:numeric" comment:"Paid fee" stats:"func:min max sum avg"`
Status types.Status `bun:"status,type:status" comment:"Transaction status" stats:"filterable"`
Error string `bun:"error,type:text" comment:"Error string if failed"`
Codespace string `bun:"codespace,type:text" comment:"Codespace" stats:"filterable"`
Hash []byte `bun:"hash" comment:"Transaction hash"`
Memo string `bun:"memo,type:text" comment:"Note or comment to send with the transaction"`
MessageTypes types.MsgTypeBits `bun:"message_types,type:bit(76)" comment:"Bit mask with containing messages" stats:"filterable"`
Messages []Message `bun:"rel:has-many,join:id=tx_id"`
Events []Event `bun:"rel:has-many"`
Signers []Address `bun:"-"`
BlobsSize int64 `bun:"-"`
BytesSize int64 `bun:"-"`
BlobsCount int `bun:"-"`
}
// TableName -
func (Tx) TableName() string {
return "tx"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"math/big"
"math/bits"
"github.com/pkg/errors"
)
var (
zero = big.NewInt(0)
)
type Bits struct {
value *big.Int
}
func NewEmptyBits() Bits {
return Bits{
big.NewInt(0),
}
}
func NewBits(value int) Bits {
return Bits{
big.NewInt(int64(value)),
}
}
func NewBitsWithPosition(position int) Bits {
b := big.NewInt(0)
b = b.SetBit(b, position, 1)
return Bits{
b,
}
}
func NewBitsFromString(value string) (Bits, error) {
b := big.NewInt(0)
b, ok := b.SetString(value, 2)
if !ok {
return Bits{}, errors.Errorf("invalid mask value: %s", value)
}
return Bits{b}, nil
}
func (b *Bits) Set(flag Bits) { b.value = b.value.Or(b.value, flag.value) }
func (b *Bits) SetBit(position int) {
b.value = b.value.SetBit(b.value, position, 1)
}
func (b *Bits) Clear(flag Bits) { b.value = b.value.AndNot(b.value, flag.value) }
func (b Bits) Has(flag Bits) bool {
and := b.value.And(b.value, flag.value)
return and.Cmp(zero) != 0
}
func (b Bits) HasBit(position int) bool {
return b.value.Bit(position) != 0
}
func (b Bits) CountBits() int {
var count int
for _, x := range b.value.Bits() {
count += bits.OnesCount(uint(x))
}
return count
}
func (b Bits) Empty() bool { return b.value == nil || b.value.Cmp(zero) == 0 }
func (b Bits) String() string {
if b.value == nil {
return "nil"
}
return b.value.String()
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
)
const (
// EventTypeUnknown is a EventType of type unknown.
EventTypeUnknown EventType = "unknown"
// EventTypeCoinReceived is a EventType of type coin_received.
EventTypeCoinReceived EventType = "coin_received"
// EventTypeCoinbase is a EventType of type coinbase.
EventTypeCoinbase EventType = "coinbase"
// EventTypeCoinSpent is a EventType of type coin_spent.
EventTypeCoinSpent EventType = "coin_spent"
// EventTypeBurn is a EventType of type burn.
EventTypeBurn EventType = "burn"
// EventTypeMint is a EventType of type mint.
EventTypeMint EventType = "mint"
// EventTypeMessage is a EventType of type message.
EventTypeMessage EventType = "message"
// EventTypeProposerReward is a EventType of type proposer_reward.
EventTypeProposerReward EventType = "proposer_reward"
// EventTypeRewards is a EventType of type rewards.
EventTypeRewards EventType = "rewards"
// EventTypeCommission is a EventType of type commission.
EventTypeCommission EventType = "commission"
// EventTypeLiveness is a EventType of type liveness.
EventTypeLiveness EventType = "liveness"
// EventTypeTransfer is a EventType of type transfer.
EventTypeTransfer EventType = "transfer"
// EventTypeCelestiablobv1EventPayForBlobs is a EventType of type celestia.blob.v1.EventPayForBlobs.
EventTypeCelestiablobv1EventPayForBlobs EventType = "celestia.blob.v1.EventPayForBlobs"
// EventTypeRedelegate is a EventType of type redelegate.
EventTypeRedelegate EventType = "redelegate"
// EventTypeAttestationRequest is a EventType of type AttestationRequest.
EventTypeAttestationRequest EventType = "AttestationRequest"
// EventTypeWithdrawRewards is a EventType of type withdraw_rewards.
EventTypeWithdrawRewards EventType = "withdraw_rewards"
// EventTypeWithdrawCommission is a EventType of type withdraw_commission.
EventTypeWithdrawCommission EventType = "withdraw_commission"
// EventTypeSetWithdrawAddress is a EventType of type set_withdraw_address.
EventTypeSetWithdrawAddress EventType = "set_withdraw_address"
// EventTypeCreateValidator is a EventType of type create_validator.
EventTypeCreateValidator EventType = "create_validator"
// EventTypeDelegate is a EventType of type delegate.
EventTypeDelegate EventType = "delegate"
// EventTypeEditValidator is a EventType of type edit_validator.
EventTypeEditValidator EventType = "edit_validator"
// EventTypeUnbond is a EventType of type unbond.
EventTypeUnbond EventType = "unbond"
// EventTypeTx is a EventType of type tx.
EventTypeTx EventType = "tx"
// EventTypeCompleteRedelegation is a EventType of type complete_redelegation.
EventTypeCompleteRedelegation EventType = "complete_redelegation"
// EventTypeCompleteUnbonding is a EventType of type complete_unbonding.
EventTypeCompleteUnbonding EventType = "complete_unbonding"
// EventTypeUseFeegrant is a EventType of type use_feegrant.
EventTypeUseFeegrant EventType = "use_feegrant"
// EventTypeRevokeFeegrant is a EventType of type revoke_feegrant.
EventTypeRevokeFeegrant EventType = "revoke_feegrant"
// EventTypeSetFeegrant is a EventType of type set_feegrant.
EventTypeSetFeegrant EventType = "set_feegrant"
// EventTypeUpdateFeegrant is a EventType of type update_feegrant.
EventTypeUpdateFeegrant EventType = "update_feegrant"
// EventTypeSlash is a EventType of type slash.
EventTypeSlash EventType = "slash"
// EventTypeProposalVote is a EventType of type proposal_vote.
EventTypeProposalVote EventType = "proposal_vote"
// EventTypeProposalDeposit is a EventType of type proposal_deposit.
EventTypeProposalDeposit EventType = "proposal_deposit"
// EventTypeSubmitProposal is a EventType of type submit_proposal.
EventTypeSubmitProposal EventType = "submit_proposal"
// EventTypeCosmosauthzv1beta1EventGrant is a EventType of type cosmos.authz.v1beta1.EventGrant.
EventTypeCosmosauthzv1beta1EventGrant EventType = "cosmos.authz.v1beta1.EventGrant"
// EventTypeSendPacket is a EventType of type send_packet.
EventTypeSendPacket EventType = "send_packet"
// EventTypeIbcTransfer is a EventType of type ibc_transfer.
EventTypeIbcTransfer EventType = "ibc_transfer"
// EventTypeFungibleTokenPacket is a EventType of type fungible_token_packet.
EventTypeFungibleTokenPacket EventType = "fungible_token_packet"
// EventTypeAcknowledgePacket is a EventType of type acknowledge_packet.
EventTypeAcknowledgePacket EventType = "acknowledge_packet"
// EventTypeCreateClient is a EventType of type create_client.
EventTypeCreateClient EventType = "create_client"
// EventTypeUpdateClient is a EventType of type update_client.
EventTypeUpdateClient EventType = "update_client"
// EventTypeConnectionOpenTry is a EventType of type connection_open_try.
EventTypeConnectionOpenTry EventType = "connection_open_try"
// EventTypeConnectionOpenInit is a EventType of type connection_open_init.
EventTypeConnectionOpenInit EventType = "connection_open_init"
// EventTypeConnectionOpenConfirm is a EventType of type connection_open_confirm.
EventTypeConnectionOpenConfirm EventType = "connection_open_confirm"
// EventTypeConnectionOpenAck is a EventType of type connection_open_ack.
EventTypeConnectionOpenAck EventType = "connection_open_ack"
// EventTypeChannelOpenTry is a EventType of type channel_open_try.
EventTypeChannelOpenTry EventType = "channel_open_try"
// EventTypeChannelOpenInit is a EventType of type channel_open_init.
EventTypeChannelOpenInit EventType = "channel_open_init"
// EventTypeChannelOpenConfirm is a EventType of type channel_open_confirm.
EventTypeChannelOpenConfirm EventType = "channel_open_confirm"
// EventTypeChannelOpenAck is a EventType of type channel_open_ack.
EventTypeChannelOpenAck EventType = "channel_open_ack"
// EventTypeRecvPacket is a EventType of type recv_packet.
EventTypeRecvPacket EventType = "recv_packet"
// EventTypeWriteAcknowledgement is a EventType of type write_acknowledgement.
EventTypeWriteAcknowledgement EventType = "write_acknowledgement"
// EventTypeTimeout is a EventType of type timeout.
EventTypeTimeout EventType = "timeout"
// EventTypeTimeoutPacket is a EventType of type timeout_packet.
EventTypeTimeoutPacket EventType = "timeout_packet"
// EventTypeCosmosauthzv1beta1EventRevoke is a EventType of type cosmos.authz.v1beta1.EventRevoke.
EventTypeCosmosauthzv1beta1EventRevoke EventType = "cosmos.authz.v1beta1.EventRevoke"
// EventTypeCosmosauthzv1EventRevoke is a EventType of type cosmos.authz.v1.EventRevoke.
EventTypeCosmosauthzv1EventRevoke EventType = "cosmos.authz.v1.EventRevoke"
// EventTypeCancelUnbondingDelegation is a EventType of type cancel_unbonding_delegation.
EventTypeCancelUnbondingDelegation EventType = "cancel_unbonding_delegation"
// EventTypeActiveProposal is a EventType of type active_proposal.
EventTypeActiveProposal EventType = "active_proposal"
// EventTypeInactiveProposal is a EventType of type inactive_proposal.
EventTypeInactiveProposal EventType = "inactive_proposal"
// EventTypeIcs27Packet is a EventType of type ics27_packet.
EventTypeIcs27Packet EventType = "ics27_packet"
// EventTypeChannelCloseConfirm is a EventType of type channel_close_confirm.
EventTypeChannelCloseConfirm EventType = "channel_close_confirm"
)
var ErrInvalidEventType = fmt.Errorf("not a valid EventType, try [%s]", strings.Join(_EventTypeNames, ", "))
var _EventTypeNames = []string{
string(EventTypeUnknown),
string(EventTypeCoinReceived),
string(EventTypeCoinbase),
string(EventTypeCoinSpent),
string(EventTypeBurn),
string(EventTypeMint),
string(EventTypeMessage),
string(EventTypeProposerReward),
string(EventTypeRewards),
string(EventTypeCommission),
string(EventTypeLiveness),
string(EventTypeTransfer),
string(EventTypeCelestiablobv1EventPayForBlobs),
string(EventTypeRedelegate),
string(EventTypeAttestationRequest),
string(EventTypeWithdrawRewards),
string(EventTypeWithdrawCommission),
string(EventTypeSetWithdrawAddress),
string(EventTypeCreateValidator),
string(EventTypeDelegate),
string(EventTypeEditValidator),
string(EventTypeUnbond),
string(EventTypeTx),
string(EventTypeCompleteRedelegation),
string(EventTypeCompleteUnbonding),
string(EventTypeUseFeegrant),
string(EventTypeRevokeFeegrant),
string(EventTypeSetFeegrant),
string(EventTypeUpdateFeegrant),
string(EventTypeSlash),
string(EventTypeProposalVote),
string(EventTypeProposalDeposit),
string(EventTypeSubmitProposal),
string(EventTypeCosmosauthzv1beta1EventGrant),
string(EventTypeSendPacket),
string(EventTypeIbcTransfer),
string(EventTypeFungibleTokenPacket),
string(EventTypeAcknowledgePacket),
string(EventTypeCreateClient),
string(EventTypeUpdateClient),
string(EventTypeConnectionOpenTry),
string(EventTypeConnectionOpenInit),
string(EventTypeConnectionOpenConfirm),
string(EventTypeConnectionOpenAck),
string(EventTypeChannelOpenTry),
string(EventTypeChannelOpenInit),
string(EventTypeChannelOpenConfirm),
string(EventTypeChannelOpenAck),
string(EventTypeRecvPacket),
string(EventTypeWriteAcknowledgement),
string(EventTypeTimeout),
string(EventTypeTimeoutPacket),
string(EventTypeCosmosauthzv1beta1EventRevoke),
string(EventTypeCosmosauthzv1EventRevoke),
string(EventTypeCancelUnbondingDelegation),
string(EventTypeActiveProposal),
string(EventTypeInactiveProposal),
string(EventTypeIcs27Packet),
string(EventTypeChannelCloseConfirm),
}
// EventTypeNames returns a list of possible string values of EventType.
func EventTypeNames() []string {
tmp := make([]string, len(_EventTypeNames))
copy(tmp, _EventTypeNames)
return tmp
}
// EventTypeValues returns a list of the values for EventType
func EventTypeValues() []EventType {
return []EventType{
EventTypeUnknown,
EventTypeCoinReceived,
EventTypeCoinbase,
EventTypeCoinSpent,
EventTypeBurn,
EventTypeMint,
EventTypeMessage,
EventTypeProposerReward,
EventTypeRewards,
EventTypeCommission,
EventTypeLiveness,
EventTypeTransfer,
EventTypeCelestiablobv1EventPayForBlobs,
EventTypeRedelegate,
EventTypeAttestationRequest,
EventTypeWithdrawRewards,
EventTypeWithdrawCommission,
EventTypeSetWithdrawAddress,
EventTypeCreateValidator,
EventTypeDelegate,
EventTypeEditValidator,
EventTypeUnbond,
EventTypeTx,
EventTypeCompleteRedelegation,
EventTypeCompleteUnbonding,
EventTypeUseFeegrant,
EventTypeRevokeFeegrant,
EventTypeSetFeegrant,
EventTypeUpdateFeegrant,
EventTypeSlash,
EventTypeProposalVote,
EventTypeProposalDeposit,
EventTypeSubmitProposal,
EventTypeCosmosauthzv1beta1EventGrant,
EventTypeSendPacket,
EventTypeIbcTransfer,
EventTypeFungibleTokenPacket,
EventTypeAcknowledgePacket,
EventTypeCreateClient,
EventTypeUpdateClient,
EventTypeConnectionOpenTry,
EventTypeConnectionOpenInit,
EventTypeConnectionOpenConfirm,
EventTypeConnectionOpenAck,
EventTypeChannelOpenTry,
EventTypeChannelOpenInit,
EventTypeChannelOpenConfirm,
EventTypeChannelOpenAck,
EventTypeRecvPacket,
EventTypeWriteAcknowledgement,
EventTypeTimeout,
EventTypeTimeoutPacket,
EventTypeCosmosauthzv1beta1EventRevoke,
EventTypeCosmosauthzv1EventRevoke,
EventTypeCancelUnbondingDelegation,
EventTypeActiveProposal,
EventTypeInactiveProposal,
EventTypeIcs27Packet,
EventTypeChannelCloseConfirm,
}
}
// String implements the Stringer interface.
func (x EventType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x EventType) IsValid() bool {
_, err := ParseEventType(string(x))
return err == nil
}
var _EventTypeValue = map[string]EventType{
"unknown": EventTypeUnknown,
"coin_received": EventTypeCoinReceived,
"coinbase": EventTypeCoinbase,
"coin_spent": EventTypeCoinSpent,
"burn": EventTypeBurn,
"mint": EventTypeMint,
"message": EventTypeMessage,
"proposer_reward": EventTypeProposerReward,
"rewards": EventTypeRewards,
"commission": EventTypeCommission,
"liveness": EventTypeLiveness,
"transfer": EventTypeTransfer,
"celestia.blob.v1.EventPayForBlobs": EventTypeCelestiablobv1EventPayForBlobs,
"redelegate": EventTypeRedelegate,
"AttestationRequest": EventTypeAttestationRequest,
"withdraw_rewards": EventTypeWithdrawRewards,
"withdraw_commission": EventTypeWithdrawCommission,
"set_withdraw_address": EventTypeSetWithdrawAddress,
"create_validator": EventTypeCreateValidator,
"delegate": EventTypeDelegate,
"edit_validator": EventTypeEditValidator,
"unbond": EventTypeUnbond,
"tx": EventTypeTx,
"complete_redelegation": EventTypeCompleteRedelegation,
"complete_unbonding": EventTypeCompleteUnbonding,
"use_feegrant": EventTypeUseFeegrant,
"revoke_feegrant": EventTypeRevokeFeegrant,
"set_feegrant": EventTypeSetFeegrant,
"update_feegrant": EventTypeUpdateFeegrant,
"slash": EventTypeSlash,
"proposal_vote": EventTypeProposalVote,
"proposal_deposit": EventTypeProposalDeposit,
"submit_proposal": EventTypeSubmitProposal,
"cosmos.authz.v1beta1.EventGrant": EventTypeCosmosauthzv1beta1EventGrant,
"send_packet": EventTypeSendPacket,
"ibc_transfer": EventTypeIbcTransfer,
"fungible_token_packet": EventTypeFungibleTokenPacket,
"acknowledge_packet": EventTypeAcknowledgePacket,
"create_client": EventTypeCreateClient,
"update_client": EventTypeUpdateClient,
"connection_open_try": EventTypeConnectionOpenTry,
"connection_open_init": EventTypeConnectionOpenInit,
"connection_open_confirm": EventTypeConnectionOpenConfirm,
"connection_open_ack": EventTypeConnectionOpenAck,
"channel_open_try": EventTypeChannelOpenTry,
"channel_open_init": EventTypeChannelOpenInit,
"channel_open_confirm": EventTypeChannelOpenConfirm,
"channel_open_ack": EventTypeChannelOpenAck,
"recv_packet": EventTypeRecvPacket,
"write_acknowledgement": EventTypeWriteAcknowledgement,
"timeout": EventTypeTimeout,
"timeout_packet": EventTypeTimeoutPacket,
"cosmos.authz.v1beta1.EventRevoke": EventTypeCosmosauthzv1beta1EventRevoke,
"cosmos.authz.v1.EventRevoke": EventTypeCosmosauthzv1EventRevoke,
"cancel_unbonding_delegation": EventTypeCancelUnbondingDelegation,
"active_proposal": EventTypeActiveProposal,
"inactive_proposal": EventTypeInactiveProposal,
"ics27_packet": EventTypeIcs27Packet,
"channel_close_confirm": EventTypeChannelCloseConfirm,
}
// ParseEventType attempts to convert a string to a EventType.
func ParseEventType(name string) (EventType, error) {
if x, ok := _EventTypeValue[name]; ok {
return x, nil
}
return EventType(""), fmt.Errorf("%s is %w", name, ErrInvalidEventType)
}
// MarshalText implements the text marshaller method.
func (x EventType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *EventType) UnmarshalText(text []byte) error {
tmp, err := ParseEventType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errEventTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *EventType) Scan(value interface{}) (err error) {
if value == nil {
*x = EventType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseEventType(v)
case []byte:
*x, err = ParseEventType(string(v))
case EventType:
*x = v
case *EventType:
if v == nil {
return errEventTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errEventTypeNilPtr
}
*x, err = ParseEventType(*v)
default:
return errors.New("invalid type for EventType")
}
return
}
// Value implements the driver Valuer interface.
func (x EventType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
)
const (
// ModuleNameAuth is a ModuleName of type auth.
ModuleNameAuth ModuleName = "auth"
// ModuleNameBlob is a ModuleName of type blob.
ModuleNameBlob ModuleName = "blob"
// ModuleNameCrisis is a ModuleName of type crisis.
ModuleNameCrisis ModuleName = "crisis"
// ModuleNameDistribution is a ModuleName of type distribution.
ModuleNameDistribution ModuleName = "distribution"
// ModuleNameIndexer is a ModuleName of type indexer.
ModuleNameIndexer ModuleName = "indexer"
// ModuleNameGov is a ModuleName of type gov.
ModuleNameGov ModuleName = "gov"
// ModuleNameSlashing is a ModuleName of type slashing.
ModuleNameSlashing ModuleName = "slashing"
// ModuleNameStaking is a ModuleName of type staking.
ModuleNameStaking ModuleName = "staking"
// ModuleNameConsensus is a ModuleName of type consensus.
ModuleNameConsensus ModuleName = "consensus"
)
var ErrInvalidModuleName = errors.New("not a valid ModuleName")
// ModuleNameValues returns a list of the values for ModuleName
func ModuleNameValues() []ModuleName {
return []ModuleName{
ModuleNameAuth,
ModuleNameBlob,
ModuleNameCrisis,
ModuleNameDistribution,
ModuleNameIndexer,
ModuleNameGov,
ModuleNameSlashing,
ModuleNameStaking,
ModuleNameConsensus,
}
}
// String implements the Stringer interface.
func (x ModuleName) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x ModuleName) IsValid() bool {
_, err := ParseModuleName(string(x))
return err == nil
}
var _ModuleNameValue = map[string]ModuleName{
"auth": ModuleNameAuth,
"blob": ModuleNameBlob,
"crisis": ModuleNameCrisis,
"distribution": ModuleNameDistribution,
"indexer": ModuleNameIndexer,
"gov": ModuleNameGov,
"slashing": ModuleNameSlashing,
"staking": ModuleNameStaking,
"consensus": ModuleNameConsensus,
}
// ParseModuleName attempts to convert a string to a ModuleName.
func ParseModuleName(name string) (ModuleName, error) {
if x, ok := _ModuleNameValue[name]; ok {
return x, nil
}
return ModuleName(""), fmt.Errorf("%s is %w", name, ErrInvalidModuleName)
}
// MarshalText implements the text marshaller method.
func (x ModuleName) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *ModuleName) UnmarshalText(text []byte) error {
tmp, err := ParseModuleName(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errModuleNameNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *ModuleName) Scan(value interface{}) (err error) {
if value == nil {
*x = ModuleName("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseModuleName(v)
case []byte:
*x, err = ParseModuleName(string(v))
case ModuleName:
*x = v
case *ModuleName:
if v == nil {
return errModuleNameNilPtr
}
*x = *v
case *string:
if v == nil {
return errModuleNameNilPtr
}
*x, err = ParseModuleName(*v)
default:
return errors.New("invalid type for ModuleName")
}
return
}
// Value implements the driver Valuer interface.
func (x ModuleName) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
)
const (
// MsgAddressTypeValidator is a MsgAddressType of type validator.
MsgAddressTypeValidator MsgAddressType = "validator"
// MsgAddressTypeDelegator is a MsgAddressType of type delegator.
MsgAddressTypeDelegator MsgAddressType = "delegator"
// MsgAddressTypeDepositor is a MsgAddressType of type depositor.
MsgAddressTypeDepositor MsgAddressType = "depositor"
// MsgAddressTypeValidatorSrc is a MsgAddressType of type validatorSrc.
MsgAddressTypeValidatorSrc MsgAddressType = "validatorSrc"
// MsgAddressTypeValidatorDst is a MsgAddressType of type validatorDst.
MsgAddressTypeValidatorDst MsgAddressType = "validatorDst"
// MsgAddressTypeFromAddress is a MsgAddressType of type fromAddress.
MsgAddressTypeFromAddress MsgAddressType = "fromAddress"
// MsgAddressTypeToAddress is a MsgAddressType of type toAddress.
MsgAddressTypeToAddress MsgAddressType = "toAddress"
// MsgAddressTypeInput is a MsgAddressType of type input.
MsgAddressTypeInput MsgAddressType = "input"
// MsgAddressTypeOutput is a MsgAddressType of type output.
MsgAddressTypeOutput MsgAddressType = "output"
// MsgAddressTypeGrantee is a MsgAddressType of type grantee.
MsgAddressTypeGrantee MsgAddressType = "grantee"
// MsgAddressTypeGranter is a MsgAddressType of type granter.
MsgAddressTypeGranter MsgAddressType = "granter"
// MsgAddressTypeSigner is a MsgAddressType of type signer.
MsgAddressTypeSigner MsgAddressType = "signer"
// MsgAddressTypeWithdraw is a MsgAddressType of type withdraw.
MsgAddressTypeWithdraw MsgAddressType = "withdraw"
// MsgAddressTypeVoter is a MsgAddressType of type voter.
MsgAddressTypeVoter MsgAddressType = "voter"
// MsgAddressTypeProposer is a MsgAddressType of type proposer.
MsgAddressTypeProposer MsgAddressType = "proposer"
// MsgAddressTypeAuthority is a MsgAddressType of type authority.
MsgAddressTypeAuthority MsgAddressType = "authority"
// MsgAddressTypeSender is a MsgAddressType of type sender.
MsgAddressTypeSender MsgAddressType = "sender"
// MsgAddressTypeReceiver is a MsgAddressType of type receiver.
MsgAddressTypeReceiver MsgAddressType = "receiver"
// MsgAddressTypeSubmitter is a MsgAddressType of type submitter.
MsgAddressTypeSubmitter MsgAddressType = "submitter"
// MsgAddressTypeAdmin is a MsgAddressType of type admin.
MsgAddressTypeAdmin MsgAddressType = "admin"
// MsgAddressTypeNewAdmin is a MsgAddressType of type newAdmin.
MsgAddressTypeNewAdmin MsgAddressType = "newAdmin"
// MsgAddressTypeGroupPolicyAddress is a MsgAddressType of type groupPolicyAddress.
MsgAddressTypeGroupPolicyAddress MsgAddressType = "groupPolicyAddress"
// MsgAddressTypeExecutor is a MsgAddressType of type executor.
MsgAddressTypeExecutor MsgAddressType = "executor"
// MsgAddressTypeGroupMember is a MsgAddressType of type groupMember.
MsgAddressTypeGroupMember MsgAddressType = "groupMember"
// MsgAddressTypeOwner is a MsgAddressType of type owner.
MsgAddressTypeOwner MsgAddressType = "owner"
// MsgAddressTypeRelayer is a MsgAddressType of type relayer.
MsgAddressTypeRelayer MsgAddressType = "relayer"
// MsgAddressTypePayee is a MsgAddressType of type payee.
MsgAddressTypePayee MsgAddressType = "payee"
)
var ErrInvalidMsgAddressType = errors.New("not a valid MsgAddressType")
// MsgAddressTypeValues returns a list of the values for MsgAddressType
func MsgAddressTypeValues() []MsgAddressType {
return []MsgAddressType{
MsgAddressTypeValidator,
MsgAddressTypeDelegator,
MsgAddressTypeDepositor,
MsgAddressTypeValidatorSrc,
MsgAddressTypeValidatorDst,
MsgAddressTypeFromAddress,
MsgAddressTypeToAddress,
MsgAddressTypeInput,
MsgAddressTypeOutput,
MsgAddressTypeGrantee,
MsgAddressTypeGranter,
MsgAddressTypeSigner,
MsgAddressTypeWithdraw,
MsgAddressTypeVoter,
MsgAddressTypeProposer,
MsgAddressTypeAuthority,
MsgAddressTypeSender,
MsgAddressTypeReceiver,
MsgAddressTypeSubmitter,
MsgAddressTypeAdmin,
MsgAddressTypeNewAdmin,
MsgAddressTypeGroupPolicyAddress,
MsgAddressTypeExecutor,
MsgAddressTypeGroupMember,
MsgAddressTypeOwner,
MsgAddressTypeRelayer,
MsgAddressTypePayee,
}
}
// String implements the Stringer interface.
func (x MsgAddressType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x MsgAddressType) IsValid() bool {
_, err := ParseMsgAddressType(string(x))
return err == nil
}
var _MsgAddressTypeValue = map[string]MsgAddressType{
"validator": MsgAddressTypeValidator,
"delegator": MsgAddressTypeDelegator,
"depositor": MsgAddressTypeDepositor,
"validatorSrc": MsgAddressTypeValidatorSrc,
"validatorDst": MsgAddressTypeValidatorDst,
"fromAddress": MsgAddressTypeFromAddress,
"toAddress": MsgAddressTypeToAddress,
"input": MsgAddressTypeInput,
"output": MsgAddressTypeOutput,
"grantee": MsgAddressTypeGrantee,
"granter": MsgAddressTypeGranter,
"signer": MsgAddressTypeSigner,
"withdraw": MsgAddressTypeWithdraw,
"voter": MsgAddressTypeVoter,
"proposer": MsgAddressTypeProposer,
"authority": MsgAddressTypeAuthority,
"sender": MsgAddressTypeSender,
"receiver": MsgAddressTypeReceiver,
"submitter": MsgAddressTypeSubmitter,
"admin": MsgAddressTypeAdmin,
"newAdmin": MsgAddressTypeNewAdmin,
"groupPolicyAddress": MsgAddressTypeGroupPolicyAddress,
"executor": MsgAddressTypeExecutor,
"groupMember": MsgAddressTypeGroupMember,
"owner": MsgAddressTypeOwner,
"relayer": MsgAddressTypeRelayer,
"payee": MsgAddressTypePayee,
}
// ParseMsgAddressType attempts to convert a string to a MsgAddressType.
func ParseMsgAddressType(name string) (MsgAddressType, error) {
if x, ok := _MsgAddressTypeValue[name]; ok {
return x, nil
}
return MsgAddressType(""), fmt.Errorf("%s is %w", name, ErrInvalidMsgAddressType)
}
// MarshalText implements the text marshaller method.
func (x MsgAddressType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *MsgAddressType) UnmarshalText(text []byte) error {
tmp, err := ParseMsgAddressType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errMsgAddressTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *MsgAddressType) Scan(value interface{}) (err error) {
if value == nil {
*x = MsgAddressType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseMsgAddressType(v)
case []byte:
*x, err = ParseMsgAddressType(string(v))
case MsgAddressType:
*x = v
case *MsgAddressType:
if v == nil {
return errMsgAddressTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errMsgAddressTypeNilPtr
}
*x, err = ParseMsgAddressType(*v)
default:
return errors.New("invalid type for MsgAddressType")
}
return
}
// Value implements the driver Valuer interface.
func (x MsgAddressType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"database/sql"
"database/sql/driver"
"fmt"
"github.com/pkg/errors"
)
type MsgTypeBits struct {
Bits
}
func NewMsgTypeBits() MsgTypeBits {
return MsgTypeBits{NewEmptyBits()}
}
const (
MsgTypeBitsUnknown int = iota
MsgTypeBitsSetWithdrawAddress
MsgTypeBitsWithdrawDelegatorReward
MsgTypeBitsWithdrawValidatorCommission
MsgTypeBitsFundCommunityPool
MsgTypeBitsCreateValidator
MsgTypeBitsEditValidator
MsgTypeBitsDelegate
MsgTypeBitsBeginRedelegate
MsgTypeBitsUndelegate
MsgTypeBitsCancelUnbondingDelegation
MsgTypeBitsUnjail
MsgTypeBitsSend
MsgTypeBitsMultiSend
MsgTypeBitsCreateVestingAccount
MsgTypeBitsCreatePermanentLockedAccount
MsgTypeBitsCreatePeriodicVestingAccount
MsgTypeBitsPayForBlobs
MsgTypeBitsGrant
MsgTypeBitsExec
MsgTypeBitsRevoke
MsgTypeBitsGrantAllowance
MsgTypeBitsRevokeAllowance
MsgTypeBitsRegisterEVMAddress
MsgTypeBitsSubmitProposal
MsgTypeBitsExecLegacyContent
MsgTypeBitsVote
MsgTypeBitsVoteWeighted
MsgTypeBitsDeposit
MsgTypeBitsIBCTransfer
MsgTypeBitsVerifyInvariant
MsgTypeBitsSubmitEvidence
MsgTypeBitsSendNFT
MsgTypeBitsCreateGroup
MsgTypeBitsUpdateGroupMembers
MsgTypeBitsUpdateGroupAdmin
MsgTypeBitsUpdateGroupMetadata
MsgTypeBitsCreateGroupPolicy
MsgTypeBitsUpdateGroupPolicyAdmin
MsgTypeBitsCreateGroupWithPolicy
MsgTypeBitsUpdateGroupPolicyDecisionPolicy
MsgTypeBitsUpdateGroupPolicyMetadata
MsgTypeBitsSubmitProposalGroup
MsgTypeBitsWithdrawProposal
MsgTypeBitsVoteGroup
MsgTypeBitsExecGroup
MsgTypeBitsLeaveGroup
MsgTypeBitsSoftwareUpgrade
MsgTypeBitsCancelUpgrade
MsgTypeBitsRegisterInterchainAccount
MsgTypeBitsSendTx
MsgTypeBitsRegisterPayee
MsgTypeBitsRegisterCounterpartyPayee
MsgTypeBitsPayPacketFee
MsgTypeBitsPayPacketFeeAsync
MsgTypeBitsTransfer
MsgTypeBitsCreateClient
MsgTypeBitsUpdateClient
MsgTypeBitsUpgradeClient
MsgTypeBitsSubmitMisbehaviour
MsgTypeBitsConnectionOpenInit
MsgTypeBitsConnectionOpenTry
MsgTypeBitsConnectionOpenAck
MsgTypeBitsConnectionOpenConfirm
MsgTypeBitsChannelOpenInit
MsgTypeBitsChannelOpenTry
MsgTypeBitsChannelOpenAck
MsgTypeBitsChannelOpenConfirm
MsgTypeBitsChannelCloseInit
MsgTypeBitsChannelCloseConfirm
MsgTypeBitsRecvPacket
MsgTypeBitsTimeout
MsgTypeBitsTimeoutOnClose
MsgTypeBitsAcknowledgement
MsgTypeBitsSignalVersion
MsgTypeBitsTryUpgrade
)
func NewMsgTypeBitMask(values ...MsgType) MsgTypeBits {
mask := NewMsgTypeBits()
for i := range values {
mask.SetByMsgType(values[i])
}
return mask
}
func (mask *MsgTypeBits) SetByMsgType(value MsgType) {
switch value {
case MsgUnknown:
mask.SetBit(MsgTypeBitsUnknown)
case MsgSetWithdrawAddress:
mask.SetBit(MsgTypeBitsSetWithdrawAddress)
case MsgWithdrawDelegatorReward:
mask.SetBit(MsgTypeBitsWithdrawDelegatorReward)
case MsgWithdrawValidatorCommission:
mask.SetBit(MsgTypeBitsWithdrawValidatorCommission)
case MsgFundCommunityPool:
mask.SetBit(MsgTypeBitsFundCommunityPool)
case MsgCreateValidator:
mask.SetBit(MsgTypeBitsCreateValidator)
case MsgEditValidator:
mask.SetBit(MsgTypeBitsEditValidator)
case MsgDelegate:
mask.SetBit(MsgTypeBitsDelegate)
case MsgBeginRedelegate:
mask.SetBit(MsgTypeBitsBeginRedelegate)
case MsgUndelegate:
mask.SetBit(MsgTypeBitsUndelegate)
case MsgCancelUnbondingDelegation:
mask.SetBit(MsgTypeBitsCancelUnbondingDelegation)
case MsgUnjail:
mask.SetBit(MsgTypeBitsUnjail)
case MsgSend:
mask.SetBit(MsgTypeBitsSend)
case MsgMultiSend:
mask.SetBit(MsgTypeBitsMultiSend)
case MsgCreateVestingAccount:
mask.SetBit(MsgTypeBitsCreateVestingAccount)
case MsgCreatePermanentLockedAccount:
mask.SetBit(MsgTypeBitsCreatePermanentLockedAccount)
case MsgCreatePeriodicVestingAccount:
mask.SetBit(MsgTypeBitsCreatePeriodicVestingAccount)
case MsgPayForBlobs:
mask.SetBit(MsgTypeBitsPayForBlobs)
case MsgGrant:
mask.SetBit(MsgTypeBitsGrant)
case MsgExec:
mask.SetBit(MsgTypeBitsExec)
case MsgRevoke:
mask.SetBit(MsgTypeBitsRevoke)
case MsgGrantAllowance:
mask.SetBit(MsgTypeBitsGrantAllowance)
case MsgRevokeAllowance:
mask.SetBit(MsgTypeBitsRevokeAllowance)
case MsgRegisterEVMAddress:
mask.SetBit(MsgTypeBitsRegisterEVMAddress)
case MsgSubmitProposal:
mask.SetBit(MsgTypeBitsSubmitProposal)
case MsgExecLegacyContent:
mask.SetBit(MsgTypeBitsExecLegacyContent)
case MsgVote:
mask.SetBit(MsgTypeBitsVote)
case MsgVoteWeighted:
mask.SetBit(MsgTypeBitsVoteWeighted)
case MsgDeposit:
mask.SetBit(MsgTypeBitsDeposit)
case IBCTransfer:
mask.SetBit(MsgTypeBitsIBCTransfer)
case MsgVerifyInvariant:
mask.SetBit(MsgTypeBitsVerifyInvariant)
case MsgSubmitEvidence:
mask.SetBit(MsgTypeBitsSubmitEvidence)
case MsgSendNFT:
mask.SetBit(MsgTypeBitsSendNFT)
case MsgCreateGroup:
mask.SetBit(MsgTypeBitsCreateGroup)
case MsgUpdateGroupMembers:
mask.SetBit(MsgTypeBitsUpdateGroupMembers)
case MsgUpdateGroupAdmin:
mask.SetBit(MsgTypeBitsUpdateGroupAdmin)
case MsgUpdateGroupMetadata:
mask.SetBit(MsgTypeBitsUpdateGroupMetadata)
case MsgCreateGroupPolicy:
mask.SetBit(MsgTypeBitsCreateGroupPolicy)
case MsgUpdateGroupPolicyAdmin:
mask.SetBit(MsgTypeBitsUpdateGroupPolicyAdmin)
case MsgCreateGroupWithPolicy:
mask.SetBit(MsgTypeBitsCreateGroupWithPolicy)
case MsgUpdateGroupPolicyDecisionPolicy:
mask.SetBit(MsgTypeBitsUpdateGroupPolicyDecisionPolicy)
case MsgUpdateGroupPolicyMetadata:
mask.SetBit(MsgTypeBitsUpdateGroupPolicyMetadata)
case MsgSubmitProposalGroup:
mask.SetBit(MsgTypeBitsSubmitProposalGroup)
case MsgWithdrawProposal:
mask.SetBit(MsgTypeBitsWithdrawProposal)
case MsgVoteGroup:
mask.SetBit(MsgTypeBitsVoteGroup)
case MsgExecGroup:
mask.SetBit(MsgTypeBitsExecGroup)
case MsgLeaveGroup:
mask.SetBit(MsgTypeBitsLeaveGroup)
case MsgSoftwareUpgrade:
mask.SetBit(MsgTypeBitsSoftwareUpgrade)
case MsgCancelUpgrade:
mask.SetBit(MsgTypeBitsCancelUpgrade)
case MsgRegisterInterchainAccount:
mask.SetBit(MsgTypeBitsRegisterInterchainAccount)
case MsgSendTx:
mask.SetBit(MsgTypeBitsSendTx)
case MsgRegisterPayee:
mask.SetBit(MsgTypeBitsRegisterPayee)
case MsgRegisterCounterpartyPayee:
mask.SetBit(MsgTypeBitsRegisterCounterpartyPayee)
case MsgPayPacketFee:
mask.SetBit(MsgTypeBitsPayPacketFee)
case MsgPayPacketFeeAsync:
mask.SetBit(MsgTypeBitsPayPacketFeeAsync)
case MsgTransfer:
mask.SetBit(MsgTypeBitsTransfer)
case MsgCreateClient:
mask.SetBit(MsgTypeBitsCreateClient)
case MsgUpdateClient:
mask.SetBit(MsgTypeBitsUpdateClient)
case MsgUpgradeClient:
mask.SetBit(MsgTypeBitsUpgradeClient)
case MsgSubmitMisbehaviour:
mask.SetBit(MsgTypeBitsSubmitMisbehaviour)
case MsgConnectionOpenInit:
mask.SetBit(MsgTypeBitsConnectionOpenInit)
case MsgConnectionOpenTry:
mask.SetBit(MsgTypeBitsConnectionOpenTry)
case MsgConnectionOpenAck:
mask.SetBit(MsgTypeBitsConnectionOpenAck)
case MsgConnectionOpenConfirm:
mask.SetBit(MsgTypeBitsConnectionOpenConfirm)
case MsgChannelOpenInit:
mask.SetBit(MsgTypeBitsChannelOpenInit)
case MsgChannelOpenTry:
mask.SetBit(MsgTypeBitsChannelOpenTry)
case MsgChannelOpenAck:
mask.SetBit(MsgTypeBitsChannelOpenAck)
case MsgChannelOpenConfirm:
mask.SetBit(MsgTypeBitsChannelOpenConfirm)
case MsgChannelCloseInit:
mask.SetBit(MsgTypeBitsChannelCloseInit)
case MsgChannelCloseConfirm:
mask.SetBit(MsgTypeBitsChannelCloseConfirm)
case MsgRecvPacket:
mask.SetBit(MsgTypeBitsRecvPacket)
case MsgTimeout:
mask.SetBit(MsgTypeBitsTimeout)
case MsgTimeoutOnClose:
mask.SetBit(MsgTypeBitsTimeoutOnClose)
case MsgAcknowledgement:
mask.SetBit(MsgTypeBitsAcknowledgement)
case MsgSignalVersion:
mask.SetBit(MsgTypeBitsSignalVersion)
case MsgTryUpgrade:
mask.SetBit(MsgTypeBitsTryUpgrade)
}
}
func (mask MsgTypeBits) Names() []MsgType {
names := make([]MsgType, mask.CountBits())
var i int
if mask.HasBit(MsgTypeBitsUnknown) {
names[i] = MsgUnknown
i++
}
if mask.HasBit(MsgTypeBitsSetWithdrawAddress) {
names[i] = MsgSetWithdrawAddress
i++
}
if mask.HasBit(MsgTypeBitsWithdrawDelegatorReward) {
names[i] = MsgWithdrawDelegatorReward
i++
}
if mask.HasBit(MsgTypeBitsWithdrawValidatorCommission) {
names[i] = MsgWithdrawValidatorCommission
i++
}
if mask.HasBit(MsgTypeBitsFundCommunityPool) {
names[i] = MsgFundCommunityPool
i++
}
if mask.HasBit(MsgTypeBitsCreateValidator) {
names[i] = MsgCreateValidator
i++
}
if mask.HasBit(MsgTypeBitsEditValidator) {
names[i] = MsgEditValidator
i++
}
if mask.HasBit(MsgTypeBitsDelegate) {
names[i] = MsgDelegate
i++
}
if mask.HasBit(MsgTypeBitsBeginRedelegate) {
names[i] = MsgBeginRedelegate
i++
}
if mask.HasBit(MsgTypeBitsUndelegate) {
names[i] = MsgUndelegate
i++
}
if mask.HasBit(MsgTypeBitsCancelUnbondingDelegation) {
names[i] = MsgCancelUnbondingDelegation
i++
}
if mask.HasBit(MsgTypeBitsUnjail) {
names[i] = MsgUnjail
i++
}
if mask.HasBit(MsgTypeBitsSend) {
names[i] = MsgSend
i++
}
if mask.HasBit(MsgTypeBitsMultiSend) {
names[i] = MsgMultiSend
i++
}
if mask.HasBit(MsgTypeBitsCreateVestingAccount) {
names[i] = MsgCreateVestingAccount
i++
}
if mask.HasBit(MsgTypeBitsCreatePermanentLockedAccount) {
names[i] = MsgCreatePermanentLockedAccount
i++
}
if mask.HasBit(MsgTypeBitsCreatePeriodicVestingAccount) {
names[i] = MsgCreatePeriodicVestingAccount
i++
}
if mask.HasBit(MsgTypeBitsPayForBlobs) {
names[i] = MsgPayForBlobs
i++
}
if mask.HasBit(MsgTypeBitsGrant) {
names[i] = MsgGrant
i++
}
if mask.HasBit(MsgTypeBitsExec) {
names[i] = MsgExec
i++
}
if mask.HasBit(MsgTypeBitsRevoke) {
names[i] = MsgRevoke
i++
}
if mask.HasBit(MsgTypeBitsGrantAllowance) {
names[i] = MsgGrantAllowance
i++
}
if mask.HasBit(MsgTypeBitsRevokeAllowance) {
names[i] = MsgRevokeAllowance
i++
}
if mask.HasBit(MsgTypeBitsRegisterEVMAddress) {
names[i] = MsgRegisterEVMAddress
i++
}
if mask.HasBit(MsgTypeBitsSubmitProposal) {
names[i] = MsgSubmitProposal
i++
}
if mask.HasBit(MsgTypeBitsExecLegacyContent) {
names[i] = MsgExecLegacyContent
i++
}
if mask.HasBit(MsgTypeBitsVote) {
names[i] = MsgVote
i++
}
if mask.HasBit(MsgTypeBitsVoteWeighted) {
names[i] = MsgVoteWeighted
i++
}
if mask.HasBit(MsgTypeBitsDeposit) {
names[i] = MsgDeposit
i++
}
if mask.HasBit(MsgTypeBitsIBCTransfer) {
names[i] = IBCTransfer
i++
}
if mask.HasBit(MsgTypeBitsVerifyInvariant) {
names[i] = MsgVerifyInvariant
i++
}
if mask.HasBit(MsgTypeBitsSubmitEvidence) {
names[i] = MsgSubmitEvidence
i++
}
if mask.HasBit(MsgTypeBitsSendNFT) {
names[i] = MsgSendNFT
i++
}
if mask.HasBit(MsgTypeBitsCreateGroup) {
names[i] = MsgCreateGroup
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupMembers) {
names[i] = MsgUpdateGroupMembers
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupAdmin) {
names[i] = MsgUpdateGroupAdmin
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupMetadata) {
names[i] = MsgUpdateGroupMetadata
i++
}
if mask.HasBit(MsgTypeBitsCreateGroupPolicy) {
names[i] = MsgCreateGroupPolicy
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupPolicyAdmin) {
names[i] = MsgUpdateGroupPolicyAdmin
i++
}
if mask.HasBit(MsgTypeBitsCreateGroupWithPolicy) {
names[i] = MsgCreateGroupWithPolicy
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupPolicyDecisionPolicy) {
names[i] = MsgUpdateGroupPolicyDecisionPolicy
i++
}
if mask.HasBit(MsgTypeBitsUpdateGroupPolicyMetadata) {
names[i] = MsgUpdateGroupPolicyMetadata
i++
}
if mask.HasBit(MsgTypeBitsSubmitProposalGroup) {
names[i] = MsgSubmitProposalGroup
i++
}
if mask.HasBit(MsgTypeBitsWithdrawProposal) {
names[i] = MsgWithdrawProposal
i++
}
if mask.HasBit(MsgTypeBitsVoteGroup) {
names[i] = MsgVoteGroup
i++
}
if mask.HasBit(MsgTypeBitsExecGroup) {
names[i] = MsgExecGroup
i++
}
if mask.HasBit(MsgTypeBitsLeaveGroup) {
names[i] = MsgLeaveGroup
i++
}
if mask.HasBit(MsgTypeBitsSoftwareUpgrade) {
names[i] = MsgSoftwareUpgrade
i++
}
if mask.HasBit(MsgTypeBitsCancelUpgrade) {
names[i] = MsgCancelUpgrade
i++
}
if mask.HasBit(MsgTypeBitsRegisterInterchainAccount) {
names[i] = MsgRegisterInterchainAccount
i++
}
if mask.HasBit(MsgTypeBitsSendTx) {
names[i] = MsgSendTx
i++
}
if mask.HasBit(MsgTypeBitsRegisterPayee) {
names[i] = MsgRegisterPayee
i++
}
if mask.HasBit(MsgTypeBitsRegisterCounterpartyPayee) {
names[i] = MsgRegisterCounterpartyPayee
i++
}
if mask.HasBit(MsgTypeBitsPayPacketFee) {
names[i] = MsgPayPacketFee
i++
}
if mask.HasBit(MsgTypeBitsPayPacketFeeAsync) {
names[i] = MsgPayPacketFeeAsync
i++
}
if mask.HasBit(MsgTypeBitsTransfer) {
names[i] = MsgTransfer
i++
}
if mask.HasBit(MsgTypeBitsCreateClient) {
names[i] = MsgCreateClient
i++
}
if mask.HasBit(MsgTypeBitsUpdateClient) {
names[i] = MsgUpdateClient
i++
}
if mask.HasBit(MsgTypeBitsUpgradeClient) {
names[i] = MsgUpgradeClient
i++
}
if mask.HasBit(MsgTypeBitsSubmitMisbehaviour) {
names[i] = MsgSubmitMisbehaviour
i++
}
if mask.HasBit(MsgTypeBitsConnectionOpenInit) {
names[i] = MsgConnectionOpenInit
i++
}
if mask.HasBit(MsgTypeBitsConnectionOpenTry) {
names[i] = MsgConnectionOpenTry
i++
}
if mask.HasBit(MsgTypeBitsConnectionOpenAck) {
names[i] = MsgConnectionOpenAck
i++
}
if mask.HasBit(MsgTypeBitsConnectionOpenConfirm) {
names[i] = MsgConnectionOpenConfirm
i++
}
if mask.HasBit(MsgTypeBitsSignalVersion) {
names[i] = MsgSignalVersion
i++
}
if mask.HasBit(MsgTypeBitsTryUpgrade) {
names[i] = MsgTryUpgrade
i++
}
if mask.HasBit(MsgTypeBitsChannelOpenInit) {
names[i] = MsgChannelOpenInit
i++
}
if mask.HasBit(MsgTypeBitsChannelOpenTry) {
names[i] = MsgChannelOpenTry
i++
}
if mask.HasBit(MsgTypeBitsChannelOpenAck) {
names[i] = MsgChannelOpenAck
i++
}
if mask.HasBit(MsgTypeBitsChannelOpenConfirm) {
names[i] = MsgChannelOpenConfirm
i++
}
if mask.HasBit(MsgTypeBitsChannelCloseInit) {
names[i] = MsgChannelCloseInit
i++
}
if mask.HasBit(MsgTypeBitsChannelCloseConfirm) {
names[i] = MsgChannelCloseConfirm
i++
}
if mask.HasBit(MsgTypeBitsRecvPacket) {
names[i] = MsgRecvPacket
i++
}
if mask.HasBit(MsgTypeBitsTimeout) {
names[i] = MsgTimeout
i++
}
if mask.HasBit(MsgTypeBitsTimeoutOnClose) {
names[i] = MsgTimeoutOnClose
i++
}
if mask.HasBit(MsgTypeBitsAcknowledgement) {
names[i] = MsgAcknowledgement
// i++
}
return names
}
func (mask MsgTypeBits) HasOne(value MsgTypeBits) bool {
return mask.value.And(mask.value, value.value).Cmp(zero) > 0
}
var _ sql.Scanner = (*MsgTypeBits)(nil)
func (mask *MsgTypeBits) Scan(src interface{}) (err error) {
switch val := src.(type) {
case []byte:
mask.Bits, err = NewBitsFromString(string(val))
if err != nil {
return err
}
case nil:
mask.Bits = NewEmptyBits()
default:
return errors.Errorf("unknown bits database type: %T", src)
}
return nil
}
var _ driver.Valuer = (*MsgTypeBits)(nil)
func (mask MsgTypeBits) Value() (driver.Value, error) {
if mask.value == nil {
return fmt.Sprintf("%076b", 0), nil
}
return fmt.Sprintf("%076b", mask.value), nil
}
func (mask MsgTypeBits) MarshalJSON() (data []byte, err error) {
if mask.value == nil {
data = []byte{'0'}
return
}
return json.Marshal(mask.value.String())
}
func (mask *MsgTypeBits) UnmarshalJSON(data []byte) error {
mask.Bits = NewEmptyBits()
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if _, ok := mask.value.SetString(s, 10); !ok {
return errors.Errorf("invalid big.Int: %s", s)
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
)
const (
// MsgUnknown is a MsgType of type MsgUnknown.
MsgUnknown MsgType = "MsgUnknown"
// MsgSetWithdrawAddress is a MsgType of type MsgSetWithdrawAddress.
MsgSetWithdrawAddress MsgType = "MsgSetWithdrawAddress"
// MsgWithdrawDelegatorReward is a MsgType of type MsgWithdrawDelegatorReward.
MsgWithdrawDelegatorReward MsgType = "MsgWithdrawDelegatorReward"
// MsgWithdrawValidatorCommission is a MsgType of type MsgWithdrawValidatorCommission.
MsgWithdrawValidatorCommission MsgType = "MsgWithdrawValidatorCommission"
// MsgFundCommunityPool is a MsgType of type MsgFundCommunityPool.
MsgFundCommunityPool MsgType = "MsgFundCommunityPool"
// MsgCreateValidator is a MsgType of type MsgCreateValidator.
MsgCreateValidator MsgType = "MsgCreateValidator"
// MsgEditValidator is a MsgType of type MsgEditValidator.
MsgEditValidator MsgType = "MsgEditValidator"
// MsgDelegate is a MsgType of type MsgDelegate.
MsgDelegate MsgType = "MsgDelegate"
// MsgBeginRedelegate is a MsgType of type MsgBeginRedelegate.
MsgBeginRedelegate MsgType = "MsgBeginRedelegate"
// MsgUndelegate is a MsgType of type MsgUndelegate.
MsgUndelegate MsgType = "MsgUndelegate"
// MsgCancelUnbondingDelegation is a MsgType of type MsgCancelUnbondingDelegation.
MsgCancelUnbondingDelegation MsgType = "MsgCancelUnbondingDelegation"
// MsgUnjail is a MsgType of type MsgUnjail.
MsgUnjail MsgType = "MsgUnjail"
// MsgSend is a MsgType of type MsgSend.
MsgSend MsgType = "MsgSend"
// MsgMultiSend is a MsgType of type MsgMultiSend.
MsgMultiSend MsgType = "MsgMultiSend"
// MsgCreateVestingAccount is a MsgType of type MsgCreateVestingAccount.
MsgCreateVestingAccount MsgType = "MsgCreateVestingAccount"
// MsgCreatePermanentLockedAccount is a MsgType of type MsgCreatePermanentLockedAccount.
MsgCreatePermanentLockedAccount MsgType = "MsgCreatePermanentLockedAccount"
// MsgCreatePeriodicVestingAccount is a MsgType of type MsgCreatePeriodicVestingAccount.
MsgCreatePeriodicVestingAccount MsgType = "MsgCreatePeriodicVestingAccount"
// MsgPayForBlobs is a MsgType of type MsgPayForBlobs.
MsgPayForBlobs MsgType = "MsgPayForBlobs"
// MsgGrant is a MsgType of type MsgGrant.
MsgGrant MsgType = "MsgGrant"
// MsgExec is a MsgType of type MsgExec.
MsgExec MsgType = "MsgExec"
// MsgRevoke is a MsgType of type MsgRevoke.
MsgRevoke MsgType = "MsgRevoke"
// MsgGrantAllowance is a MsgType of type MsgGrantAllowance.
MsgGrantAllowance MsgType = "MsgGrantAllowance"
// MsgRevokeAllowance is a MsgType of type MsgRevokeAllowance.
MsgRevokeAllowance MsgType = "MsgRevokeAllowance"
// MsgRegisterEVMAddress is a MsgType of type MsgRegisterEVMAddress.
MsgRegisterEVMAddress MsgType = "MsgRegisterEVMAddress"
// MsgSubmitProposal is a MsgType of type MsgSubmitProposal.
MsgSubmitProposal MsgType = "MsgSubmitProposal"
// MsgExecLegacyContent is a MsgType of type MsgExecLegacyContent.
MsgExecLegacyContent MsgType = "MsgExecLegacyContent"
// MsgVote is a MsgType of type MsgVote.
MsgVote MsgType = "MsgVote"
// MsgVoteWeighted is a MsgType of type MsgVoteWeighted.
MsgVoteWeighted MsgType = "MsgVoteWeighted"
// MsgDeposit is a MsgType of type MsgDeposit.
MsgDeposit MsgType = "MsgDeposit"
// IBCTransfer is a MsgType of type IBCTransfer.
IBCTransfer MsgType = "IBCTransfer"
// MsgVerifyInvariant is a MsgType of type MsgVerifyInvariant.
MsgVerifyInvariant MsgType = "MsgVerifyInvariant"
// MsgSubmitEvidence is a MsgType of type MsgSubmitEvidence.
MsgSubmitEvidence MsgType = "MsgSubmitEvidence"
// MsgSendNFT is a MsgType of type MsgSendNFT.
MsgSendNFT MsgType = "MsgSendNFT"
// MsgCreateGroup is a MsgType of type MsgCreateGroup.
MsgCreateGroup MsgType = "MsgCreateGroup"
// MsgUpdateGroupMembers is a MsgType of type MsgUpdateGroupMembers.
MsgUpdateGroupMembers MsgType = "MsgUpdateGroupMembers"
// MsgUpdateGroupAdmin is a MsgType of type MsgUpdateGroupAdmin.
MsgUpdateGroupAdmin MsgType = "MsgUpdateGroupAdmin"
// MsgUpdateGroupMetadata is a MsgType of type MsgUpdateGroupMetadata.
MsgUpdateGroupMetadata MsgType = "MsgUpdateGroupMetadata"
// MsgCreateGroupPolicy is a MsgType of type MsgCreateGroupPolicy.
MsgCreateGroupPolicy MsgType = "MsgCreateGroupPolicy"
// MsgUpdateGroupPolicyAdmin is a MsgType of type MsgUpdateGroupPolicyAdmin.
MsgUpdateGroupPolicyAdmin MsgType = "MsgUpdateGroupPolicyAdmin"
// MsgCreateGroupWithPolicy is a MsgType of type MsgCreateGroupWithPolicy.
MsgCreateGroupWithPolicy MsgType = "MsgCreateGroupWithPolicy"
// MsgUpdateGroupPolicyDecisionPolicy is a MsgType of type MsgUpdateGroupPolicyDecisionPolicy.
MsgUpdateGroupPolicyDecisionPolicy MsgType = "MsgUpdateGroupPolicyDecisionPolicy"
// MsgUpdateGroupPolicyMetadata is a MsgType of type MsgUpdateGroupPolicyMetadata.
MsgUpdateGroupPolicyMetadata MsgType = "MsgUpdateGroupPolicyMetadata"
// MsgSubmitProposalGroup is a MsgType of type MsgSubmitProposalGroup.
MsgSubmitProposalGroup MsgType = "MsgSubmitProposalGroup"
// MsgWithdrawProposal is a MsgType of type MsgWithdrawProposal.
MsgWithdrawProposal MsgType = "MsgWithdrawProposal"
// MsgVoteGroup is a MsgType of type MsgVoteGroup.
MsgVoteGroup MsgType = "MsgVoteGroup"
// MsgExecGroup is a MsgType of type MsgExecGroup.
MsgExecGroup MsgType = "MsgExecGroup"
// MsgLeaveGroup is a MsgType of type MsgLeaveGroup.
MsgLeaveGroup MsgType = "MsgLeaveGroup"
// MsgSoftwareUpgrade is a MsgType of type MsgSoftwareUpgrade.
MsgSoftwareUpgrade MsgType = "MsgSoftwareUpgrade"
// MsgCancelUpgrade is a MsgType of type MsgCancelUpgrade.
MsgCancelUpgrade MsgType = "MsgCancelUpgrade"
// MsgRegisterInterchainAccount is a MsgType of type MsgRegisterInterchainAccount.
MsgRegisterInterchainAccount MsgType = "MsgRegisterInterchainAccount"
// MsgSendTx is a MsgType of type MsgSendTx.
MsgSendTx MsgType = "MsgSendTx"
// MsgRegisterPayee is a MsgType of type MsgRegisterPayee.
MsgRegisterPayee MsgType = "MsgRegisterPayee"
// MsgRegisterCounterpartyPayee is a MsgType of type MsgRegisterCounterpartyPayee.
MsgRegisterCounterpartyPayee MsgType = "MsgRegisterCounterpartyPayee"
// MsgPayPacketFee is a MsgType of type MsgPayPacketFee.
MsgPayPacketFee MsgType = "MsgPayPacketFee"
// MsgPayPacketFeeAsync is a MsgType of type MsgPayPacketFeeAsync.
MsgPayPacketFeeAsync MsgType = "MsgPayPacketFeeAsync"
// MsgTransfer is a MsgType of type MsgTransfer.
MsgTransfer MsgType = "MsgTransfer"
// MsgCreateClient is a MsgType of type MsgCreateClient.
MsgCreateClient MsgType = "MsgCreateClient"
// MsgUpdateClient is a MsgType of type MsgUpdateClient.
MsgUpdateClient MsgType = "MsgUpdateClient"
// MsgUpgradeClient is a MsgType of type MsgUpgradeClient.
MsgUpgradeClient MsgType = "MsgUpgradeClient"
// MsgSubmitMisbehaviour is a MsgType of type MsgSubmitMisbehaviour.
MsgSubmitMisbehaviour MsgType = "MsgSubmitMisbehaviour"
// MsgConnectionOpenInit is a MsgType of type MsgConnectionOpenInit.
MsgConnectionOpenInit MsgType = "MsgConnectionOpenInit"
// MsgConnectionOpenTry is a MsgType of type MsgConnectionOpenTry.
MsgConnectionOpenTry MsgType = "MsgConnectionOpenTry"
// MsgConnectionOpenAck is a MsgType of type MsgConnectionOpenAck.
MsgConnectionOpenAck MsgType = "MsgConnectionOpenAck"
// MsgConnectionOpenConfirm is a MsgType of type MsgConnectionOpenConfirm.
MsgConnectionOpenConfirm MsgType = "MsgConnectionOpenConfirm"
// MsgChannelOpenInit is a MsgType of type MsgChannelOpenInit.
MsgChannelOpenInit MsgType = "MsgChannelOpenInit"
// MsgChannelOpenTry is a MsgType of type MsgChannelOpenTry.
MsgChannelOpenTry MsgType = "MsgChannelOpenTry"
// MsgChannelOpenAck is a MsgType of type MsgChannelOpenAck.
MsgChannelOpenAck MsgType = "MsgChannelOpenAck"
// MsgChannelOpenConfirm is a MsgType of type MsgChannelOpenConfirm.
MsgChannelOpenConfirm MsgType = "MsgChannelOpenConfirm"
// MsgChannelCloseInit is a MsgType of type MsgChannelCloseInit.
MsgChannelCloseInit MsgType = "MsgChannelCloseInit"
// MsgChannelCloseConfirm is a MsgType of type MsgChannelCloseConfirm.
MsgChannelCloseConfirm MsgType = "MsgChannelCloseConfirm"
// MsgRecvPacket is a MsgType of type MsgRecvPacket.
MsgRecvPacket MsgType = "MsgRecvPacket"
// MsgTimeout is a MsgType of type MsgTimeout.
MsgTimeout MsgType = "MsgTimeout"
// MsgTimeoutOnClose is a MsgType of type MsgTimeoutOnClose.
MsgTimeoutOnClose MsgType = "MsgTimeoutOnClose"
// MsgAcknowledgement is a MsgType of type MsgAcknowledgement.
MsgAcknowledgement MsgType = "MsgAcknowledgement"
// MsgSignalVersion is a MsgType of type MsgSignalVersion.
MsgSignalVersion MsgType = "MsgSignalVersion"
// MsgTryUpgrade is a MsgType of type MsgTryUpgrade.
MsgTryUpgrade MsgType = "MsgTryUpgrade"
)
var ErrInvalidMsgType = fmt.Errorf("not a valid MsgType, try [%s]", strings.Join(_MsgTypeNames, ", "))
var _MsgTypeNames = []string{
string(MsgUnknown),
string(MsgSetWithdrawAddress),
string(MsgWithdrawDelegatorReward),
string(MsgWithdrawValidatorCommission),
string(MsgFundCommunityPool),
string(MsgCreateValidator),
string(MsgEditValidator),
string(MsgDelegate),
string(MsgBeginRedelegate),
string(MsgUndelegate),
string(MsgCancelUnbondingDelegation),
string(MsgUnjail),
string(MsgSend),
string(MsgMultiSend),
string(MsgCreateVestingAccount),
string(MsgCreatePermanentLockedAccount),
string(MsgCreatePeriodicVestingAccount),
string(MsgPayForBlobs),
string(MsgGrant),
string(MsgExec),
string(MsgRevoke),
string(MsgGrantAllowance),
string(MsgRevokeAllowance),
string(MsgRegisterEVMAddress),
string(MsgSubmitProposal),
string(MsgExecLegacyContent),
string(MsgVote),
string(MsgVoteWeighted),
string(MsgDeposit),
string(IBCTransfer),
string(MsgVerifyInvariant),
string(MsgSubmitEvidence),
string(MsgSendNFT),
string(MsgCreateGroup),
string(MsgUpdateGroupMembers),
string(MsgUpdateGroupAdmin),
string(MsgUpdateGroupMetadata),
string(MsgCreateGroupPolicy),
string(MsgUpdateGroupPolicyAdmin),
string(MsgCreateGroupWithPolicy),
string(MsgUpdateGroupPolicyDecisionPolicy),
string(MsgUpdateGroupPolicyMetadata),
string(MsgSubmitProposalGroup),
string(MsgWithdrawProposal),
string(MsgVoteGroup),
string(MsgExecGroup),
string(MsgLeaveGroup),
string(MsgSoftwareUpgrade),
string(MsgCancelUpgrade),
string(MsgRegisterInterchainAccount),
string(MsgSendTx),
string(MsgRegisterPayee),
string(MsgRegisterCounterpartyPayee),
string(MsgPayPacketFee),
string(MsgPayPacketFeeAsync),
string(MsgTransfer),
string(MsgCreateClient),
string(MsgUpdateClient),
string(MsgUpgradeClient),
string(MsgSubmitMisbehaviour),
string(MsgConnectionOpenInit),
string(MsgConnectionOpenTry),
string(MsgConnectionOpenAck),
string(MsgConnectionOpenConfirm),
string(MsgChannelOpenInit),
string(MsgChannelOpenTry),
string(MsgChannelOpenAck),
string(MsgChannelOpenConfirm),
string(MsgChannelCloseInit),
string(MsgChannelCloseConfirm),
string(MsgRecvPacket),
string(MsgTimeout),
string(MsgTimeoutOnClose),
string(MsgAcknowledgement),
string(MsgSignalVersion),
string(MsgTryUpgrade),
}
// MsgTypeNames returns a list of possible string values of MsgType.
func MsgTypeNames() []string {
tmp := make([]string, len(_MsgTypeNames))
copy(tmp, _MsgTypeNames)
return tmp
}
// MsgTypeValues returns a list of the values for MsgType
func MsgTypeValues() []MsgType {
return []MsgType{
MsgUnknown,
MsgSetWithdrawAddress,
MsgWithdrawDelegatorReward,
MsgWithdrawValidatorCommission,
MsgFundCommunityPool,
MsgCreateValidator,
MsgEditValidator,
MsgDelegate,
MsgBeginRedelegate,
MsgUndelegate,
MsgCancelUnbondingDelegation,
MsgUnjail,
MsgSend,
MsgMultiSend,
MsgCreateVestingAccount,
MsgCreatePermanentLockedAccount,
MsgCreatePeriodicVestingAccount,
MsgPayForBlobs,
MsgGrant,
MsgExec,
MsgRevoke,
MsgGrantAllowance,
MsgRevokeAllowance,
MsgRegisterEVMAddress,
MsgSubmitProposal,
MsgExecLegacyContent,
MsgVote,
MsgVoteWeighted,
MsgDeposit,
IBCTransfer,
MsgVerifyInvariant,
MsgSubmitEvidence,
MsgSendNFT,
MsgCreateGroup,
MsgUpdateGroupMembers,
MsgUpdateGroupAdmin,
MsgUpdateGroupMetadata,
MsgCreateGroupPolicy,
MsgUpdateGroupPolicyAdmin,
MsgCreateGroupWithPolicy,
MsgUpdateGroupPolicyDecisionPolicy,
MsgUpdateGroupPolicyMetadata,
MsgSubmitProposalGroup,
MsgWithdrawProposal,
MsgVoteGroup,
MsgExecGroup,
MsgLeaveGroup,
MsgSoftwareUpgrade,
MsgCancelUpgrade,
MsgRegisterInterchainAccount,
MsgSendTx,
MsgRegisterPayee,
MsgRegisterCounterpartyPayee,
MsgPayPacketFee,
MsgPayPacketFeeAsync,
MsgTransfer,
MsgCreateClient,
MsgUpdateClient,
MsgUpgradeClient,
MsgSubmitMisbehaviour,
MsgConnectionOpenInit,
MsgConnectionOpenTry,
MsgConnectionOpenAck,
MsgConnectionOpenConfirm,
MsgChannelOpenInit,
MsgChannelOpenTry,
MsgChannelOpenAck,
MsgChannelOpenConfirm,
MsgChannelCloseInit,
MsgChannelCloseConfirm,
MsgRecvPacket,
MsgTimeout,
MsgTimeoutOnClose,
MsgAcknowledgement,
MsgSignalVersion,
MsgTryUpgrade,
}
}
// String implements the Stringer interface.
func (x MsgType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x MsgType) IsValid() bool {
_, err := ParseMsgType(string(x))
return err == nil
}
var _MsgTypeValue = map[string]MsgType{
"MsgUnknown": MsgUnknown,
"MsgSetWithdrawAddress": MsgSetWithdrawAddress,
"MsgWithdrawDelegatorReward": MsgWithdrawDelegatorReward,
"MsgWithdrawValidatorCommission": MsgWithdrawValidatorCommission,
"MsgFundCommunityPool": MsgFundCommunityPool,
"MsgCreateValidator": MsgCreateValidator,
"MsgEditValidator": MsgEditValidator,
"MsgDelegate": MsgDelegate,
"MsgBeginRedelegate": MsgBeginRedelegate,
"MsgUndelegate": MsgUndelegate,
"MsgCancelUnbondingDelegation": MsgCancelUnbondingDelegation,
"MsgUnjail": MsgUnjail,
"MsgSend": MsgSend,
"MsgMultiSend": MsgMultiSend,
"MsgCreateVestingAccount": MsgCreateVestingAccount,
"MsgCreatePermanentLockedAccount": MsgCreatePermanentLockedAccount,
"MsgCreatePeriodicVestingAccount": MsgCreatePeriodicVestingAccount,
"MsgPayForBlobs": MsgPayForBlobs,
"MsgGrant": MsgGrant,
"MsgExec": MsgExec,
"MsgRevoke": MsgRevoke,
"MsgGrantAllowance": MsgGrantAllowance,
"MsgRevokeAllowance": MsgRevokeAllowance,
"MsgRegisterEVMAddress": MsgRegisterEVMAddress,
"MsgSubmitProposal": MsgSubmitProposal,
"MsgExecLegacyContent": MsgExecLegacyContent,
"MsgVote": MsgVote,
"MsgVoteWeighted": MsgVoteWeighted,
"MsgDeposit": MsgDeposit,
"IBCTransfer": IBCTransfer,
"MsgVerifyInvariant": MsgVerifyInvariant,
"MsgSubmitEvidence": MsgSubmitEvidence,
"MsgSendNFT": MsgSendNFT,
"MsgCreateGroup": MsgCreateGroup,
"MsgUpdateGroupMembers": MsgUpdateGroupMembers,
"MsgUpdateGroupAdmin": MsgUpdateGroupAdmin,
"MsgUpdateGroupMetadata": MsgUpdateGroupMetadata,
"MsgCreateGroupPolicy": MsgCreateGroupPolicy,
"MsgUpdateGroupPolicyAdmin": MsgUpdateGroupPolicyAdmin,
"MsgCreateGroupWithPolicy": MsgCreateGroupWithPolicy,
"MsgUpdateGroupPolicyDecisionPolicy": MsgUpdateGroupPolicyDecisionPolicy,
"MsgUpdateGroupPolicyMetadata": MsgUpdateGroupPolicyMetadata,
"MsgSubmitProposalGroup": MsgSubmitProposalGroup,
"MsgWithdrawProposal": MsgWithdrawProposal,
"MsgVoteGroup": MsgVoteGroup,
"MsgExecGroup": MsgExecGroup,
"MsgLeaveGroup": MsgLeaveGroup,
"MsgSoftwareUpgrade": MsgSoftwareUpgrade,
"MsgCancelUpgrade": MsgCancelUpgrade,
"MsgRegisterInterchainAccount": MsgRegisterInterchainAccount,
"MsgSendTx": MsgSendTx,
"MsgRegisterPayee": MsgRegisterPayee,
"MsgRegisterCounterpartyPayee": MsgRegisterCounterpartyPayee,
"MsgPayPacketFee": MsgPayPacketFee,
"MsgPayPacketFeeAsync": MsgPayPacketFeeAsync,
"MsgTransfer": MsgTransfer,
"MsgCreateClient": MsgCreateClient,
"MsgUpdateClient": MsgUpdateClient,
"MsgUpgradeClient": MsgUpgradeClient,
"MsgSubmitMisbehaviour": MsgSubmitMisbehaviour,
"MsgConnectionOpenInit": MsgConnectionOpenInit,
"MsgConnectionOpenTry": MsgConnectionOpenTry,
"MsgConnectionOpenAck": MsgConnectionOpenAck,
"MsgConnectionOpenConfirm": MsgConnectionOpenConfirm,
"MsgChannelOpenInit": MsgChannelOpenInit,
"MsgChannelOpenTry": MsgChannelOpenTry,
"MsgChannelOpenAck": MsgChannelOpenAck,
"MsgChannelOpenConfirm": MsgChannelOpenConfirm,
"MsgChannelCloseInit": MsgChannelCloseInit,
"MsgChannelCloseConfirm": MsgChannelCloseConfirm,
"MsgRecvPacket": MsgRecvPacket,
"MsgTimeout": MsgTimeout,
"MsgTimeoutOnClose": MsgTimeoutOnClose,
"MsgAcknowledgement": MsgAcknowledgement,
"MsgSignalVersion": MsgSignalVersion,
"MsgTryUpgrade": MsgTryUpgrade,
}
// ParseMsgType attempts to convert a string to a MsgType.
func ParseMsgType(name string) (MsgType, error) {
if x, ok := _MsgTypeValue[name]; ok {
return x, nil
}
return MsgType(""), fmt.Errorf("%s is %w", name, ErrInvalidMsgType)
}
// MarshalText implements the text marshaller method.
func (x MsgType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *MsgType) UnmarshalText(text []byte) error {
tmp, err := ParseMsgType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errMsgTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *MsgType) Scan(value interface{}) (err error) {
if value == nil {
*x = MsgType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseMsgType(v)
case []byte:
*x, err = ParseMsgType(string(v))
case MsgType:
*x = v
case *MsgType:
if v == nil {
return errMsgTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errMsgTypeNilPtr
}
*x, err = ParseMsgType(*v)
default:
return errors.New("invalid type for MsgType")
}
return
}
// Value implements the driver Valuer interface.
func (x MsgType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"bytes"
"database/sql"
"database/sql/driver"
"github.com/andybalholm/brotli"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type PackedBytes map[string]any
var _ sql.Scanner = (*PackedBytes)(nil)
func (pb *PackedBytes) Scan(src interface{}) error {
if src == nil {
return nil
}
b, ok := src.([]byte)
if !ok {
return errors.Errorf("invalid packed bytes type: %T", src)
}
result := bytes.NewBuffer(b)
return json.NewDecoder(brotli.NewReader(result)).Decode(pb)
}
var _ driver.Valuer = (*PackedBytes)(nil)
func (pb PackedBytes) Value() (driver.Value, error) {
return pb.ToBytes()
}
func (pb PackedBytes) ToBytes() ([]byte, error) {
b, err := json.Marshal(pb)
if err != nil {
return nil, err
}
result := bytes.NewBuffer(nil)
writer := brotli.NewWriterLevel(result, brotli.BestSpeed)
if _, err := writer.Write(b); err != nil {
return nil, err
}
if err := writer.Close(); err != nil {
return nil, err
}
return result.Bytes(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
)
const (
// RollupCategoryUncategorized is a RollupCategory of type uncategorized.
RollupCategoryUncategorized RollupCategory = "uncategorized"
// RollupCategoryFinance is a RollupCategory of type finance.
RollupCategoryFinance RollupCategory = "finance"
// RollupCategoryGaming is a RollupCategory of type gaming.
RollupCategoryGaming RollupCategory = "gaming"
// RollupCategoryNft is a RollupCategory of type nft.
RollupCategoryNft RollupCategory = "nft"
// RollupCategorySocial is a RollupCategory of type social.
RollupCategorySocial RollupCategory = "social"
)
var ErrInvalidRollupCategory = fmt.Errorf("not a valid RollupCategory, try [%s]", strings.Join(_RollupCategoryNames, ", "))
var _RollupCategoryNames = []string{
string(RollupCategoryUncategorized),
string(RollupCategoryFinance),
string(RollupCategoryGaming),
string(RollupCategoryNft),
string(RollupCategorySocial),
}
// RollupCategoryNames returns a list of possible string values of RollupCategory.
func RollupCategoryNames() []string {
tmp := make([]string, len(_RollupCategoryNames))
copy(tmp, _RollupCategoryNames)
return tmp
}
// RollupCategoryValues returns a list of the values for RollupCategory
func RollupCategoryValues() []RollupCategory {
return []RollupCategory{
RollupCategoryUncategorized,
RollupCategoryFinance,
RollupCategoryGaming,
RollupCategoryNft,
RollupCategorySocial,
}
}
// String implements the Stringer interface.
func (x RollupCategory) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x RollupCategory) IsValid() bool {
_, err := ParseRollupCategory(string(x))
return err == nil
}
var _RollupCategoryValue = map[string]RollupCategory{
"uncategorized": RollupCategoryUncategorized,
"finance": RollupCategoryFinance,
"gaming": RollupCategoryGaming,
"nft": RollupCategoryNft,
"social": RollupCategorySocial,
}
// ParseRollupCategory attempts to convert a string to a RollupCategory.
func ParseRollupCategory(name string) (RollupCategory, error) {
if x, ok := _RollupCategoryValue[name]; ok {
return x, nil
}
return RollupCategory(""), fmt.Errorf("%s is %w", name, ErrInvalidRollupCategory)
}
// MarshalText implements the text marshaller method.
func (x RollupCategory) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *RollupCategory) UnmarshalText(text []byte) error {
tmp, err := ParseRollupCategory(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errRollupCategoryNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *RollupCategory) Scan(value interface{}) (err error) {
if value == nil {
*x = RollupCategory("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseRollupCategory(v)
case []byte:
*x, err = ParseRollupCategory(string(v))
case RollupCategory:
*x = v
case *RollupCategory:
if v == nil {
return errRollupCategoryNilPtr
}
*x = *v
case *string:
if v == nil {
return errRollupCategoryNilPtr
}
*x, err = ParseRollupCategory(*v)
default:
return errors.New("invalid type for RollupCategory")
}
return
}
// Value implements the driver Valuer interface.
func (x RollupCategory) Value() (driver.Value, error) {
return x.String(), nil
}
const (
// RollupTypeSovereign is a RollupType of type sovereign.
RollupTypeSovereign RollupType = "sovereign"
// RollupTypeSettled is a RollupType of type settled.
RollupTypeSettled RollupType = "settled"
)
var ErrInvalidRollupType = fmt.Errorf("not a valid RollupType, try [%s]", strings.Join(_RollupTypeNames, ", "))
var _RollupTypeNames = []string{
string(RollupTypeSovereign),
string(RollupTypeSettled),
}
// RollupTypeNames returns a list of possible string values of RollupType.
func RollupTypeNames() []string {
tmp := make([]string, len(_RollupTypeNames))
copy(tmp, _RollupTypeNames)
return tmp
}
// RollupTypeValues returns a list of the values for RollupType
func RollupTypeValues() []RollupType {
return []RollupType{
RollupTypeSovereign,
RollupTypeSettled,
}
}
// String implements the Stringer interface.
func (x RollupType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x RollupType) IsValid() bool {
_, err := ParseRollupType(string(x))
return err == nil
}
var _RollupTypeValue = map[string]RollupType{
"sovereign": RollupTypeSovereign,
"settled": RollupTypeSettled,
}
// ParseRollupType attempts to convert a string to a RollupType.
func ParseRollupType(name string) (RollupType, error) {
if x, ok := _RollupTypeValue[name]; ok {
return x, nil
}
return RollupType(""), fmt.Errorf("%s is %w", name, ErrInvalidRollupType)
}
// MarshalText implements the text marshaller method.
func (x RollupType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *RollupType) UnmarshalText(text []byte) error {
tmp, err := ParseRollupType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errRollupTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *RollupType) Scan(value interface{}) (err error) {
if value == nil {
*x = RollupType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseRollupType(v)
case []byte:
*x, err = ParseRollupType(string(v))
case RollupType:
*x = v
case *RollupType:
if v == nil {
return errRollupTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errRollupTypeNilPtr
}
*x, err = ParseRollupType(*v)
default:
return errors.New("invalid type for RollupType")
}
return
}
// Value implements the driver Valuer interface.
func (x RollupType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
)
const (
// StakingLogTypeDelegation is a StakingLogType of type delegation.
StakingLogTypeDelegation StakingLogType = "delegation"
// StakingLogTypeUnbonding is a StakingLogType of type unbonding.
StakingLogTypeUnbonding StakingLogType = "unbonding"
// StakingLogTypeRewards is a StakingLogType of type rewards.
StakingLogTypeRewards StakingLogType = "rewards"
// StakingLogTypeCommissions is a StakingLogType of type commissions.
StakingLogTypeCommissions StakingLogType = "commissions"
)
var ErrInvalidStakingLogType = fmt.Errorf("not a valid StakingLogType, try [%s]", strings.Join(_StakingLogTypeNames, ", "))
var _StakingLogTypeNames = []string{
string(StakingLogTypeDelegation),
string(StakingLogTypeUnbonding),
string(StakingLogTypeRewards),
string(StakingLogTypeCommissions),
}
// StakingLogTypeNames returns a list of possible string values of StakingLogType.
func StakingLogTypeNames() []string {
tmp := make([]string, len(_StakingLogTypeNames))
copy(tmp, _StakingLogTypeNames)
return tmp
}
// StakingLogTypeValues returns a list of the values for StakingLogType
func StakingLogTypeValues() []StakingLogType {
return []StakingLogType{
StakingLogTypeDelegation,
StakingLogTypeUnbonding,
StakingLogTypeRewards,
StakingLogTypeCommissions,
}
}
// String implements the Stringer interface.
func (x StakingLogType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x StakingLogType) IsValid() bool {
_, err := ParseStakingLogType(string(x))
return err == nil
}
var _StakingLogTypeValue = map[string]StakingLogType{
"delegation": StakingLogTypeDelegation,
"unbonding": StakingLogTypeUnbonding,
"rewards": StakingLogTypeRewards,
"commissions": StakingLogTypeCommissions,
}
// ParseStakingLogType attempts to convert a string to a StakingLogType.
func ParseStakingLogType(name string) (StakingLogType, error) {
if x, ok := _StakingLogTypeValue[name]; ok {
return x, nil
}
return StakingLogType(""), fmt.Errorf("%s is %w", name, ErrInvalidStakingLogType)
}
// MarshalText implements the text marshaller method.
func (x StakingLogType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *StakingLogType) UnmarshalText(text []byte) error {
tmp, err := ParseStakingLogType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errStakingLogTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *StakingLogType) Scan(value interface{}) (err error) {
if value == nil {
*x = StakingLogType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseStakingLogType(v)
case []byte:
*x, err = ParseStakingLogType(string(v))
case StakingLogType:
*x = v
case *StakingLogType:
if v == nil {
return errStakingLogTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errStakingLogTypeNilPtr
}
*x, err = ParseStakingLogType(*v)
default:
return errors.New("invalid type for StakingLogType")
}
return
}
// Value implements the driver Valuer interface.
func (x StakingLogType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
)
const (
// StatusSuccess is a Status of type success.
StatusSuccess Status = "success"
// StatusFailed is a Status of type failed.
StatusFailed Status = "failed"
)
var ErrInvalidStatus = fmt.Errorf("not a valid Status, try [%s]", strings.Join(_StatusNames, ", "))
var _StatusNames = []string{
string(StatusSuccess),
string(StatusFailed),
}
// StatusNames returns a list of possible string values of Status.
func StatusNames() []string {
tmp := make([]string, len(_StatusNames))
copy(tmp, _StatusNames)
return tmp
}
// StatusValues returns a list of the values for Status
func StatusValues() []Status {
return []Status{
StatusSuccess,
StatusFailed,
}
}
// String implements the Stringer interface.
func (x Status) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x Status) IsValid() bool {
_, err := ParseStatus(string(x))
return err == nil
}
var _StatusValue = map[string]Status{
"success": StatusSuccess,
"failed": StatusFailed,
}
// ParseStatus attempts to convert a string to a Status.
func ParseStatus(name string) (Status, error) {
if x, ok := _StatusValue[name]; ok {
return x, nil
}
return Status(""), fmt.Errorf("%s is %w", name, ErrInvalidStatus)
}
// MarshalText implements the text marshaller method.
func (x Status) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *Status) UnmarshalText(text []byte) error {
tmp, err := ParseStatus(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errStatusNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *Status) Scan(value interface{}) (err error) {
if value == nil {
*x = Status("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseStatus(v)
case []byte:
*x, err = ParseStatus(string(v))
case Status:
*x = v
case *Status:
if v == nil {
return errStatusNilPtr
}
*x = *v
case *string:
if v == nil {
return errStatusNilPtr
}
*x, err = ParseStatus(*v)
default:
return errors.New("invalid type for Status")
}
return
}
// Value implements the driver Valuer interface.
func (x Status) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by go-enum DO NOT EDIT.
// Version: 0.5.7
// Revision: bf63e108589bbd2327b13ec2c5da532aad234029
// Build Date: 2023-07-25T23:27:55Z
// Built By: goreleaser
package types
import (
"database/sql/driver"
"errors"
"fmt"
)
const (
// VestingTypeDelayed is a VestingType of type delayed.
VestingTypeDelayed VestingType = "delayed"
// VestingTypePeriodic is a VestingType of type periodic.
VestingTypePeriodic VestingType = "periodic"
// VestingTypePermanent is a VestingType of type permanent.
VestingTypePermanent VestingType = "permanent"
// VestingTypeContinuous is a VestingType of type continuous.
VestingTypeContinuous VestingType = "continuous"
)
var ErrInvalidVestingType = errors.New("not a valid VestingType")
// VestingTypeValues returns a list of the values for VestingType
func VestingTypeValues() []VestingType {
return []VestingType{
VestingTypeDelayed,
VestingTypePeriodic,
VestingTypePermanent,
VestingTypeContinuous,
}
}
// String implements the Stringer interface.
func (x VestingType) String() string {
return string(x)
}
// IsValid provides a quick way to determine if the typed value is
// part of the allowed enumerated values
func (x VestingType) IsValid() bool {
_, err := ParseVestingType(string(x))
return err == nil
}
var _VestingTypeValue = map[string]VestingType{
"delayed": VestingTypeDelayed,
"periodic": VestingTypePeriodic,
"permanent": VestingTypePermanent,
"continuous": VestingTypeContinuous,
}
// ParseVestingType attempts to convert a string to a VestingType.
func ParseVestingType(name string) (VestingType, error) {
if x, ok := _VestingTypeValue[name]; ok {
return x, nil
}
return VestingType(""), fmt.Errorf("%s is %w", name, ErrInvalidVestingType)
}
// MarshalText implements the text marshaller method.
func (x VestingType) MarshalText() ([]byte, error) {
return []byte(string(x)), nil
}
// UnmarshalText implements the text unmarshaller method.
func (x *VestingType) UnmarshalText(text []byte) error {
tmp, err := ParseVestingType(string(text))
if err != nil {
return err
}
*x = tmp
return nil
}
var errVestingTypeNilPtr = errors.New("value pointer is nil") // one per type for package clashes
// Scan implements the Scanner interface.
func (x *VestingType) Scan(value interface{}) (err error) {
if value == nil {
*x = VestingType("")
return
}
// A wider range of scannable types.
// driver.Value values at the top of the list for expediency
switch v := value.(type) {
case string:
*x, err = ParseVestingType(v)
case []byte:
*x, err = ParseVestingType(string(v))
case VestingType:
*x = v
case *VestingType:
if v == nil {
return errVestingTypeNilPtr
}
*x = *v
case *string:
if v == nil {
return errVestingTypeNilPtr
}
*x, err = ParseVestingType(*v)
default:
return errors.New("invalid type for VestingType")
}
return
}
// Value implements the driver Valuer interface.
func (x VestingType) Value() (driver.Value, error) {
return x.String(), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IUndelegation interface {
storage.Table[*Undelegation]
ByAddress(ctx context.Context, addressId uint64, limit, offset int) ([]Undelegation, error)
}
// Undelegation -
type Undelegation struct {
bun.BaseModel `bun:"undelegation" comment:"Table with undelegations"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal id"`
Time time.Time `bun:"time,notnull" comment:"The time of block"`
Height pkgTypes.Level `bun:",notnull" comment:"The number (height) of this block"`
AddressId uint64 `bun:"address_id" comment:"Internal address id"`
ValidatorId uint64 `bun:"validator_id" comment:"Internal validator id"`
Amount decimal.Decimal `bun:"amount,type:numeric" comment:"Delegated amount"`
CompletionTime time.Time `bun:"completion_time" comment:"Time when undelegation will be completed"`
Address *Address `bun:"rel:belongs-to,join:address_id=id"`
Validator *Validator `bun:"rel:belongs-to,join:validator_id=id"`
}
// TableName -
func (Undelegation) TableName() string {
return "undelegation"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IValidator interface {
storage.Table[*Validator]
ByAddress(ctx context.Context, address string) (Validator, error)
TotalVotingPower(ctx context.Context) (decimal.Decimal, error)
ListByPower(ctx context.Context, fltrs ValidatorFilters) ([]Validator, error)
JailedCount(ctx context.Context) (int, error)
}
type Validator struct {
bun.BaseModel `bun:"validator" comment:"Table with celestia validators."`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Delegator string `bun:"delegator,type:text" comment:"Delegator address" json:"-"`
Address string `bun:"address,unique:address_validator,type:text" comment:"Validator address" json:"-"`
ConsAddress string `bun:"cons_address" comment:"Consensus address" json:"-"`
Moniker string `bun:"moniker,type:text" comment:"Human-readable name for the validator" json:"-"`
Website string `bun:"website,type:text" comment:"Website link" json:"-"`
Identity string `bun:"identity,type:text" comment:"Optional identity signature" json:"-"`
Contacts string `bun:"contacts,type:text" comment:"Contacts" json:"-"`
Details string `bun:"details,type:text" comment:"Detailed information about validator" json:"-"`
Rate decimal.Decimal `bun:"rate,type:numeric" comment:"Commission rate charged to delegators, as a fraction" json:"-"`
MaxRate decimal.Decimal `bun:"max_rate,type:numeric" comment:"Maximum commission rate which validator can ever charge, as a fraction" json:"-"`
MaxChangeRate decimal.Decimal `bun:"max_change_rate,type:numeric" comment:"Maximum daily increase of the validator commission, as a fraction" json:"-"`
MinSelfDelegation decimal.Decimal `bun:"min_self_delegation,type:numeric" comment:"" json:"-"`
Stake decimal.Decimal `bun:"stake,type:numeric" comment:"Validator's stake" json:"-"`
Rewards decimal.Decimal `bun:"rewards,type:numeric" comment:"Validator's rewards" json:"-"`
Commissions decimal.Decimal `bun:"commissions,type:numeric" comment:"Commissions" json:"-"`
Height pkgTypes.Level `bun:"height" comment:"Height when validator was created" json:"-"`
Jailed *bool `bun:"jailed" comment:"True if validator was punished" json:"-"`
}
func (Validator) TableName() string {
return "validator"
}
const DoNotModify = "[do-not-modify]"
func EmptyValidator() Validator {
return Validator{
Rate: decimal.Zero,
MaxRate: decimal.Zero,
MaxChangeRate: decimal.Zero,
MinSelfDelegation: decimal.Zero,
Rewards: decimal.Zero,
Commissions: decimal.Zero,
Stake: decimal.Zero,
Contacts: DoNotModify,
Details: DoNotModify,
Identity: DoNotModify,
Moniker: DoNotModify,
Website: DoNotModify,
}
}
type ValidatorFilters struct {
Limit int
Offset int
Jailed *bool
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IVestingAccount interface {
storage.Table[*VestingAccount]
ByAddress(ctx context.Context, addressId uint64, limit, offset int, showEnded bool) ([]VestingAccount, error)
}
type VestingAccount struct {
bun.BaseModel `bun:"vesting_account" comment:"Table with vesting accounts"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Height pkgTypes.Level `bun:"height,notnull" comment:"The number (height) of this block"`
Time time.Time `bun:"time,notnull" comment:"The time of block"`
TxId *uint64 `bun:"tx_id" comment:"Transaction internal identity"`
AddressId uint64 `bun:"address_id,notnull" comment:"Address internal id"`
Type types.VestingType `bun:"type,type:vesting_type" comment:"Type vesting account"`
Amount decimal.Decimal `bun:"amount,type:numeric" comment:"Vested amount"`
StartTime *time.Time `bun:"start_time" comment:"Start time of unlock value"`
EndTime *time.Time `bun:"end_time" comment:"End time of unlock value"`
Address *Address `bun:"rel:has-one"`
Tx *Tx `bun:"rel:has-one"`
VestingPeriods []VestingPeriod `bun:"rel:has-many"`
}
func (VestingAccount) TableName() string {
return "vesting_account"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/shopspring/decimal"
"github.com/uptrace/bun"
)
//go:generate mockgen -source=$GOFILE -destination=mock/$GOFILE -package=mock -typed
type IVestingPeriod interface {
storage.Table[*VestingPeriod]
ByVesting(ctx context.Context, id uint64, limit, offset int) ([]VestingPeriod, error)
}
type VestingPeriod struct {
bun.BaseModel `bun:"vesting_period" comment:"Table with vesting periods"`
Id uint64 `bun:"id,pk,notnull,autoincrement" comment:"Unique internal identity"`
Height pkgTypes.Level `bun:"height,notnull" comment:"The number (height) of this block"`
VestingAccountId uint64 `bun:"vesting_account_id" comment:"Vesting account internal identity"`
Time time.Time `bun:"time,notnull" comment:"The time of periodic vesting"`
Amount decimal.Decimal `bun:"amount,type:numeric" comment:"Vested amount"`
}
func (VestingPeriod) TableName() string {
return "vesting_period"
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package testsuite
import (
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
tmTypes "github.com/tendermint/tendermint/types"
)
func EmptyBlock() (types.BlockData, time.Time) {
return CreateTestBlock(types.ResponseDeliverTx{}, 0)
}
var txMsgBeginRedelegate = []byte{10, 252, 1, 10, 225, 1, 10, 42, 47, 99, 111, 115, 109, 111, 115, 46, 115, 116, 97, 107, 105, 110, 103, 46, 118, 49, 98, 101, 116, 97, 49, 46, 77, 115, 103, 66, 101, 103, 105, 110, 82, 101, 100, 101, 108, 101, 103, 97, 116, 101, 18, 178, 1, 10, 47, 99, 101, 108, 101, 115, 116, 105, 97, 49, 100, 97, 118, 122, 52, 48, 107, 97, 116, 57, 51, 116, 52, 57, 108, 106, 114, 107, 109, 107, 108, 53, 117, 113, 104, 113, 113, 52, 53, 101, 48, 116, 101, 100, 103, 102, 56, 97, 18, 54, 99, 101, 108, 101, 115, 116, 105, 97, 118, 97, 108, 111, 112, 101, 114, 49, 114, 102, 108, 117, 116, 107, 51, 101, 117, 119, 56, 100, 99, 119, 97, 101, 104, 120, 119, 117, 103, 99, 109, 57, 112, 101, 119, 107, 100, 110, 53, 54, 120, 106, 108, 104, 50, 54, 26, 54, 99, 101, 108, 101, 115, 116, 105, 97, 118, 97, 108, 111, 112, 101, 114, 49, 100, 97, 118, 122, 52, 48, 107, 97, 116, 57, 51, 116, 52, 57, 108, 106, 114, 107, 109, 107, 108, 53, 117, 113, 104, 113, 113, 52, 53, 101, 48, 116, 117, 106, 50, 115, 51, 109, 34, 15, 10, 4, 117, 116, 105, 97, 18, 7, 49, 48, 48, 48, 48, 48, 48, 18, 22, 116, 101, 115, 116, 32, 117, 105, 32, 114, 101, 100, 101, 108, 101, 103, 97, 116, 101, 32, 116, 120, 32, 18, 103, 10, 80, 10, 70, 10, 31, 47, 99, 111, 115, 109, 111, 115, 46, 99, 114, 121, 112, 116, 111, 46, 115, 101, 99, 112, 50, 53, 54, 107, 49, 46, 80, 117, 98, 75, 101, 121, 18, 35, 10, 33, 2, 205, 82, 66, 173, 172, 164, 110, 151, 162, 183, 151, 111, 80, 96, 191, 38, 188, 141, 208, 175, 86, 52, 254, 146, 134, 204, 43, 40, 79, 127, 106, 1, 18, 4, 10, 2, 8, 127, 24, 39, 18, 19, 10, 13, 10, 4, 117, 116, 105, 97, 18, 5, 55, 50, 52, 51, 49, 16, 185, 215, 17, 26, 64, 98, 225, 18, 145, 187, 225, 213, 198, 229, 6, 6, 240, 177, 0, 28, 112, 160, 126, 193, 177, 221, 161, 96, 79, 5, 192, 224, 168, 253, 161, 12, 33, 9, 118, 215, 22, 219, 239, 73, 133, 79, 37, 218, 83, 238, 115, 44, 232, 16, 163, 242, 174, 100, 175, 162, 213, 142, 194, 58, 69, 84, 81, 3, 70}
func CreateTestBlock(tx types.ResponseDeliverTx, count int) (types.BlockData, time.Time) {
now := time.Now()
headerBlock := types.Block{
Header: types.Header{
Time: now,
},
Data: types.Data{
Txs: make(tmTypes.Txs, count),
},
}
var txResults = make([]*types.ResponseDeliverTx, count)
for i := 0; i < count; i++ {
txResults[i] = &tx
headerBlock.Data.Txs[i] = txMsgBeginRedelegate
}
block := types.BlockData{
ResultBlock: types.ResultBlock{
Block: &headerBlock,
},
ResultBlockResults: types.ResultBlockResults{
TxsResults: txResults,
},
}
return block, now
}
func CreateBlockWithTxs(tx types.ResponseDeliverTx, txData []byte, count int) (types.BlockData, time.Time) {
now := time.Now()
headerBlock := types.Block{
Header: types.Header{
Time: now,
},
Data: types.Data{
Txs: make(tmTypes.Txs, count),
},
}
var txResults = make([]*types.ResponseDeliverTx, count)
for i := 0; i < count; i++ {
txResults[i] = &tx
headerBlock.Data.Txs[i] = txData
}
block := types.BlockData{
ResultBlock: types.ResultBlock{
Block: &headerBlock,
},
ResultBlockResults: types.ResultBlockResults{
TxsResults: txResults,
},
}
return block, now
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package testsuite
import (
"crypto/rand"
"encoding/hex"
"math/big"
"github.com/shopspring/decimal"
)
// Ptr - returns pointer of value for testing purpose
//
// one := Ptr(1) // one is pointer to int
func Ptr[T any](t T) *T {
return &t
}
// MustHexDecode - returns decoded hex string, if it can't decode throws panic
//
// data := MustHexDecode("deadbeaf")
func MustHexDecode(s string) []byte {
data, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return data
}
// RandomDecimal - returns random decimal value
//
// data := RandomDecimal()
func RandomDecimal() decimal.Decimal {
val, _ := rand.Int(rand.Reader, big.NewInt(1000))
return decimal.NewFromBigInt(val, 1)
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// RandomText - generates random string with fixed size
//
// data := RandomText(10)
func RandomText(n int) string {
b := make([]rune, n)
for i := range b {
ids, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterRunes))))
b[i] = letterRunes[ids.Int64()]
}
return string(b)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package config
import (
"github.com/celenium-io/celestia-indexer/internal/profiler"
"github.com/dipdup-net/go-lib/config"
)
type Config struct {
config.Config `yaml:",inline"`
LogLevel string `validate:"omitempty,oneof=debug trace info warn error fatal panic" yaml:"log_level"`
Indexer Indexer `yaml:"indexer"`
Profiler *profiler.Config `validate:"omitempty" yaml:"profiler"`
}
type Indexer struct {
Name string `validate:"omitempty" yaml:"name"`
ThreadsCount uint32 `validate:"omitempty,min=1" yaml:"threads_count"`
StartLevel int64 `validate:"omitempty" yaml:"start_level"`
BlockPeriod int64 `validate:"omitempty" yaml:"block_period"`
ScriptsDir string `validate:"omitempty,dir" yaml:"scripts_dir"`
}
// Substitute -
func (c *Config) Substitute() error {
if err := c.Config.Substitute(); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package context
import (
"cosmossdk.io/errors"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/sync"
)
type Context struct {
Validators *sync.Map[string, *storage.Validator]
Addresses *sync.Map[string, *storage.Address]
Delegations *sync.Map[string, *storage.Delegation]
Jails *sync.Map[string, *storage.Jail]
Redelegations []storage.Redelegation
Undelegations []storage.Undelegation
CancelUnbonding []storage.Undelegation
StakingLogs []storage.StakingLog
Block *storage.Block
}
func NewContext() *Context {
return &Context{
Validators: sync.NewMap[string, *storage.Validator](),
Addresses: sync.NewMap[string, *storage.Address](),
Delegations: sync.NewMap[string, *storage.Delegation](),
Jails: sync.NewMap[string, *storage.Jail](),
Redelegations: make([]storage.Redelegation, 0),
Undelegations: make([]storage.Undelegation, 0),
CancelUnbonding: make([]storage.Undelegation, 0),
StakingLogs: make([]storage.StakingLog, 0),
}
}
func (ctx *Context) AddAddress(address *storage.Address) error {
if addr, ok := ctx.Addresses.Get(address.String()); ok {
addr.Balance.Spendable = addr.Balance.Spendable.Add(address.Balance.Spendable)
addr.Balance.Delegated = addr.Balance.Delegated.Add(address.Balance.Delegated)
addr.Balance.Unbonding = addr.Balance.Unbonding.Add(address.Balance.Unbonding)
} else {
if len(address.Hash) == 0 {
_, hash, err := pkgTypes.Address(address.Address).Decode()
if err != nil {
return errors.Wrap(err, address.Address)
}
address.Hash = hash
}
ctx.Addresses.Set(address.String(), address)
}
return nil
}
func (ctx *Context) AddValidator(validator storage.Validator) {
if val, ok := ctx.Validators.Get(validator.Address); ok {
if !validator.Stake.IsZero() {
val.Stake = val.Stake.Add(validator.Stake)
}
if !validator.Commissions.IsZero() {
val.Commissions = val.Commissions.Add(validator.Commissions)
}
if !validator.Rewards.IsZero() {
val.Rewards = val.Rewards.Add(validator.Rewards)
}
if !validator.MaxChangeRate.IsZero() {
val.MaxChangeRate = validator.MaxChangeRate.Copy()
}
if !validator.MaxRate.IsZero() {
val.MaxRate = validator.MaxRate.Copy()
}
if !validator.MinSelfDelegation.IsZero() {
val.MinSelfDelegation = validator.MinSelfDelegation.Copy()
}
if !validator.Rate.IsZero() {
val.Rate = validator.Rate.Copy()
}
if validator.Delegator != "" {
val.Delegator = validator.Delegator
}
if validator.Contacts != storage.DoNotModify {
val.Contacts = validator.Contacts
}
if validator.Details != storage.DoNotModify {
val.Details = validator.Details
}
if validator.Identity != storage.DoNotModify {
val.Identity = validator.Identity
}
if validator.Moniker != storage.DoNotModify {
val.Moniker = validator.Moniker
}
if validator.Website != storage.DoNotModify {
val.Website = validator.Website
}
} else {
ctx.Validators.Set(validator.Address, &validator)
}
}
func (ctx *Context) AddSupply(data map[string]any) {
ctx.Block.Stats.SupplyChange = ctx.Block.Stats.SupplyChange.Add(decoder.Amount(data))
}
func (ctx *Context) SubSupply(data map[string]any) {
ctx.Block.Stats.SupplyChange = ctx.Block.Stats.SupplyChange.Sub(decoder.Amount(data))
}
func (ctx *Context) SetInflation(data map[string]any) {
ctx.Block.Stats.InflationRate = decoder.DecimalFromMap(data, "inflation_rate")
}
func (ctx *Context) GetValidators() []*storage.Validator {
validators := make([]*storage.Validator, 0)
_ = ctx.Validators.Range(func(_ string, value *storage.Validator) (error, bool) {
validators = append(validators, value)
return nil, false
})
return validators
}
func (ctx *Context) GetAddresses() []*storage.Address {
addresses := make([]*storage.Address, 0)
_ = ctx.Addresses.Range(func(_ string, value *storage.Address) (error, bool) {
addresses = append(addresses, value)
return nil, false
})
return addresses
}
func (ctx *Context) AddDelegation(d storage.Delegation) {
if val, ok := ctx.Delegations.Get(d.String()); ok {
val.Amount = val.Amount.Add(d.Amount)
} else {
ctx.Delegations.Set(d.String(), &d)
}
}
func (ctx *Context) AddRedelegation(r storage.Redelegation) {
ctx.Redelegations = append(ctx.Redelegations, r)
}
func (ctx *Context) AddUndelegation(u storage.Undelegation) {
ctx.Undelegations = append(ctx.Undelegations, u)
}
func (ctx *Context) AddCancelUndelegation(u storage.Undelegation) {
ctx.CancelUnbonding = append(ctx.CancelUnbonding, u)
}
func (ctx *Context) AddJail(jail storage.Jail) {
if j, ok := ctx.Jails.Get(jail.Validator.ConsAddress); ok {
if jail.Reason != "" {
j.Reason = jail.Reason
}
if !jail.Burned.IsZero() {
j.Validator.Stake = j.Validator.Stake.Sub(jail.Burned)
j.Burned = j.Burned.Add(jail.Burned)
}
if jail.Validator.Jailed != nil {
j.Validator.Jailed = jail.Validator.Jailed
}
} else {
ctx.Jails.Set(jail.Validator.ConsAddress, &jail)
}
}
func (ctx *Context) AddStakingLog(l storage.StakingLog) {
ctx.StakingLogs = append(ctx.StakingLogs, l)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decoder
import (
"strconv"
"strings"
"time"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/cosmos/cosmos-sdk/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func DecimalFromMap(m map[string]any, key string) decimal.Decimal {
str := StringFromMap(m, key)
if str == "" {
return decimal.Zero
}
str = strings.TrimRight(str, letters)
dec, err := decimal.NewFromString(str)
if err != nil {
return decimal.Zero
}
return dec
}
func Amount(m map[string]any) decimal.Decimal {
return DecimalFromMap(m, "amount")
}
func StringFromMap(m map[string]any, key string) string {
val, ok := m[key]
if !ok {
return ""
}
str, ok := val.(string)
if !ok {
return ""
}
return str
}
func BalanceFromMap(m map[string]any, key string) (*types.Coin, error) {
str := StringFromMap(m, key)
if str == "" {
return nil, nil
}
coin, err := types.ParseCoinNormalized(str)
if err != nil {
return nil, err
}
return &coin, nil
}
func AmountFromMap(m map[string]any, key string) decimal.Decimal {
str := StringFromMap(m, key)
if str == "" {
return decimal.Zero
}
str = strings.TrimSuffix(str, currency.DefaultCurrency)
return decimal.RequireFromString(str)
}
func TimeFromMap(m map[string]any, key string) (time.Time, error) {
val, ok := m[key]
if !ok {
return time.Time{}, errors.Errorf("can't find key: %s", key)
}
str, ok := val.(string)
if !ok {
return time.Time{}, errors.Errorf("key '%s' is not a string", key)
}
return time.Parse(time.RFC3339, str)
}
func Int64FromMap(m map[string]any, key string) (int64, error) {
val, ok := m[key]
if !ok {
return 0, errors.Errorf("can't find key: %s", key)
}
str, ok := val.(string)
if !ok {
return 0, errors.Errorf("key '%s' is not a string", key)
}
return strconv.ParseInt(str, 10, 64)
}
func AuthMsgIndexFromMap(m map[string]any) (*int64, error) {
val, ok := m["authz_msg_index"]
if !ok {
return nil, nil
}
str, ok := val.(string)
if !ok {
return nil, errors.New("key 'auth_msg_index' is not a string")
}
i, err := strconv.ParseInt(str, 10, 64)
return &i, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"time"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/cosmos/cosmos-sdk/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
type CoinReceived struct {
Amount *types.Coin
Receiver string
}
func NewCoinReceived(m map[string]any) (body CoinReceived, err error) {
body.Receiver = decoder.StringFromMap(m, "receiver")
if body.Receiver == "" {
err = errors.Errorf("receiver key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type CoinSpent struct {
Amount *types.Coin
Spender string
}
func NewCoinSpent(m map[string]any) (body CoinSpent, err error) {
body.Spender = decoder.StringFromMap(m, "spender")
if body.Spender == "" {
err = errors.Errorf("spender key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type CompleteRedelegation struct {
Amount *types.Coin
Delegator string
DestValidator string
SrcValidator string
}
func NewCompleteRedelegation(m map[string]any) (body CompleteRedelegation, err error) {
body.Delegator = decoder.StringFromMap(m, "delegator")
if body.Delegator == "" {
err = errors.Errorf("delegator key not found in %##v", m)
return
}
body.DestValidator = decoder.StringFromMap(m, "destination_validator")
if body.DestValidator == "" {
err = errors.Errorf("destination_validator key not found in %##v", m)
return
}
body.SrcValidator = decoder.StringFromMap(m, "source_validator")
if body.SrcValidator == "" {
err = errors.Errorf("source_validator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type CompleteUnbonding struct {
Amount *types.Coin
Delegator string
Validator string
}
func NewCompleteUnbonding(m map[string]any) (body CompleteUnbonding, err error) {
body.Delegator = decoder.StringFromMap(m, "delegator")
if body.Delegator == "" {
err = errors.Errorf("delegator key not found in %##v", m)
return
}
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type Commission struct {
Amount decimal.Decimal
Validator string
}
func NewCommission(m map[string]any) (body Commission, err error) {
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Amount = decoder.AmountFromMap(m, "amount")
return
}
type Rewards struct {
Amount decimal.Decimal
Validator string
}
func NewRewards(m map[string]any) (body Rewards, err error) {
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Amount = decoder.AmountFromMap(m, "amount")
return
}
type WithdrawRewards struct {
Amount *types.Coin
Validator string
Delegator string
}
func NewWithdrawRewards(m map[string]any) (body WithdrawRewards, err error) {
body.Delegator = decoder.StringFromMap(m, "delegator")
if body.Delegator == "" {
err = errors.Errorf("delegator key not found in %##v", m)
return
}
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type WithdrawCommission struct {
Amount *types.Coin
}
func NewWithdrawCommission(m map[string]any) (body WithdrawCommission, err error) {
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type Redelegate struct {
Amount *types.Coin
DestValidator string
SrcValidator string
CompletionTime time.Time
}
func NewRedelegate(m map[string]any) (body Redelegate, err error) {
body.CompletionTime, err = decoder.TimeFromMap(m, "completion_time")
if err != nil {
err = errors.Wrap(err, "completion_time")
return
}
body.DestValidator = decoder.StringFromMap(m, "destination_validator")
if body.DestValidator == "" {
err = errors.Errorf("destination_validator key not found in %##v", m)
return
}
body.SrcValidator = decoder.StringFromMap(m, "source_validator")
if body.SrcValidator == "" {
err = errors.Errorf("source_validator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type Unbond struct {
Amount *types.Coin
Validator string
CompletionTime time.Time
}
func NewUnbond(m map[string]any) (body Unbond, err error) {
body.CompletionTime, err = decoder.TimeFromMap(m, "completion_time")
if err != nil {
err = errors.Wrap(err, "completion_time")
return
}
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type Delegate struct {
Amount *types.Coin
NewShares decimal.Decimal
Validator string
}
func NewDelegate(m map[string]any) (body Delegate, err error) {
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.NewShares = decoder.DecimalFromMap(m, "new_shares")
body.Amount, err = decoder.BalanceFromMap(m, "amount")
return
}
type CancelUnbondingDelegation struct {
Amount *types.Coin
Validator string
Delegator string
CreationHeight int64
}
func NewCancelUnbondingDelegation(m map[string]any) (body CancelUnbondingDelegation, err error) {
body.Validator = decoder.StringFromMap(m, "validator")
if body.Validator == "" {
err = errors.Errorf("validator key not found in %##v", m)
return
}
body.Delegator = decoder.StringFromMap(m, "delegator")
if body.Delegator == "" {
err = errors.Errorf("delegator key not found in %##v", m)
return
}
body.Amount, err = decoder.BalanceFromMap(m, "amount")
if err != nil {
return
}
body.CreationHeight, err = decoder.Int64FromMap(m, "creation_height")
return
}
type Slash struct {
Power decimal.Decimal
Jailed string
Reason string
Address string
BurnedCoins decimal.Decimal
}
func NewSlash(m map[string]any) (body Slash, err error) {
body.Power = decoder.DecimalFromMap(m, "power")
body.BurnedCoins = decoder.DecimalFromMap(m, "burned_coins")
body.Reason = decoder.StringFromMap(m, "reason")
body.Jailed = decoder.StringFromMap(m, "jailed")
body.Address = decoder.StringFromMap(m, "address")
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/cosmos/cosmos-sdk/x/authz"
bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/fatih/structs"
)
// MsgGrant is a request type for Grant method. It declares authorization to the grantee
// on behalf of the granter with the provided expiration time.
func MsgGrant(ctx *context.Context, status types.Status, m *authz.MsgGrant) (storageTypes.MsgType, []storage.AddressWithType, []storage.Grant, error) {
msgType := storageTypes.MsgGrant
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, ctx.Block.Height)
if err != nil || status == types.StatusFailed {
return msgType, addresses, nil, err
}
grants, err := parseGrants(m, ctx.Block.Time, ctx.Block.Height)
return msgType, addresses, grants, err
}
// MsgExec attempts to execute the provided messages using
// authorizations granted to the grantee. Each message should have only
// one signer corresponding to the granter of the authorization.
func MsgExec(ctx *context.Context, status types.Status, m *authz.MsgExec) (storageTypes.MsgType, []storage.AddressWithType, []string, error) {
msgType := storageTypes.MsgExec
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, ctx.Block.Height)
// MsgExecute also has Msgs field, where also can be addresses.
// Authorization Msg requests to execute. Each msg must implement Authorization interface
// The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
// triple and validate it.
if err != nil {
return msgType, addresses, nil, err
}
if status == types.StatusFailed {
return msgType, addresses, nil, nil
}
msgs := make([]string, len(m.Msgs))
for i := range m.Msgs {
msgs[i] = m.Msgs[i].TypeUrl
}
return msgType, addresses, msgs, nil
}
// MsgRevoke revokes any authorization with the provided sdk.Msg type on the
// granter's account with that has been granted to the grantee.
func MsgRevoke(ctx *context.Context, status types.Status, m *authz.MsgRevoke) (storageTypes.MsgType, []storage.AddressWithType, []storage.Grant, error) {
msgType := storageTypes.MsgRevoke
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, ctx.Block.Height)
if err != nil || status == types.StatusFailed {
return msgType, addresses, nil, err
}
grant := storage.Grant{
Granter: &storage.Address{
Address: m.Granter,
},
Grantee: &storage.Address{
Address: m.Grantee,
},
Revoked: true,
Authorization: m.MsgTypeUrl,
RevokeHeight: &ctx.Block.Height,
}
return msgType, addresses, []storage.Grant{grant}, nil
}
func parseGrants(msg *authz.MsgGrant, t time.Time, height pkgTypes.Level) ([]storage.Grant, error) {
if msg == nil {
return nil, nil
}
switch msg.Grant.Authorization.TypeUrl {
case "/cosmos.authz.v1beta1.GenericAuthorization":
var typ authz.GenericAuthorization
if err := typ.Unmarshal(msg.Grant.Authorization.Value); err != nil {
return nil, err
}
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: typ.MsgTypeURL(),
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
case "/cosmos.bank.v1beta1.SendAuthorization":
var typ bankTypes.SendAuthorization
if err := typ.Unmarshal(msg.Grant.Authorization.Value); err != nil {
return nil, err
}
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: "/cosmos.bank.v1beta1.MsgSend",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
case "/cosmos.staking.v1beta1.StakeAuthorization":
var typ stakingTypes.StakeAuthorization
if err := typ.Unmarshal(msg.Grant.Authorization.Value); err != nil {
return nil, err
}
switch typ.AuthorizationType {
case stakingTypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE:
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgDelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
case stakingTypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE:
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgRedelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
case stakingTypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE:
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgUndelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
case stakingTypes.AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED:
return []storage.Grant{
{
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgDelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
}, {
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgRedelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
}, {
Params: structs.Map(typ),
Authorization: "/cosmos.staking.v1beta1.MsgUndelegate",
Granter: &storage.Address{
Address: msg.Granter,
},
Grantee: &storage.Address{
Address: msg.Grantee,
},
Height: height,
Expiration: msg.Grant.Expiration,
Time: t,
},
}, nil
}
}
return nil, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cosmosBankTypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
// MsgSend represents a message to send coins from one account to another.
func MsgSend(ctx *context.Context, m *cosmosBankTypes.MsgSend) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSend
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgMultiSend represents an arbitrary multi-in, multi-out send message.
func MsgMultiSend(ctx *context.Context, m *cosmosBankTypes.MsgMultiSend) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgMultiSend
aData := make(addressesData, len(m.Inputs)+len(m.Outputs))
var i int64
for _, input := range m.Inputs {
aData[i] = addressData{t: storageTypes.MsgAddressTypeInput, address: input.Address}
i++
}
for _, output := range m.Outputs {
aData[i] = addressData{t: storageTypes.MsgAddressTypeOutput, address: output.Address}
i++
}
addresses, err := createAddresses(ctx, aData, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"encoding/base64"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
appBlobTypes "github.com/celestiaorg/celestia-app/v3/x/blob/types"
nsPackage "github.com/celestiaorg/go-square/v2/share"
"github.com/pkg/errors"
)
// MsgPayForBlobs pays for the inclusion of a blob in the block.
func MsgPayForBlobs(ctx *context.Context, status storageTypes.Status, m *appBlobTypes.MsgPayForBlobs) (storageTypes.MsgType, []storage.AddressWithType, []storage.Namespace, []*storage.BlobLog, int64, error) {
var blobsSize int64
uniqueNs := make(map[string]*storage.Namespace)
blobLogs := make([]*storage.BlobLog, 0)
for nsI, ns := range m.Namespaces {
if len(m.BlobSizes) < nsI {
return storageTypes.MsgUnknown, nil, nil, nil, 0, errors.Errorf(
"blob sizes length=%d is less then namespaces index=%d", len(m.BlobSizes), nsI)
}
if len(m.ShareCommitments) < nsI {
return storageTypes.MsgUnknown, nil, nil, nil, 0, errors.Errorf(
"share commitment sizes length=%d is less then namespaces index=%d", len(m.ShareCommitments), nsI)
}
appNS, err := nsPackage.NewNamespaceFromBytes(ns)
if err != nil {
return storageTypes.MsgUnknown, nil, nil, nil, 0, errors.Wrap(err, "NewNamespaceFromBytes")
}
size := int64(m.BlobSizes[nsI])
blobsSize += size
namespace := storage.Namespace{
FirstHeight: ctx.Block.Height,
Version: appNS.Version(),
NamespaceID: appNS.ID(),
PfbCount: 1,
Reserved: appNS.IsReserved(),
LastHeight: ctx.Block.Height,
LastMessageTime: ctx.Block.Time,
}
if status == storageTypes.StatusSuccess {
namespace.BlobsCount = 1
namespace.Size = size
blobLog := &storage.BlobLog{
Commitment: base64.StdEncoding.EncodeToString(m.ShareCommitments[nsI]),
Size: size,
Namespace: &namespace,
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Signer: &storage.Address{
Address: m.Signer,
},
}
blobLogs = append(blobLogs, blobLog)
}
if n, ok := uniqueNs[namespace.String()]; ok {
n.Size += size
n.BlobsCount += namespace.BlobsCount
} else {
uniqueNs[namespace.String()] = namespace.Copy()
}
}
namespaces := make([]storage.Namespace, 0, len(uniqueNs))
for _, namespace := range uniqueNs {
namespaces = append(namespaces, *namespace)
}
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return storageTypes.MsgPayForBlobs, addresses, namespaces, blobLogs, blobsSize, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
coreChannel "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types"
)
// MsgChannelOpenInit defines an sdk.Msg to initialize a channel handshake. It
// is called by a relayer on Chain A.
func MsgChannelOpenInit(ctx *context.Context, m *coreChannel.MsgChannelOpenInit) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelOpenInit
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgChannelOpenTry defines a msg sent by a Relayer to try to open a channel
// on Chain B. The version field within the Channel field has been deprecated. Its
// value will be ignored by core IBC.
func MsgChannelOpenTry(ctx *context.Context, m *coreChannel.MsgChannelOpenTry) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelOpenTry
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgChannelOpenAck defines a msg sent by a Relayer to Chain A to acknowledge
// the change of channel state to TRYOPEN on Chain B.
func MsgChannelOpenAck(ctx *context.Context, m *coreChannel.MsgChannelOpenAck) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelOpenAck
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgChannelOpenConfirm defines a msg sent by a Relayer to Chain B to
// acknowledge the change of channel state to OPEN on Chain A.
func MsgChannelOpenConfirm(ctx *context.Context, m *coreChannel.MsgChannelOpenConfirm) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelOpenConfirm
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgChannelCloseInit defines a msg sent by a Relayer to Chain A
// to close a channel with Chain B.
func MsgChannelCloseInit(ctx *context.Context, m *coreChannel.MsgChannelCloseInit) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelCloseInit
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgChannelCloseConfirm defines a msg sent by a Relayer to Chain B
// to acknowledge the change of channel state to CLOSED on Chain A.
func MsgChannelCloseConfirm(ctx *context.Context, m *coreChannel.MsgChannelCloseConfirm) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgChannelCloseConfirm
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgRecvPacket receives an incoming IBC packet
func MsgRecvPacket(ctx *context.Context, m *coreChannel.MsgRecvPacket) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRecvPacket
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgTimeout receives a timed-out packet
func MsgTimeout(ctx *context.Context, m *coreChannel.MsgTimeout) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgTimeout
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgTimeoutOnClose timed-out packet upon counterparty channel closure
func MsgTimeoutOnClose(ctx *context.Context, m *coreChannel.MsgTimeoutOnClose) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgTimeoutOnClose
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgAcknowledgement receives incoming IBC acknowledgement
func MsgAcknowledgement(ctx *context.Context, m *coreChannel.MsgAcknowledgement) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgAcknowledgement
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
coreClient "github.com/cosmos/ibc-go/v6/modules/core/02-client/types"
tmTypes "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint/types"
)
// MsgCreateClient defines a message to create an IBC client
func MsgCreateClient(ctx *context.Context, m *coreClient.MsgCreateClient) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateClient
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateClient defines a sdk.Msg to update an IBC client state using the given header
func MsgUpdateClient(ctx *context.Context, status types.Status, m *coreClient.MsgUpdateClient) (storageTypes.MsgType, []storage.AddressWithType, *tmTypes.Header, error) {
msgType := storageTypes.MsgUpdateClient
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
if err != nil || status == types.StatusFailed {
return msgType, addresses, nil, err
}
var header tmTypes.Header
err = header.Unmarshal(m.Header.Value)
return msgType, addresses, &header, err
}
// MsgUpgradeClient defines a sdk.Msg to upgrade an IBC client to a new client state
func MsgUpgradeClient(ctx *context.Context, m *coreClient.MsgUpgradeClient) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpgradeClient
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgSubmitMisbehaviour defines a sdk.Msg type that submits Evidence for light client misbehavior
func MsgSubmitMisbehaviour(ctx *context.Context, m *coreClient.MsgSubmitMisbehaviour) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSubmitMisbehaviour
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
coreConnection "github.com/cosmos/ibc-go/v6/modules/core/03-connection/types"
)
// MsgConnectionOpenInit defines the msg sent by an account on Chain A to initialize a connection with Chain B.
func MsgConnectionOpenInit(ctx *context.Context, m *coreConnection.MsgConnectionOpenInit) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgConnectionOpenInit
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgConnectionOpenTry defines a msg sent by a Relayer to try to open a connection on Chain B.
func MsgConnectionOpenTry(ctx *context.Context, m *coreConnection.MsgConnectionOpenTry) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgConnectionOpenTry
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgConnectionOpenAck defines a msg sent by a Relayer to Chain A to
// acknowledge the change of connection state to TRYOPEN on Chain B.
func MsgConnectionOpenAck(ctx *context.Context, m *coreConnection.MsgConnectionOpenAck) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgConnectionOpenAck
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgConnectionOpenConfirm defines a msg sent by a Relayer to Chain B to
// acknowledge the change of connection state to OPEN on Chain A.
func MsgConnectionOpenConfirm(ctx *context.Context, m *coreConnection.MsgConnectionOpenConfirm) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgConnectionOpenConfirm
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
type addressData struct {
t storageTypes.MsgAddressType
address string
}
type addressesData []addressData
func createAddresses(ctx *context.Context, data addressesData, level types.Level) ([]storage.AddressWithType, error) {
addresses := make([]storage.AddressWithType, len(data))
for i, d := range data {
_, hash, err := types.Address(d.address).Decode()
if err != nil {
return nil, err
}
address := storage.Address{
Hash: hash,
Height: level,
LastHeight: level,
Address: d.address,
Balance: storage.EmptyBalance(),
}
if err := ctx.AddAddress(&address); err != nil {
return addresses, nil
}
addresses[i] = storage.AddressWithType{
Type: d.t,
Address: address,
}
}
return addresses, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
crisisTypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
)
// MsgVerifyInvariant represents a message to verify a particular invariance.
func MsgVerifyInvariant(ctx *context.Context, m *crisisTypes.MsgVerifyInvariant) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVerifyInvariant
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSender, address: m.Sender},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cosmosDistributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
)
// MsgSetWithdrawAddress sets the withdrawal address for
// a delegator (or validator self-delegation).
func MsgSetWithdrawAddress(ctx *context.Context, m *cosmosDistributionTypes.MsgSetWithdrawAddress) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSetWithdrawAddress
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeWithdraw, address: m.WithdrawAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator
// from a single validator.
func MsgWithdrawDelegatorReward(ctx *context.Context, m *cosmosDistributionTypes.MsgWithdrawDelegatorReward) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgWithdrawDelegatorReward
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgWithdrawValidatorCommission withdraws the full commission to the validator
// address.
func MsgWithdrawValidatorCommission(ctx *context.Context, m *cosmosDistributionTypes.MsgWithdrawValidatorCommission) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgWithdrawValidatorCommission
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgFundCommunityPool allows an account to directly
// fund the community pool.
func MsgFundCommunityPool(ctx *context.Context, m *cosmosDistributionTypes.MsgFundCommunityPool) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgFundCommunityPool
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDepositor, address: m.Depositor},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
evidenceTypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
)
// MsgSubmitEvidence represents a message that supports submitting arbitrary
// Evidence of misbehavior such as equivocation or counterfactual signing.
func MsgSubmitEvidence(ctx *context.Context, m *evidenceTypes.MsgSubmitEvidence) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSubmitEvidence
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSubmitter, address: m.Submitter},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
fee "github.com/cosmos/ibc-go/v6/modules/apps/29-fee/types"
)
// MsgRegisterPayee defines the request type for the RegisterPayee rpc
func MsgRegisterPayee(ctx *context.Context, m *fee.MsgRegisterPayee) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRegisterPayee
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeRelayer, address: m.Relayer},
{t: storageTypes.MsgAddressTypePayee, address: m.Payee},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgRegisterCounterpartyPayee defines the request type for the RegisterCounterpartyPayee rpc
func MsgRegisterCounterpartyPayee(ctx *context.Context, m *fee.MsgRegisterCounterpartyPayee) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRegisterCounterpartyPayee
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeRelayer, address: m.Relayer},
{t: storageTypes.MsgAddressTypePayee, address: m.CounterpartyPayee}, // the counterparty payee address
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgPayPacketFee defines the request type for the PayPacketFee rpc
// This Msg can be used to pay for a packet at the next sequence send & should be combined with the Msg that will be
// paid for
func MsgPayPacketFee(ctx *context.Context, m *fee.MsgPayPacketFee) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgPayPacketFee
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgPayPacketFeeAsync defines the request type for the PayPacketFeeAsync rpc
// This Msg can be used to pay for a packet at a specified sequence (instead of the next sequence sends)
func MsgPayPacketFeeAsync() (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgPayPacketFeeAsync
return msgType, []storage.AddressWithType{}, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/cosmos/cosmos-sdk/x/feegrant"
"github.com/fatih/structs"
)
// MsgGrantAllowance adds permission for Grantee to spend up to Allowance
// of fees from the account of Granter.
func MsgGrantAllowance(ctx *context.Context, status types.Status, m *feegrant.MsgGrantAllowance) (storageTypes.MsgType, []storage.AddressWithType, []storage.Grant, error) {
msgType := storageTypes.MsgGrantAllowance
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, ctx.Block.Height)
if err != nil || status == types.StatusFailed {
return msgType, addresses, nil, err
}
grant := storage.Grant{
Granter: &storage.Address{
Address: m.Granter,
},
Grantee: &storage.Address{
Address: m.Grantee,
},
Authorization: "fee",
Height: ctx.Block.Height,
Time: ctx.Block.Time,
}
err = parseGrantFee(m, &grant)
return msgType, addresses, []storage.Grant{grant}, err
}
// MsgRevokeAllowance removes any existing Allowance from Granter to Grantee.
func MsgRevokeAllowance(ctx *context.Context, status types.Status, m *feegrant.MsgRevokeAllowance) (storageTypes.MsgType, []storage.AddressWithType, []storage.Grant, error) {
msgType := storageTypes.MsgRevokeAllowance
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, ctx.Block.Height)
if err != nil || status == types.StatusFailed {
return msgType, addresses, nil, err
}
grant := storage.Grant{
Granter: &storage.Address{
Address: m.Granter,
},
Grantee: &storage.Address{
Address: m.Grantee,
},
Revoked: true,
Authorization: "fee",
RevokeHeight: &ctx.Block.Height,
}
return msgType, addresses, []storage.Grant{grant}, nil
}
func parseGrantFee(m *feegrant.MsgGrantAllowance, g *storage.Grant) error {
switch m.Allowance.TypeUrl {
case "/cosmos.feegrant.v1beta1.BasicAllowance":
var body feegrant.BasicAllowance
if err := body.Unmarshal(m.Allowance.Value); err != nil {
return err
}
g.Params = structs.Map(body)
g.Expiration = body.Expiration
case "/cosmos.feegrant.v1beta1.PeriodicAllowance":
var body feegrant.PeriodicAllowance
if err := body.Unmarshal(m.Allowance.Value); err != nil {
return err
}
g.Params = structs.Map(body)
g.Expiration = body.Basic.Expiration
case "/cosmos.feegrant.v1beta1.AllowedMsgAllowance":
var body feegrant.AllowedMsgAllowance
if err := body.Unmarshal(m.Allowance.Value); err != nil {
return err
}
var basic feegrant.BasicAllowance
if err := basic.Unmarshal(body.Allowance.Value); err != nil {
return err
}
g.Params = structs.Map(body)
g.Params["Allowance"] = basic
g.Expiration = basic.Expiration
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cosmosGovTypesV1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
)
// MsgSubmitProposal defines a sdk.Msg type that supports submitting arbitrary
// proposal Content.
func MsgSubmitProposal(ctx *context.Context, proposerAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSubmitProposal
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeProposer, address: proposerAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgExecLegacyContent is used to wrap the legacy content field into a message.
// This ensures backwards compatibility with v1beta1.MsgSubmitProposal.
func MsgExecLegacyContent(ctx *context.Context, m *cosmosGovTypesV1.MsgExecLegacyContent) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgExecLegacyContent
addresses, err := createAddresses(
ctx,
addressesData{
{t: storageTypes.MsgAddressTypeAuthority, address: m.Authority},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgVote defines a message to cast a vote.
func MsgVote(ctx *context.Context, voterAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVote
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeVoter, address: voterAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgVoteWeighted defines a message to cast a vote.
func MsgVoteWeighted(ctx *context.Context, voterAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVoteWeighted
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeVoter, address: voterAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgDeposit defines a message to submit a deposit to an existing proposal.
func MsgDeposit(ctx *context.Context, depositorAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgDeposit
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDepositor, address: depositorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/cosmos/cosmos-sdk/x/group"
)
// MsgCreateGroup is the Msg/CreateGroup request type.
func MsgCreateGroup(ctx *context.Context, m *group.MsgCreateGroup) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateGroup
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupMembers is the Msg/UpdateGroupMembers request type.
func MsgUpdateGroupMembers(ctx *context.Context, m *group.MsgUpdateGroupMembers) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupMembers
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupAdmin is the Msg/UpdateGroupAdmin request type.
func MsgUpdateGroupAdmin(ctx *context.Context, m *group.MsgUpdateGroupAdmin) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupAdmin
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
{t: storageTypes.MsgAddressTypeNewAdmin, address: m.NewAdmin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupMetadata is the Msg/UpdateGroupMetadata request type.
func MsgUpdateGroupMetadata(ctx *context.Context, m *group.MsgUpdateGroupMetadata) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupMetadata
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgCreateGroupPolicy is the Msg/CreateGroupPolicy request type.
func MsgCreateGroupPolicy(ctx *context.Context, m *group.MsgCreateGroupPolicy) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateGroupPolicy
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupPolicyAdmin is the Msg/UpdateGroupPolicyAdmin request type.
func MsgUpdateGroupPolicyAdmin(ctx *context.Context, m *group.MsgUpdateGroupPolicyAdmin) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupPolicyAdmin
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgCreateGroupWithPolicy is the Msg/CreateGroupWithPolicy request type.
func MsgCreateGroupWithPolicy(ctx *context.Context, m *group.MsgCreateGroupWithPolicy) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateGroupWithPolicy
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupPolicyDecisionPolicy is the Msg/UpdateGroupPolicyDecisionPolicy request type.
func MsgUpdateGroupPolicyDecisionPolicy(ctx *context.Context, m *group.MsgUpdateGroupPolicyDecisionPolicy) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupPolicyDecisionPolicy
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
{t: storageTypes.MsgAddressTypeGroupPolicyAddress, address: m.GroupPolicyAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUpdateGroupPolicyMetadata is the Msg/UpdateGroupPolicyMetadata request type.
func MsgUpdateGroupPolicyMetadata(ctx *context.Context, m *group.MsgUpdateGroupPolicyMetadata) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUpdateGroupPolicyMetadata
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Admin},
{t: storageTypes.MsgAddressTypeGroupPolicyAddress, address: m.GroupPolicyAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgSubmitProposal is the Msg/SubmitProposal request type.
func MsgSubmitProposalGroup(ctx *context.Context, m *group.MsgSubmitProposal) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSubmitProposalGroup
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGroupPolicyAddress, address: m.GroupPolicyAddress},
// Proposers - list of proposer addresses
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgWithdrawProposal is the Msg/WithdrawProposal request type.
func MsgWithdrawProposal(ctx *context.Context, m *group.MsgWithdrawProposal) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgWithdrawProposal
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAdmin, address: m.Address}, // address is the admin of the group policy or one of the proposer of the proposal.
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgVote is the Msg/Vote request type.
func MsgVoteGroup(ctx *context.Context, m *group.MsgVote) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVoteGroup
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeVoter, address: m.Voter},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgExec is the Msg/Exec request type.
func MsgExecGroup(ctx *context.Context, m *group.MsgExec) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgExecGroup
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeExecutor, address: m.Executor},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgLeaveGroup is the Msg/LeaveGroup request type.
func MsgLeaveGroup(ctx *context.Context, m *group.MsgLeaveGroup) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgLeaveGroup
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeGroupMember, address: m.Address},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
ibcTypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
)
// IBCTransfer defines a msg to transfer fungible tokens (i.e., Coins) between
// ICS20 enabled chains. See ICS Spec here:
// https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#data-structures
func IBCTransfer(ctx *context.Context, m *ibcTypes.MsgTransfer) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.IBCTransfer
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSender, address: m.Sender},
// {t: storageTypes.MsgAddressTypeReceiver,
// address: m.Receiver}, // TODO: is it data to do IBC Transfer on cosmos network?
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
interchainAccounts "github.com/cosmos/ibc-go/v6/modules/apps/27-interchain-accounts/controller/types"
)
// MsgRegisterInterchainAccount defines the payload for Msg/MsgRegisterInterchainAccount
func MsgRegisterInterchainAccount(ctx *context.Context, m *interchainAccounts.MsgRegisterInterchainAccount) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRegisterInterchainAccount
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeOwner, address: m.Owner},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgSendTx defines the payload for Msg/SendTx
func MsgSendTx(ctx *context.Context, m *interchainAccounts.MsgSendTx) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSendTx
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeOwner, address: m.Owner},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/cosmos/cosmos-sdk/x/nft"
)
// MsgSendNFT represents a message to send a nft from one account to another account.
func MsgSendNFT(ctx *context.Context, m *nft.MsgSend) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSendNFT
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSender, address: m.Sender},
{t: storageTypes.MsgAddressTypeReceiver, address: m.Receiver},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
qgbTypes "github.com/celestiaorg/celestia-app/v3/x/blobstream/types"
)
// MsgRegisterEVMAddress registers an evm address to a validator.
func MsgRegisterEVMAddress(ctx *context.Context, m *qgbTypes.MsgRegisterEVMAddress) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRegisterEVMAddress
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
// TODO: think about EVM addresses
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
)
// MsgSignalVersion -
func MsgSignalVersion(ctx *context.Context, validatorAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSignalVersion
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: validatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgTryUpgrade -
func MsgTryUpgrade(ctx *context.Context, signer string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgTryUpgrade
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: signer},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cosmosSlashingTypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
)
// MsgUnjail defines the Msg/Unjail request type
func MsgUnjail(ctx *context.Context, m *cosmosSlashingTypes.MsgUnjail) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUnjail
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddr},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
cosmosStakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/rs/zerolog/log"
"github.com/shopspring/decimal"
)
// MsgCreateValidator defines an SDK message for creating a new validator.
func MsgCreateValidator(ctx *context.Context, status storageTypes.Status, m *cosmosStakingTypes.MsgCreateValidator) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateValidator
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
if err != nil {
return msgType, addresses, err
}
if status == storageTypes.StatusFailed {
return msgType, addresses, nil
}
var consAddress string
if m.Pubkey != nil {
pk, ok := m.Pubkey.GetCachedValue().(cryptotypes.PubKey)
if ok {
consAddress = pk.Address().String()
} else {
log.Warn().Msg("can't decode consensus address of validator")
}
}
jailed := false
validator := storage.Validator{
Delegator: m.DelegatorAddress,
Address: m.ValidatorAddress,
ConsAddress: consAddress,
Moniker: m.Description.Moniker,
Identity: m.Description.Identity,
Website: m.Description.Website,
Details: m.Description.Details,
Contacts: m.Description.SecurityContact,
Height: ctx.Block.Height,
Rate: decimal.Zero,
MaxRate: decimal.Zero,
MaxChangeRate: decimal.Zero,
MinSelfDelegation: decimal.Zero,
Stake: decimal.Zero,
Jailed: &jailed,
}
if !m.Value.IsNil() {
amount := decimal.RequireFromString(m.Value.Amount.String())
validator.Stake = amount
address := storage.Address{
Address: m.DelegatorAddress,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Unbonding: decimal.Zero,
Delegated: amount.Copy(),
},
}
if err := ctx.AddAddress(&address); err != nil {
return msgType, nil, err
}
addresses[0].Balance = address.Balance
ctx.AddDelegation(storage.Delegation{
Address: &address,
Validator: &validator,
Amount: amount.Copy(),
})
ctx.AddStakingLog(storage.StakingLog{
Time: ctx.Block.Time,
Height: ctx.Block.Height,
Address: &address,
Validator: &validator,
Change: amount.Copy(),
Type: storageTypes.StakingLogTypeDelegation,
})
}
if !m.Commission.Rate.IsNil() {
validator.Rate = decimal.RequireFromString(m.Commission.Rate.String())
}
if !m.Commission.MaxRate.IsNil() {
validator.MaxRate = decimal.RequireFromString(m.Commission.MaxRate.String())
}
if !m.Commission.MaxChangeRate.IsNil() {
validator.MaxChangeRate = decimal.RequireFromString(m.Commission.MaxChangeRate.String())
}
if !m.MinSelfDelegation.IsNil() {
validator.MinSelfDelegation = decimal.RequireFromString(m.MinSelfDelegation.String())
}
ctx.AddValidator(validator)
return msgType, addresses, err
}
// MsgEditValidator defines a SDK message for editing an existing validator.
func MsgEditValidator(ctx *context.Context, status storageTypes.Status, m *cosmosStakingTypes.MsgEditValidator) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgEditValidator
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
if err != nil {
return msgType, addresses, err
}
if status == storageTypes.StatusFailed {
return msgType, addresses, nil
}
validator := storage.Validator{
Address: m.ValidatorAddress,
Moniker: m.Description.Moniker,
Identity: m.Description.Identity,
Website: m.Description.Website,
Details: m.Description.Details,
Contacts: m.Description.SecurityContact,
Height: ctx.Block.Height,
Rate: decimal.Zero,
MinSelfDelegation: decimal.Zero,
Stake: decimal.Zero,
}
if m.CommissionRate != nil && !m.CommissionRate.IsNil() {
validator.Rate = decimal.RequireFromString(m.CommissionRate.String())
}
if m.MinSelfDelegation != nil && !m.MinSelfDelegation.IsNil() {
validator.MinSelfDelegation = decimal.RequireFromString(m.MinSelfDelegation.String())
}
ctx.AddValidator(validator)
return msgType, addresses, err
}
// MsgDelegate defines a SDK message for performing a delegation of coins
// from a delegator to a validator.
func MsgDelegate(ctx *context.Context, m *cosmosStakingTypes.MsgDelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgDelegate
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgBeginRedelegate defines an SDK message for performing a redelegation
// of coins from a delegator and source validator to a destination validator.
func MsgBeginRedelegate(ctx *context.Context, m *cosmosStakingTypes.MsgBeginRedelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgBeginRedelegate
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidatorSrc, address: m.ValidatorSrcAddress},
{t: storageTypes.MsgAddressTypeValidatorDst, address: m.ValidatorDstAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgUndelegate defines a SDK message for performing an undelegation from a
// delegate and a validator.
func MsgUndelegate(ctx *context.Context, m *cosmosStakingTypes.MsgUndelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUndelegate
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgCancelUnbondingDelegation defines the SDK message for performing a cancel unbonding delegation for delegator
//
// Since: cosmos-sdk 0.46
func MsgCancelUnbondingDelegation(ctx *context.Context, m *cosmosStakingTypes.MsgCancelUnbondingDelegation) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCancelUnbondingDelegation
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/types"
)
// MsgSoftwareUpgrade is the Msg/SoftwareUpgrade request type.
func MsgSoftwareUpgrade(ctx *context.Context, m *upgrade.MsgSoftwareUpgrade) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSoftwareUpgrade
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAuthority, address: m.Authority},
}, ctx.Block.Height)
return msgType, addresses, err
}
// MsgSoftwareUpgrade is the Msg/SoftwareUpgrade request type.
func MsgCancelUpgrade(ctx *context.Context, m *upgrade.MsgCancelUpgrade) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCancelUpgrade
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeAuthority, address: m.Authority},
}, ctx.Block.Height)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
cosmosVestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/shopspring/decimal"
)
// MsgCreateVestingAccount defines a message that enables creating a vesting
// account.
func MsgCreateVestingAccount(ctx *context.Context, status storageTypes.Status, m *cosmosVestingTypes.MsgCreateVestingAccount) (storageTypes.MsgType, []storage.AddressWithType, *storage.VestingAccount, error) {
msgType := storageTypes.MsgCreateVestingAccount
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, ctx.Block.Height)
if err != nil || status == storageTypes.StatusFailed {
return msgType, addresses, nil, err
}
v := &storage.VestingAccount{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Address: &storage.Address{
Address: m.ToAddress,
},
}
amount := decimal.NewFromBigInt(m.Amount.AmountOf(currency.Utia).BigInt(), 0)
v.Amount = v.Amount.Add(amount)
if m.EndTime > 0 {
t := time.Unix(m.EndTime, 0).UTC()
v.EndTime = &t
}
if m.StartTime > 0 {
t := time.Unix(m.StartTime, 0).UTC()
v.StartTime = &t
}
if m.Delayed {
v.Type = storageTypes.VestingTypeDelayed
} else {
v.Type = storageTypes.VestingTypeContinuous
}
return msgType, addresses, v, err
}
// MsgCreatePermanentLockedAccount defines a message that enables creating a permanent
// locked account.
//
// Since: cosmos-sdk 0.46
func MsgCreatePermanentLockedAccount(ctx *context.Context, status storageTypes.Status, m *cosmosVestingTypes.MsgCreatePermanentLockedAccount) (storageTypes.MsgType, []storage.AddressWithType, *storage.VestingAccount, error) {
msgType := storageTypes.MsgCreatePermanentLockedAccount
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, ctx.Block.Height)
if err != nil || status == storageTypes.StatusFailed {
return msgType, addresses, nil, err
}
v := &storage.VestingAccount{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Address: &storage.Address{
Address: m.ToAddress,
},
Type: storageTypes.VestingTypePermanent,
}
amount := decimal.NewFromBigInt(m.Amount.AmountOf(currency.Utia).BigInt(), 0)
v.Amount = v.Amount.Add(amount)
return msgType, addresses, v, err
}
// MsgCreateVestingAccount defines a message that enables creating a vesting
// account.
//
// Since: cosmos-sdk 0.46
func MsgCreatePeriodicVestingAccount(ctx *context.Context, status storageTypes.Status, m *cosmosVestingTypes.MsgCreatePeriodicVestingAccount) (storageTypes.MsgType, []storage.AddressWithType, *storage.VestingAccount, error) {
msgType := storageTypes.MsgCreatePeriodicVestingAccount
addresses, err := createAddresses(ctx, addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, ctx.Block.Height)
if err != nil || status == storageTypes.StatusFailed {
return msgType, addresses, nil, err
}
v := &storage.VestingAccount{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Address: &storage.Address{
Address: m.ToAddress,
},
Type: storageTypes.VestingTypePeriodic,
Amount: decimal.Zero,
}
periodTime := v.Time
if m.StartTime > 0 {
t := time.Unix(m.StartTime, 0).UTC()
v.StartTime = &t
periodTime = t
}
for i := range m.VestingPeriods {
period := storage.VestingPeriod{
Height: v.Height,
}
period.Amount = decimal.NewFromBigInt(m.VestingPeriods[i].Amount.AmountOf(currency.Utia).BigInt(), 0)
v.Amount = v.Amount.Add(period.Amount)
periodTime = periodTime.Add(time.Second * time.Duration(m.VestingPeriods[i].Length))
period.Time = periodTime
v.VestingPeriods = append(v.VestingPeriods, period)
}
return msgType, addresses, v, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/handle"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/x/authz"
crisisTypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
evidenceTypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/group"
"github.com/cosmos/cosmos-sdk/x/nft"
upgrade "github.com/cosmos/cosmos-sdk/x/upgrade/types"
interchainAccounts "github.com/cosmos/ibc-go/v6/modules/apps/27-interchain-accounts/controller/types"
fee "github.com/cosmos/ibc-go/v6/modules/apps/29-fee/types"
ibcTypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
coreClient "github.com/cosmos/ibc-go/v6/modules/core/02-client/types"
coreConnection "github.com/cosmos/ibc-go/v6/modules/core/03-connection/types"
coreChannel "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types"
"github.com/rs/zerolog/log"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
appBlobTypes "github.com/celestiaorg/celestia-app/v3/x/blob/types"
qgbTypes "github.com/celestiaorg/celestia-app/v3/x/blobstream/types"
appSignalTypes "github.com/celestiaorg/celestia-app/v3/x/signal/types"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
cosmosVestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
cosmosBankTypes "github.com/cosmos/cosmos-sdk/x/bank/types"
cosmosDistributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
cosmosFeegrant "github.com/cosmos/cosmos-sdk/x/feegrant"
cosmosGovTypesV1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
cosmosGovTypesV1Beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
cosmosSlashingTypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
cosmosStakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/fatih/structs"
"github.com/pkg/errors"
)
type DecodedMsg struct {
Msg storage.Message
BlobsSize int64
Addresses []storage.AddressWithType
}
type measurable interface {
Size() int
}
func Message(
ctx *context.Context,
msg cosmosTypes.Msg,
position int,
status storageTypes.Status,
) (d DecodedMsg, err error) {
d.Msg.Position = int64(position)
d.Msg.Data = structs.Map(msg)
d.Msg.Height = ctx.Block.Height
d.Msg.Time = ctx.Block.Time
switch typedMsg := msg.(type) {
// distribution module
case *cosmosDistributionTypes.MsgSetWithdrawAddress:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSetWithdrawAddress(ctx, typedMsg)
case *cosmosDistributionTypes.MsgWithdrawDelegatorReward:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgWithdrawDelegatorReward(ctx, typedMsg)
case *cosmosDistributionTypes.MsgWithdrawValidatorCommission:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgWithdrawValidatorCommission(ctx, typedMsg)
case *cosmosDistributionTypes.MsgFundCommunityPool:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgFundCommunityPool(ctx, typedMsg)
// staking module
case *cosmosStakingTypes.MsgCreateValidator:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateValidator(ctx, status, typedMsg)
if err != nil {
return d, err
}
if pk, ok := typedMsg.Pubkey.GetCachedValue().(cryptotypes.PubKey); ok {
d.Msg.Data["Pubkey"] = map[string]any{
"key": pk.Bytes(),
"type": pk.Type(),
}
}
case *cosmosStakingTypes.MsgEditValidator:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgEditValidator(ctx, status, typedMsg)
case *cosmosStakingTypes.MsgDelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDelegate(ctx, typedMsg)
case *cosmosStakingTypes.MsgBeginRedelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgBeginRedelegate(ctx, typedMsg)
case *cosmosStakingTypes.MsgUndelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUndelegate(ctx, typedMsg)
case *cosmosStakingTypes.MsgCancelUnbondingDelegation:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCancelUnbondingDelegation(ctx, typedMsg)
// slashing module
case *cosmosSlashingTypes.MsgUnjail:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUnjail(ctx, typedMsg)
// bank module
case *cosmosBankTypes.MsgSend:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSend(ctx, typedMsg)
case *cosmosBankTypes.MsgMultiSend:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgMultiSend(ctx, typedMsg)
// vesting module
case *cosmosVestingTypes.MsgCreateVestingAccount:
d.Msg.Type, d.Msg.Addresses, d.Msg.VestingAccount, err = handle.MsgCreateVestingAccount(ctx, status, typedMsg)
case *cosmosVestingTypes.MsgCreatePermanentLockedAccount:
d.Msg.Type, d.Msg.Addresses, d.Msg.VestingAccount, err = handle.MsgCreatePermanentLockedAccount(ctx, status, typedMsg)
case *cosmosVestingTypes.MsgCreatePeriodicVestingAccount:
d.Msg.Type, d.Msg.Addresses, d.Msg.VestingAccount, err = handle.MsgCreatePeriodicVestingAccount(ctx, status, typedMsg)
// blob module
case *appBlobTypes.MsgPayForBlobs:
d.Msg.Type, d.Msg.Addresses, d.Msg.Namespace, d.Msg.BlobLogs, d.BlobsSize, err = handle.MsgPayForBlobs(ctx, status, typedMsg)
// feegrant module
case *cosmosFeegrant.MsgGrantAllowance:
d.Msg.Type, d.Msg.Addresses, d.Msg.Grants, err = handle.MsgGrantAllowance(ctx, status, typedMsg)
case *cosmosFeegrant.MsgRevokeAllowance:
d.Msg.Type, d.Msg.Addresses, d.Msg.Grants, err = handle.MsgRevokeAllowance(ctx, status, typedMsg)
// qgb module
case *qgbTypes.MsgRegisterEVMAddress:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRegisterEVMAddress(ctx, typedMsg)
// authz module
case *authz.MsgGrant:
d.Msg.Type, d.Msg.Addresses, d.Msg.Grants, err = handle.MsgGrant(ctx, status, typedMsg)
case *authz.MsgExec:
d.Msg.Type, d.Msg.Addresses, d.Msg.InternalMsgs, err = handle.MsgExec(ctx, status, typedMsg)
if err != nil {
return d, err
}
msgs := make([]any, 0)
for i := range typedMsg.Msgs {
msg, err := cosmosTypes.GetMsgFromTypeURL(cfg.Codec, typedMsg.Msgs[i].TypeUrl)
if err != nil {
return d, err
}
if err := cfg.Codec.UnpackAny(typedMsg.Msgs[i], &msg); err != nil {
return d, err
}
msgs = append(msgs, structs.Map(msg))
}
d.Msg.Data["Msgs"] = msgs
case *authz.MsgRevoke:
d.Msg.Type, d.Msg.Addresses, d.Msg.Grants, err = handle.MsgRevoke(ctx, status, typedMsg)
// gov module
case *cosmosGovTypesV1.MsgSubmitProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitProposal(ctx, typedMsg.Proposer)
case *cosmosGovTypesV1Beta1.MsgSubmitProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitProposal(ctx, typedMsg.Proposer)
case *cosmosGovTypesV1.MsgExecLegacyContent:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgExecLegacyContent(ctx, typedMsg)
case *cosmosGovTypesV1.MsgVote:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVote(ctx, typedMsg.Voter)
case *cosmosGovTypesV1Beta1.MsgVote:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVote(ctx, typedMsg.Voter)
case *cosmosGovTypesV1.MsgVoteWeighted:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVoteWeighted(ctx, typedMsg.Voter)
case *cosmosGovTypesV1Beta1.MsgVoteWeighted:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVoteWeighted(ctx, typedMsg.Voter)
case *cosmosGovTypesV1.MsgDeposit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDeposit(ctx, typedMsg.Depositor)
case *cosmosGovTypesV1Beta1.MsgDeposit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDeposit(ctx, typedMsg.Depositor)
// ibc module
case *ibcTypes.MsgTransfer:
d.Msg.Type, d.Msg.Addresses, err = handle.IBCTransfer(ctx, typedMsg)
// crisis module
case *crisisTypes.MsgVerifyInvariant:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVerifyInvariant(ctx, typedMsg)
// evidence module
case *evidenceTypes.MsgSubmitEvidence:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitEvidence(ctx, typedMsg)
// nft module
case *nft.MsgSend:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSendNFT(ctx, typedMsg)
// group module
case *group.MsgCreateGroup:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateGroup(ctx, typedMsg)
case *group.MsgUpdateGroupMembers:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupMembers(ctx, typedMsg)
case *group.MsgUpdateGroupAdmin:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupAdmin(ctx, typedMsg)
case *group.MsgUpdateGroupMetadata:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupMetadata(ctx, typedMsg)
case *group.MsgCreateGroupPolicy:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateGroupPolicy(ctx, typedMsg)
case *group.MsgUpdateGroupPolicyAdmin:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupPolicyAdmin(ctx, typedMsg)
case *group.MsgCreateGroupWithPolicy:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateGroupWithPolicy(ctx, typedMsg)
case *group.MsgUpdateGroupPolicyDecisionPolicy:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupPolicyDecisionPolicy(ctx, typedMsg)
case *group.MsgUpdateGroupPolicyMetadata:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpdateGroupPolicyMetadata(ctx, typedMsg)
case *group.MsgSubmitProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitProposalGroup(ctx, typedMsg)
case *group.MsgWithdrawProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgWithdrawProposal(ctx, typedMsg)
case *group.MsgVote:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVoteGroup(ctx, typedMsg)
case *group.MsgExec:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgExecGroup(ctx, typedMsg)
case *group.MsgLeaveGroup:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgLeaveGroup(ctx, typedMsg)
// upgrade module
case *upgrade.MsgSoftwareUpgrade:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSoftwareUpgrade(ctx, typedMsg)
case *upgrade.MsgCancelUpgrade:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCancelUpgrade(ctx, typedMsg)
// interchainAccounts module
case *interchainAccounts.MsgRegisterInterchainAccount:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRegisterInterchainAccount(ctx, typedMsg)
case *interchainAccounts.MsgSendTx:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSendTx(ctx, typedMsg)
// fee module
case *fee.MsgRegisterPayee:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRegisterPayee(ctx, typedMsg)
case *fee.MsgRegisterCounterpartyPayee:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRegisterCounterpartyPayee(ctx, typedMsg)
case *fee.MsgPayPacketFee:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgPayPacketFee(ctx, typedMsg)
case *fee.MsgPayPacketFeeAsync:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgPayPacketFeeAsync()
// coreClient module
case *coreClient.MsgCreateClient:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateClient(ctx, typedMsg)
case *coreClient.MsgUpdateClient:
typ, addrs, header, errParse := handle.MsgUpdateClient(ctx, status, typedMsg)
d.Msg.Addresses = addrs
d.Msg.Type = typ
err = errParse
if header != nil {
d.Msg.Data["Header"] = header
}
case *coreClient.MsgUpgradeClient:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUpgradeClient(ctx, typedMsg)
case *coreClient.MsgSubmitMisbehaviour:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitMisbehaviour(ctx, typedMsg)
// coreConnection module
case *coreConnection.MsgConnectionOpenInit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgConnectionOpenInit(ctx, typedMsg)
case *coreConnection.MsgConnectionOpenTry:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgConnectionOpenTry(ctx, typedMsg)
case *coreConnection.MsgConnectionOpenAck:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgConnectionOpenAck(ctx, typedMsg)
case *coreConnection.MsgConnectionOpenConfirm:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgConnectionOpenConfirm(ctx, typedMsg)
// coreChannel module
case *coreChannel.MsgChannelOpenInit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelOpenInit(ctx, typedMsg)
case *coreChannel.MsgChannelOpenTry:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelOpenTry(ctx, typedMsg)
case *coreChannel.MsgChannelOpenAck:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelOpenAck(ctx, typedMsg)
case *coreChannel.MsgChannelOpenConfirm:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelOpenConfirm(ctx, typedMsg)
case *coreChannel.MsgChannelCloseInit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelCloseInit(ctx, typedMsg)
case *coreChannel.MsgChannelCloseConfirm:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgChannelCloseConfirm(ctx, typedMsg)
case *coreChannel.MsgRecvPacket:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRecvPacket(ctx, typedMsg)
case *coreChannel.MsgTimeout:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgTimeout(ctx, typedMsg)
case *coreChannel.MsgTimeoutOnClose:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgTimeoutOnClose(ctx, typedMsg)
case *coreChannel.MsgAcknowledgement:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgAcknowledgement(ctx, typedMsg)
// signal module
case *appSignalTypes.MsgSignalVersion:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSignalVersion(ctx, typedMsg.GetValidatorAddress())
case *appSignalTypes.MsgTryUpgrade:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgTryUpgrade(ctx, typedMsg.GetSigner())
default:
log.Err(errors.New("unknown message type")).Msgf("got type %T", msg)
d.Msg.Type = storageTypes.MsgUnknown
}
if err != nil {
err = errors.Wrapf(err, "while decoding msg(%T) on position=%d", msg, position)
}
if d.Msg.Type != storageTypes.MsgUnknown {
if m, ok := msg.(measurable); ok {
d.Msg.Size = m.Size()
} else {
return d, errors.Errorf("message %T does not implement Size method: %##v", msg, msg)
}
}
d.Addresses = append(d.Addresses, d.Msg.Addresses...)
return
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celestiaorg/celestia-app/v3/app"
"github.com/celestiaorg/celestia-app/v3/app/encoding"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
blobTypes "github.com/tendermint/tendermint/proto/tendermint/types"
tmTypes "github.com/tendermint/tendermint/types"
)
type DecodedTx struct {
AuthInfo tx.AuthInfo
TimeoutHeight uint64
Memo string
Messages []cosmosTypes.Msg
Fee decimal.Decimal
Signers map[types.Address][]byte
Blobs []*blobTypes.Blob
}
var (
cfg, txDecoder = createDecoder()
)
func Tx(b types.BlockData, index int) (d DecodedTx, err error) {
raw := b.Block.Txs[index]
if bTx, isBlob := tmTypes.UnmarshalBlobTx(raw); isBlob {
raw = bTx.Tx
d.Blobs = bTx.Blobs
}
d.AuthInfo, d.Fee, err = decodeAuthInfo(cfg, raw)
if err != nil {
return
}
d.TimeoutHeight, d.Memo, d.Messages, err = decodeCosmosTx(txDecoder, raw)
if err != nil {
return
}
d.Signers = make(map[types.Address][]byte)
for i := range d.Messages {
for _, signer := range d.Messages[i].GetSigners() {
if signer.Empty() {
continue
}
signerBytes := signer.Bytes()
address, err := types.NewAddressFromBytes(signerBytes)
if err != nil {
return d, err
}
d.Signers[address] = signerBytes
}
}
return
}
func decodeCosmosTx(decoder cosmosTypes.TxDecoder, raw tmTypes.Tx) (timeoutHeight uint64, memo string, messages []cosmosTypes.Msg, err error) {
txDecoded, err := decoder(raw)
if err != nil {
err = errors.Wrap(err, "decoding tx error")
return
}
if t, ok := txDecoded.(cosmosTypes.TxWithTimeoutHeight); ok {
timeoutHeight = t.GetTimeoutHeight()
}
if t, ok := txDecoded.(cosmosTypes.TxWithMemo); ok {
memo = t.GetMemo()
}
messages = txDecoded.GetMsgs()
return
}
func decodeAuthInfo(cfg encoding.Config, raw tmTypes.Tx) (tx.AuthInfo, decimal.Decimal, error) {
var txRaw tx.TxRaw
if e := cfg.Codec.Unmarshal(raw, &txRaw); e != nil {
return tx.AuthInfo{}, decimal.Decimal{}, errors.Wrap(e, "unmarshalling tx error")
}
var authInfo tx.AuthInfo
if e := cfg.Codec.Unmarshal(txRaw.AuthInfoBytes, &authInfo); e != nil {
return tx.AuthInfo{}, decimal.Decimal{}, errors.Wrap(e, "decoding tx auth_info error")
}
fee, err := decodeFee(authInfo)
if err != nil {
return authInfo, decimal.Zero, err
}
return authInfo, fee, nil
}
func decodeFee(authInfo tx.AuthInfo) (decimal.Decimal, error) {
amount := authInfo.GetFee().GetAmount()
if amount == nil {
return decimal.Zero, nil
}
if len(amount) > 1 {
// TODO stop indexer if tx is not in failed status
return decimal.Zero, errors.Errorf("found fee in %d currencies", len(amount))
}
fee, ok := getFeeInDenom(amount, currency.Utia)
if !ok {
if fee, ok = getFeeInDenom(amount, currency.Tia); !ok {
// TODO stop indexer if tx is not in failed status
return decimal.Zero, errors.New("couldn't find fee amount in utia or in tia denom")
}
}
return fee, nil
}
func getFeeInDenom(amount cosmosTypes.Coins, denom string) (decimal.Decimal, bool) {
ok, utiaCoin := amount.Find(denom)
if !ok {
return decimal.Zero, false
}
switch denom {
case currency.Utia:
fee := decimal.NewFromBigInt(utiaCoin.Amount.BigInt(), 0)
return fee, true
case currency.Tia:
fee := decimal.NewFromBigInt(utiaCoin.Amount.BigInt(), 6)
return fee, true
default:
return decimal.Zero, false
}
}
func createDecoder() (encoding.Config, cosmosTypes.TxDecoder) {
cfg := encoding.MakeConfig(app.ModuleEncodingRegisters...)
return cfg, cfg.TxConfig.TxDecoder()
}
func JsonTx(raw []byte) (cosmosTypes.Tx, error) {
return cfg.TxConfig.TxJSONDecoder()(raw)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"strconv"
"strings"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
)
func (module *Module) parseConstants(appState types.AppState, consensus pkgTypes.ConsensusParams, data *parsedData) {
// consensus
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "block_max_bytes",
Value: strconv.FormatInt(consensus.Block.MaxBytes, 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "block_max_gas",
Value: strconv.FormatInt(consensus.Block.MaxGas, 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "evidence_max_age_num_blocks",
Value: strconv.FormatInt(consensus.Evidence.MaxAgeNumBlocks, 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "evidence_max_bytes",
Value: strconv.FormatInt(consensus.Evidence.MaxBytes, 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "evidence_max_age_duration",
Value: consensus.Evidence.MaxAgeDuration.String(),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameConsensus,
Name: "validator_pub_key_types",
Value: strings.Join(consensus.Validator.PubKeyTypes, ", "),
})
// auth
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameAuth,
Name: "max_memo_characters",
Value: appState.Auth.Params.MaxMemoCharacters,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameAuth,
Name: "tx_sig_limit",
Value: appState.Auth.Params.TxSigLimit,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameAuth,
Name: "tx_size_cost_per_byte",
Value: appState.Auth.Params.TxSizeCostPerByte,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameAuth,
Name: "sig_verify_cost_ed25519",
Value: appState.Auth.Params.SigVerifyCostEd25519,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameAuth,
Name: "sig_verify_cost_secp256k1",
Value: appState.Auth.Params.SigVerifyCostSecp256K1,
})
// blob
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameBlob,
Name: "gas_per_blob_byte",
Value: strconv.FormatInt(int64(appState.Blob.Params.GasPerBlobByte), 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameBlob,
Name: "gov_max_square_size",
Value: appState.Blob.Params.GovMaxSquareSize,
})
// crisis
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameCrisis,
Name: "constant_fee",
Value: appState.Crisis.ConstantFee.String(),
})
// distribution
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameDistribution,
Name: "community_tax",
Value: appState.Distribution.Params.CommunityTax,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameDistribution,
Name: "base_proposer_reward",
Value: appState.Distribution.Params.BaseProposerReward,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameDistribution,
Name: "bonus_proposer_reward",
Value: appState.Distribution.Params.BonusProposerReward,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameDistribution,
Name: "withdraw_addr_enabled",
Value: strconv.FormatBool(appState.Distribution.Params.WithdrawAddrEnabled),
})
// gov
if len(appState.Gov.DepositParams.MinDeposit) > 0 {
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "min_deposit",
Value: appState.Gov.DepositParams.MinDeposit[0].String(),
})
}
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "max_deposit_period",
Value: appState.Gov.DepositParams.MaxDepositPeriod,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "voting_period",
Value: appState.Gov.VotingParams.VotingPeriod,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "quorum",
Value: appState.Gov.TallyParams.Quorum,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "threshold",
Value: appState.Gov.TallyParams.Threshold,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameGov,
Name: "veto_threshold",
Value: appState.Gov.TallyParams.VetoThreshold,
})
// slashing
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameSlashing,
Name: "signed_blocks_window",
Value: appState.Slashing.Params.SignedBlocksWindow,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameSlashing,
Name: "min_signed_per_window",
Value: appState.Slashing.Params.MinSignedPerWindow,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameSlashing,
Name: "downtime_jail_duration",
Value: appState.Slashing.Params.DowntimeJailDuration,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameSlashing,
Name: "slash_fraction_double_sign",
Value: appState.Slashing.Params.SlashFractionDoubleSign,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameSlashing,
Name: "slash_fraction_downtime",
Value: appState.Slashing.Params.SlashFractionDowntime,
})
// staking
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "unbonding_time",
Value: appState.Staking.Params.UnbondingTime,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "max_validators",
Value: strconv.FormatInt(int64(appState.Staking.Params.MaxValidators), 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "max_entries",
Value: strconv.FormatInt(int64(appState.Staking.Params.MaxEntries), 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "historical_entries",
Value: strconv.FormatInt(int64(appState.Staking.Params.HistoricalEntries), 10),
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "bond_denom",
Value: appState.Staking.Params.BondDenom,
})
data.constants = append(data.constants, storage.Constant{
Module: storageTypes.ModuleNameStaking,
Name: "min_commission_rate",
Value: appState.Staking.Params.MinCommissionRate,
})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
)
func (module *Module) parseDenomMetadata(raw []types.DenomMetadata, data *parsedData) {
for i := range raw {
dm := storage.DenomMetadata{
Description: raw[i].Description,
Base: raw[i].Base,
Display: raw[i].Display,
Name: raw[i].Name,
Symbol: raw[i].Symbol,
Uri: raw[i].URI,
Units: raw[i].DenomUnits,
}
data.denomMetadata = append(data.denomMetadata, dm)
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
)
// constants
const (
InputName = "block"
OutputName = "finished"
StopOutput = "stop"
)
// Module - saves received from input genesis block to storage and notify if it was success.
//
// |----------------|
// | |
// -- storage.Block -> | MODULE | -- struct{} ->
// | |
// |----------------|
type Module struct {
modules.BaseModule
storage postgres.Storage
indexerName string
}
var _ modules.Module = (*Module)(nil)
// NewModule -
func NewModule(pg postgres.Storage, cfg config.Indexer) Module {
m := Module{
BaseModule: modules.New("genesis"),
storage: pg,
indexerName: cfg.Name,
}
m.CreateInput(InputName)
m.CreateOutput(OutputName)
m.CreateOutput(StopOutput)
return m
}
// Start -
func (module *Module) Start(ctx context.Context) {
module.G.GoCtx(ctx, module.listen)
}
func (module *Module) listen(ctx context.Context) {
module.Log.Info().Msg("module started")
input := module.MustInput(InputName)
for {
select {
case <-ctx.Done():
return
case msg, ok := <-input.Listen():
if !ok {
module.Log.Warn().Msg("can't read message from input")
return
}
genesis, ok := msg.(types.Genesis)
if !ok {
module.Log.Warn().Msgf("invalid message type: %T", msg)
return
}
module.Log.Info().Msg("received genesis message")
block, err := module.parse(genesis)
if err != nil {
module.Log.Err(err).Msgf("parsing genesis block")
return
}
module.Log.Info().Msg("parsed genesis message")
if err := module.save(ctx, block); err != nil {
module.Log.Err(err).Msg("saving genesis block error")
return
}
module.Log.Info().Msg("saved genesis message")
module.MustOutput(OutputName).Push(struct{}{})
return
}
}
}
// Close -
func (module *Module) Close() error {
module.Log.Info().Msg("closing module...")
module.G.Wait()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"strings"
"time"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
type parsedData struct {
block storage.Block
addresses map[string]*storage.Address
validators []*storage.Validator
stakingLogs []storage.StakingLog
delegations []storage.Delegation
constants []storage.Constant
denomMetadata []storage.DenomMetadata
vestings []*storage.VestingAccount
}
func newParsedData() parsedData {
return parsedData{
addresses: make(map[string]*storage.Address),
validators: make([]*storage.Validator, 0),
stakingLogs: make([]storage.StakingLog, 0),
delegations: make([]storage.Delegation, 0),
constants: make([]storage.Constant, 0),
denomMetadata: make([]storage.DenomMetadata, 0),
vestings: make([]*storage.VestingAccount, 0),
}
}
func (module *Module) parse(genesis types.Genesis) (parsedData, error) {
data := newParsedData()
block := storage.Block{
Time: genesis.GenesisTime,
Height: pkgTypes.Level(genesis.InitialHeight - 1),
AppHash: []byte(genesis.AppHash),
ChainId: genesis.ChainID,
Txs: make([]storage.Tx, 0),
Stats: storage.BlockStats{
Time: genesis.GenesisTime,
Height: pkgTypes.Level(genesis.InitialHeight - 1),
TxCount: int64(len(genesis.AppState.Genutil.GenTxs)),
EventsCount: 0,
Fee: decimal.Zero,
SupplyChange: decimal.Zero,
InflationRate: decimal.Zero,
},
MessageTypes: storageTypes.NewMsgTypeBits(),
}
decodeCtx := context.NewContext()
decodeCtx.Block = &block
for index, genTx := range genesis.AppState.Genutil.GenTxs {
txDecoded, err := decode.JsonTx(genTx)
if err != nil {
return data, errors.Wrapf(err, "failed to decode GenTx '%s'", genTx)
}
memoTx, ok := txDecoded.(cosmosTypes.TxWithMemo)
if !ok {
return data, errors.Wrapf(err, "expected TxWithMemo, got %T", genTx)
}
txWithTimeoutHeight, ok := txDecoded.(cosmosTypes.TxWithTimeoutHeight)
if !ok {
return data, errors.Wrapf(err, "expected TxWithTimeoutHeight, got %T", genTx)
}
tx := storage.Tx{
Height: block.Height,
Time: block.Time,
Position: int64(index),
TimeoutHeight: txWithTimeoutHeight.GetTimeoutHeight(),
MessagesCount: int64(len(txDecoded.GetMsgs())),
Fee: decimal.Zero,
Status: storageTypes.StatusSuccess,
Memo: memoTx.GetMemo(),
MessageTypes: storageTypes.NewMsgTypeBitMask(),
Messages: make([]storage.Message, len(txDecoded.GetMsgs())),
Events: nil,
}
for msgIndex, msg := range txDecoded.GetMsgs() {
decoded, err := decode.Message(decodeCtx, msg, msgIndex, storageTypes.StatusSuccess)
if err != nil {
return data, errors.Wrap(err, "decode genesis message")
}
tx.Messages[msgIndex] = decoded.Msg
tx.MessageTypes.SetByMsgType(decoded.Msg.Type)
block.MessageTypes.SetByMsgType(decoded.Msg.Type)
tx.BlobsSize += decoded.BlobsSize
}
block.Txs = append(block.Txs, tx)
}
for _, addr := range decodeCtx.GetAddresses() {
data.addresses[addr.String()] = addr
}
module.parseDenomMetadata(genesis.AppState.Bank.DenomMetadata, &data)
module.parseConstants(genesis.AppState, genesis.ConsensusParams, &data)
module.parseTotalSupply(genesis.AppState.Bank.Supply, &block)
if err := module.parseAccounts(genesis.AppState.Auth.Accounts, block, &data); err != nil {
return data, errors.Wrap(err, "parse genesis accounts")
}
if err := module.parseBalances(genesis.AppState.Bank.Balances, block.Height, &data); err != nil {
return data, errors.Wrap(err, "parse genesis account balances")
}
data.validators = decodeCtx.GetValidators()
data.stakingLogs = decodeCtx.StakingLogs
_ = decodeCtx.Delegations.Range(func(_ string, value *storage.Delegation) (error, bool) {
data.delegations = append(data.delegations, *value)
return nil, false
})
data.block = block
return data, nil
}
func (module *Module) parseTotalSupply(supply []types.Supply, block *storage.Block) {
if len(supply) == 0 {
return
}
if totalSupply, err := decimal.NewFromString(supply[0].Amount); err == nil {
block.Stats.SupplyChange = totalSupply
}
}
func (module *Module) parseAccounts(accounts []types.Accounts, block storage.Block, data *parsedData) error {
currencyBase := currency.DefaultCurrency
if len(data.denomMetadata) > 0 {
currencyBase = data.denomMetadata[0].Base
}
for i := range accounts {
address := storage.Address{
Height: block.Height,
LastHeight: block.Height,
Balance: storage.Balance{
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
Currency: currencyBase,
},
}
var readableAddress string
switch {
case strings.Contains(accounts[i].Type, "PeriodicVestingAccount"):
readableAddress = accounts[i].BaseVestingAccount.BaseAccount.Address
if err := parseVesting(accounts[i], block, readableAddress, storageTypes.VestingTypePeriodic, data); err != nil {
return err
}
case strings.Contains(accounts[i].Type, "ModuleAccount"):
readableAddress = accounts[i].BaseAccount.Address
case strings.Contains(accounts[i].Type, "BaseAccount"):
readableAddress = accounts[i].Address
case strings.Contains(accounts[i].Type, "ContinuousVestingAccount"):
readableAddress = accounts[i].BaseVestingAccount.BaseAccount.Address
if err := parseVesting(accounts[i], block, readableAddress, storageTypes.VestingTypeContinuous, data); err != nil {
return err
}
case strings.Contains(accounts[i].Type, "DelayedVestingAccount"):
readableAddress = accounts[i].BaseVestingAccount.BaseAccount.Address
if err := parseVesting(accounts[i], block, readableAddress, storageTypes.VestingTypeDelayed, data); err != nil {
return err
}
default:
return errors.Errorf("unknown account type: %s", accounts[i].Type)
}
if _, ok := data.addresses[readableAddress]; !ok {
_, hash, err := pkgTypes.Address(readableAddress).Decode()
if err != nil {
return err
}
address.Hash = hash
address.Address = readableAddress
data.addresses[address.String()] = &address
}
}
return nil
}
func (module *Module) parseBalances(balances []types.Balances, height pkgTypes.Level, data *parsedData) error {
for i := range balances {
if len(balances[i].Coins) == 0 {
continue
}
_, hash, err := pkgTypes.Address(balances[i].Address).Decode()
if err != nil {
return err
}
address := storage.Address{
Hash: hash,
Address: balances[i].Address,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
Currency: balances[i].Coins[0].Denom,
},
}
if balance, err := decimal.NewFromString(balances[i].Coins[0].Amount); err == nil {
address.Balance.Spendable = address.Balance.Spendable.Add(balance)
}
if addr, ok := data.addresses[address.String()]; ok {
addr.Balance.Spendable = addr.Balance.Spendable.Add(address.Balance.Spendable)
} else {
data.addresses[address.String()] = &address
}
}
return nil
}
func getAmountFromOriginalVesting(vestings []types.Coins) (decimal.Decimal, error) {
var amount = decimal.Zero.Copy()
for i := range vestings {
val, err := decimal.NewFromString(vestings[i].Amount)
if err != nil {
return amount, err
}
amount = amount.Add(val)
}
return amount, nil
}
func parseVesting(acc types.Accounts, block storage.Block, address string, typ storageTypes.VestingType, data *parsedData) error {
amount, err := getAmountFromOriginalVesting(acc.BaseVestingAccount.OriginalVesting)
if err != nil {
return err
}
v := storage.VestingAccount{
Height: block.Height,
Time: block.Time,
Address: &storage.Address{
Address: address,
},
Type: typ,
Amount: amount,
VestingPeriods: make([]storage.VestingPeriod, 0),
}
if acc.BaseVestingAccount.EndTime > 0 {
t := time.Unix(acc.BaseVestingAccount.EndTime, 0).UTC()
v.EndTime = &t
}
var periodTime = v.Time
if acc.StartTime != nil {
t := time.Unix(*acc.StartTime, 0).UTC()
v.StartTime = &t
periodTime = t
}
for i := range acc.VestingPeriods {
period := storage.VestingPeriod{
Height: v.Height,
}
amount, err := getAmountFromOriginalVesting(acc.VestingPeriods[i].Amount)
if err != nil {
return err
}
period.Amount = amount
periodTime = periodTime.Add(time.Second * time.Duration(acc.VestingPeriods[i].Length))
period.Time = periodTime
v.VestingPeriods = append(v.VestingPeriods, period)
}
data.vestings = append(data.vestings, &v)
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/shopspring/decimal"
)
func (module *Module) save(ctx context.Context, data parsedData) error {
start := time.Now()
module.Log.Info().Uint64("height", uint64(data.block.Height)).Msg("saving block...")
tx, err := postgres.BeginTransaction(ctx, module.storage.Transactable)
if err != nil {
return err
}
defer tx.Close(ctx)
if err := tx.SaveConstants(ctx, data.constants...); err != nil {
return tx.HandleError(ctx, err)
}
for i := range data.denomMetadata {
if err := tx.Add(ctx, &data.denomMetadata[i]); err != nil {
return tx.HandleError(ctx, err)
}
}
if err := tx.Add(ctx, &data.block); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.Add(ctx, &data.block.Stats); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.SaveTransactions(ctx, data.block.Txs...); err != nil {
return tx.HandleError(ctx, err)
}
var (
messages = make([]*storage.Message, 0)
events = make([]any, len(data.block.Events))
namespaces = make(map[string]*storage.Namespace, 0)
)
for i := range data.block.Events {
events[i] = &data.block.Events[i]
}
for i := range data.block.Txs {
for j := range data.block.Txs[i].Messages {
data.block.Txs[i].Messages[j].TxId = data.block.Txs[i].Id
messages = append(messages, &data.block.Txs[i].Messages[j])
for k := range data.block.Txs[i].Messages[j].Namespace {
key := data.block.Txs[i].Messages[j].Namespace[k].String()
if _, ok := namespaces[key]; !ok {
data.block.Txs[i].Messages[j].Namespace[k].PfbCount = 1
namespaces[key] = &data.block.Txs[i].Messages[j].Namespace[k]
}
}
}
for j := range data.block.Txs[i].Events {
data.block.Txs[i].Events[j].TxId = &data.block.Txs[i].Id
events = append(events, &data.block.Txs[i].Events[j])
}
for j := range data.block.Txs[i].Signers {
key := data.block.Txs[i].Signers[j].String()
if addr, ok := data.addresses[key]; !ok {
data.addresses[key] = &data.block.Txs[i].Signers[j]
} else {
addr.Balance.Spendable = addr.Balance.Spendable.Add(data.block.Txs[i].Signers[j].Balance.Spendable)
}
}
}
var totalAccounts int64
if len(data.addresses) > 0 {
entities := make([]*storage.Address, 0, len(data.addresses))
for key := range data.addresses {
entities = append(entities, data.addresses[key])
}
totalAccounts, err = tx.SaveAddresses(ctx, entities...)
if err != nil {
return tx.HandleError(ctx, err)
}
balances := make([]storage.Balance, len(entities))
for i := range entities {
balances[i] = entities[i].Balance
}
if err := tx.SaveBalances(ctx, balances...); err != nil {
return tx.HandleError(ctx, err)
}
}
var totalNamespaces int64
if len(namespaces) > 0 {
entities := make([]*storage.Namespace, 0, len(namespaces))
for key := range namespaces {
entities = append(entities, namespaces[key])
}
totalNamespaces, err = tx.SaveNamespaces(ctx, entities...)
if err != nil {
return tx.HandleError(ctx, err)
}
}
if err := tx.SaveMessages(ctx, messages...); err != nil {
return tx.HandleError(ctx, err)
}
totalValidators, err := tx.SaveValidators(ctx, data.validators...)
if err != nil {
return tx.HandleError(ctx, err)
}
totalStake := decimal.NewFromInt(0)
for i := range data.validators {
totalStake = totalStake.Add(data.validators[i].Stake)
}
for i := range data.stakingLogs {
if address, ok := data.addresses[data.stakingLogs[i].Address.Address]; ok {
data.stakingLogs[i].AddressId = &address.Id
}
for j := range data.validators {
if data.validators[j].Address == data.stakingLogs[i].Validator.Address {
data.stakingLogs[i].ValidatorId = data.validators[j].Id
break
}
}
}
if err := tx.SaveStakingLogs(ctx, data.stakingLogs...); err != nil {
return tx.HandleError(ctx, err)
}
for i := range data.vestings {
if address, ok := data.addresses[data.vestings[i].Address.Address]; ok {
data.vestings[i].AddressId = address.Id
}
}
if err := tx.SaveVestingAccounts(ctx, data.vestings...); err != nil {
return tx.HandleError(ctx, err)
}
periods := make([]storage.VestingPeriod, 0)
for i := range data.vestings {
for j := range data.vestings[i].VestingPeriods {
data.vestings[i].VestingPeriods[j].VestingAccountId = data.vestings[i].Id
}
periods = append(periods, data.vestings[i].VestingPeriods...)
}
if err := tx.SaveVestingPeriods(ctx, periods...); err != nil {
return tx.HandleError(ctx, err)
}
for i := range data.delegations {
if address, ok := data.addresses[data.delegations[i].Address.Address]; ok {
data.delegations[i].AddressId = address.Id
}
for j := range data.validators {
if data.validators[j].Address == data.delegations[i].Validator.Address {
data.delegations[i].ValidatorId = data.validators[j].Id
break
}
}
}
if err := tx.SaveDelegations(ctx, data.delegations...); err != nil {
return tx.HandleError(ctx, err)
}
if len(events) > 0 {
if err := tx.BulkSave(ctx, events); err != nil {
return tx.HandleError(ctx, err)
}
}
var namespaceMsgs []storage.NamespaceMessage
for i := range messages {
for j := range messages[i].Namespace {
if messages[i].Namespace[j].Id == 0 { // in case of duplication of writing to one namespace inside one messages
continue
}
namespaceMsgs = append(namespaceMsgs, storage.NamespaceMessage{
MsgId: messages[i].Id,
NamespaceId: messages[i].Namespace[j].Id,
Time: messages[i].Time,
Height: messages[i].Height,
TxId: messages[i].TxId,
Size: uint64(messages[i].Namespace[j].Size),
})
}
}
if err := tx.SaveNamespaceMessage(ctx, namespaceMsgs...); err != nil {
return tx.HandleError(ctx, err)
}
var signers []storage.Signer
for _, transaction := range data.block.Txs {
for _, address := range transaction.Signers {
signers = append(signers, storage.Signer{
TxId: transaction.Id,
AddressId: address.Id,
})
}
}
if err := tx.SaveSigners(ctx, signers...); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.Add(ctx, &storage.State{
Name: module.indexerName,
LastHeight: data.block.Height,
LastTime: data.block.Time,
LastHash: data.block.Hash,
ChainId: data.block.ChainId,
TotalTx: data.block.Stats.TxCount,
TotalSupply: data.block.Stats.SupplyChange,
TotalFee: data.block.Stats.Fee,
TotalBlobsSize: data.block.Stats.BlobsSize,
TotalAccounts: totalAccounts,
TotalNamespaces: totalNamespaces,
TotalValidators: totalValidators,
TotalStake: totalStake,
}); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
return tx.HandleError(ctx, err)
}
module.Log.Info().
Uint64("height", data.block.Id).
Int64("block_ns_size", data.block.Stats.BlobsSize).
Str("block_fee", data.block.Stats.Fee.String()).
Int64("ms", time.Since(start).Milliseconds()).
Msg("block saved")
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package indexer
import (
"context"
"sync"
"github.com/dipdup-net/indexer-sdk/pkg/modules/stopper"
"github.com/tendermint/tendermint/rpc/client/http"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
internalStorage "github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/indexer/genesis"
"github.com/celenium-io/celestia-indexer/pkg/indexer/parser"
"github.com/celenium-io/celestia-indexer/pkg/indexer/rollback"
"github.com/celenium-io/celestia-indexer/pkg/indexer/storage"
"github.com/celenium-io/celestia-indexer/pkg/node"
"github.com/celenium-io/celestia-indexer/pkg/node/rpc"
"github.com/pkg/errors"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
"github.com/celenium-io/celestia-indexer/pkg/indexer/receiver"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type Indexer struct {
cfg config.Config
api node.Api
receiver *receiver.Module
parser *parser.Module
storage *storage.Module
rollback *rollback.Module
genesis *genesis.Module
stopper modules.Module
pg postgres.Storage
wg *sync.WaitGroup
log zerolog.Logger
}
func New(ctx context.Context, cfg config.Config, stopperModule modules.Module) (Indexer, error) {
pg, err := postgres.Create(ctx, cfg.Database, cfg.Indexer.ScriptsDir, true)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating pg context")
}
api, r, err := createReceiver(ctx, cfg, pg)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating receiver module")
}
rb, err := createRollback(r, pg, &api, cfg.Indexer)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating rollback module")
}
p, err := createParser(cfg.Indexer, r)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating parser module")
}
s, err := createStorage(pg, cfg, p)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating storage module")
}
genesisModule, err := createGenesis(pg, cfg, r)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating genesis module")
}
err = attachStopper(stopperModule, r, p, s, rb, genesisModule)
if err != nil {
return Indexer{}, errors.Wrap(err, "while creating stopper module")
}
return Indexer{
cfg: cfg,
api: &api,
receiver: r,
parser: p,
storage: s,
rollback: rb,
genesis: genesisModule,
stopper: stopperModule,
pg: pg,
wg: new(sync.WaitGroup),
log: log.With().Str("module", "indexer").Logger(),
}, nil
}
func (i *Indexer) Start(ctx context.Context) {
i.log.Info().Msg("starting...")
i.genesis.Start(ctx)
i.storage.Start(ctx)
i.parser.Start(ctx)
i.receiver.Start(ctx)
}
func (i *Indexer) Close() error {
i.log.Info().Msg("closing...")
i.wg.Wait()
if err := i.receiver.Close(); err != nil {
log.Err(err).Msg("closing receiver")
}
if err := i.genesis.Close(); err != nil {
log.Err(err).Msg("closing genesis")
}
if err := i.parser.Close(); err != nil {
log.Err(err).Msg("closing parser")
}
if err := i.storage.Close(); err != nil {
log.Err(err).Msg("closing storage")
}
if err := i.rollback.Close(); err != nil {
log.Err(err).Msg("closing rollback")
}
if err := i.pg.Close(); err != nil {
log.Err(err).Msg("closing postgres connection")
}
return nil
}
func createReceiver(ctx context.Context, cfg config.Config, pg postgres.Storage) (rpc.API, *receiver.Module, error) {
state, err := loadState(pg, ctx, cfg.Indexer.Name)
if err != nil {
return rpc.API{}, nil, errors.Wrap(err, "while loading state")
}
api := rpc.NewAPI(cfg.DataSources["node_rpc"])
var ws *http.HTTP
if source, ok := cfg.DataSources["node_ws"]; ok && source.URL != "" {
ws, err = http.New(source.URL, "/websocket")
if err != nil {
return rpc.API{}, nil, errors.Wrap(err, "create websocket")
}
}
receiverModule := receiver.NewModule(cfg.Indexer, &api, ws, state)
return api, &receiverModule, nil
}
func createRollback(receiverModule modules.Module, pg postgres.Storage, api node.Api, cfg config.Indexer) (*rollback.Module, error) {
rollbackModule := rollback.NewModule(pg.Transactable, pg.State, pg.Blocks, api, cfg)
// rollback <- listen signal -- receiver
if err := rollbackModule.AttachTo(receiverModule, receiver.RollbackOutput, rollback.InputName); err != nil {
return nil, errors.Wrap(err, "while attaching rollback to receiver")
}
// receiver <- listen state -- rollback
if err := receiverModule.AttachTo(&rollbackModule, rollback.OutputName, receiver.RollbackInput); err != nil {
return nil, errors.Wrap(err, "while attaching receiver to rollback")
}
return &rollbackModule, nil
}
func createParser(cfg config.Indexer, receiverModule modules.Module) (*parser.Module, error) {
parserModule := parser.NewModule(cfg)
if err := parserModule.AttachTo(receiverModule, receiver.BlocksOutput, parser.InputName); err != nil {
return nil, errors.Wrap(err, "while attaching parser to receiver")
}
return &parserModule, nil
}
func createStorage(pg postgres.Storage, cfg config.Config, parserModule modules.Module) (*storage.Module, error) {
storageModule := storage.NewModule(pg.Transactable, pg.Constants, pg.Validator, pg.Notificator, cfg.Indexer)
if err := storageModule.AttachTo(parserModule, parser.OutputName, storage.InputName); err != nil {
return nil, errors.Wrap(err, "while attaching storage to parser")
}
return &storageModule, nil
}
func createGenesis(pg postgres.Storage, cfg config.Config, receiverModule modules.Module) (*genesis.Module, error) {
genesisModule := genesis.NewModule(pg, cfg.Indexer)
if err := genesisModule.AttachTo(receiverModule, receiver.GenesisOutput, genesis.InputName); err != nil {
return nil, errors.Wrap(err, "while attaching genesis to receiver")
}
genesisModulePtr := &genesisModule
if err := receiverModule.AttachTo(genesisModulePtr, genesis.OutputName, receiver.GenesisDoneInput); err != nil {
return nil, errors.Wrap(err, "while attaching receiver to genesis")
}
return genesisModulePtr, nil
}
func attachStopper(
stopperModule modules.Module,
receiverModule modules.Module,
parserModule modules.Module,
storageModule modules.Module,
rollbackModule modules.Module,
genesisModule modules.Module,
) error {
if err := stopperModule.AttachTo(receiverModule, receiver.StopOutput, stopper.InputName); err != nil {
return errors.Wrap(err, "while attaching stopper to receiver")
}
if err := stopperModule.AttachTo(parserModule, parser.StopOutput, stopper.InputName); err != nil {
return errors.Wrap(err, "while attaching stopper to parser")
}
if err := stopperModule.AttachTo(storageModule, storage.StopOutput, stopper.InputName); err != nil {
return errors.Wrap(err, "while attaching stopper to storage")
}
if err := stopperModule.AttachTo(rollbackModule, rollback.StopOutput, stopper.InputName); err != nil {
return errors.Wrap(err, "while attaching stopper to rollback")
}
if err := stopperModule.AttachTo(genesisModule, genesis.StopOutput, stopper.InputName); err != nil {
return errors.Wrap(err, "while attaching stopper to genesis")
}
return nil
}
func loadState(pg postgres.Storage, ctx context.Context, indexerName string) (*internalStorage.State, error) {
state, err := pg.State.ByName(ctx, indexerName)
if err != nil {
if pg.State.IsNoRows(err) {
return nil, nil
}
return nil, err
}
return &state, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"net/http"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celestiaorg/celestia-app/v3/pkg/appconsts"
appshares "github.com/celestiaorg/go-square/v2/share"
"github.com/shopspring/decimal"
)
var gasPerBlobByte = decimal.NewFromInt(int64(appconsts.DefaultGasPerBlobByte))
func processBlob(blobs []*storage.BlobLog, d decode.DecodedTx, t *storage.Tx) {
if len(blobs) == 0 || len(d.Blobs) != len(blobs) {
return
}
t.BlobsCount += len(blobs)
var (
gasConsumedOnBlobs = decimal.Zero.Copy()
gasConsumedPerBlob = make([]decimal.Decimal, len(blobs))
)
for i := range blobs {
blobs[i].ContentType = http.DetectContentType(d.Blobs[i].Data)
//nolint:gosec
sharesUsed := appshares.SparseSharesNeeded(uint32(blobs[i].Size))
gas := decimal.NewFromInt(int64(sharesUsed)).Mul(gasPerBlobByte)
gasConsumedOnBlobs = gasConsumedOnBlobs.Add(gas)
gasConsumedPerBlob[i] = gas
}
gasUsed := decimal.NewFromInt(t.GasUsed)
// fix_gas_per_blob = (gas_used - consumed_gas_on_blobs) / blobs_count
fix := gasUsed.Copy().
Sub(gasConsumedOnBlobs).
Div(decimal.NewFromInt(int64(len(blobs))))
for i := range gasConsumedPerBlob {
// share_in_gas = (gas_consumed_on_blob + fix_gas_per_blob) / gas_used
share := gasConsumedPerBlob[i].Add(fix).Div(gasUsed)
blobs[i].Fee = t.Fee.Copy().Mul(share)
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"encoding/hex"
"strings"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/shopspring/decimal"
)
func parseCoinSpent(ctx *context.Context, data map[string]any, height pkgTypes.Level) error {
coinSpent, err := decode.NewCoinSpent(data)
if err != nil {
return err
}
if coinSpent.Spender == "" {
return nil
}
address := &storage.Address{
Address: coinSpent.Spender,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
},
}
if coinSpent.Amount != nil {
amount, err := decimal.NewFromString(coinSpent.Amount.Amount.String())
if err != nil {
return err
}
address.Balance.Spendable = amount.Neg()
}
return ctx.AddAddress(address)
}
func parseCoinReceived(ctx *context.Context, data map[string]any, height pkgTypes.Level) error {
coinReceived, err := decode.NewCoinReceived(data)
if err != nil {
return err
}
if coinReceived.Receiver == "" {
return nil
}
address := &storage.Address{
Address: coinReceived.Receiver,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
},
}
if coinReceived.Amount != nil {
amount, err := decimal.NewFromString(coinReceived.Amount.Amount.String())
if err != nil {
return err
}
address.Balance.Spendable = amount
}
return ctx.AddAddress(address)
}
func parseCompleteUnbonding(ctx *context.Context, data map[string]any, height pkgTypes.Level) error {
unbonding, err := decode.NewCompleteUnbonding(data)
if err != nil {
return err
}
if unbonding.Validator == "" || unbonding.Delegator == "" {
return nil
}
address := &storage.Address{
Address: unbonding.Delegator,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
},
}
if unbonding.Amount != nil {
amount, err := decimal.NewFromString(unbonding.Amount.Amount.String())
if err != nil {
return err
}
address.Balance.Unbonding = amount.Copy().Neg()
}
return ctx.AddAddress(address)
}
func parseCommission(ctx *context.Context, data map[string]any) error {
commission, err := decode.NewCommission(data)
if err != nil {
return err
}
if commission.Validator == "" {
return nil
}
validator := storage.EmptyValidator()
validator.Address = commission.Validator
if !commission.Amount.IsZero() {
validator.Commissions = commission.Amount.Copy()
ctx.Block.Stats.Commissions = ctx.Block.Stats.Commissions.Add(commission.Amount.Copy())
ctx.AddStakingLog(storage.StakingLog{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Validator: &validator,
Change: commission.Amount.Copy(),
Type: types.StakingLogTypeCommissions,
})
}
ctx.AddValidator(validator)
return nil
}
func parseRewards(ctx *context.Context, data map[string]any) error {
rewards, err := decode.NewRewards(data)
if err != nil {
return err
}
if rewards.Validator == "" {
return nil
}
validator := storage.EmptyValidator()
validator.Address = rewards.Validator
if !rewards.Amount.IsZero() {
validator.Rewards = rewards.Amount.Copy()
ctx.Block.Stats.Rewards = ctx.Block.Stats.Rewards.Add(rewards.Amount)
ctx.AddStakingLog(storage.StakingLog{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Validator: &validator,
Change: rewards.Amount.Copy(),
Type: types.StakingLogTypeRewards,
})
}
ctx.AddValidator(validator)
return nil
}
func parseSlash(ctx *context.Context, data map[string]any) error {
slash, err := decode.NewSlash(data)
if err != nil {
return err
}
if slash.Address != "" && slash.Reason != "" {
_, hash, err := pkgTypes.Address(slash.Address).Decode()
if err != nil {
return err
}
consAddress := strings.ToUpper(hex.EncodeToString(hash))
jailed := true
ctx.AddJail(storage.Jail{
Height: ctx.Block.Height,
Time: ctx.Block.Time,
Reason: slash.Reason,
Burned: slash.BurnedCoins,
Validator: &storage.Validator{
ConsAddress: consAddress,
Stake: slash.BurnedCoins.Copy(),
Jailed: &jailed,
},
})
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func handleCancelUnbonding(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.staking.v1beta1.MsgCancelUnbondingDelegation" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processCancelUnbonding(ctx, events, msg, idx)
}
func processCancelUnbonding(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameStaking.String() {
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawRewards:
if err := parseWithdrawRewards(ctx, msg, events[i].Data); err != nil {
return err
}
case storageTypes.EventTypeCancelUnbondingDelegation:
cancel, err := decode.NewCancelUnbondingDelegation(events[i].Data)
if err != nil {
return err
}
amount := decimal.RequireFromString(cancel.Amount.Amount.String())
validator := storage.EmptyValidator()
validator.Address = cancel.Validator
validator.Stake = amount.Copy()
ctx.AddValidator(validator)
address := &storage.Address{
Address: cancel.Delegator,
Height: msg.Height,
LastHeight: msg.Height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Delegated: amount.Copy(),
Unbonding: amount.Copy().Neg(),
},
}
if err := ctx.AddAddress(address); err != nil {
return err
}
ctx.AddDelegation(storage.Delegation{
Validator: &validator,
Address: address,
Amount: amount,
})
ctx.AddCancelUndelegation(storage.Undelegation{
Validator: &validator,
Address: address,
Height: types.Level(cancel.CreationHeight),
Time: msg.Time,
Amount: amount,
})
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Address: address,
Validator: &validator,
Change: amount.Copy(),
Type: storageTypes.StakingLogTypeUnbonding,
})
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func handleDelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.staking.v1beta1.MsgDelegate" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processDelegate(ctx, events, msg, idx)
}
func processDelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
var (
validator = storage.EmptyValidator()
delegation = storage.Delegation{
Validator: &validator,
}
)
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameStaking.String() {
delegator := decoder.StringFromMap(events[i].Data, "sender")
address := &storage.Address{
Address: delegator,
Height: msg.Height,
LastHeight: msg.Height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Delegated: delegation.Amount,
},
}
if err := ctx.AddAddress(address); err != nil {
return err
}
delegation.Address = address
ctx.AddDelegation(delegation)
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Address: address,
Validator: delegation.Validator,
Change: delegation.Amount,
Type: storageTypes.StakingLogTypeDelegation,
})
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawRewards:
if err := parseWithdrawRewards(ctx, msg, events[i].Data); err != nil {
return err
}
case storageTypes.EventTypeDelegate:
delegate, err := decode.NewDelegate(events[i].Data)
if err != nil {
return err
}
delegation.Amount = decimal.RequireFromString(delegate.Amount.Amount.String())
delegation.Validator.Address = delegate.Validator
delegation.Validator.Stake = delegation.Amount
ctx.AddValidator(*delegation.Validator)
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
)
func handleExec(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.authz.v1beta1.MsgExec" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
for i := range msg.InternalMsgs {
switch msg.InternalMsgs[i] {
case "/cosmos.staking.v1beta1.MsgCancelUnbondingDelegation":
if err := processCancelUnbonding(ctx, events, msg, idx); err != nil {
return err
}
case "/cosmos.staking.v1beta1.MsgDelegate":
if err := processDelegate(ctx, events, msg, idx); err != nil {
return err
}
case "/cosmos.staking.v1beta1.MsgBeginRedelegate":
msgsAny, ok := msg.Data["Msgs"]
if !ok {
return errors.Errorf("can't find Msgs key in MsgExec: %##v", msg.Data)
}
msgsArr, ok := msgsAny.([]any)
if !ok {
return errors.Errorf("Msgs is not an array in MsgExec: %T", msgsAny)
}
msgs, ok := msgsArr[i].(map[string]any)
if !ok {
return errors.Errorf("Msgs invalid type in MsgExec: %T", msgsArr[i])
}
if err := processRedelegate(ctx, events, &storage.Message{
Data: msgs,
}, idx); err != nil {
return err
}
case "/cosmos.staking.v1beta1.MsgUndelegate":
if err := processUndelegate(ctx, events, msg, idx); err != nil {
return err
}
case "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission":
if err := processWithdrawValidatorCommission(ctx, events, msg, idx); err != nil {
return err
}
case "cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward":
if err := processWithdrawDelegatorRewards(ctx, events, msg, idx); err != nil {
return err
}
case "/cosmos.slashing.v1beta1.MsgUnjail":
if err := processUnjail(ctx, events, idx); err != nil {
return err
}
default:
for j := *idx; j < len(events); j++ {
authMsgIdxPtr, err := decoder.AuthMsgIndexFromMap(events[*idx].Data)
if err != nil {
return err
}
if authMsgIdxPtr == nil {
break
}
if *authMsgIdxPtr != int64(i) {
break
}
*idx = j + 1
}
}
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
)
type EventHandler func(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error
var eventHandlers = map[storageTypes.MsgType]EventHandler{
storageTypes.MsgDelegate: handleDelegate,
storageTypes.MsgBeginRedelegate: handleRedelegate,
storageTypes.MsgUndelegate: handleUndelegate,
storageTypes.MsgCancelUnbondingDelegation: handleCancelUnbonding,
storageTypes.MsgExec: handleExec,
storageTypes.MsgWithdrawValidatorCommission: handleWithdrawValidatorCommission,
storageTypes.MsgWithdrawDelegatorReward: handleWithdrawDelegatorRewards,
storageTypes.MsgUnjail: handleUnjail,
}
func Handle(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if handler, ok := eventHandlers[msg.Type]; ok {
return handler(ctx, events, msg, idx)
}
// if event handler is not found list events to another action
*idx++
startIndex := *idx
for _, event := range events[startIndex:] {
if event.Type != types.EventTypeMessage {
*idx++
continue
}
if action := decoder.StringFromMap(event.Data, "action"); action == "" {
*idx++
continue
}
break
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func handleRedelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.staking.v1beta1.MsgBeginRedelegate" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processRedelegate(ctx, events, msg, idx)
}
func processRedelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameStaking.String() {
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawRewards:
if err := parseWithdrawRewards(ctx, msg, events[i].Data); err != nil {
return err
}
case storageTypes.EventTypeRedelegate:
redelegate, err := decode.NewRedelegate(events[i].Data)
if err != nil {
return err
}
amount := decimal.RequireFromString(redelegate.Amount.Amount.String())
source := storage.EmptyValidator()
source.Address = redelegate.SrcValidator
source.Stake = amount.Copy().Neg()
ctx.AddValidator(source)
dest := storage.EmptyValidator()
dest.Address = redelegate.DestValidator
dest.Stake = amount
ctx.AddValidator(dest)
delegator := decoder.StringFromMap(msg.Data, "DelegatorAddress")
address := &storage.Address{
Address: delegator,
Height: msg.Height,
LastHeight: msg.Height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Delegated: decimal.Zero,
},
}
if err := ctx.AddAddress(address); err != nil {
return err
}
ctx.AddDelegation(storage.Delegation{
Validator: &source,
Address: address,
Amount: amount.Copy().Neg(),
})
ctx.AddDelegation(storage.Delegation{
Validator: &dest,
Address: address,
Amount: amount.Copy(),
})
ctx.AddRedelegation(storage.Redelegation{
Source: &source,
Destination: &dest,
Address: address,
Amount: amount,
Time: msg.Time,
Height: msg.Height,
CompletionTime: redelegate.CompletionTime,
})
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Address: address,
Validator: &source,
Change: amount.Copy().Neg(),
Type: storageTypes.StakingLogTypeDelegation,
})
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Address: address,
Validator: &dest,
Change: amount.Copy(),
Type: storageTypes.StakingLogTypeDelegation,
})
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"time"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func handleUndelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.staking.v1beta1.MsgUndelegate" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processUndelegate(ctx, events, msg, idx)
}
func processUndelegate(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
var (
amount = decimal.Zero
validator = storage.EmptyValidator()
completionTime = time.Now()
)
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameStaking.String() {
delegator := decoder.StringFromMap(events[i].Data, "sender")
address := &storage.Address{
Address: delegator,
Height: msg.Height,
LastHeight: msg.Height,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Delegated: amount.Copy().Neg(),
Unbonding: amount,
},
}
if err := ctx.AddAddress(address); err != nil {
return err
}
ctx.AddDelegation(storage.Delegation{
Address: address,
Validator: &validator,
Amount: amount.Copy().Neg(),
})
ctx.AddUndelegation(storage.Undelegation{
Validator: &validator,
Address: address,
Amount: amount,
Time: msg.Time,
Height: msg.Height,
CompletionTime: completionTime,
})
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Address: address,
Validator: &validator,
Change: amount.Copy().Neg(),
Type: storageTypes.StakingLogTypeUnbonding,
})
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawRewards:
if err := parseWithdrawRewards(ctx, msg, events[i].Data); err != nil {
return err
}
case storageTypes.EventTypeUnbond:
unbond, err := decode.NewUnbond(events[i].Data)
if err != nil {
return err
}
completionTime = unbond.CompletionTime
amount = decimal.RequireFromString(unbond.Amount.Amount.String())
validator.Address = unbond.Validator
validator.Stake = amount.Copy().Neg()
ctx.AddValidator(validator)
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
)
func handleUnjail(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.slashing.v1beta1.MsgUnjail" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processUnjail(ctx, events, idx)
}
func processUnjail(ctx *context.Context, events []storage.Event, idx *int) error {
if events[*idx].Type != types.EventTypeMessage {
return errors.Errorf("slashing unexpected event type: %s", events[*idx].Type)
}
module := decoder.StringFromMap(events[*idx].Data, "module")
if module != types.ModuleNameSlashing.String() {
return errors.Errorf("slashing unexpected module name: %s", module)
}
sender := decoder.StringFromMap(events[*idx].Data, "sender")
if sender == "" {
return errors.Errorf("slashing unexpected sender value: %s", sender)
}
jailed := false
v := storage.EmptyValidator()
v.Address = sender
v.Jailed = &jailed
ctx.AddValidator(v)
*idx += 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func parseWithdrawRewards(ctx *context.Context, msg *storage.Message, data map[string]any) error {
rewards, err := decode.NewWithdrawRewards(data)
if err != nil {
return err
}
if rewards.Validator == "" || rewards.Delegator != "" {
return nil
}
validator := storage.EmptyValidator()
validator.Address = rewards.Validator
if rewards.Amount != nil {
amount, err := decimal.NewFromString(rewards.Amount.Amount.String())
if err != nil {
return err
}
validator.Rewards = amount.Neg()
}
ctx.AddValidator(validator)
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Validator: &validator,
Change: validator.Rewards.Copy(),
Type: storageTypes.StakingLogTypeRewards,
})
return nil
}
func handleWithdrawDelegatorRewards(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processWithdrawDelegatorRewards(ctx, events, msg, idx)
}
func processWithdrawDelegatorRewards(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameDistribution.String() {
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawRewards:
if err := parseWithdrawRewards(ctx, msg, events[i].Data); err != nil {
return err
}
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package events
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func handleWithdrawValidatorCommission(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
if idx == nil {
return errors.New("nil event index")
}
if msg == nil {
return errors.New("nil message in events hanler")
}
if action := decoder.StringFromMap(events[*idx].Data, "action"); action != "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission" {
return errors.Errorf("unexpected event action %s for message type %s", action, msg.Type.String())
}
*idx += 1
return processWithdrawValidatorCommission(ctx, events, msg, idx)
}
func processWithdrawValidatorCommission(ctx *context.Context, events []storage.Event, msg *storage.Message, idx *int) error {
var validator = storage.EmptyValidator()
for i := *idx; i < len(events); i++ {
switch events[i].Type {
case storageTypes.EventTypeMessage:
if module := decoder.StringFromMap(events[i].Data, "module"); module == storageTypes.ModuleNameDistribution.String() {
if !validator.Commissions.IsZero() {
validator.Address = decoder.StringFromMap(events[i].Data, "sender")
ctx.AddValidator(validator)
ctx.AddStakingLog(storage.StakingLog{
Height: msg.Height,
Time: msg.Time,
Validator: &validator,
Change: validator.Commissions.Copy(),
Type: storageTypes.StakingLogTypeCommissions,
})
}
*idx = i + 1
return nil
}
case storageTypes.EventTypeWithdrawCommission:
commission, err := decode.NewWithdrawCommission(events[i].Data)
if err != nil {
return err
}
if commission.Amount == nil {
continue
}
amount := decimal.RequireFromString(commission.Amount.Amount.String())
validator.Commissions = amount.Neg()
}
}
*idx = len(events) - 1
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"context"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
func (p *Module) listen(ctx context.Context) {
p.Log.Info().Msg("module started")
input := p.MustInput(InputName)
for {
select {
case <-ctx.Done():
return
case msg, ok := <-input.Listen():
if !ok {
p.Log.Warn().Msg("can't read message from input, it was drained and closed")
p.MustOutput(StopOutput).Push(struct{}{})
return
}
block, ok := msg.(types.BlockData)
if !ok {
p.Log.Warn().Msgf("invalid message type: %T", msg)
continue
}
if err := p.parse(block); err != nil {
p.Log.Err(err).
Uint64("height", uint64(block.Height)).
Msg("block parsing error")
p.MustOutput(StopOutput).Push(struct{}{})
continue
}
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"encoding/hex"
"strings"
"time"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
dCtx "github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func (p *Module) parse(b types.BlockData) error {
start := time.Now()
p.Log.Info().
Int64("height", b.Block.Height).
Msg("parsing block...")
decodeCtx := dCtx.NewContext()
decodeCtx.Block = &storage.Block{
Height: b.Height,
Time: b.Block.Time,
VersionBlock: b.Block.Version.Block,
VersionApp: b.Block.Version.App,
MessageTypes: storageTypes.NewMsgTypeBitMask(),
Hash: []byte(b.BlockID.Hash),
ParentHash: []byte(b.Block.LastBlockID.Hash),
LastCommitHash: b.Block.LastCommitHash,
DataHash: b.Block.DataHash,
ValidatorsHash: b.Block.ValidatorsHash,
NextValidatorsHash: b.Block.NextValidatorsHash,
ConsensusHash: b.Block.ConsensusHash,
AppHash: b.Block.AppHash,
LastResultsHash: b.Block.LastResultsHash,
EvidenceHash: b.Block.EvidenceHash,
ProposerAddress: b.Block.ProposerAddress.String(),
ChainId: b.Block.ChainID,
Events: nil,
Stats: storage.BlockStats{
Height: b.Height,
Time: b.Block.Time,
TxCount: int64(len(b.Block.Data.Txs)),
EventsCount: int64(len(b.BeginBlockEvents) + len(b.EndBlockEvents)),
BlobsSize: 0,
Fee: decimal.Zero,
SupplyChange: decimal.Zero,
InflationRate: decimal.Zero,
Commissions: decimal.Zero,
Rewards: decimal.Zero,
SquareSize: b.Block.Data.SquareSize,
},
}
txs, err := p.parseTxs(decodeCtx, b)
if err != nil {
return errors.Wrapf(err, "while parsing block on level=%d", b.Height)
}
decodeCtx.Block.Txs = txs
for i := range b.Block.Txs {
decodeCtx.Block.Stats.BytesInBlock += int64(len(b.Block.Txs[i]))
}
decodeCtx.Block.BlockSignatures = p.parseBlockSignatures(b.Block.LastCommit)
decodeCtx.Block.Events, err = parseEvents(decodeCtx, b, b.ResultBlockResults.BeginBlockEvents)
if err != nil {
return errors.Wrap(err, "parsing begin block events")
}
endEvents, err := parseEvents(decodeCtx, b, b.ResultBlockResults.EndBlockEvents)
if err != nil {
return errors.Wrap(err, "parsing begin end events")
}
decodeCtx.Block.Events = append(decodeCtx.Block.Events, endEvents...)
p.Log.Info().
Uint64("height", uint64(decodeCtx.Block.Height)).
Int64("ms", time.Since(start).Milliseconds()).
Msg("block parsed")
output := p.MustOutput(OutputName)
output.Push(decodeCtx)
return nil
}
func (p *Module) parseBlockSignatures(commit *types.Commit) []storage.BlockSignature {
signs := make([]storage.BlockSignature, 0)
for i := range commit.Signatures {
if commit.Signatures[i].BlockIDFlag != 2 {
continue
}
signs = append(signs, storage.BlockSignature{
Height: types.Level(commit.Height),
Time: commit.Signatures[i].Timestamp,
Validator: &storage.Validator{
ConsAddress: strings.ToUpper(hex.EncodeToString(commit.Signatures[i].ValidatorAddress)),
},
})
}
return signs
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"github.com/rs/zerolog/log"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
func parseEvents(ctx *context.Context, b types.BlockData, events []types.Event) ([]storage.Event, error) {
result := make([]storage.Event, len(events))
for i := range events {
if err := parseEvent(ctx, b, events[i], i, &result[i]); err != nil {
return nil, err
}
}
return result, nil
}
func parseEvent(ctx *context.Context, b types.BlockData, eN types.Event, index int, resultEvent *storage.Event) error {
eventType, err := storageTypes.ParseEventType(eN.Type)
if err != nil {
log.Err(err).Msgf("got type %v", eN.Type)
eventType = storageTypes.EventTypeUnknown
}
resultEvent.Height = b.Height
resultEvent.Time = b.Block.Time
resultEvent.Position = int64(index)
resultEvent.Type = eventType
resultEvent.Data = make(map[string]any, len(eN.Attributes))
for i := range eN.Attributes {
resultEvent.Data[string(eN.Attributes[i].Key)] = string(eN.Attributes[i].Value)
}
return processEvent(ctx, resultEvent)
}
func processEvent(ctx *context.Context, event *storage.Event) error {
switch event.Type {
case storageTypes.EventTypeBurn:
ctx.SubSupply(event.Data)
case storageTypes.EventTypeMint:
ctx.SetInflation(event.Data)
ctx.AddSupply(event.Data)
case storageTypes.EventTypeCoinReceived:
return parseCoinReceived(ctx, event.Data, event.Height)
case storageTypes.EventTypeCoinSpent:
return parseCoinSpent(ctx, event.Data, event.Height)
case storageTypes.EventTypeCompleteUnbonding:
return parseCompleteUnbonding(ctx, event.Data, event.Height)
case storageTypes.EventTypeCommission:
return parseCommission(ctx, event.Data)
case storageTypes.EventTypeRewards:
return parseRewards(ctx, event.Data)
case storageTypes.EventTypeProposerReward:
return parseRewards(ctx, event.Data)
case storageTypes.EventTypeSlash:
return parseSlash(ctx, event.Data)
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
storageTypes "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode/decoder"
"github.com/celenium-io/celestia-indexer/pkg/indexer/parser/events"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func (p *Module) parseTxs(ctx *context.Context, b types.BlockData) ([]storage.Tx, error) {
txs := make([]storage.Tx, len(b.TxsResults))
for i := range b.TxsResults {
if err := p.parseTx(ctx, b, i, b.TxsResults[i], &txs[i]); err != nil {
return nil, err
}
}
return txs, nil
}
func (p *Module) parseTx(ctx *context.Context, b types.BlockData, index int, txRes *types.ResponseDeliverTx, t *storage.Tx) error {
d, err := decode.Tx(b, index)
if err != nil {
return errors.Wrapf(err, "while parsing Tx on index %d", index)
}
t.Height = b.Height
t.Time = b.Block.Time
t.Position = int64(index)
t.GasWanted = txRes.GasWanted
t.GasUsed = txRes.GasUsed
t.TimeoutHeight = d.TimeoutHeight
t.EventsCount = int64(len(txRes.Events))
t.MessagesCount = int64(len(d.Messages))
t.Fee = d.Fee
t.Status = storageTypes.StatusSuccess
t.Codespace = txRes.Codespace
t.Hash = b.Block.Txs[index].Hash()
t.Memo = d.Memo
t.MessageTypes = storageTypes.NewMsgTypeBitMask()
t.Messages = make([]storage.Message, len(d.Messages))
t.Events = nil
t.Signers = make([]storage.Address, 0)
t.BlobsSize = 0
t.BytesSize = int64(len(txRes.Data))
for signer, signerBytes := range d.Signers {
address := storage.Address{
Address: signer.String(),
Height: t.Height,
LastHeight: t.Height,
Hash: signerBytes,
Balance: storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
Delegated: decimal.Zero,
Unbonding: decimal.Zero,
},
}
t.Signers = append(t.Signers, address)
if err := ctx.AddAddress(&address); err != nil {
return err
}
}
if txRes.IsFailed() {
t.Status = storageTypes.StatusFailed
t.Error = txRes.Log
}
t.Events, err = parseEvents(ctx, b, txRes.Events)
if err != nil {
return errors.Wrap(err, "parsing events")
}
var eventsIdx int
// find first action
for i := range t.Events {
if t.Events[i].Type != storageTypes.EventTypeMessage {
continue
}
if action := decoder.StringFromMap(t.Events[i].Data, "action"); action != "" {
eventsIdx = i
break
}
}
for i := range d.Messages {
dm, err := decode.Message(ctx, d.Messages[i], i, t.Status)
if err != nil {
return errors.Wrapf(err, "while parsing tx=%v on index=%d", t.Hash, t.Position)
}
processBlob(dm.Msg.BlobLogs, d, t)
if txRes.IsFailed() {
dm.Msg.Namespace = nil
dm.BlobsSize = 0
}
t.Messages[i] = dm.Msg
t.MessageTypes.SetByMsgType(dm.Msg.Type)
t.BlobsSize += dm.BlobsSize
if !txRes.IsFailed() {
if err := events.Handle(ctx, t.Events, &t.Messages[i], &eventsIdx); err != nil {
return err
}
}
}
ctx.Block.Stats.Fee = ctx.Block.Stats.Fee.Add(t.Fee)
ctx.Block.MessageTypes.Set(t.MessageTypes.Bits)
ctx.Block.Stats.BlobsSize += t.BlobsSize
ctx.Block.Stats.GasLimit += t.GasWanted
ctx.Block.Stats.GasUsed += t.GasUsed
ctx.Block.Stats.BlobsCount += t.BlobsCount
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"context"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
)
type Module struct {
modules.BaseModule
cfg config.Indexer
}
var _ modules.Module = (*Module)(nil)
const (
InputName = "blocks"
OutputName = "data"
OutputBlobsName = "blobs"
StopOutput = "stop"
)
func NewModule(cfg config.Indexer) Module {
m := Module{
BaseModule: modules.New("parser"),
cfg: cfg,
}
m.CreateInputWithCapacity(InputName, 32)
m.CreateOutput(OutputName)
m.CreateOutput(OutputBlobsName)
m.CreateOutput(StopOutput)
return m
}
func (p *Module) Start(ctx context.Context) {
p.Log.Info().Msg("starting parser module...")
p.G.GoCtx(ctx, p.listen)
}
func (p *Module) Close() error {
p.Log.Info().Msg("closing...")
p.G.Wait()
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import "context"
func (r *Module) receiveGenesis(ctx context.Context) error {
r.Log.Info().Msg("receiving genesis block")
genesis, err := r.api.Genesis(ctx)
if err != nil {
return err
}
r.Log.Info().Msgf("got initial height of genesis block: %d", genesis.InitialHeight)
r.MustOutput(GenesisOutput).Push(genesis)
genesisDoneInput := r.MustInput(GenesisDoneInput)
// Wait until the genesis block will be saved
for {
select {
case <-ctx.Done():
return nil
case <-genesisDoneInput.Listen():
return nil
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"sync"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
"github.com/celenium-io/celestia-indexer/pkg/node"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/dipdup-io/workerpool"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
sdkSync "github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/rs/zerolog/log"
"github.com/tendermint/tendermint/rpc/client/http"
)
const (
BlocksOutput = "blocks"
RollbackOutput = "signal"
RollbackInput = "state"
GenesisOutput = "genesis"
GenesisDoneInput = "genesis_done"
StopOutput = "stop"
)
// Module - runs through a chain aiming to catch up the head
//
// and identifies whether the block fits in sequence or signals of rollback.
//
// |----------------|
// | | -- types.BlockData -> BlocksOutput
// | MODULE |
// | Receiver | -- struct{} -> RollbackOutput
// | | <- storage.State -- RollbackInput
// |----------------|
type Module struct {
modules.BaseModule
api node.Api
ws *http.HTTP
cfg config.Indexer
pool *workerpool.Pool[types.Level]
blocks chan types.BlockData
level types.Level
hash []byte
needGenesis bool
taskQueue *sdkSync.Map[types.Level, struct{}]
mx *sync.RWMutex
rollbackSync *sync.WaitGroup
cancelWorkers context.CancelFunc
cancelReadBlocks context.CancelFunc
}
var _ modules.Module = (*Module)(nil)
func NewModule(cfg config.Indexer, api node.Api, ws *http.HTTP, state *storage.State) Module {
level := types.Level(cfg.StartLevel)
var lastHash []byte
if state != nil {
level = state.LastHeight
lastHash = state.LastHash
}
receiver := Module{
BaseModule: modules.New("receiver"),
api: api,
ws: ws,
cfg: cfg,
blocks: make(chan types.BlockData, cfg.ThreadsCount*10),
needGenesis: state == nil,
level: level,
hash: lastHash,
taskQueue: sdkSync.NewMap[types.Level, struct{}](),
mx: new(sync.RWMutex),
rollbackSync: new(sync.WaitGroup),
}
receiver.CreateInput(RollbackInput)
receiver.CreateInput(GenesisDoneInput)
receiver.CreateOutput(BlocksOutput)
receiver.CreateOutput(RollbackOutput)
receiver.CreateOutput(GenesisOutput)
receiver.CreateOutput(StopOutput)
receiver.pool = workerpool.NewPool(receiver.worker, int(cfg.ThreadsCount))
return receiver
}
func (r *Module) Start(ctx context.Context) {
r.Log.Info().Msg("starting receiver...")
workersCtx, cancelWorkers := context.WithCancel(ctx)
r.cancelWorkers = cancelWorkers
r.pool.Start(workersCtx)
if r.needGenesis {
if err := r.receiveGenesis(ctx); err != nil {
log.Err(err).Msg("receiving genesis error")
return
}
}
r.G.GoCtx(ctx, r.sequencer)
r.G.GoCtx(ctx, r.sync)
r.G.GoCtx(ctx, r.rollback)
}
func (r *Module) Close() error {
r.Log.Info().Msg("closing...")
r.G.Wait()
if err := r.pool.Close(); err != nil {
return err
}
close(r.blocks)
return nil
}
func (r *Module) Level() (types.Level, []byte) {
r.mx.RLock()
defer r.mx.RUnlock()
return r.level, r.hash
}
func (r *Module) setLevel(level types.Level, hash []byte) {
r.mx.Lock()
defer r.mx.Unlock()
r.level = level
r.hash = hash
}
func (r *Module) rollback(ctx context.Context) {
rollbackInput := r.MustInput(RollbackInput)
for {
select {
case <-ctx.Done():
return
case msg, ok := <-rollbackInput.Listen():
if !ok {
r.Log.Warn().Msg("can't read message from rollback input, channel is closed and drained")
continue
}
state, ok := msg.(storage.State)
if !ok {
r.Log.Warn().Msgf("invalid message type: %T", msg)
continue
}
r.taskQueue.Clear()
r.setLevel(state.LastHeight, state.LastHash)
r.Log.Info().Msgf("caught return from rollback to level=%d", state.LastHeight)
r.rollbackSync.Done()
}
}
}
func (r *Module) stopAll() {
r.MustOutput(StopOutput).Push(struct{}{})
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"bytes"
"context"
"encoding/hex"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
func (r *Module) sequencer(ctx context.Context) {
orderedBlocks := map[int64]types.BlockData{}
l, prevBlockHash := r.Level()
currentBlock := int64(l + 1)
for {
select {
case <-ctx.Done():
return
case block, ok := <-r.blocks:
if !ok {
r.Log.Warn().Msg("can't read message from blocks input, channel was dried and closed")
r.stopAll()
return
}
orderedBlocks[block.Block.Height] = block
b, ok := orderedBlocks[currentBlock]
for ok {
if prevBlockHash != nil {
if !bytes.Equal(b.Block.LastBlockID.Hash, prevBlockHash) {
prevBlockHash, currentBlock, orderedBlocks = r.startRollback(ctx, b, prevBlockHash)
break
}
}
r.MustOutput(BlocksOutput).Push(b)
r.setLevel(types.Level(currentBlock), b.BlockID.Hash)
r.Log.Debug().
Uint64("height", uint64(currentBlock)).
Msg("put in order block")
prevBlockHash = b.BlockID.Hash
delete(orderedBlocks, currentBlock)
currentBlock += 1
b, ok = orderedBlocks[currentBlock]
}
}
}
}
func (r *Module) startRollback(
ctx context.Context,
b types.BlockData,
prevBlockHash []byte,
) ([]byte, int64, map[int64]types.BlockData) {
r.Log.Info().
Str("current.lastBlockHash", hex.EncodeToString(b.Block.LastBlockID.Hash)).
Str("prevBlockHash", hex.EncodeToString(prevBlockHash)).
Uint64("level", uint64(b.Height)).
Msg("rollback detected")
// Pause all receiver routines
r.rollbackSync.Add(1)
// Stop readBlocks
if r.cancelReadBlocks != nil {
r.cancelReadBlocks()
}
// Stop pool workers
if r.cancelWorkers != nil {
r.cancelWorkers()
}
clearChannel(r.blocks)
// Start rollback
r.MustOutput(RollbackOutput).Push(struct{}{})
// Wait until rollback will be finished
r.rollbackSync.Wait()
// Reset empty state
level, hash := r.Level()
currentBlock := int64(level)
prevBlockHash = hash
orderedBlocks := map[int64]types.BlockData{}
// Restart workers pool that read blocks
workersCtx, cancelWorkers := context.WithCancel(ctx)
r.cancelWorkers = cancelWorkers
r.pool.Start(workersCtx)
return prevBlockHash, currentBlock, orderedBlocks
}
func clearChannel(blocks <-chan types.BlockData) {
for len(blocks) > 0 {
<-blocks
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
tendermint "github.com/tendermint/tendermint/types"
)
func (r *Module) sync(ctx context.Context) {
var blocksCtx context.Context
blocksCtx, r.cancelReadBlocks = context.WithCancel(ctx)
if err := r.readBlocks(blocksCtx); err != nil {
r.Log.Err(err).Msg("while reading blocks")
r.stopAll()
return
}
if ctx.Err() != nil {
return
}
if r.ws != nil {
if err := r.live(ctx); err != nil {
r.Log.Err(err).Msg("while reading blocks")
r.stopAll()
return
}
} else {
ticker := time.NewTicker(time.Second * time.Duration(r.cfg.BlockPeriod))
defer ticker.Stop()
for {
r.rollbackSync.Wait()
select {
case <-ctx.Done():
return
case <-ticker.C:
blocksCtx, r.cancelReadBlocks = context.WithCancel(ctx)
if err := r.readBlocks(blocksCtx); err != nil && !errors.Is(err, context.Canceled) {
r.Log.Err(err).Msg("while reading blocks by timer")
r.stopAll()
return
}
}
}
}
}
func (r *Module) live(ctx context.Context) error {
if err := r.ws.Start(); err != nil {
return err
}
r.Log.Info().Msg("websocket started")
ch, err := r.ws.Subscribe(ctx, "test", "tm.event = 'NewBlockHeader'")
if err != nil {
return err
}
r.Log.Info().Msg("websocket was subscribed on block header events")
for {
r.rollbackSync.Wait()
select {
case <-ctx.Done():
return nil
case block := <-ch:
if block.Data == nil {
continue
}
blockHeader := block.Data.(tendermint.EventDataNewBlockHeader)
r.Log.Info().Int64("height", blockHeader.Header.Height).Msg("new block received")
r.passBlocks(ctx, types.Level(blockHeader.Header.Height))
}
}
}
func (r *Module) readBlocks(ctx context.Context) error {
for {
headLevel, err := r.headLevel(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
if level, _ := r.Level(); level == headLevel {
time.Sleep(time.Second)
continue
}
r.passBlocks(ctx, headLevel)
return nil
}
}
func (r *Module) passBlocks(ctx context.Context, head types.Level) {
level, _ := r.Level()
level += 1
for ; level <= head; level++ {
select {
case <-ctx.Done():
return
default:
if _, ok := r.taskQueue.Get(level); !ok {
r.taskQueue.Set(level, struct{}{})
r.pool.AddTask(level)
}
}
}
}
func (r *Module) headLevel(ctx context.Context) (types.Level, error) {
status, err := r.api.Status(ctx)
if err != nil {
return 0, err
}
return status.SyncInfo.LatestBlockHeight, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
)
func (r *Module) worker(ctx context.Context, level types.Level) {
defer r.taskQueue.Delete(level)
start := time.Now()
var result types.BlockData
for {
select {
case <-ctx.Done():
return
default:
}
requestTimeout, cancel := context.WithTimeout(ctx, time.Minute)
block, err := r.api.BlockDataGet(requestTimeout, level)
if err != nil {
cancel()
if errors.Is(err, context.Canceled) {
return
}
r.Log.Err(err).
Uint64("height", uint64(level)).
Msg("while getting block data")
time.Sleep(time.Second)
continue
}
result = block
cancel()
break
}
r.Log.Info().
Uint64("height", uint64(result.Height)).
Int64("ms", time.Since(start).Milliseconds()).
Msg("received block")
r.blocks <- result
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/indexer/decode"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func (module *Module) rollbackBalances(
ctx context.Context,
tx storage.Transaction,
deletedEvents []storage.Event,
deletedAddresses []storage.Address,
) error {
var (
ids = make([]uint64, len(deletedAddresses))
deleted = make(map[string]struct{}, len(deletedAddresses))
)
for i := range deletedAddresses {
ids[i] = deletedAddresses[i].Id
deleted[deletedAddresses[i].Address] = struct{}{}
}
if err := tx.DeleteBalances(ctx, ids); err != nil {
return err
}
if len(deletedEvents) == 0 {
return nil
}
updates, err := getBalanceUpdates(ctx, tx, deleted, deletedEvents)
if err != nil {
return err
}
_, err = tx.SaveAddresses(ctx, updates...)
return err
}
func getBalanceUpdates(
ctx context.Context,
tx storage.Transaction,
deletedAddress map[string]struct{},
deletedEvents []storage.Event,
) ([]*storage.Address, error) {
updates := make(map[string]*storage.Address)
for _, event := range deletedEvents {
var (
address *storage.Address
err error
)
switch event.Type {
case types.EventTypeCoinSpent:
address, err = coinSpent(event.Data)
case types.EventTypeCoinReceived:
address, err = coinReceived(event.Data)
default:
continue
}
if err != nil {
return nil, err
}
if _, ok := deletedAddress[address.Address]; ok {
continue
}
if addr, ok := updates[address.Address]; ok {
addr.Balance.Spendable = addr.Balance.Spendable.Add(address.Balance.Spendable)
} else {
lastHeight, err := tx.LastAddressAction(ctx, address.Hash)
if err != nil {
return nil, err
}
//nolint:gosec
address.LastHeight = pkgTypes.Level(lastHeight)
updates[address.Address] = address
}
}
result := make([]*storage.Address, 0, len(updates))
for i := range updates {
result = append(result, updates[i])
}
return result, nil
}
func coinSpent(data map[string]any) (*storage.Address, error) {
coinSpent, err := decode.NewCoinSpent(data)
if err != nil {
return nil, err
}
_, hash, err := pkgTypes.Address(coinSpent.Spender).Decode()
if err != nil {
return nil, errors.Wrapf(err, "decode spender: %s", coinSpent.Spender)
}
balance := storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
}
if coinSpent.Amount != nil {
balance.Spendable = decimal.NewFromBigInt(coinSpent.Amount.Amount.BigInt(), 0)
balance.Currency = coinSpent.Amount.Denom
}
return &storage.Address{
Address: coinSpent.Spender,
Hash: hash,
Balance: balance,
}, nil
}
func coinReceived(data map[string]any) (*storage.Address, error) {
coinReceived, err := decode.NewCoinReceived(data)
if err != nil {
return nil, err
}
_, hash, err := pkgTypes.Address(coinReceived.Receiver).Decode()
if err != nil {
return nil, errors.Wrapf(err, "decode receiver: %s", coinReceived.Receiver)
}
balance := storage.Balance{
Currency: currency.DefaultCurrency,
Spendable: decimal.Zero,
}
if coinReceived.Amount != nil {
balance.Spendable = decimal.NewFromBigInt(coinReceived.Amount.Amount.Neg().BigInt(), 0)
balance.Currency = coinReceived.Amount.Denom
}
return &storage.Address{
Address: coinReceived.Receiver,
Hash: hash,
Balance: balance,
}, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
)
func (module *Module) rollbackMessages(ctx context.Context, tx storage.Transaction, height types.Level) (int64, error) {
msgs, err := tx.RollbackMessages(ctx, height)
if err != nil {
return 0, err
}
if len(msgs) == 0 {
return 0, nil
}
ids := make([]uint64, len(msgs))
for i := range msgs {
ids[i] = msgs[i].Id
}
if err := tx.RollbackMessageAddresses(ctx, ids); err != nil {
return 0, err
}
nsMsgs, err := tx.RollbackNamespaceMessages(ctx, height)
if err != nil {
return 0, err
}
ns, err := tx.RollbackNamespaces(ctx, height)
if err != nil {
return 0, err
}
if err := module.rollbackNamespaces(ctx, tx, nsMsgs, ns, msgs); err != nil {
return 0, errors.Wrap(err, "namespace rollback")
}
return int64(len(ns)), nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"encoding/base64"
"encoding/hex"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/pkg/errors"
)
var errInvalidPayForBlob = errors.New("invalid MsgPayForBlob content")
func (module *Module) rollbackNamespaces(
ctx context.Context,
tx storage.Transaction,
nsMsgs []storage.NamespaceMessage,
deletedNs []storage.Namespace,
deletedMsgs []storage.Message,
) error {
if len(nsMsgs) == 0 {
return nil
}
deleted := make(map[uint64]struct{}, len(deletedNs))
for i := range deletedNs {
deleted[deletedNs[i].Id] = struct{}{}
}
deletedMessages := make(map[uint64]storage.Message, len(deletedMsgs))
for i := range deletedMsgs {
deletedMessages[deletedMsgs[i].Id] = deletedMsgs[i]
}
diffs := make(map[uint64]*storage.Namespace)
for i := range nsMsgs {
nsId := nsMsgs[i].NamespaceId
if _, ok := deleted[nsId]; ok {
continue
}
msgId := nsMsgs[i].MsgId
msg, ok := deletedMessages[msgId]
if !ok {
return errors.Errorf("unknown message: %d", msgId)
}
nsSize, err := newNamespaceSize(msg.Data)
if err != nil {
return err
}
ns, err := tx.Namespace(ctx, nsId)
if err != nil {
return err
}
size, ok := nsSize[ns.String()]
if !ok {
return errors.Errorf("message does not contain info about namespace: ns_id=%d msg_id=%d", nsId, msgId)
}
if diff, ok := diffs[nsId]; ok {
diff.PfbCount -= 1
diff.Size -= size
} else {
ns.PfbCount -= 1
ns.Size -= size
diffs[nsId] = &ns
}
}
namespaces := make([]*storage.Namespace, 0, len(diffs))
for key := range diffs {
last, err := tx.LastNamespaceMessage(ctx, diffs[key].Id)
if err != nil {
return errors.Wrap(err, "receiving last namespace message")
}
diffs[key].LastHeight = last.Height
diffs[key].LastMessageTime = last.Time
namespaces = append(namespaces, diffs[key])
}
_, err := tx.SaveNamespaces(ctx, namespaces...)
return err
}
type namespaceSize map[string]int64
func newNamespaceSize(data map[string]any) (namespaceSize, error) {
sizesRaw, ok := data["blob_sizes"]
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
sizesAny, ok := sizesRaw.([]any)
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
if len(sizesAny) == 0 {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
nsRaw, ok := data["namespaces"]
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
nsAny, ok := nsRaw.([]any)
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
if len(nsAny) != len(sizesAny) {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
size := make(namespaceSize)
for i := range nsAny {
nsString, ok := nsAny[i].(string)
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
nsSize, ok := sizesAny[i].(int)
if !ok {
return nil, errors.Wrapf(errInvalidPayForBlob, "%##v", data)
}
data, err := base64.StdEncoding.DecodeString(nsString)
if err != nil {
return nil, errors.Wrap(err, nsString)
}
size[hex.EncodeToString(data)] = int64(nsSize)
}
return size, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"bytes"
"context"
"github.com/celenium-io/celestia-indexer/pkg/node"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const (
InputName = "signal"
OutputName = "state"
StopOutput = "stop"
)
// Module - executes rollback on signal from input and notify all subscribers about new state after rollback operation.
//
// |----------------|
// | |
// -- struct{} -> | MODULE | -- storage.State ->
// | |
// |----------------|
type Module struct {
modules.BaseModule
tx sdk.Transactable
state storage.IState
blocks storage.IBlock
node node.Api
indexName string
}
var _ modules.Module = (*Module)(nil)
func NewModule(
tx sdk.Transactable,
state storage.IState,
blocks storage.IBlock,
node node.Api,
cfg config.Indexer,
) Module {
module := Module{
BaseModule: modules.New("rollback"),
tx: tx,
state: state,
blocks: blocks,
node: node,
indexName: cfg.Name,
}
module.CreateInput(InputName)
module.CreateOutput(OutputName)
module.CreateOutput(StopOutput)
return module
}
// Start -
func (module *Module) Start(ctx context.Context) {
module.G.GoCtx(ctx, module.listen)
}
func (module *Module) listen(ctx context.Context) {
module.Log.Info().Msg("module started")
input := module.MustInput(InputName)
for {
select {
case <-ctx.Done():
return
case _, ok := <-input.Listen():
if !ok {
module.Log.Warn().Msg("can't read message from input, channel was dried and closed")
module.MustOutput(StopOutput).Push(struct{}{})
return
}
if err := module.rollback(ctx); err != nil {
module.Log.Err(err).Msgf("error occurred")
}
}
}
}
// Close -
func (module *Module) Close() error {
module.Log.Info().Msg("closing module...")
module.G.Wait()
return nil
}
func (module *Module) rollback(ctx context.Context) error {
for {
select {
case <-ctx.Done():
default:
lastBlock, err := module.blocks.Last(ctx)
if err != nil {
return errors.Wrap(err, "receive last block from database")
}
nodeBlock, err := module.node.Block(ctx, lastBlock.Height)
if err != nil {
return errors.Wrapf(err, "receive block from node by height: %d", lastBlock.Height)
}
log.Debug().
Uint64("height", uint64(lastBlock.Height)).
Hex("db_block_hash", lastBlock.Hash).
Hex("node_block_hash", nodeBlock.BlockID.Hash).
Msg("comparing hash...")
if bytes.Equal(lastBlock.Hash, nodeBlock.BlockID.Hash) {
return module.finish(ctx)
}
log.Warn().
Uint64("height", uint64(lastBlock.Height)).
Hex("db_block_hash", lastBlock.Hash).
Hex("node_block_hash", nodeBlock.BlockID.Hash).
Msg("need rollback")
if err := module.rollbackBlock(ctx, lastBlock.Height); err != nil {
return errors.Wrapf(err, "rollback block: %d", lastBlock.Height)
}
}
}
}
func (module *Module) finish(ctx context.Context) error {
newState, err := module.state.ByName(ctx, module.indexName)
if err != nil {
return err
}
module.MustOutput(OutputName).Push(newState)
log.Info().
Uint64("new_height", uint64(newState.LastHeight)).
Msg("roll backed to new height")
return nil
}
func (module *Module) rollbackBlock(ctx context.Context, height types.Level) error {
tx, err := postgres.BeginTransaction(ctx, module.tx)
if err != nil {
return err
}
defer tx.Close(ctx)
if err := tx.RollbackBlock(ctx, height); err != nil {
return tx.HandleError(ctx, err)
}
blockStats, err := tx.RollbackBlockStats(ctx, height)
if err != nil {
return tx.HandleError(ctx, err)
}
addresses, err := tx.RollbackAddresses(ctx, height)
if err != nil {
return tx.HandleError(ctx, err)
}
if err := module.rollbackTransactions(ctx, tx, height); err != nil {
return tx.HandleError(ctx, err)
}
totalNamespaces, err := module.rollbackMessages(ctx, tx, height)
if err != nil {
return tx.HandleError(ctx, err)
}
events, err := tx.RollbackEvents(ctx, height)
if err != nil {
return tx.HandleError(ctx, err)
}
if err := module.rollbackBalances(ctx, tx, events, addresses); err != nil {
return tx.HandleError(ctx, err)
}
vals, err := rollbackValidators(ctx, tx, height)
if err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.RollbackBlockSignatures(ctx, height); err != nil {
return err
}
if err := tx.RollbackBlobLog(ctx, height); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.RollbackGrants(ctx, height); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.RollbackVestingPeriods(ctx, height); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.RollbackVestingAccounts(ctx, height); err != nil {
return tx.HandleError(ctx, err)
}
newBlock, err := tx.LastBlock(ctx)
if err != nil {
return tx.HandleError(ctx, err)
}
state, err := tx.State(ctx, module.indexName)
if err != nil {
return tx.HandleError(ctx, err)
}
state.LastHeight = newBlock.Height
state.LastHash = newBlock.Hash
state.LastTime = newBlock.Time
state.TotalTx -= blockStats.TxCount
state.TotalBlobsSize -= blockStats.BlobsSize
state.TotalNamespaces -= totalNamespaces
state.TotalAccounts -= int64(len(addresses))
state.TotalValidators -= vals.count
state.TotalFee = state.TotalFee.Sub(blockStats.Fee)
state.TotalSupply = state.TotalSupply.Sub(blockStats.SupplyChange)
state.TotalStake = state.TotalStake.Sub(vals.stake)
if err := tx.Update(ctx, &state); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
return tx.HandleError(ctx, err)
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
func (module *Module) rollbackTransactions(ctx context.Context, tx storage.Transaction, height types.Level) error {
txs, err := tx.RollbackTxs(ctx, height)
if err != nil {
return nil
}
if len(txs) == 0 {
return nil
}
ids := make([]uint64, len(txs))
for i := range txs {
ids[i] = txs[i].Id
}
if err := tx.RollbackSigners(ctx, ids); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"fmt"
"github.com/celenium-io/celestia-indexer/internal/currency"
"github.com/celenium-io/celestia-indexer/internal/storage"
st "github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/shopspring/decimal"
)
type rollbackedValidators struct {
count int
stake decimal.Decimal
}
func rollbackValidators(
ctx context.Context,
tx storage.Transaction,
height types.Level,
) (result rollbackedValidators, err error) {
removedValidators, err := tx.RollbackValidators(ctx, height)
if err != nil {
return result, err
}
result.count = len(removedValidators)
var (
removedIds = make([]uint64, len(removedValidators))
mapRemovedIds = make(map[uint64]struct{}, 0)
updated = make(map[uint64]*storage.Validator)
balances = make(map[uint64]*storage.Balance)
delegations = make(map[string]*storage.Delegation)
)
for i := range removedValidators {
removedIds[i] = removedValidators[i].Id
mapRemovedIds[removedValidators[i].Id] = struct{}{}
}
if err := tx.RollbackUndelegations(ctx, height); err != nil {
return result, err
}
if err := tx.RollbackRedelegations(ctx, height); err != nil {
return result, err
}
jails, err := tx.RollbackJails(ctx, height)
if err != nil {
return result, err
}
for i := range jails {
jailed := false
if val, ok := updated[jails[i].ValidatorId]; ok {
val.Jailed = &jailed
} else {
updated[jails[i].ValidatorId] = &storage.Validator{
Id: jails[i].ValidatorId,
Jailed: &jailed,
}
}
}
logs, err := tx.RollbackStakingLogs(ctx, height)
if err != nil {
return result, err
}
for i := range logs {
_, removed := mapRemovedIds[logs[i].ValidatorId]
switch logs[i].Type {
case st.StakingLogTypeDelegation:
if logs[i].AddressId != nil {
addressId := *logs[i].AddressId
if val, ok := balances[addressId]; ok {
val.Delegated = val.Delegated.Sub(logs[i].Change)
} else {
balances[addressId] = &storage.Balance{
Id: addressId,
Delegated: logs[i].Change.Copy().Neg(),
Currency: currency.DefaultCurrency,
}
}
if !removed {
dId := delegationId(addressId, logs[i].ValidatorId)
if val, ok := delegations[dId]; ok {
val.Amount = val.Amount.Sub(logs[i].Change.Copy())
} else {
delegations[dId] = &storage.Delegation{
AddressId: addressId,
ValidatorId: logs[i].ValidatorId,
Amount: logs[i].Change.Copy().Neg(),
}
}
}
}
if !removed {
if val, ok := updated[logs[i].ValidatorId]; ok {
val.Stake = val.Stake.Sub(logs[i].Change)
} else {
updated[logs[i].ValidatorId] = &storage.Validator{
Id: logs[i].ValidatorId,
Stake: logs[i].Change.Copy().Neg(),
}
}
}
result.stake = result.stake.Sub(logs[i].Change)
case st.StakingLogTypeUnbonding:
if logs[i].AddressId != nil {
addressId := *logs[i].AddressId
if val, ok := balances[addressId]; ok {
val.Delegated = val.Delegated.Sub(logs[i].Change)
val.Unbonding = val.Unbonding.Add(logs[i].Change)
} else {
balances[addressId] = &storage.Balance{
Id: addressId,
Delegated: logs[i].Change.Copy().Neg(),
Unbonding: logs[i].Change.Copy(),
Currency: currency.DefaultCurrency,
}
}
if !removed {
dId := delegationId(addressId, logs[i].ValidatorId)
if val, ok := delegations[dId]; ok {
val.Amount = val.Amount.Sub(logs[i].Change.Copy())
} else {
delegations[dId] = &storage.Delegation{
AddressId: addressId,
ValidatorId: logs[i].ValidatorId,
Amount: logs[i].Change.Copy().Neg(),
}
}
}
}
if !removed {
if val, ok := updated[logs[i].ValidatorId]; ok {
val.Stake = val.Stake.Add(logs[i].Change)
} else {
updated[logs[i].ValidatorId] = &storage.Validator{
Id: logs[i].ValidatorId,
Stake: logs[i].Change.Copy(),
}
}
}
result.stake = result.stake.Add(logs[i].Change)
case st.StakingLogTypeCommissions:
if removed {
continue
}
if val, ok := updated[logs[i].ValidatorId]; ok {
val.Commissions = val.Commissions.Sub(logs[i].Change)
} else {
updated[logs[i].ValidatorId] = &storage.Validator{
Id: logs[i].ValidatorId,
Commissions: logs[i].Change.Copy().Neg(),
}
}
case st.StakingLogTypeRewards:
if removed {
continue
}
if val, ok := updated[logs[i].ValidatorId]; ok {
val.Rewards = val.Rewards.Sub(logs[i].Change)
} else {
updated[logs[i].ValidatorId] = &storage.Validator{
Id: logs[i].ValidatorId,
Rewards: logs[i].Change.Copy().Neg(),
}
}
}
}
if len(updated) > 0 {
arr := make([]*storage.Validator, 0)
for _, value := range updated {
arr = append(arr, value)
}
if err = tx.UpdateValidators(ctx, arr...); err != nil {
return
}
}
if len(balances) > 0 {
arr := make([]storage.Balance, 0)
for _, value := range balances {
arr = append(arr, *value)
}
if err = tx.SaveBalances(ctx, arr...); err != nil {
return
}
}
if len(delegations) > 0 {
arr := make([]storage.Delegation, 0)
for _, value := range delegations {
arr = append(arr, *value)
}
if err = tx.SaveDelegations(ctx, arr...); err != nil {
return
}
}
if len(removedIds) > 0 {
if err = tx.DeleteDelegationsByValidator(ctx, removedIds...); err != nil {
return
}
}
return
}
func delegationId(addrId, valId uint64) string {
return fmt.Sprintf("%d_%d", addrId, valId)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
func saveAddresses(
ctx context.Context,
tx storage.Transaction,
addresses []*storage.Address,
) (map[string]uint64, int64, error) {
if len(addresses) == 0 {
return nil, 0, nil
}
totalAccounts, err := tx.SaveAddresses(ctx, addresses...)
if err != nil {
return nil, 0, err
}
addToId := make(map[string]uint64)
balances := make([]storage.Balance, len(addresses))
for i := range addresses {
addToId[addresses[i].Address] = addresses[i].Id
addresses[i].Balance.Id = addresses[i].Id
balances[i] = addresses[i].Balance
}
err = tx.SaveBalances(ctx, balances...)
return addToId, totalAccounts, err
}
func saveSigners(
ctx context.Context,
tx storage.Transaction,
addrToId map[string]uint64,
txs []storage.Tx,
) error {
if len(txs) == 0 || len(addrToId) == 0 {
return nil
}
var txAddresses []storage.Signer
for i := range txs {
for j := range txs[i].Signers {
if addrId, ok := addrToId[txs[i].Signers[j].Address]; ok {
txAddresses = append(txAddresses, storage.Signer{
TxId: txs[i].Id,
AddressId: addrId,
})
}
}
}
return tx.SaveSigners(ctx, txAddresses...)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
)
const (
countOfStoringSignsInLevels = 1_000
)
func (module *Module) saveBlockSignatures(
ctx context.Context,
tx storage.Transaction,
signs []storage.BlockSignature,
height types.Level,
) error {
retentionLevel := height - countOfStoringSignsInLevels
if retentionLevel > 0 && height%10 == 0 { // make retention on every ten block
if err := tx.RetentionBlockSignatures(ctx, retentionLevel); err != nil {
return err
}
}
if len(signs) == 0 {
return nil
}
for i := range signs {
if signs[i].Validator == nil {
return errors.New("nil validator of block signature")
}
if id, ok := module.validatorsByConsAddress[signs[i].Validator.ConsAddress]; ok {
signs[i].ValidatorId = id
} else {
return errors.Errorf("unknown validator: %s", signs[i].Validator.ConsAddress)
}
}
return tx.SaveBlockSignatures(ctx, signs...)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
decodeContext "github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
const (
withdrawStakeReason = "not enough self delegation"
)
type jailed struct {
storage.Jail
addressId uint64
}
func (module *Module) saveDelegations(
ctx context.Context,
tx storage.Transaction,
dCtx *decodeContext.Context,
addrToId map[string]uint64,
) (decimal.Decimal, error) {
total := decimal.NewFromInt(0)
if len(dCtx.StakingLogs) > 0 {
for i := range dCtx.StakingLogs {
if dCtx.StakingLogs[i].Address != nil {
addressId, ok := addrToId[dCtx.StakingLogs[i].Address.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "delegation address %s", dCtx.StakingLogs[i].Address.Address)
}
dCtx.StakingLogs[i].AddressId = &addressId
}
validatorId, ok := module.validatorsByAddress[dCtx.StakingLogs[i].Validator.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "delegation validator address %s", dCtx.StakingLogs[i].Validator.Address)
}
dCtx.StakingLogs[i].ValidatorId = validatorId
}
if err := tx.SaveStakingLogs(ctx, dCtx.StakingLogs...); err != nil {
return total, err
}
}
if dCtx.Delegations.Len() > 0 {
delegations := make([]storage.Delegation, 0)
if err := dCtx.Delegations.Range(func(_ string, value *storage.Delegation) (error, bool) {
addressId, ok := addrToId[value.Address.Address]
if !ok {
return errors.Wrapf(errCantFindAddress, "delegation address %s", value.Address.Address), false
}
value.AddressId = addressId
validatorId, ok := module.validatorsByAddress[value.Validator.Address]
if !ok {
return errors.Wrapf(errCantFindAddress, "delegation validator address %s", value.Validator.Address), false
}
value.ValidatorId = validatorId
delegations = append(delegations, *value)
total = total.Add(value.Amount)
return nil, false
}); err != nil {
return total, err
}
if err := tx.SaveDelegations(ctx, delegations...); err != nil {
return total, err
}
}
withdrawStake := make(map[uint64]jailed)
if len(dCtx.Redelegations) > 0 {
for i := range dCtx.Redelegations {
addressId, ok := addrToId[dCtx.Redelegations[i].Address.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "delegation address %s", dCtx.Redelegations[i].Address.Address)
}
dCtx.Redelegations[i].AddressId = addressId
srcId, ok := module.validatorsByAddress[dCtx.Redelegations[i].Source.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "source validator address %s", dCtx.Redelegations[i].Source.Address)
}
dCtx.Redelegations[i].SrcId = srcId
destId, ok := module.validatorsByAddress[dCtx.Redelegations[i].Destination.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "dest validator address %s", dCtx.Redelegations[i].Destination.Address)
}
dCtx.Redelegations[i].DestId = destId
if id, ok := module.validatorsByDelegator[dCtx.Redelegations[i].Address.Address]; ok && id == srcId {
withdrawStake[id] = jailed{
Jail: storage.Jail{
Height: dCtx.Block.Height,
Time: dCtx.Block.Time,
ValidatorId: srcId,
Reason: withdrawStakeReason,
Burned: decimal.Zero,
},
addressId: addressId,
}
}
}
if err := tx.SaveRedelegations(ctx, dCtx.Redelegations...); err != nil {
return total, err
}
}
if len(dCtx.Undelegations) > 0 {
for i := range dCtx.Undelegations {
addressId, ok := addrToId[dCtx.Undelegations[i].Address.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "delegation address %s", dCtx.Undelegations[i].Address.Address)
}
dCtx.Undelegations[i].AddressId = addressId
validatorId, ok := module.validatorsByAddress[dCtx.Undelegations[i].Validator.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "validator address %s", dCtx.Undelegations[i].Validator.Address)
}
dCtx.Undelegations[i].ValidatorId = validatorId
total = total.Sub(dCtx.Undelegations[i].Amount)
if id, ok := module.validatorsByDelegator[dCtx.Undelegations[i].Address.Address]; ok && id == validatorId {
withdrawStake[id] = jailed{
Jail: storage.Jail{
Height: dCtx.Block.Height,
Time: dCtx.Block.Time,
ValidatorId: validatorId,
Reason: withdrawStakeReason,
Burned: decimal.Zero,
},
addressId: addressId,
}
}
}
if err := tx.SaveUndelegations(ctx, dCtx.Undelegations...); err != nil {
return total, err
}
}
if len(dCtx.CancelUnbonding) > 0 {
for i := range dCtx.CancelUnbonding {
validatorId, ok := module.validatorsByAddress[dCtx.CancelUnbonding[i].Validator.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "cancel undelegation validator address %s", dCtx.CancelUnbonding[i].Validator.Address)
}
dCtx.CancelUnbonding[i].ValidatorId = validatorId
addressId, ok := addrToId[dCtx.CancelUnbonding[i].Address.Address]
if !ok {
return total, errors.Wrapf(errCantFindAddress, "cancel undelegation address %s", dCtx.CancelUnbonding[i].Address.Address)
}
dCtx.CancelUnbonding[i].AddressId = addressId
total = total.Add(dCtx.CancelUnbonding[i].Amount)
}
if err := tx.CancelUnbondings(ctx, dCtx.CancelUnbonding...); err != nil {
return total, err
}
}
if err := tx.RetentionCompletedRedelegations(ctx, dCtx.Block.Time); err != nil {
return total, errors.Wrap(err, "retention completed redelegations")
}
if err := tx.RetentionCompletedUnbondings(ctx, dCtx.Block.Time); err != nil {
return total, errors.Wrap(err, "retention completed unbondings")
}
for validatorId, jail := range withdrawStake {
validator, err := tx.Validator(ctx, validatorId)
if err != nil {
return total, errors.Wrap(err, "can't find validator")
}
delegation, err := tx.Delegation(ctx, validatorId, jail.addressId)
if err != nil {
return total, errors.Wrap(err, "can't find delegation")
}
if delegation.Amount.IsPositive() && delegation.Amount.GreaterThanOrEqual(validator.MinSelfDelegation) {
continue
}
j := true
validator.Jailed = &j
validator.Stake = decimal.Zero
if err := tx.Jail(ctx, &validator); err != nil {
return total, errors.Wrap(err, "jail on withdraw stake")
}
if err := tx.SaveJails(ctx, jail.Jail); err != nil {
return total, errors.Wrap(err, "save jail on withdraw stake")
}
}
return total, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import "github.com/celenium-io/celestia-indexer/internal/storage"
func setNamespacesFromMessage(msg storage.Message, namespaces map[string]*storage.Namespace) {
for i := range msg.Namespace {
key := msg.Namespace[i].String()
if ns, ok := namespaces[key]; !ok {
msg.Namespace[i].PfbCount = 1
namespaces[key] = &msg.Namespace[i]
} else {
ns.PfbCount += 1
ns.Size += msg.Namespace[i].Size
}
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/pkg/errors"
)
var errCantFindAddress = errors.New("can't find address")
func (module *Module) saveMessages(
ctx context.Context,
tx storage.Transaction,
messages []*storage.Message,
addrToId map[string]uint64,
) error {
if err := tx.SaveMessages(ctx, messages...); err != nil {
return err
}
var (
namespaceMsgs []storage.NamespaceMessage
msgAddress []storage.MsgAddress
blobLogs = make([]storage.BlobLog, 0)
vestingAccounts = make([]*storage.VestingAccount, 0)
grants = make(map[string]storage.Grant)
namespaces = make(map[string]uint64)
addedMsgId = make(map[uint64]struct{})
msgAddrMap = make(map[string]struct{})
)
for i := range messages {
for j := range messages[i].Namespace {
nsId := messages[i].Namespace[j].Id
key := messages[i].Namespace[j].String()
if nsId == 0 {
if _, ok := addedMsgId[messages[i].Id]; ok { // in case of duplication of writing to one namespace inside one messages
continue
}
id, ok := namespaces[key]
if !ok {
continue
}
nsId = id
} else {
namespaces[key] = nsId
}
addedMsgId[messages[i].Id] = struct{}{}
namespaceMsgs = append(namespaceMsgs, storage.NamespaceMessage{
MsgId: messages[i].Id,
NamespaceId: nsId,
Time: messages[i].Time,
Height: messages[i].Height,
TxId: messages[i].TxId,
Size: uint64(messages[i].Namespace[j].Size),
})
}
for j := range messages[i].Addresses {
id, ok := addrToId[messages[i].Addresses[j].String()]
if !ok {
continue
}
msgAddressEntity := storage.MsgAddress{
MsgId: messages[i].Id,
AddressId: id,
Type: messages[i].Addresses[j].Type,
}
key := msgAddressEntity.String()
if _, ok := msgAddrMap[key]; !ok {
msgAddress = append(msgAddress, msgAddressEntity)
msgAddrMap[key] = struct{}{}
}
}
for j := range messages[i].BlobLogs {
if err := processPayForBlob(addrToId, namespaces, messages[i], messages[i].BlobLogs[j]); err != nil {
return err
}
blobLogs = append(blobLogs, *messages[i].BlobLogs[j])
}
if messages[i].VestingAccount != nil {
addrId, ok := addrToId[messages[i].VestingAccount.Address.Address]
if !ok {
continue
}
messages[i].VestingAccount.AddressId = addrId
messages[i].VestingAccount.TxId = &messages[i].TxId
vestingAccounts = append(vestingAccounts, messages[i].VestingAccount)
}
for j := range messages[i].Grants {
if err := processGrants(addrToId, &messages[i].Grants[j]); err != nil {
return err
}
grants[messages[i].Grants[j].String()] = messages[i].Grants[j]
}
}
if err := tx.SaveNamespaceMessage(ctx, namespaceMsgs...); err != nil {
return err
}
if err := tx.SaveMsgAddresses(ctx, msgAddress...); err != nil {
return err
}
if err := tx.SaveBlobLogs(ctx, blobLogs...); err != nil {
return err
}
grantsArr := make([]storage.Grant, 0)
for _, g := range grants {
grantsArr = append(grantsArr, g)
}
if err := tx.SaveGrants(ctx, grantsArr...); err != nil {
return err
}
if len(vestingAccounts) > 0 {
if err := tx.SaveVestingAccounts(ctx, vestingAccounts...); err != nil {
return err
}
vestingPeriods := make([]storage.VestingPeriod, 0)
for i := range vestingAccounts {
for j := range vestingAccounts[i].VestingPeriods {
vestingAccounts[i].VestingPeriods[j].VestingAccountId = vestingAccounts[i].Id
}
vestingPeriods = append(vestingPeriods, vestingAccounts[i].VestingPeriods...)
}
if err := tx.SaveVestingPeriods(ctx, vestingPeriods...); err != nil {
return err
}
}
return nil
}
func processPayForBlob(addrToId map[string]uint64, namespaces map[string]uint64, msg *storage.Message, blob *storage.BlobLog) error {
if blob.Namespace == nil {
return errors.New("nil namespace in pay for blob message")
}
nsId, ok := namespaces[blob.Namespace.String()]
if !ok {
return errors.Errorf("can't find namespace for pay for blob message: %s", blob.Namespace.String())
}
if blob.Signer == nil {
return errors.New("nil signer address in pay for blob message")
}
signerId, ok := addrToId[blob.Signer.Address]
if !ok {
return errors.Wrapf(errCantFindAddress, "signer for pay for blob message: %s", blob.Signer.Address)
}
blob.MsgId = msg.Id
blob.TxId = msg.TxId
blob.SignerId = signerId
blob.NamespaceId = nsId
return nil
}
func processGrants(addrToId map[string]uint64, grant *storage.Grant) error {
granteeId, ok := addrToId[grant.Grantee.Address]
if !ok {
return errors.Wrapf(errCantFindAddress, "grantee: %s", grant.Grantee.Address)
}
grant.GranteeId = granteeId
granterId, ok := addrToId[grant.Granter.Address]
if !ok {
return errors.Wrapf(errCantFindAddress, "granter: %s", grant.Granter.Address)
}
grant.GranterId = granterId
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
)
func saveNamespaces(
ctx context.Context,
tx storage.Transaction,
namespaces map[string]*storage.Namespace,
) (int64, error) {
if len(namespaces) == 0 {
return 0, nil
}
data := make([]*storage.Namespace, 0, len(namespaces))
for key := range namespaces {
data = append(data, namespaces[key])
}
totalNamespaces, err := tx.SaveNamespaces(ctx, data...)
if err != nil {
return 0, err
}
return totalNamespaces, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/shopspring/decimal"
)
func updateState(block *storage.Block, totalAccounts, totalNamespaces int64, totalValidators int, totalVotingPower decimal.Decimal, state *storage.State) {
if block.Id <= uint64(state.LastHeight) {
return
}
state.LastHeight = block.Height
state.LastHash = block.Hash
state.LastTime = block.Time
state.TotalTx += block.Stats.TxCount
state.TotalAccounts += totalAccounts
state.TotalNamespaces += totalNamespaces
state.TotalBlobsSize += block.Stats.BlobsSize
state.TotalValidators += totalValidators
state.TotalFee = state.TotalFee.Add(block.Stats.Fee)
state.TotalSupply = state.TotalSupply.Add(block.Stats.SupplyChange)
state.TotalStake = state.TotalStake.Add(totalVotingPower)
state.ChainId = block.ChainId
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/celenium-io/celestia-indexer/pkg/indexer/config"
decodeContext "github.com/celenium-io/celestia-indexer/pkg/indexer/decode/context"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/celenium-io/celestia-indexer/internal/storage/postgres"
"github.com/celenium-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
)
const (
InputName = "data"
StopOutput = "stop"
)
// Module - saves received from input block to storage.
//
// |----------------|
// | |
// -- storage.Block -> | MODULE |
// | |
// |----------------|
type Module struct {
modules.BaseModule
storage sdk.Transactable
constants storage.IConstant
validators storage.IValidator
notificator storage.Notificator
validatorsByConsAddress map[string]uint64
validatorsByAddress map[string]uint64
validatorsByDelegator map[string]uint64
slashingForDowntime decimal.Decimal
slashingForDoubleSign decimal.Decimal
indexerName string
}
var _ modules.Module = (*Module)(nil)
// NewModule -
func NewModule(
tx sdk.Transactable,
constants storage.IConstant,
validators storage.IValidator,
notificator storage.Notificator,
cfg config.Indexer,
) Module {
m := Module{
BaseModule: modules.New("storage"),
storage: tx,
constants: constants,
validators: validators,
notificator: notificator,
validatorsByConsAddress: make(map[string]uint64),
validatorsByAddress: make(map[string]uint64),
validatorsByDelegator: make(map[string]uint64),
slashingForDowntime: decimal.Zero,
slashingForDoubleSign: decimal.Zero,
indexerName: cfg.Name,
}
m.CreateInputWithCapacity(InputName, 16)
m.CreateOutput(StopOutput)
return m
}
// Start -
func (module *Module) Start(ctx context.Context) {
if err := module.init(ctx); err != nil {
panic(err)
}
module.G.GoCtx(ctx, module.listen)
}
func (module *Module) init(ctx context.Context) error {
var (
limit = 100
offset = 0
end = false
)
for !end {
validators, err := module.validators.List(ctx, uint64(limit), uint64(offset), sdk.SortOrderDesc)
if err != nil {
return err
}
for i := range validators {
module.validatorsByConsAddress[validators[i].ConsAddress] = validators[i].Id
module.validatorsByAddress[validators[i].Address] = validators[i].Id
module.validatorsByDelegator[validators[i].Delegator] = validators[i].Id
}
offset += len(validators)
end = limit > len(validators)
}
return module.initConstants(ctx)
}
func (module *Module) isConstantsEmpty() bool {
return module.slashingForDoubleSign.IsZero() || module.slashingForDowntime.IsZero()
}
func (module *Module) initConstants(ctx context.Context) error {
doubleSign, err := module.constants.Get(ctx, types.ModuleNameSlashing, "slash_fraction_double_sign")
if err != nil {
if module.validators.IsNoRows(err) {
return nil
}
return err
}
module.slashingForDoubleSign, err = decimal.NewFromString(doubleSign.Value)
if err != nil {
return err
}
downtime, err := module.constants.Get(ctx, types.ModuleNameSlashing, "slash_fraction_downtime")
if err != nil {
if module.validators.IsNoRows(err) {
return nil
}
return err
}
module.slashingForDowntime, err = decimal.NewFromString(downtime.Value)
if err != nil {
return err
}
return nil
}
func (module *Module) listen(ctx context.Context) {
module.Log.Info().Msg("module started")
input := module.MustInput(InputName)
for {
select {
case <-ctx.Done():
return
case msg, ok := <-input.Listen():
if !ok {
module.Log.Warn().Msg("can't read message from input")
module.MustOutput(StopOutput).Push(struct{}{})
continue
}
decodedContext, ok := msg.(*decodeContext.Context)
if !ok {
module.Log.Warn().Msgf("invalid message type: %T", msg)
continue
}
if module.isConstantsEmpty() {
if err := module.initConstants(ctx); err != nil {
module.Log.Warn().Err(err).Msgf("constant initialization error")
continue
}
}
state, err := module.saveBlock(ctx, decodedContext)
if err != nil {
module.Log.Err(err).
Uint64("height", uint64(decodedContext.Block.Height)).
Msg("block saving error")
module.MustOutput(StopOutput).Push(struct{}{})
continue
}
if err := module.notify(ctx, state, *decodedContext.Block); err != nil {
module.Log.Err(err).Msg("block notification error")
}
}
}
}
// Close -
func (module *Module) Close() error {
module.Log.Info().Msg("closing module...")
module.G.Wait()
return nil
}
func (module *Module) saveBlock(ctx context.Context, dCtx *decodeContext.Context) (storage.State, error) {
start := time.Now()
module.Log.Info().Uint64("height", uint64(dCtx.Block.Height)).Msg("saving block...")
tx, err := postgres.BeginTransaction(ctx, module.storage)
if err != nil {
return storage.State{}, err
}
defer tx.Close(ctx)
state, err := module.processBlockInTransaction(ctx, tx, dCtx)
if err != nil {
return state, tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
return state, tx.HandleError(ctx, err)
}
module.Log.Info().
Uint64("height", uint64(dCtx.Block.Height)).
Time("block_time", dCtx.Block.Time).
Int64("block_ns_size", dCtx.Block.Stats.BlobsSize).
Str("block_fee", dCtx.Block.Stats.Fee.String()).
Int64("ms", time.Since(start).Milliseconds()).
Int("tx_count", len(dCtx.Block.Txs)).
Msg("block saved")
return state, nil
}
func (module *Module) processBlockInTransaction(ctx context.Context, tx storage.Transaction, dCtx *decodeContext.Context) (storage.State, error) {
block := dCtx.Block
state, err := tx.State(ctx, module.indexerName)
if err != nil {
return state, err
}
if block.Height == 1 {
// init after genesis block
if err := module.init(ctx); err != nil {
return state, err
}
}
block.Stats.BlockTime = uint64(block.Time.Sub(state.LastTime).Milliseconds())
if len(module.validatorsByConsAddress) > 0 {
if id, ok := module.validatorsByConsAddress[block.ProposerAddress]; ok {
block.ProposerId = id
} else {
return state, errors.Errorf("unknown block proposer: %s", block.ProposerAddress)
}
} else {
proposerId, err := tx.GetProposerId(ctx, block.ProposerAddress)
if err != nil {
return state, errors.Wrap(err, "can't find block proposer")
}
block.ProposerId = proposerId
}
if err := tx.Add(ctx, block); err != nil {
return state, err
}
if err := tx.Add(ctx, &block.Stats); err != nil {
return state, err
}
if err := tx.SaveTransactions(ctx, block.Txs...); err != nil {
return state, err
}
if err := tx.SaveEvents(ctx, block.Events...); err != nil {
return state, err
}
var (
messages = make([]*storage.Message, 0)
namespaces = make(map[string]*storage.Namespace, 0)
)
events := make([]storage.Event, 0, 10000)
for i := range block.Txs {
for j := range block.Txs[i].Messages {
block.Txs[i].Messages[j].TxId = block.Txs[i].Id
messages = append(messages, &block.Txs[i].Messages[j])
setNamespacesFromMessage(block.Txs[i].Messages[j], namespaces)
}
for j := range block.Txs[i].Events {
block.Txs[i].Events[j].TxId = &block.Txs[i].Id
}
events = append(events, block.Txs[i].Events...)
if len(events) >= 10000 {
if err := tx.SaveEvents(ctx, events...); err != nil {
return state, err
}
events = make([]storage.Event, 0, 10000)
}
}
if len(events) > 0 {
if err := tx.SaveEvents(ctx, events...); err != nil {
return state, err
}
}
addrToId, totalAccounts, err := saveAddresses(ctx, tx, dCtx.GetAddresses())
if err != nil {
return state, err
}
if err := saveSigners(ctx, tx, addrToId, block.Txs); err != nil {
return state, err
}
totalNamespaces, err := saveNamespaces(ctx, tx, namespaces)
if err != nil {
return state, err
}
if err := module.saveMessages(ctx, tx, messages, addrToId); err != nil {
return state, err
}
totalValidators, err := module.saveValidators(ctx, tx, dCtx.GetValidators(), dCtx.Jails)
if err != nil {
return state, err
}
totalVotingPower, err := module.saveDelegations(ctx, tx, dCtx, addrToId)
if err != nil {
return state, err
}
if err := module.saveBlockSignatures(ctx, tx, block.BlockSignatures, block.Height); err != nil {
return state, err
}
updateState(block, totalAccounts, totalNamespaces, totalValidators, totalVotingPower, &state)
err = tx.Update(ctx, &state)
return state, err
}
func (module *Module) notify(ctx context.Context, state storage.State, block storage.Block) error {
if time.Since(block.Time) > time.Hour {
// do not notify all about events if initial indexing is in progress
return nil
}
rawState, err := jsoniter.MarshalToString(state)
if err != nil {
return err
}
if err := module.notificator.Notify(ctx, storage.ChannelHead, rawState); err != nil {
return err
}
rawBlock, err := jsoniter.MarshalToString(block)
if err != nil {
return err
}
if err := module.notificator.Notify(ctx, storage.ChannelBlock, rawBlock); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func (module *Module) saveValidators(
ctx context.Context,
tx storage.Transaction,
validators []*storage.Validator,
jails *sync.Map[string, *storage.Jail],
) (int, error) {
if jails.Len() > 0 {
jailedVals := make([]*storage.Validator, 0)
jailsArr := make([]storage.Jail, 0)
err := jails.Range(func(address string, j *storage.Jail) (error, bool) {
if id, ok := module.validatorsByConsAddress[address]; ok {
j.ValidatorId = id
j.Validator.Id = id
jailedVals = append(jailedVals, j.Validator)
} else {
return errors.Errorf("unknown jailed validator: %s", address), false
}
jailsArr = append(jailsArr, *j)
fraction := decimal.Zero
switch j.Reason {
case "double_sign":
fraction = module.slashingForDoubleSign.Copy()
case "missing_signature":
fraction = module.slashingForDowntime.Copy()
}
if !fraction.IsPositive() {
return nil, false
}
balanceUpdates, err := tx.UpdateSlashedDelegations(ctx, j.ValidatorId, fraction)
if err != nil {
return err, false
}
if err := tx.SaveBalances(ctx, balanceUpdates...); err != nil {
return err, false
}
return nil, false
})
if err != nil {
return 0, err
}
if err := tx.Jail(ctx, jailedVals...); err != nil {
return 0, err
}
if err := tx.SaveJails(ctx, jailsArr...); err != nil {
return 0, err
}
}
if len(validators) == 0 {
return 0, nil
}
count, err := tx.SaveValidators(ctx, validators...)
if err != nil {
return 0, errors.Wrap(err, "saving validators")
}
if count == 0 {
return 0, nil
}
for i := range validators {
if validators[i].ConsAddress != "" {
module.validatorsByConsAddress[validators[i].ConsAddress] = validators[i].Id
}
if validators[i].Address != "" {
module.validatorsByAddress[validators[i].Address] = validators[i].Id
}
if validators[i].Delegator != "" {
module.validatorsByDelegator[validators[i].Delegator] = validators[i].Id
}
}
return count, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package dal
import (
"context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/pkg/errors"
)
// Blobs - returns all blobs under the given namespaces and height.
func (node *Node) Blobs(ctx context.Context, height pkgTypes.Level, namespaces ...string) ([]types.Blob, error) {
if len(namespaces) == 0 {
return nil, nil
}
var response types.Response[[]types.Blob]
if err := node.post(ctx, "blob.GetAll", []any{height, namespaces}, &response); err != nil {
return nil, err
}
if response.Error != nil {
return nil, errors.Wrapf(types.ErrRequest, "request %d error: %s", response.Id, response.Error.Error())
}
return response.Result, nil
}
// Blob - retrieves the blob by commitment under the given namespace and height.
func (node *Node) Blob(ctx context.Context, height pkgTypes.Level, namespace, commitment string) (types.Blob, error) {
var response types.Response[types.Blob]
if err := node.post(ctx, "blob.Get", []any{height, namespace, commitment}, &response); err != nil {
return response.Result, err
}
if response.Error != nil {
return response.Result, errors.Wrapf(types.ErrRequest, "request %d error: %s", response.Id, response.Error.Error())
}
return response.Result, nil
}
// Proofs - retrieves proofs in the given namespaces at the given height by commitment.
func (node *Node) Proofs(ctx context.Context, height pkgTypes.Level, namespace, commitment string) ([]types.Proof, error) {
var response types.Response[[]types.Proof]
if err := node.post(ctx, "blob.GetProof", []any{height, namespace, commitment}, &response); err != nil {
return response.Result, err
}
if response.Error != nil {
return response.Result, errors.Wrapf(types.ErrRequest, "request %d error: %s", response.Id, response.Error.Error())
}
return response.Result, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package dal
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"sync/atomic"
"time"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/goccy/go-json"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
)
type Node struct {
rateLimit *rate.Limiter
client *http.Client
host string
jsonRpcVersion string
token string
id *atomic.Int64
log zerolog.Logger
}
func New(baseUrl string) *Node {
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = 10
t.MaxConnsPerHost = 10
t.MaxIdleConnsPerHost = 10
return &Node{
host: baseUrl,
client: &http.Client{
Transport: t,
},
jsonRpcVersion: "2.0",
id: new(atomic.Int64),
log: log.With().Str("module", "dal").Logger(),
}
}
func (node *Node) WithRateLimit(requestPerSecond int) *Node {
if requestPerSecond > 0 {
node.rateLimit = rate.NewLimiter(rate.Every(time.Second/time.Duration(requestPerSecond)), requestPerSecond)
}
return node
}
func (node *Node) WithStartId(id int64) *Node {
if id > 0 {
node.id.Store(id)
}
return node
}
func (node *Node) WithJsonRpcVersion(version string) *Node {
if version != "" {
node.jsonRpcVersion = version
}
return node
}
func (node *Node) WithAuthToken(token string) *Node {
if token != "" {
node.token = token
}
return node
}
func (node *Node) post(ctx context.Context, method string, params []any, output any) error {
query := types.Request{
JsonRpc: node.jsonRpcVersion,
Id: node.id.Add(1),
Method: method,
Params: params,
}
body := new(bytes.Buffer)
if err := json.NewEncoder(body).Encode(query); err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, node.host, body)
if err != nil {
return err
}
request.Header.Add("Content-Type", "application/json")
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", node.token))
if node.rateLimit != nil {
if err := node.rateLimit.Wait(ctx); err != nil {
return err
}
}
start := time.Now()
response, err := node.client.Do(request)
if err != nil {
return err
}
defer closeWithLogError(response.Body, node.log)
node.log.Trace().
Int64("ms", time.Since(start).Milliseconds()).
Str("method", query.Method).
Int64("request_id", query.Id).
Msg("request")
if response.StatusCode != http.StatusOK {
return errors.Errorf("invalid status: %d", response.StatusCode)
}
err = json.NewDecoder(response.Body).DecodeContext(ctx, output)
return err
}
func closeWithLogError(stream io.ReadCloser, log zerolog.Logger) {
if _, err := io.Copy(io.Discard, stream); err != nil {
log.Err(err).Msg("api copy GET body response to discard")
}
if err := stream.Close(); err != nil {
log.Err(err).Msg("api close GET body request")
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
// Code generated by MockGen. DO NOT EDIT.
// Source: api.go
//
// Generated by this command:
//
// mockgen -source=api.go -destination=mock/api.go -package=mock -typed
//
// Package mock is a generated GoMock package.
package mock
import (
context "context"
reflect "reflect"
types "github.com/celenium-io/celestia-indexer/pkg/node/types"
types0 "github.com/celenium-io/celestia-indexer/pkg/types"
gomock "go.uber.org/mock/gomock"
)
// MockApi is a mock of Api interface.
type MockApi struct {
ctrl *gomock.Controller
recorder *MockApiMockRecorder
}
// MockApiMockRecorder is the mock recorder for MockApi.
type MockApiMockRecorder struct {
mock *MockApi
}
// NewMockApi creates a new mock instance.
func NewMockApi(ctrl *gomock.Controller) *MockApi {
mock := &MockApi{ctrl: ctrl}
mock.recorder = &MockApiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockApi) EXPECT() *MockApiMockRecorder {
return m.recorder
}
// Block mocks base method.
func (m *MockApi) Block(ctx context.Context, level types0.Level) (types0.ResultBlock, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Block", ctx, level)
ret0, _ := ret[0].(types0.ResultBlock)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Block indicates an expected call of Block.
func (mr *MockApiMockRecorder) Block(ctx, level any) *MockApiBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Block", reflect.TypeOf((*MockApi)(nil).Block), ctx, level)
return &MockApiBlockCall{Call: call}
}
// MockApiBlockCall wrap *gomock.Call
type MockApiBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiBlockCall) Return(arg0 types0.ResultBlock, arg1 error) *MockApiBlockCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiBlockCall) Do(f func(context.Context, types0.Level) (types0.ResultBlock, error)) *MockApiBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiBlockCall) DoAndReturn(f func(context.Context, types0.Level) (types0.ResultBlock, error)) *MockApiBlockCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BlockData mocks base method.
func (m *MockApi) BlockData(ctx context.Context, level types0.Level) (types0.BlockData, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BlockData", ctx, level)
ret0, _ := ret[0].(types0.BlockData)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BlockData indicates an expected call of BlockData.
func (mr *MockApiMockRecorder) BlockData(ctx, level any) *MockApiBlockDataCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockData", reflect.TypeOf((*MockApi)(nil).BlockData), ctx, level)
return &MockApiBlockDataCall{Call: call}
}
// MockApiBlockDataCall wrap *gomock.Call
type MockApiBlockDataCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiBlockDataCall) Return(arg0 types0.BlockData, arg1 error) *MockApiBlockDataCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiBlockDataCall) Do(f func(context.Context, types0.Level) (types0.BlockData, error)) *MockApiBlockDataCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiBlockDataCall) DoAndReturn(f func(context.Context, types0.Level) (types0.BlockData, error)) *MockApiBlockDataCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BlockDataGet mocks base method.
func (m *MockApi) BlockDataGet(ctx context.Context, level types0.Level) (types0.BlockData, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BlockDataGet", ctx, level)
ret0, _ := ret[0].(types0.BlockData)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BlockDataGet indicates an expected call of BlockDataGet.
func (mr *MockApiMockRecorder) BlockDataGet(ctx, level any) *MockApiBlockDataGetCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockDataGet", reflect.TypeOf((*MockApi)(nil).BlockDataGet), ctx, level)
return &MockApiBlockDataGetCall{Call: call}
}
// MockApiBlockDataGetCall wrap *gomock.Call
type MockApiBlockDataGetCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiBlockDataGetCall) Return(arg0 types0.BlockData, arg1 error) *MockApiBlockDataGetCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiBlockDataGetCall) Do(f func(context.Context, types0.Level) (types0.BlockData, error)) *MockApiBlockDataGetCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiBlockDataGetCall) DoAndReturn(f func(context.Context, types0.Level) (types0.BlockData, error)) *MockApiBlockDataGetCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// BlockResults mocks base method.
func (m *MockApi) BlockResults(ctx context.Context, level types0.Level) (types0.ResultBlockResults, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BlockResults", ctx, level)
ret0, _ := ret[0].(types0.ResultBlockResults)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BlockResults indicates an expected call of BlockResults.
func (mr *MockApiMockRecorder) BlockResults(ctx, level any) *MockApiBlockResultsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockResults", reflect.TypeOf((*MockApi)(nil).BlockResults), ctx, level)
return &MockApiBlockResultsCall{Call: call}
}
// MockApiBlockResultsCall wrap *gomock.Call
type MockApiBlockResultsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiBlockResultsCall) Return(arg0 types0.ResultBlockResults, arg1 error) *MockApiBlockResultsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiBlockResultsCall) Do(f func(context.Context, types0.Level) (types0.ResultBlockResults, error)) *MockApiBlockResultsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiBlockResultsCall) DoAndReturn(f func(context.Context, types0.Level) (types0.ResultBlockResults, error)) *MockApiBlockResultsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Genesis mocks base method.
func (m *MockApi) Genesis(ctx context.Context) (types.Genesis, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Genesis", ctx)
ret0, _ := ret[0].(types.Genesis)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Genesis indicates an expected call of Genesis.
func (mr *MockApiMockRecorder) Genesis(ctx any) *MockApiGenesisCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockApi)(nil).Genesis), ctx)
return &MockApiGenesisCall{Call: call}
}
// MockApiGenesisCall wrap *gomock.Call
type MockApiGenesisCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiGenesisCall) Return(arg0 types.Genesis, arg1 error) *MockApiGenesisCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiGenesisCall) Do(f func(context.Context) (types.Genesis, error)) *MockApiGenesisCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiGenesisCall) DoAndReturn(f func(context.Context) (types.Genesis, error)) *MockApiGenesisCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Head mocks base method.
func (m *MockApi) Head(ctx context.Context) (types0.ResultBlock, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Head", ctx)
ret0, _ := ret[0].(types0.ResultBlock)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Head indicates an expected call of Head.
func (mr *MockApiMockRecorder) Head(ctx any) *MockApiHeadCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Head", reflect.TypeOf((*MockApi)(nil).Head), ctx)
return &MockApiHeadCall{Call: call}
}
// MockApiHeadCall wrap *gomock.Call
type MockApiHeadCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiHeadCall) Return(arg0 types0.ResultBlock, arg1 error) *MockApiHeadCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiHeadCall) Do(f func(context.Context) (types0.ResultBlock, error)) *MockApiHeadCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiHeadCall) DoAndReturn(f func(context.Context) (types0.ResultBlock, error)) *MockApiHeadCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Status mocks base method.
func (m *MockApi) Status(ctx context.Context) (types.Status, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Status", ctx)
ret0, _ := ret[0].(types.Status)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Status indicates an expected call of Status.
func (mr *MockApiMockRecorder) Status(ctx any) *MockApiStatusCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockApi)(nil).Status), ctx)
return &MockApiStatusCall{Call: call}
}
// MockApiStatusCall wrap *gomock.Call
type MockApiStatusCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockApiStatusCall) Return(arg0 types.Status, arg1 error) *MockApiStatusCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockApiStatusCall) Do(f func(context.Context) (types.Status, error)) *MockApiStatusCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockApiStatusCall) DoAndReturn(f func(context.Context) (types.Status, error)) *MockApiStatusCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MockDalApi is a mock of DalApi interface.
type MockDalApi struct {
ctrl *gomock.Controller
recorder *MockDalApiMockRecorder
}
// MockDalApiMockRecorder is the mock recorder for MockDalApi.
type MockDalApiMockRecorder struct {
mock *MockDalApi
}
// NewMockDalApi creates a new mock instance.
func NewMockDalApi(ctrl *gomock.Controller) *MockDalApi {
mock := &MockDalApi{ctrl: ctrl}
mock.recorder = &MockDalApiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDalApi) EXPECT() *MockDalApiMockRecorder {
return m.recorder
}
// Blob mocks base method.
func (m *MockDalApi) Blob(ctx context.Context, height types0.Level, namespace, commitment string) (types.Blob, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Blob", ctx, height, namespace, commitment)
ret0, _ := ret[0].(types.Blob)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Blob indicates an expected call of Blob.
func (mr *MockDalApiMockRecorder) Blob(ctx, height, namespace, commitment any) *MockDalApiBlobCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Blob", reflect.TypeOf((*MockDalApi)(nil).Blob), ctx, height, namespace, commitment)
return &MockDalApiBlobCall{Call: call}
}
// MockDalApiBlobCall wrap *gomock.Call
type MockDalApiBlobCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockDalApiBlobCall) Return(arg0 types.Blob, arg1 error) *MockDalApiBlobCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockDalApiBlobCall) Do(f func(context.Context, types0.Level, string, string) (types.Blob, error)) *MockDalApiBlobCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockDalApiBlobCall) DoAndReturn(f func(context.Context, types0.Level, string, string) (types.Blob, error)) *MockDalApiBlobCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Blobs mocks base method.
func (m *MockDalApi) Blobs(ctx context.Context, height types0.Level, hash ...string) ([]types.Blob, error) {
m.ctrl.T.Helper()
varargs := []any{ctx, height}
for _, a := range hash {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Blobs", varargs...)
ret0, _ := ret[0].([]types.Blob)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Blobs indicates an expected call of Blobs.
func (mr *MockDalApiMockRecorder) Blobs(ctx, height any, hash ...any) *MockDalApiBlobsCall {
mr.mock.ctrl.T.Helper()
varargs := append([]any{ctx, height}, hash...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Blobs", reflect.TypeOf((*MockDalApi)(nil).Blobs), varargs...)
return &MockDalApiBlobsCall{Call: call}
}
// MockDalApiBlobsCall wrap *gomock.Call
type MockDalApiBlobsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *MockDalApiBlobsCall) Return(arg0 []types.Blob, arg1 error) *MockDalApiBlobsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *MockDalApiBlobsCall) Do(f func(context.Context, types0.Level, ...string) ([]types.Blob, error)) *MockDalApiBlobsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *MockDalApiBlobsCall) DoAndReturn(f func(context.Context, types0.Level, ...string) ([]types.Blob, error)) *MockDalApiBlobsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"bytes"
"context"
"io"
"net/http"
"net/url"
"time"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/dipdup-net/go-lib/config"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
const (
celeniumUserAgent = "Celenium Indexer"
)
type API struct {
client *http.Client
cfg config.DataSource
rps int
rateLimit *rate.Limiter
log zerolog.Logger
}
func NewAPI(cfg config.DataSource) API {
rps := cfg.RequestsPerSecond
if cfg.RequestsPerSecond < 1 || cfg.RequestsPerSecond > 100 {
rps = 10
}
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = rps
t.MaxConnsPerHost = rps
t.MaxIdleConnsPerHost = rps
return API{
client: &http.Client{
Transport: t,
},
cfg: cfg,
rps: rps,
rateLimit: rate.NewLimiter(rate.Every(time.Second/time.Duration(rps)), rps),
log: log.With().Str("module", "node rpc").Logger(),
}
}
func (api *API) get(ctx context.Context, path string, args map[string]string, output any) error {
u, err := url.Parse(api.cfg.URL)
if err != nil {
return err
}
u.Path, err = url.JoinPath(u.Path, path)
if err != nil {
return err
}
values := u.Query()
for key, value := range args {
values.Add(key, value)
}
u.RawQuery = values.Encode()
if api.rateLimit != nil {
if err := api.rateLimit.Wait(ctx); err != nil {
return err
}
}
start := time.Now()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", celeniumUserAgent)
response, err := api.client.Do(req)
if err != nil {
return err
}
defer closeWithLogError(response.Body, api.log)
api.log.Trace().
Int64("ms", time.Since(start).Milliseconds()).
Str("url", u.String()).
Msg("request")
if response.StatusCode != http.StatusOK {
return errors.Errorf("invalid status: %d", response.StatusCode)
}
err = json.NewDecoder(response.Body).Decode(output)
return err
}
func (api *API) post(ctx context.Context, requests []types.Request, output any) error {
u, err := url.Parse(api.cfg.URL)
if err != nil {
return err
}
body := new(bytes.Buffer)
if err := json.NewEncoder(body).Encode(requests); err != nil {
return errors.Wrap(err, "invalid bulk post request")
}
if api.rateLimit != nil {
if err := api.rateLimit.Wait(ctx); err != nil {
return err
}
}
start := time.Now()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), body)
if err != nil {
return err
}
req.Header.Set("User-Agent", celeniumUserAgent)
response, err := api.client.Do(req)
if err != nil {
return err
}
defer closeWithLogError(response.Body, api.log)
api.log.Trace().
Int64("ms", time.Since(start).Milliseconds()).
Str("url", u.String()).
Msg("post request")
if response.StatusCode != http.StatusOK {
return errors.Errorf("invalid status: %d", response.StatusCode)
}
err = json.NewDecoder(response.Body).Decode(output)
return err
}
func closeWithLogError(stream io.ReadCloser, log zerolog.Logger) {
if _, err := io.Copy(io.Discard, stream); err != nil {
log.Err(err).Msg("api copy GET body response to discard")
}
if err := stream.Close(); err != nil {
log.Err(err).Msg("api close GET body request")
}
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"context"
"strconv"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/pkg/errors"
)
const pathBlock = "block"
func (api *API) Block(ctx context.Context, level pkgTypes.Level) (pkgTypes.ResultBlock, error) {
args := make(map[string]string)
if level != 0 {
args["height"] = strconv.FormatInt(int64(level), 10)
}
var gbr types.Response[pkgTypes.ResultBlock]
if err := api.get(ctx, pathBlock, args, &gbr); err != nil {
return gbr.Result, errors.Wrap(err, "api.get")
}
if gbr.Error != nil {
return gbr.Result, errors.Wrapf(types.ErrRequest, "request %d error: %s", gbr.Id, gbr.Error.Error())
}
return gbr.Result, nil
}
func (api *API) BlockData(ctx context.Context, level pkgTypes.Level) (pkgTypes.BlockData, error) {
block := types.Response[pkgTypes.ResultBlock]{}
results := types.Response[pkgTypes.ResultBlockResults]{}
responses := []any{
&block,
&results,
}
levelString := level.String()
requests := []types.Request{
{
Method: pathBlock,
JsonRpc: "2.0",
Id: -1,
Params: []any{
levelString,
},
}, {
Method: pathBlockResults,
JsonRpc: "2.0",
Id: -1,
Params: []any{
levelString,
},
},
}
var blockData pkgTypes.BlockData
if err := api.post(ctx, requests, &responses); err != nil {
return blockData, errors.Wrap(err, "api.post")
}
if block.Error != nil {
return blockData, errors.Wrapf(types.ErrRequest, "request error: %s", block.Error.Error())
}
if results.Error != nil {
return blockData, errors.Wrapf(types.ErrRequest, "request error: %s", results.Error.Error())
}
blockData.ResultBlock = block.Result
blockData.ResultBlockResults = results.Result
return blockData, nil
}
func (api *API) BlockDataGet(ctx context.Context, level pkgTypes.Level) (pkgTypes.BlockData, error) {
var blockData pkgTypes.BlockData
block, err := api.Block(ctx, level)
if err != nil {
return blockData, errors.Wrapf(types.ErrRequest, "request error: %s", err.Error())
}
results, err := api.BlockResults(ctx, level)
if err != nil {
return blockData, errors.Wrapf(types.ErrRequest, "request error: %s", err.Error())
}
blockData.ResultBlock = block
blockData.ResultBlockResults = results
return blockData, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"context"
"strconv"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/pkg/errors"
)
type GenesisChunk struct {
Chunk int64 `json:"chunk,string"`
Total int64 `json:"total,string"`
Data []byte `json:"data"`
}
func (api *API) Genesis(ctx context.Context) (types.Genesis, error) {
path := "genesis_chunked"
genesisData := make([]byte, 0)
var chunk int64
var total int64
for chunk == 0 || chunk < total {
args := map[string]string{
"chunk": strconv.FormatInt(chunk, 10),
}
var gr types.Response[GenesisChunk]
if err := api.get(ctx, path, args, &gr); err != nil {
return types.Genesis{}, errors.Wrap(err, "genesis block request")
}
if gr.Error != nil {
return types.Genesis{}, errors.Wrapf(types.ErrRequest, "request %d error: %s", gr.Id, gr.Error.Error())
}
chunk += 1
total = gr.Result.Total
genesisData = append(genesisData, gr.Result.Data...)
}
var genesis types.Genesis
err := json.Unmarshal(genesisData, &genesis)
return genesis, err
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"context"
pkgTypes "github.com/celenium-io/celestia-indexer/pkg/types"
"strconv"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/pkg/errors"
)
const pathBlockResults = "block_results"
func (api *API) BlockResults(ctx context.Context, level pkgTypes.Level) (pkgTypes.ResultBlockResults, error) {
args := make(map[string]string)
if level != 0 {
args["height"] = strconv.FormatUint(uint64(level), 10)
}
var gbr types.Response[pkgTypes.ResultBlockResults]
if err := api.get(ctx, pathBlockResults, args, &gbr); err != nil {
return gbr.Result, errors.Wrap(err, "api.get")
}
if gbr.Error != nil {
return gbr.Result, errors.Wrapf(types.ErrRequest, "request %d error: %s", gbr.Id, gbr.Error.Error())
}
return gbr.Result, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"context"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
func (api *API) Head(ctx context.Context) (types.ResultBlock, error) {
return api.Block(ctx, 0)
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rpc
import (
"context"
"github.com/celenium-io/celestia-indexer/pkg/node/types"
"github.com/pkg/errors"
)
const pathStatus = "status"
func (api *API) Status(ctx context.Context) (types.Status, error) {
var sr types.Response[types.Status]
if err := api.get(ctx, pathStatus, nil, &sr); err != nil {
return sr.Result, errors.Wrap(err, "api.get")
}
if sr.Error != nil {
return sr.Result, errors.Wrapf(types.ErrRequest, "status request %d error: %s", sr.Id, sr.Error.Error())
}
return sr.Result, nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"encoding/json"
"fmt"
"time"
"github.com/celenium-io/celestia-indexer/pkg/types"
)
type Genesis struct {
GenesisTime time.Time `json:"genesis_time"`
ChainID string `json:"chain_id"`
InitialHeight int64 `json:"initial_height,string"`
ConsensusParams types.ConsensusParams `json:"consensus_params"`
AppHash types.Hex `json:"app_hash"`
AppState AppState `json:"app_state"`
}
type AuthParams struct {
MaxMemoCharacters string `json:"max_memo_characters"`
TxSigLimit string `json:"tx_sig_limit"`
TxSizeCostPerByte string `json:"tx_size_cost_per_byte"`
SigVerifyCostEd25519 string `json:"sig_verify_cost_ed25519"`
SigVerifyCostSecp256K1 string `json:"sig_verify_cost_secp256k1"`
}
type BaseAccount struct {
Address string `json:"address"`
PubKey interface{} `json:"pub_key"`
AccountNumber string `json:"account_number"`
Sequence string `json:"sequence"`
}
type BaseVestingAccount struct {
BaseAccount BaseAccount `json:"base_account"`
OriginalVesting []Coins `json:"original_vesting"`
DelegatedFree []Coins `json:"delegated_free"`
DelegatedVesting []Coins `json:"delegated_vesting"`
EndTime int64 `json:"end_time,string,omitempty"`
}
type Accounts struct {
Type string `json:"@type"`
Address string `json:"address,omitempty"`
PubKey interface{} `json:"pub_key,omitempty"`
AccountNumber string `json:"account_number,omitempty"`
Sequence string `json:"sequence,omitempty"`
BaseAccount BaseAccount `json:"base_account,omitempty"`
BaseVestingAccount BaseVestingAccount `json:"base_vesting_account,omitempty"`
Name string `json:"name,omitempty"`
Permissions []interface{} `json:"permissions,omitempty"`
StartTime *int64 `json:"start_time,string,omitempty"`
VestingPeriods []VestingPeriod `json:"vesting_periods,omitempty"`
}
type VestingPeriod struct {
Length int64 `json:"length,string"`
Amount []Coins `json:"amount"`
}
type Auth struct {
Params AuthParams `json:"params"`
Accounts []Accounts `json:"accounts"`
}
type Authz struct {
Authorization []interface{} `json:"authorization"`
}
type BankParams struct {
SendEnabled []interface{} `json:"send_enabled"`
DefaultSendEnabled bool `json:"default_send_enabled"`
}
type Coins struct {
Denom string `json:"denom"`
Amount string `json:"amount"`
}
func (c Coins) String() string {
return fmt.Sprintf("%s%s", c.Amount, c.Denom)
}
type Balances struct {
Address string `json:"address"`
Coins []Coins `json:"coins"`
}
type Supply struct {
Denom string `json:"denom"`
Amount string `json:"amount"`
}
type DenomMetadata struct {
Description string `json:"description"`
DenomUnits json.RawMessage `json:"denom_units"`
Base string `json:"base"`
Display string `json:"display"`
Name string `json:"name"`
Symbol string `json:"symbol"`
URI string `json:"uri"`
URIHash string `json:"uri_hash"`
}
type Bank struct {
Params BankParams `json:"params"`
Balances []Balances `json:"balances"`
Supply []Supply `json:"supply"`
DenomMetadata []DenomMetadata `json:"denom_metadata"`
}
type BlobParams struct {
GasPerBlobByte int `json:"gas_per_blob_byte"`
GovMaxSquareSize string `json:"gov_max_square_size"`
}
type BlobState struct {
Params BlobParams `json:"params"`
}
type Capability struct {
Index string `json:"index"`
Owners []interface{} `json:"owners"`
}
type Crisis struct {
ConstantFee Coins `json:"constant_fee"`
}
type DistributionParams struct {
CommunityTax string `json:"community_tax"`
BaseProposerReward string `json:"base_proposer_reward"`
BonusProposerReward string `json:"bonus_proposer_reward"`
WithdrawAddrEnabled bool `json:"withdraw_addr_enabled"`
}
type FeePool struct {
CommunityPool []interface{} `json:"community_pool"`
}
type Distribution struct {
Params DistributionParams `json:"params"`
FeePool FeePool `json:"fee_pool"`
DelegatorWithdrawInfos []interface{} `json:"delegator_withdraw_infos"`
PreviousProposer string `json:"previous_proposer"`
OutstandingRewards []interface{} `json:"outstanding_rewards"`
ValidatorAccumulatedCommissions []interface{} `json:"validator_accumulated_commissions"`
ValidatorHistoricalRewards []interface{} `json:"validator_historical_rewards"`
ValidatorCurrentRewards []interface{} `json:"validator_current_rewards"`
DelegatorStartingInfos []interface{} `json:"delegator_starting_infos"`
ValidatorSlashEvents []interface{} `json:"validator_slash_events"`
}
type Evidence struct {
Evidence []interface{} `json:"evidence"`
}
type Feegrant struct {
Allowances []interface{} `json:"allowances"`
}
type Description struct {
Moniker string `json:"moniker"`
Identity string `json:"identity"`
Website string `json:"website"`
SecurityContact string `json:"security_contact"`
Details string `json:"details"`
}
type Commission struct {
Rate string `json:"rate"`
MaxRate string `json:"max_rate"`
MaxChangeRate string `json:"max_change_rate"`
}
type Pubkey struct {
Type string `json:"@type"`
Key string `json:"key"`
}
type Messages struct {
Type string `json:"@type"`
Description Description `json:"description"`
Commission Commission `json:"commission"`
MinSelfDelegation string `json:"min_self_delegation"`
DelegatorAddress string `json:"delegator_address"`
ValidatorAddress string `json:"validator_address"`
Pubkey Pubkey `json:"pubkey"`
Value Coins `json:"value"`
EvmAddress string `json:"evm_address"`
}
type Body struct {
Messages []Messages `json:"messages"`
Memo string `json:"memo"`
TimeoutHeight uint64 `json:"timeout_height,string"`
ExtensionOptions []interface{} `json:"extension_options"`
NonCriticalExtensionOptions []interface{} `json:"non_critical_extension_options"`
}
type Single struct {
Mode string `json:"mode"`
}
type ModeInfo struct {
Single Single `json:"single"`
}
type SignerInfos struct {
PublicKey Pubkey `json:"public_key"`
ModeInfo ModeInfo `json:"mode_info"`
Sequence string `json:"sequence"`
}
type Fee struct {
Amount []interface{} `json:"amount"`
GasLimit string `json:"gas_limit"`
Payer string `json:"payer"`
Granter string `json:"granter"`
}
type AuthInfo struct {
SignerInfos []SignerInfos `json:"signer_infos"`
Fee Fee `json:"fee"`
Tip interface{} `json:"tip"`
}
type GenTxs struct {
Body Body `json:"body"`
AuthInfo AuthInfo `json:"auth_info"`
Signatures []string `json:"signatures"`
}
type Genutil struct {
GenTxs []json.RawMessage `json:"gen_txs"`
}
type DepositParams struct {
MinDeposit []Coins `json:"min_deposit"`
MaxDepositPeriod string `json:"max_deposit_period"`
}
type VotingParams struct {
VotingPeriod string `json:"voting_period"`
}
type TallyParams struct {
Quorum string `json:"quorum"`
Threshold string `json:"threshold"`
VetoThreshold string `json:"veto_threshold"`
}
type Gov struct {
StartingProposalID string `json:"starting_proposal_id"`
Deposits []interface{} `json:"deposits"`
Votes []interface{} `json:"votes"`
Proposals []interface{} `json:"proposals"`
DepositParams DepositParams `json:"deposit_params"`
VotingParams VotingParams `json:"voting_params"`
TallyParams TallyParams `json:"tally_params"`
}
type ClientGenesisParams struct {
AllowedClients []string `json:"allowed_clients"`
}
type ClientGenesis struct {
Clients []interface{} `json:"clients"`
ClientsConsensus []interface{} `json:"clients_consensus"`
ClientsMetadata []interface{} `json:"clients_metadata"`
Params ClientGenesisParams `json:"params"`
CreateLocalhost bool `json:"create_localhost"`
NextClientSequence string `json:"next_client_sequence"`
}
type ConnectionGenesisParams struct {
MaxExpectedTimePerBlock string `json:"max_expected_time_per_block"`
}
type ConnectionGenesis struct {
Connections []interface{} `json:"connections"`
ClientConnectionPaths []interface{} `json:"client_connection_paths"`
NextConnectionSequence string `json:"next_connection_sequence"`
Params ConnectionGenesisParams `json:"params"`
}
type ChannelGenesis struct {
Channels []interface{} `json:"channels"`
Acknowledgements []interface{} `json:"acknowledgements"`
Commitments []interface{} `json:"commitments"`
Receipts []interface{} `json:"receipts"`
SendSequences []interface{} `json:"send_sequences"`
RecvSequences []interface{} `json:"recv_sequences"`
AckSequences []interface{} `json:"ack_sequences"`
NextChannelSequence string `json:"next_channel_sequence"`
}
type Ibc struct {
ClientGenesis ClientGenesis `json:"client_genesis"`
ConnectionGenesis ConnectionGenesis `json:"connection_genesis"`
ChannelGenesis ChannelGenesis `json:"channel_genesis"`
}
type Minter struct {
InflationRate string `json:"inflation_rate"`
AnnualProvisions string `json:"annual_provisions"`
PreviousBlockTime interface{} `json:"previous_block_time"`
BondDenom string `json:"bond_denom"`
}
type Mint struct {
Minter Minter `json:"minter"`
}
type QgbParams struct {
DataCommitmentWindow string `json:"data_commitment_window"`
}
type Qgb struct {
Params QgbParams `json:"params"`
}
type SlashingParams struct {
SignedBlocksWindow string `json:"signed_blocks_window"`
MinSignedPerWindow string `json:"min_signed_per_window"`
DowntimeJailDuration string `json:"downtime_jail_duration"`
SlashFractionDoubleSign string `json:"slash_fraction_double_sign"`
SlashFractionDowntime string `json:"slash_fraction_downtime"`
}
type Slashing struct {
Params SlashingParams `json:"params"`
SigningInfos []interface{} `json:"signing_infos"`
MissedBlocks []interface{} `json:"missed_blocks"`
}
type StakingParams struct {
UnbondingTime string `json:"unbonding_time"`
MaxValidators int `json:"max_validators"`
MaxEntries int `json:"max_entries"`
HistoricalEntries int `json:"historical_entries"`
BondDenom string `json:"bond_denom"`
MinCommissionRate string `json:"min_commission_rate"`
}
type Staking struct {
Params StakingParams `json:"params"`
LastTotalPower string `json:"last_total_power"`
LastValidatorPowers []interface{} `json:"last_validator_powers"`
Validators []interface{} `json:"validators"`
Delegations []interface{} `json:"delegations"`
UnbondingDelegations []interface{} `json:"unbonding_delegations"`
Redelegations []interface{} `json:"redelegations"`
Exported bool `json:"exported"`
}
type TransferParams struct {
SendEnabled bool `json:"send_enabled"`
ReceiveEnabled bool `json:"receive_enabled"`
}
type Transfer struct {
PortID string `json:"port_id"`
DenomTraces []interface{} `json:"denom_traces"`
Params TransferParams `json:"params"`
}
type Vesting struct {
}
type AppState struct {
Auth Auth `json:"auth"`
Authz Authz `json:"authz"`
Bank Bank `json:"bank"`
Blob BlobState `json:"blob"`
Capability Capability `json:"capability"`
Crisis Crisis `json:"crisis"`
Distribution Distribution `json:"distribution"`
Evidence Evidence `json:"evidence"`
Feegrant Feegrant `json:"feegrant"`
Genutil Genutil `json:"genutil"`
Gov Gov `json:"gov"`
Ibc Ibc `json:"ibc"`
Mint Mint `json:"mint"`
Params interface{} `json:"params"`
Qgb Qgb `json:"qgb"`
Slashing Slashing `json:"slashing"`
Staking Staking `json:"staking"`
Transfer Transfer `json:"transfer"`
Vesting Vesting `json:"vesting"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"encoding/json"
"fmt"
)
type Request struct {
Method string `json:"method"`
Params []any `json:"params"`
Id int64 `json:"id"`
JsonRpc string `json:"jsonrpc"`
}
type Response[T any] struct {
Id int64 `json:"id"`
JsonRpc string `json:"jsonrpc"`
Error *Error `json:"error,omitempty"`
Result T `json:"result"`
}
// Error -
type Error struct {
Code int64 `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
// Error -
func (e Error) Error() string {
return fmt.Sprintf("code=%d message=%s data=%s", e.Code, e.Message, string(e.Data))
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package quotes
import (
"context"
"database/sql"
"time"
"github.com/celenium-io/celestia-indexer/internal/binance"
"github.com/celenium-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/config"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
"github.com/pkg/errors"
)
const (
PricesOutput = "prices"
symbol = "TIAUSDT"
interval = "1m"
)
var (
startOfTime = time.Date(2023, 5, 1, 0, 0, 0, 0, time.UTC)
)
type Module struct {
modules.BaseModule
api binance.IApi
storage storage.IPrice
currentTime time.Time
}
func New(cfg config.DataSource, storage storage.IPrice) *Module {
module := Module{
BaseModule: modules.New("quotes"),
storage: storage,
api: binance.NewAPI(cfg),
currentTime: startOfTime,
}
module.CreateOutput(PricesOutput)
return &module
}
func (m *Module) Start(ctx context.Context) {
m.Log.Info().Msg("starting receiver...")
if err := m.init(ctx); err != nil {
m.Log.Err(err).Msg("initialization")
return
}
m.G.GoCtx(ctx, m.receive)
}
func (m *Module) init(ctx context.Context) error {
last, err := m.storage.Last(ctx)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil
}
return errors.Wrap(err, "get prices from database")
}
m.currentTime = last.Time
return nil
}
func (m *Module) Close() error {
m.Log.Info().Msg("closing...")
m.G.Wait()
return nil
}
func (m *Module) receive(ctx context.Context) {
if err := m.get(ctx); err != nil {
m.Log.Err(err).Msg("receiving prices")
return
}
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := m.get(ctx); err != nil {
m.Log.Err(err).Msg("receiving prices")
}
}
}
}
func (m *Module) getPrices(ctx context.Context) (bool, error) {
requestCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
start := m.currentTime.Add(time.Minute).UnixMilli()
candles, err := m.api.OHLC(requestCtx, symbol, interval, &binance.OHLCArgs{
Start: start,
})
if err != nil {
return true, err
}
for i := range candles {
if err := m.storage.Save(ctx, &storage.Price{
Time: candles[i].Time,
Open: candles[i].Open,
High: candles[i].High,
Low: candles[i].Low,
Close: candles[i].Close,
}); err != nil {
return true, errors.Wrap(err, "saving price")
}
m.currentTime = candles[i].Time
}
end := len(candles) == 0
if !end {
m.Log.Info().Str("current_time", m.currentTime.String()).Msg("received quotes")
}
return end, nil
}
func (m *Module) get(ctx context.Context) error {
var (
end bool
err error
)
for !end {
end, err = m.getPrices(ctx)
if err != nil {
return err
}
if !end {
time.Sleep(time.Millisecond * 500)
}
}
return nil
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"crypto/ed25519"
"encoding/hex"
"math/big"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
// celestia prefixes
const (
AddressPrefixCelestia = "celestia"
AddressPrefixValoper = "celestiavaloper"
AddressPrefixValCons = "celestiavalcons"
)
type Address string
// Decode decodes address, returning the human-readable part and the data part excluding the checksum.
func (a Address) Decode() (string, []byte, error) {
return bech32.DecodeAndConvert(a.String())
}
func (a Address) String() string {
return string(a)
}
func (a Address) Decimal() (decimal.Decimal, error) {
_, data, err := a.Decode()
if err != nil {
return decimal.Zero, err
}
if bi, ok := new(big.Int).SetString(hex.EncodeToString(data), 16); ok {
return decimal.NewFromBigInt(bi, 0), nil
}
return decimal.Zero, errors.Errorf("invalid decoded address: %x %s", data, a)
}
func NewAddressFromBytes(data []byte) (Address, error) {
s, err := bech32.ConvertAndEncode(AddressPrefixCelestia, data)
if err != nil {
return "", nil
}
return Address(s), nil
}
func NewConsAddressFromBytes(data []byte) (Address, error) {
s, err := bech32.ConvertAndEncode(AddressPrefixValCons, data)
if err != nil {
return "", nil
}
return Address(s), nil
}
func NewValoperAddressFromBytes(data []byte) (Address, error) {
s, err := bech32.ConvertAndEncode(AddressPrefixValoper, data)
if err != nil {
return "", nil
}
return Address(s), nil
}
func GetConsAddressBytesFromPubKey(data []byte) []byte {
pk := cryptotypes.PubKey{
Key: ed25519.PublicKey(data),
}
return pk.Address().Bytes()
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"time"
"github.com/goccy/go-json"
)
// ResultBlockResults is an ABCI results from a block
// origin: github.com/celestiaorg/celestia-core@v1.26.2-tm-v0.34.28/rpc/core/types/responses.go
type ResultBlockResults struct {
Height Level `json:"height,string"`
TxsResults []*ResponseDeliverTx `json:"txs_results"`
BeginBlockEvents []Event `json:"begin_block_events"`
EndBlockEvents []Event `json:"end_block_events"`
// ValidatorUpdates []ValidatorUpdate `json:"validator_updates"`
// ConsensusParamUpdates *ConsensusParams `json:"consensus_param_updates"`
}
type ResponseDeliverTx struct {
Code uint32 `json:"code,omitempty" protobuf:"varint,1,opt,name=code,proto3"`
Data json.RawMessage `json:"data,omitempty" protobuf:"bytes,2,opt,name=data,proto3"`
Log string `json:"log,omitempty" protobuf:"bytes,3,opt,name=log,proto3"`
Info string `json:"info,omitempty" protobuf:"bytes,4,opt,name=info,proto3"`
GasWanted int64 `json:"gas_wanted,omitempty,string" protobuf:"varint,5,opt,name=gas_wanted,proto3"`
GasUsed int64 `json:"gas_used,omitempty,string" protobuf:"varint,6,opt,name=gas_used,proto3"`
Events []Event `json:"events,omitempty" protobuf:"bytes,7,rep,name=events,proto3"`
Codespace string `json:"codespace,omitempty" protobuf:"bytes,8,opt,name=codespace,proto3"`
}
func (tx *ResponseDeliverTx) IsFailed() bool {
return tx.Code != 0
}
// Event allows application developers to attach additional information to
// ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx.
// Later transactions may be queried using these events.
type Event struct {
Type string `json:"type,omitempty" protobuf:"bytes,1,opt,name=type,proto3"`
Attributes []EventAttribute `json:"attributes,omitempty" protobuf:"bytes,2,rep,name=attributes,proto3"`
}
// EventAttribute is a single key-value pair, associated with an event.
type EventAttribute struct {
Key []byte `json:"key,omitempty" protobuf:"bytes,1,opt,name=key,proto3"`
Value []byte `json:"value,omitempty" protobuf:"bytes,2,opt,name=value,proto3"`
Index bool `json:"index,omitempty" protobuf:"varint,3,opt,name=index,proto3"`
}
// ValidatorUpdate
type ValidatorUpdate struct {
PubKey PubKey `json:"pub_key"`
Power *int64 `json:"power,omitempty,string"`
}
type PubKey struct {
Sum struct {
Type string `json:"type"`
Value struct {
Ed25519 []byte `json:"ed25519"`
} `json:"value"`
} `json:"Sum"`
}
// ConsensusParams contains all consensus-relevant parameters
// that can be adjusted by the abci app
type ConsensusParams struct {
Block *BlockParams `json:"block" protobuf:"bytes,1,opt,name=block,proto3"`
Evidence *EvidenceParams `json:"evidence" protobuf:"bytes,2,opt,name=evidence,proto3"`
Validator *ValidatorParams `json:"validator" protobuf:"bytes,3,opt,name=validator,proto3"`
Version *VersionParams `json:"version" protobuf:"bytes,4,opt,name=version,proto3"`
}
// BlockParams contains limits on the block size.
type BlockParams struct {
// Note: must be greater than 0
MaxBytes int64 `json:"max_bytes,omitempty,string" protobuf:"varint,1,opt,name=max_bytes,json=maxBytes,proto3"`
// Note: must be greater or equal to -1
MaxGas int64 `json:"max_gas,omitempty,string" protobuf:"varint,2,opt,name=max_gas,json=maxGas,proto3"`
}
// EvidenceParams determine how we handle evidence of malfeasance.
type EvidenceParams struct {
// Max age of evidence, in blocks.
//
// The basic formula for calculating this is: MaxAgeDuration / {average block
// time}.
MaxAgeNumBlocks int64 `json:"max_age_num_blocks,omitempty,string" protobuf:"varint,1,opt,name=max_age_num_blocks,json=maxAgeNumBlocks,proto3"`
// Max age of evidence, in time.
//
// It should correspond with an app's "unbonding period" or other similar
// mechanism for handling [Nothing-At-Stake
// attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed).
MaxAgeDuration time.Duration `json:"max_age_duration,string" protobuf:"bytes,2,opt,name=max_age_duration,json=maxAgeDuration,proto3,stdduration"`
// This sets the maximum size of total evidence in bytes that can be committed in a single block.
// And should fall comfortably under the max block bytes.
// Default is 1048576 or 1MB
MaxBytes int64 `json:"max_bytes,omitempty,string" protobuf:"varint,3,opt,name=max_bytes,json=maxBytes,proto3"`
}
// ValidatorParams restrict the public key types validators can use.
// NOTE: uses ABCI pubkey naming, not Amino names.
type ValidatorParams struct {
PubKeyTypes []string `json:"pub_key_types,omitempty" protobuf:"bytes,1,rep,name=pub_key_types,json=pubKeyTypes,proto3"`
}
// VersionParams contains the ABCI application version.
type VersionParams struct {
AppVersion uint64 `json:"app_version,omitempty,string" protobuf:"varint,1,opt,name=app_version,json=appVersion,proto3"`
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"bytes"
"database/sql/driver"
"encoding/hex"
"strconv"
"strings"
"github.com/pkg/errors"
)
type Hex []byte
var nullBytes = "null"
func HexFromString(s string) (Hex, error) {
data, err := hex.DecodeString(s)
if err != nil {
return nil, err
}
return Hex(data), nil
}
func (h *Hex) UnmarshalJSON(data []byte) error {
if h == nil {
return nil
}
if nullBytes == string(data) {
*h = nil
return nil
}
length := len(data)
if length%2 == 1 {
return errors.Errorf("odd hex length: %d %v", length, data)
}
if data[0] != '"' || data[length-1] != '"' {
return errors.Errorf("hex should be quotted string: got=%s", data)
}
data = bytes.Trim(data, `"`)
*h = make(Hex, hex.DecodedLen(length-1))
if length-1 == 0 {
return nil
}
_, err := hex.Decode(*h, data)
return err
}
func (h Hex) MarshalJSON() ([]byte, error) {
if h == nil {
return []byte(nullBytes), nil
}
return []byte(strconv.Quote(h.String())), nil
}
func (h *Hex) Scan(src interface{}) (err error) {
switch val := src.(type) {
case []byte:
*h = make(Hex, len(val))
_ = copy(*h, val)
case nil:
*h = make(Hex, 0)
default:
return errors.Errorf("unknown hex database type: %T", src)
}
return nil
}
var _ driver.Valuer = (*Hex)(nil)
func (h Hex) Value() (driver.Value, error) {
return []byte(h), nil
}
func (h Hex) Bytes() []byte {
return []byte(h)
}
func (h Hex) String() string {
return strings.ToUpper(hex.EncodeToString([]byte(h)))
}
// SPDX-FileCopyrightText: 2024 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import "fmt"
type Level int64
func (l Level) String() string {
return fmt.Sprintf("%d", l)
}