// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"time"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
_ "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/labstack/echo/v4"
)
type AddressHandler struct {
address storage.IAddress
txs storage.ITx
state storage.IState
indexerName string
}
func NewAddressHandler(
address storage.IAddress,
txs storage.ITx,
state storage.IState,
indexerName string,
) *AddressHandler {
return &AddressHandler{
address: address,
txs: txs,
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(48) maxlength(48)
// @Produce json
// @Success 200 {object} responses.Address
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/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 := handleError(c, err, handler.address); err != nil {
return err
}
return c.JSON(http.StatusOK, responses.NewAddress(address))
}
// 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)
// @Produce json
// @Success 200 {array} responses.Address
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/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: int(req.Limit),
Offset: int(req.Offset),
Sort: pgSort(req.Sort),
}
address, err := handler.address.ListWithBalance(c.Request().Context(), fltrs)
if err := handleError(c, err, handler.address); err != nil {
return err
}
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 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 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)
// @Produce json
// @Success 200 {array} responses.Tx
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/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)
}
address, err := handler.address.ByHash(c.Request().Context(), hash)
if err := handleError(c, err, handler.address); err != nil {
return err
}
fltrs := storage.TxFilter{
Limit: int(req.Limit),
Offset: int(req.Offset),
Sort: pgSort(req.Sort),
Status: req.Status,
Height: req.Height,
}
if req.From > 0 {
fltrs.TimeFrom = time.Unix(req.From, 0).UTC()
}
if req.To > 0 {
fltrs.TimeTo = time.Unix(req.To, 0).UTC()
}
txs, err := handler.txs.ByAddress(c.Request().Context(), address.Id, fltrs)
if err := handleError(c, err, handler.txs); err != nil {
return err
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[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 /v1/address/count [get]
func (handler *AddressHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err := handleError(c, err, handler.state); err != nil {
return err
}
return c.JSON(http.StatusOK, state.TotalAccounts)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"github.com/dipdup-io/celestia-indexer/pkg/types"
"net/http"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-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
state storage.IState
indexerName string
}
func NewBlockHandler(
block storage.IBlock,
blockStats storage.IBlockStats,
events storage.IEvent,
namespace storage.INamespace,
state storage.IState,
indexerName string,
) *BlockHandler {
return &BlockHandler{
block: block,
blockStats: blockStats,
events: events,
namespace: namespace,
state: state,
indexerName: indexerName,
}
}
type getBlockByHeightRequest struct {
Height types.Level `param:"height" validate:"required,min=0"`
}
type getBlockRequest struct {
Height types.Level `param:"height" validate:"required,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 /v1/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 := handleError(c, err, handler.block); err != nil {
return err
}
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 /v1/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 := handleError(c, err, handler.block); err != nil {
return err
}
response := make([]responses.Block, len(blocks))
for i := range blocks {
response[i] = responses.NewBlock(*blocks[i], req.Stats)
}
return returnArray(c, response)
}
// 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)
// @Produce json
// @Success 200 {array} responses.Event
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/block/{height}/events [get]
func (handler *BlockHandler) GetEvents(c echo.Context) error {
req, err := bindAndValidate[getBlockByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
events, err := handler.events.ByBlock(c.Request().Context(), req.Height)
if err := handleError(c, err, handler.events); err != nil {
return err
}
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 /v1/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 := handleError(c, err, handler.events); err != nil {
return err
}
return c.JSON(http.StatusOK, responses.NewBlockStats(stats))
}
// GetNamespaces godoc
//
// @Summary Get namesapces affected in the block
// @Description Get namesapces affected in the block
// @Tags block
// @ID get-block-namespaces
// @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.NamespaceMessage
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/block/{height}/namespace [get]
func (handler *BlockHandler) GetNamespaces(c echo.Context) error {
req, err := bindAndValidate[namespacesByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
messages, err := handler.namespace.MessagesByHeight(c.Request().Context(), req.Height, int(req.Limit), int(req.Offset))
if err := handleError(c, err, handler.events); err != nil {
return err
}
response := make([]responses.NamespaceMessage, len(messages))
for i := range response {
msg, err := responses.NewNamespaceMessage(messages[i])
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
response[i] = msg
}
return c.JSON(http.StatusOK, response)
}
// GetNamespacesCount godoc
//
// @Summary Get count of affected in the block namespaces
// @Description Get count of affected in the block namespaces
// @Tags block
// @ID get-block-namespaces-count
// @Param height path integer true "Block height" minimum(1)
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /v1/block/{height}/namespace/count [get]
func (handler *BlockHandler) GetNamespacesCount(c echo.Context) error {
req, err := bindAndValidate[getBlockByHeightRequest](c)
if err != nil {
return badRequestError(c, err)
}
count, err := handler.namespace.CountMessagesByHeight(c.Request().Context(), req.Height)
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
return c.JSON(http.StatusOK, count)
}
// 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 /v1/block/count [get]
func (handler *BlockHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err := handleError(c, err, handler.state); err != nil {
return err
}
return c.JSON(http.StatusOK, state.LastHeight+1) // + genesis block
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type ConstantHandler struct {
constants storage.IConstant
denomMetadata storage.IDenomMetadata
address storage.IAddress
}
func NewConstantHandler(constants storage.IConstant, denomMetadata storage.IDenomMetadata, address storage.IAddress) *ConstantHandler {
return &ConstantHandler{
constants: constants,
denomMetadata: denomMetadata,
}
}
// 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 /v1/constants [get]
func (handler *ConstantHandler) Get(c echo.Context) error {
consts, err := handler.constants.All(c.Request().Context())
if err := handleError(c, err, handler.address); err != nil {
return err
}
dm, err := handler.denomMetadata.All(c.Request().Context())
if err := handleError(c, err, handler.address); err != nil {
return err
}
return c.JSON(http.StatusOK, responses.NewConstants(consts, dm))
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
var (
errInvalidNamespaceLength = errors.New("invalid namespace: should be 29 bytes length")
errInvalidHashLength = errors.New("invalid hash: should be 32 bytes length")
errInvalidAddress = errors.New("invalid address")
)
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 {
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 noRows.IsNoRows(err) {
return c.NoContent(http.StatusNoContent)
}
if errors.Is(err, errInvalidAddress) {
return badRequestError(c, err)
}
return internalServerError(c, err)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/base64"
"encoding/hex"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"net/http"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/pkg/node"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type NamespaceHandler struct {
namespace storage.INamespace
blob node.DalApi
state storage.IState
indexerName string
}
func NewNamespaceHandler(
namespace storage.INamespace,
state storage.IState,
indexerName string,
blob node.DalApi,
) *NamespaceHandler {
return &NamespaceHandler{
namespace: namespace,
blob: blob,
state: state,
indexerName: indexerName,
}
}
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 /v1/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 := handleError(c, err, handler.namespace); err != nil {
return err
}
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"`
}
// 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 /v1/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)
}
if len(hash) != 29 {
return badRequestError(c, errors.Wrapf(errInvalidNamespaceLength, "got %d", len(hash)))
}
version := hash[0]
namespaceId := hash[1:]
namespace, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, version)
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
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 /v1/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 := handleError(c, err, handler.namespace); err != nil {
return err
}
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" Enums(asc, desc)
// @Produce json
// @Success 200 {array} responses.Namespace
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/namespace [get]
func (handler *NamespaceHandler) List(c echo.Context) error {
req, err := bindAndValidate[limitOffsetPagination](c)
if err != nil {
return badRequestError(c, err)
}
req.SetDefault()
namespace, err := handler.namespace.List(c.Request().Context(), req.Limit, req.Offset, pgSort(req.Sort))
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
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 /v1/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 getBlobRequest struct {
Hash string `param:"hash" validate:"required,base64"`
Height types.Level `param:"height" validation:"required,min=1"`
Commitment string `param:"commitment" validate:"required,base64"`
}
// GetBlob godoc
//
// @Summary Get namespace blob by commitment on height
// @Description Returns blob
// @Tags namespace
// @ID get-namespace-blob
// @Param hash path string true "Base64-encoded namespace id and version"
// @Param height path integer true "Block heigth" minimum(1)
// @Param commitment path string true "Blob commitment"
// @Produce json
// @Success 200 {object} responses.Blob
// @Failure 400 {object} Error
// @Router /v1/namespace_by_hash/{hash}/{height}/{commitment} [get]
func (handler *NamespaceHandler) GetBlob(c echo.Context) error {
req, err := bindAndValidate[getBlobRequest](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)
}
return c.JSON(http.StatusOK, blob)
}
type getNamespaceMessages struct {
Id string `param:"id" validate:"required,hexadecimal,len=56"`
Version byte `param:"version"`
Limit uint64 `query:"limit" validate:"omitempty,min=1,max=100"`
Offset uint64 `query:"offset" validate:"omitempty,min=0"`
}
// 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 /v1/namespace/{id}/{version}/messages [get]
func (handler *NamespaceHandler) GetMessages(c echo.Context) error {
req, err := bindAndValidate[getNamespaceMessages](c)
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 := handleError(c, err, handler.namespace); err != nil {
return err
}
messages, err := handler.namespace.Messages(c.Request().Context(), ns.Id, int(req.Limit), int(req.Offset))
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
response := make([]responses.NamespaceMessage, len(messages))
for i := range response {
msg, err := responses.NewNamespaceMessage(messages[i])
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
response[i] = msg
}
return returnArray(c, response)
}
// GetActive godoc
//
// @Summary Get last used namespace
// @Description Get last used namespace
// @Tags namespace
// @ID get-namespace-active
// @Produce json
// @Success 200 {array} responses.ActiveNamespace
// @Failure 500 {object} Error
// @Router /v1/namespace/active [get]
func (handler *NamespaceHandler) GetActive(c echo.Context) error {
active, err := handler.namespace.Active(c.Request().Context(), 5)
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
response := make([]responses.ActiveNamespace, len(active))
for i := range response {
response[i] = responses.NewActiveNamespace(active[i])
}
return returnArray(c, response)
}
// Count godoc
//
// @Summary Get count of namespaces in network
// @Description Get count of namespaces in network
// @Tags namespace
// @ID get-namespace-count
// @Produce json
// @Success 200 {integer} uint64
// @Failure 500 {object} Error
// @Router /v1/namespace/count [get]
func (handler *NamespaceHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err := handleError(c, err, handler.state); err != nil {
return err
}
return c.JSON(http.StatusOK, state.TotalNamespaces)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"strings"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/labstack/echo/v4"
)
const (
asc = "asc"
desc = "desc"
)
type limitOffsetPagination struct {
Limit uint64 `json:"limit" param:"limit" query:"limit" validate:"omitempty,min=1,max=100"`
Offset uint64 `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
}
}
type addressListRequest 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"`
Balances *bool `query:"balances" validate:"omitempty"`
}
func (p *addressListRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
if p.Sort == "" {
p.Sort = asc
}
if p.Balances == nil {
b := true
p.Balances = &b
}
}
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 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"`
Height uint64 `query:"height" validate:"omitempty,min=1"`
Status StringArray `query:"status" validate:"omitempty,dive,status"`
MsgType StringArray `query:"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 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"`
Height uint64 `query:"height" validate:"omitempty,min=1"`
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 namespacesByHeightRequest struct {
Limit uint64 `query:"limit" validate:"omitempty,min=1,max=100"`
Offset uint64 `query:"offset" validate:"omitempty,min=0"`
Height pkgTypes.Level `param:"height" validate:"required,min=1"`
}
func (p *namespacesByHeightRequest) SetDefault() {
if p.Limit == 0 {
p.Limit = 10
}
}
// SPDX-FileCopyrightText: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
)
// 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"`
}
func NewAddress(addr storage.Address) Address {
return Address{
Id: addr.Id,
Height: addr.Height,
LastHeight: addr.LastHeight,
Hash: addr.Address,
Balance: Balance{
Currency: addr.Balance.Currency,
Value: addr.Balance.Total.String(),
},
}
}
func (Address) SearchType() string {
return "address"
}
// Balance info
//
// @Description Balance of address information
type Balance struct {
Currency string `example:"utia" json:"currency" swaggertype:"string"`
Value string `example:"10000000000" json:"value" swaggertype:"string"`
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"strconv"
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/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"`
ProposerAddress pkgTypes.Hex `example:"652452A670018D629CC116E510BA88C1CABE061336661B1F3D206D248BD558AF" json:"proposer_address" swaggertype:"string"`
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,
ProposerAddress: block.ProposerAddress,
MessageTypes: block.MessageTypes.Names(),
}
if withStats {
result.Stats = NewBlockStats(block.Stats)
}
return result
}
func (Block) SearchType() string {
return "block"
}
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"`
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"`
BlockTime uint64 `example:"12354" json:"block_time" swaggertype:"integer"`
MessagesCounts map[types.MsgType]int64 `example:"{MsgPayForBlobs:10,MsgUnjail:1}" json:"messages_counts" swaggertype:"string"`
}
func NewBlockStats(stats storage.BlockStats) *BlockStats {
return &BlockStats{
TxCount: stats.TxCount,
EventsCount: stats.EventsCount,
BlobsSize: stats.BlobsSize,
Fee: stats.Fee.String(),
SupplyChange: stats.SupplyChange.String(),
InflationRate: stats.InflationRate.String(),
BlockTime: stats.BlockTime,
MessagesCounts: stats.MessagesCounts,
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/goccy/go-json"
)
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 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] = consts[i].Value
} else {
response.Module[string(consts[i].Module)] = Params{
consts[i].Name: 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
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/dipdup-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"`
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"`
}
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,
Data: msg.Data,
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"github.com/dipdup-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"`
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"`
Reserved bool `example:"true" json:"reserved"`
PfbCount int64 `example:"12" format:"integer" json:"pfb_count" swaggertype:"integer"`
}
func NewNamespace(ns storage.Namespace) Namespace {
return Namespace{
ID: ns.Id,
Size: ns.Size,
Version: ns.Version,
NamespaceID: hex.EncodeToString(ns.NamespaceID),
Hash: ns.Hash(),
Reserved: ns.Reserved,
PfbCount: ns.PfbCount,
}
}
func (Namespace) SearchType() string {
return "namespace"
}
type ActiveNamespace struct {
ID uint64 `example:"321" format:"integer" json:"id" swaggertype:"integer"`
Size int64 `example:"12345" format:"integer" json:"size" 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"`
Reserved bool `example:"true" json:"reserved"`
PfbCount int64 `example:"12" format:"integer" json:"pfb_count" 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"`
}
func NewActiveNamespace(ns storage.ActiveNamespace) ActiveNamespace {
return ActiveNamespace{
ID: ns.Id,
Size: ns.Size,
Version: ns.Version,
NamespaceID: hex.EncodeToString(ns.NamespaceID),
Hash: ns.Hash(),
Reserved: ns.Reserved,
PfbCount: ns.PfbCount,
Height: ns.Height,
Time: ns.Time,
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"time"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
type Searchable interface {
Block | Address | Namespace | Tx
SearchType() string
}
type SearchResponse[T Searchable] struct {
// Search result. Can be one of folowwing types: Block, Address, Namespace, Tx
Result T `json:"result" swaggertype:"object"`
// Result type which is in the result. Can be 'block', 'address', 'namespace', 'tx'
Type string `json:"type"`
} // @name SearchResponse
func NewSearchResponse[T Searchable](val T) SearchResponse[T] {
return SearchResponse[T]{
Result: val,
Type: val.SearchType(),
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"github.com/dipdup-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"`
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"`
TotalSupply string `example:"312" format:"string" json:"total_supply" swaggertype:"string"`
}
func NewState(state storage.State) State {
return State{
Id: state.Id,
Name: state.Name,
LastHeight: state.LastHeight,
LastHash: hex.EncodeToString(state.LastHash),
LastTime: state.LastTime,
TotalTx: state.TotalTx,
TotalAccounts: state.TotalAccounts,
TotalFee: state.TotalFee.String(),
TotalBlobsSize: state.TotalBlobsSize,
TotalSupply: state.TotalSupply.String(),
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package responses
import (
"encoding/hex"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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"`
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),
}
for i := range tx.Messages {
result.Messages = append(result.Messages, NewMessage(tx.Messages[i]))
}
return result
}
func (Tx) SearchType() string {
return "tx"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/base64"
"encoding/hex"
"net/http"
"regexp"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
)
type SearchHandler struct {
address storage.IAddress
block storage.IBlock
namespace storage.INamespace
tx storage.ITx
}
func NewSearchHandler(
address storage.IAddress,
block storage.IBlock,
namespace storage.INamespace,
tx storage.ITx,
) SearchHandler {
return SearchHandler{
address: address,
block: block,
namespace: namespace,
tx: tx,
}
}
type searchRequest struct {
Search string `query:"query" validate:"required"`
}
var (
hashRegexp = regexp.MustCompile("[a-fA-f0-9]{64}")
namespaceRegexp = regexp.MustCompile("[a-fA-f0-9]{58}")
base64Regexp = regexp.MustCompile("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$")
)
// Get godoc
//
// @Summary Search by hash
// @Description.markdown search
// @Tags search
// @ID search
// @Param query query string true "Search string"
// @Produce json
// @Success 200 {object} responses.SearchResponse[responses.Searchable]
// @Success 204
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/search [get]
func (handler SearchHandler) Search(c echo.Context) error {
req, err := bindAndValidate[searchRequest](c)
if err != nil {
return badRequestError(c, err)
}
switch {
case isAddress(req.Search):
if err := handler.searchAddress(c, req.Search); err != nil {
return internalServerError(c, err)
}
case hashRegexp.MatchString(req.Search):
if err := handler.searchHash(c, req.Search); err != nil {
return internalServerError(c, err)
}
case namespaceRegexp.MatchString(req.Search):
if err := handler.searchNamespaceById(c, req.Search); err != nil {
return internalServerError(c, err)
}
case base64Regexp.MatchString(req.Search):
if err := handler.searchNamespaceByBase64(c, req.Search); err != nil {
return internalServerError(c, err)
}
}
return c.NoContent(http.StatusNoContent)
}
func (handler SearchHandler) searchAddress(c echo.Context, search string) error {
_, hash, err := types.Address(search).Decode()
if err != nil {
return badRequestError(c, err)
}
address, err := handler.address.ByHash(c.Request().Context(), hash)
if err := handleError(c, err, handler.address); err != nil {
return err
}
return c.JSON(http.StatusOK, responses.NewSearchResponse(responses.NewAddress(address)))
}
func (handler SearchHandler) searchHash(c echo.Context, search string) error {
data, err := hex.DecodeString(search)
if err != nil {
return badRequestError(c, err)
}
if len(data) != 32 {
return badRequestError(c, errors.Wrapf(errInvalidHashLength, "got %d", len(data)))
}
tx, err := handler.tx.ByHash(c.Request().Context(), data)
if err == nil {
return c.JSON(http.StatusOK, responses.NewSearchResponse(responses.NewTx(tx)))
}
if !handler.tx.IsNoRows(err) {
return internalServerError(c, err)
}
block, err := handler.block.ByHash(c.Request().Context(), data)
if err == nil {
return c.JSON(http.StatusOK, responses.NewSearchResponse(responses.NewBlock(block, false)))
}
if !handler.tx.IsNoRows(err) {
return internalServerError(c, err)
}
return c.NoContent(http.StatusNoContent)
}
func (handler SearchHandler) searchNamespaceById(c echo.Context, search string) error {
data, err := hex.DecodeString(search)
if err != nil {
return badRequestError(c, err)
}
if len(data) != 29 {
return badRequestError(c, errors.Wrapf(errInvalidNamespaceLength, "got %d", len(data)))
}
return handler.getNamespace(c, data)
}
func (handler SearchHandler) searchNamespaceByBase64(c echo.Context, search string) error {
data, err := base64.StdEncoding.DecodeString(search)
if err != nil {
return badRequestError(c, err)
}
if len(data) != 29 {
return badRequestError(c, errors.Wrapf(errInvalidNamespaceLength, "got %d", len(data)))
}
return handler.getNamespace(c, data)
}
func (handler SearchHandler) getNamespace(c echo.Context, data []byte) error {
version := data[0]
namespaceId := data[1:]
ns, err := handler.namespace.ByNamespaceIdAndVersion(c.Request().Context(), namespaceId, version)
if err := handleError(c, err, handler.namespace); err != nil {
return err
}
response := responses.NewNamespace(ns)
return c.JSON(http.StatusOK, responses.NewSearchResponse(response))
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/labstack/echo/v4"
)
type StateHandler struct {
state storage.IState
}
func NewStateHandler(state storage.IState) *StateHandler {
return &StateHandler{
state: state,
}
}
// 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 /v1/head [get]
func (sh *StateHandler) Head(c echo.Context) error {
state, err := sh.state.List(c.Request().Context(), 1, 0, sdk.SortOrderAsc)
if err != nil {
return internalServerError(c, err)
}
if len(state) == 0 {
return c.NoContent(http.StatusNoContent)
}
return c.JSON(http.StatusOK, responses.NewState(*state[0]))
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/labstack/echo/v4"
)
type StatsHandler struct {
repo storage.IStats
}
func NewStatsHandler(repo storage.IStats) StatsHandler {
return StatsHandler{
repo: repo,
}
}
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 /v1/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 {
return internalServerError(c, err)
}
return c.JSON(http.StatusOK, summary)
}
type histogramRequest struct {
Table string `example:"block" param:"table" swaggertype:"string" validate:"required,oneof=block tx event message"`
Function string `example:"count" param:"function" swaggertype:"string" validate:"required,oneof=avg sum min max count"`
Timeframe string `example:"hour" param:"timeframe" swaggertype:"string" validate:"required,oneof=hour day week month year"`
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"`
}
// Histogram godoc
//
// @Summary Get histogram
// @Description.markdown histogram
// @Tags stats
// @ID stats-histogram
// @Param table path string true "Table name" Enums(block, tx, event, message)
// @Param function path string true "Function name" Enums(min, max, avg, sum, count)
// @Param timeframe path string true "Timeframe" Enums(hour, day, week, month, year)
// @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 {array} responses.HistogramItem
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/stats/histogram/{table}/{function}/{timeframe} [get]
func (sh StatsHandler) Histogram(c echo.Context) error {
req, err := bindAndValidate[histogramRequest](c)
if err != nil {
return badRequestError(c, err)
}
var (
histogram []storage.HistogramItem
countRequest = storage.CountRequest{
Table: req.Table,
From: req.From,
To: req.To,
}
)
if req.Function == "count" {
histogram, err = sh.repo.HistogramCount(c.Request().Context(), storage.HistogramCountRequest{
CountRequest: countRequest,
Timeframe: storage.Timeframe(req.Timeframe),
})
} else {
histogram, err = sh.repo.Histogram(c.Request().Context(), storage.HistogramRequest{
SummaryRequest: storage.SummaryRequest{
CountRequest: countRequest,
Function: req.Function,
Column: req.Column,
},
Timeframe: storage.Timeframe(req.Timeframe),
})
}
if err != nil {
return internalServerError(c, err)
}
response := make([]responses.HistogramItem, len(histogram))
for i := range histogram {
response[i] = responses.NewHistogramItem(histogram[i])
}
return c.JSON(http.StatusOK, response)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"encoding/hex"
"net/http"
"time"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/labstack/echo/v4"
)
type TxHandler struct {
tx storage.ITx
events storage.IEvent
messages storage.IMessage
state storage.IState
indexerName string
}
func NewTxHandler(
tx storage.ITx,
events storage.IEvent,
messages storage.IMessage,
state storage.IState,
indexerName string,
) *TxHandler {
return &TxHandler{
tx: tx,
events: events,
messages: messages,
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 /v1/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 := handleError(c, err, handler.tx); err != nil {
return err
}
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 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 /v1/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: int(req.Limit),
Offset: int(req.Offset),
Sort: pgSort(req.Sort),
Status: req.Status,
Height: req.Height,
MessageTypes: 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.SetBit(storageTypes.MsgType(req.MsgType[i]))
}
txs, err := handler.tx.Filter(c.Request().Context(), fltrs)
if err := handleError(c, err, handler.tx); err != nil {
return err
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[i])
}
return returnArray(c, response)
}
// 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)
// @Produce json
// @Success 200 {array} responses.Event
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/tx/{hash}/events [get]
func (handler *TxHandler) GetEvents(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 := handleError(c, err, handler.tx); err != nil {
return err
}
events, err := handler.events.ByTxId(c.Request().Context(), tx.Id)
if err := handleError(c, err, handler.tx); err != nil {
return err
}
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)
// @Produce json
// @Success 200 {array} responses.Message
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/tx/{hash}/messages [get]
func (handler *TxHandler) GetMessages(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 := handleError(c, err, handler.tx); err != nil {
return err
}
messages, err := handler.messages.ByTxId(c.Request().Context(), tx.Id)
if err := handleError(c, err, handler.tx); err != nil {
return err
}
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 /v1/tx/count [get]
func (handler *TxHandler) Count(c echo.Context) error {
state, err := handler.state.ByName(c.Request().Context(), handler.indexerName)
if err := handleError(c, err, handler.state); err != nil {
return err
}
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" mininum(1)
// @Produce json
// @Success 200 {array} responses.Tx
// @Failure 400 {object} Error
// @Failure 500 {object} Error
// @Router /v1/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(), int(req.Limit), int(req.Offset), pgSort(req.Sort))
if err := handleError(c, err, handler.tx); err != nil {
return err
}
response := make([]responses.Tx, len(txs))
for i := range txs {
response[i] = responses.NewTx(txs[i])
}
return returnArray(c, response)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handler
import (
"net/http"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"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)
}
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 {
switch len(address) {
case 47:
return validateAddress(address, pkgTypes.AddressPrefixCelestia)
case 54:
return validateAddress(address, pkgTypes.AddressPrefixValoper)
default:
return false
}
}
func validateAddress(address string, wantPrefix string) bool {
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())
}
}
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
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
sdkSync "github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/workerpool"
"github.com/lib/pq"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type identifiable[M any] interface {
GetById(ctx context.Context, id uint64) (M, error)
}
type processor[I, M any] func(ctx context.Context, payload string, repo identifiable[I]) (M, error)
type Channel[I, M any] struct {
storageChannelName string
clients *sdkSync.Map[uint64, client]
listener storage.Listener
log zerolog.Logger
processor processor[I, M]
filters Filterable[M]
repo identifiable[I]
g workerpool.Group
}
func NewChannel[I, M any](storageChannelName string, processor processor[I, M], repo identifiable[I], filters Filterable[M]) *Channel[I, M] {
return &Channel[I, M]{
storageChannelName: storageChannelName,
clients: sdkSync.NewMap[uint64, client](),
processor: processor,
filters: filters,
repo: repo,
log: log.With().Str("channel", storageChannelName).Logger(),
g: workerpool.NewGroup(),
}
}
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]) String() string {
return channel.storageChannelName
}
func (channel *Channel[I, M]) Start(ctx context.Context, factory storage.ListenerFactory) {
if channel.processor == nil {
channel.log.Panic().Msg("nil processor in channel")
return
}
if channel.filters == nil {
channel.log.Panic().Msg("nil filters in channel")
return
}
if factory == nil {
channel.log.Panic().Msg("nil listener factory in channel")
return
}
channel.listener = factory.CreateListener()
if err := channel.listener.Subscribe(ctx, channel.storageChannelName); err != nil {
channel.log.Panic().Err(err).Msg("subscribe on storage channel")
return
}
channel.g.GoCtx(ctx, channel.waitMessage)
}
func (channel *Channel[I, M]) waitMessage(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case msg, ok := <-channel.listener.Listen():
if !ok {
return
}
if msg.Channel != channel.storageChannelName {
channel.log.Error().
Str("msg", msg.Channel).
Msg("unexpected channel message")
continue
}
if channel.clients.Len() == 0 {
continue
}
if err := channel.processMessage(ctx, msg); err != nil {
log.Err(err).
Str("msg", msg.Channel).
Str("payload", msg.Extra).
Msg("processing channel message")
}
}
}
}
func (channel *Channel[I, M]) processMessage(ctx context.Context, msg *pq.Notification) error {
log.Trace().
Str("channel", msg.Channel).
Str("payload", msg.Extra).
Msg("message received")
notification, err := channel.processor(ctx, msg.Extra, channel.repo)
if err != nil {
return errors.Wrap(err, "processing channel message")
}
if err := channel.clients.Range(func(_ uint64, value client) (error, bool) {
if channel.filters.Filter(value, notification) {
value.Notify(notification)
}
return nil, false
}); err != nil {
return errors.Wrap(err, "write message to client")
}
return nil
}
func (channel *Channel[I, M]) Close() error {
channel.g.Wait()
if channel.listener != nil {
if err := channel.listener.Close(); err != nil {
return err
}
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
"io"
"net"
"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, sub *Client, 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 becuase otherwise it will send a new Ping before getting response
pingInterval = (pongWait * 9) / 10
)
type Client struct {
id uint64
manager *Manager
filters *Filters
ch chan any
g workerpool.Group
}
func newClient(id uint64, manager *Manager) *Client {
return &Client{
id: id,
manager: manager,
ch: make(chan any, 1024),
g: workerpool.NewGroup(),
}
}
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 ChannelTx:
if c.filters.tx == nil {
c.filters.tx = newTxFilters()
}
var fltr TransactionFilters
if err := json.Unmarshal(msg.Filters, &fltr); err != nil {
return err
}
if err := c.filters.tx.Fill(fltr); err != nil {
return err
}
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 ChannelTx:
c.filters.tx = nil
default:
return errors.Wrap(ErrUnknownChannel, msg.Channel)
}
return nil
}
func (c *Client) Notify(msg any) {
c.ch <- msg
}
func (c *Client) Close() error {
c.g.Wait()
close(c.ch)
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, sub *Client, 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(ctx, 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):
c.manager.RemoveClientFromChannel(ChannelHead, c)
c.manager.RemoveClientFromChannel(ChannelTx, c)
return
}
log.Errorf("read websocket message: %s", err.Error())
}
}
}
}
func (c *Client) read(ctx context.Context, ws *websocket.Conn) error {
var msg Message
if err := ws.ReadJSON(&msg); err != nil {
return err
}
switch msg.Method {
case MethodSubscribe:
return c.handleSubscribeMessage(ctx, msg)
case MethodUnsubscribe:
return c.handleUnsubscribeMessage(ctx, msg)
default:
return errors.Wrap(ErrUnknownMethod, msg.Method)
}
}
func (c *Client) handleSubscribeMessage(ctx context.Context, 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
}
c.manager.AddClientToChannel(subscribeMsg.Channel, c)
return nil
}
func (c *Client) handleUnsubscribeMessage(ctx context.Context, 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
}
c.manager.RemoveClientFromChannel(unsubscribeMsg.Channel, c)
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/pkg/errors"
)
type Filterable[M any] interface {
Filter(c client, msg M) bool
}
type HeadFilter struct{}
func (hf HeadFilter) Filter(c client, msg *responses.Block) bool {
if msg == nil {
return false
}
fltrs := c.Filters()
if fltrs == nil {
return false
}
return fltrs.head
}
type TxFilter struct{}
func (hf TxFilter) Filter(c client, msg *responses.Tx) bool {
if msg == nil {
return false
}
fltrs := c.Filters()
if fltrs == nil || fltrs.tx == nil {
return false
}
fltr := fltrs.tx
if len(fltr.status) > 0 {
if _, ok := fltr.status[msg.Status]; !ok {
return false
}
}
if !fltr.msgs.Empty() {
if !fltr.msgs.HasOne(msg.MsgTypeMask) {
return false
}
}
return true
}
type Filters struct {
head bool
tx *txFilters
}
func newFilters() *Filters {
return &Filters{
tx: newTxFilters(),
}
}
type txFilters struct {
status map[types.Status]struct{}
msgs types.MsgTypeBits
}
func newTxFilters() *txFilters {
return &txFilters{
status: make(map[types.Status]struct{}, 2),
msgs: types.NewMsgTypeBitMask(),
}
}
func (f *txFilters) Fill(msg TransactionFilters) error {
for i := range msg.Status {
status, err := types.ParseStatus(msg.Status[i])
if err != nil {
return errors.Wrapf(ErrUnavailableFilter, "status %s", msg.Status[i])
}
f.status[status] = struct{}{}
}
for i := range msg.Messages {
f.msgs.SetBit(types.MsgType(msg.Messages[i]))
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
"net/http"
"sync/atomic"
sdkSync "github.com/dipdup-net/indexer-sdk/pkg/sync"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-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]
head *Channel[storage.Block, *responses.Block]
tx *Channel[storage.Tx, *responses.Tx]
factory storage.ListenerFactory
}
func NewManager(factory storage.ListenerFactory, blockRepo storage.IBlock, txRepo storage.ITx) *Manager {
manager := &Manager{
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
clientId: new(atomic.Uint64),
clients: sdkSync.NewMap[uint64, *Client](),
factory: factory,
}
manager.head = NewChannel[storage.Block, *responses.Block](
storage.ChannelHead,
HeadProcessor,
newBlockRepo(blockRepo),
HeadFilter{},
)
manager.tx = NewChannel[storage.Tx, *responses.Tx](
storage.ChannelTx,
TxProcessor,
newTxRepo(txRepo),
TxFilter{},
)
return manager
}
// Handle godoc
//
// @Summary Websocket API
// @Description.markdown websocket
// @Tags websocket
// @ID websocket
// @Produce json
// @Router /v1/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)
manager.clients.Set(sId, sub)
ctx, cancel := context.WithCancel(c.Request().Context())
sub.WriteMessages(ctx, ws, c.Logger())
sub.ReadMessages(ctx, ws, sub, 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.head.Start(ctx, manager.factory)
manager.tx.Start(ctx, manager.factory)
}
func (manager *Manager) Close() error {
if err := manager.clients.Range(func(_ uint64, value *Client) (error, bool) {
if err := value.Close(); err != nil {
return err, false
}
return nil, false
}); err != nil {
return err
}
if err := manager.head.Close(); err != nil {
return err
}
if err := manager.tx.Close(); err != nil {
return err
}
return nil
}
func (manager *Manager) AddClientToChannel(channel string, client *Client) {
switch channel {
case ChannelHead:
manager.head.AddClient(client)
case ChannelTx:
manager.tx.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 ChannelTx:
manager.tx.RemoveClient(client.id)
default:
log.Error().Str("channel", channel).Msg("unknown channel name")
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package websocket
import (
"context"
"strconv"
"github.com/dipdup-io/celestia-indexer/cmd/api/handler/responses"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/pkg/errors"
)
type blockRepo struct {
repo storage.IBlock
}
func newBlockRepo(repo storage.IBlock) blockRepo {
return blockRepo{repo}
}
func (block blockRepo) GetById(ctx context.Context, id uint64) (storage.Block, error) {
b, err := block.repo.ByIdWithRelations(ctx, id)
if err != nil {
return storage.Block{}, err
}
return b, nil
}
func HeadProcessor(ctx context.Context, payload string, repo identifiable[storage.Block]) (*responses.Block, error) {
blockId, err := strconv.ParseUint(payload, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "parse block id")
}
b, err := repo.GetById(ctx, blockId)
if err != nil {
return nil, errors.Wrap(err, "receive block by id")
}
block := responses.NewBlock(b, true)
return &block, nil
}
type txRepo struct {
repo storage.ITx
}
func newTxRepo(repo storage.ITx) txRepo {
return txRepo{repo}
}
func (tx txRepo) GetById(ctx context.Context, id uint64) (storage.Tx, error) {
return tx.repo.ByIdWithRelations(ctx, id)
}
func TxProcessor(ctx context.Context, payload string, repo identifiable[storage.Tx]) (*responses.Tx, error) {
txId, err := strconv.ParseUint(payload, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "parse tx id")
}
tx, err := repo.GetById(ctx, txId)
if err != nil {
return nil, errors.Wrap(err, "receive transaction by id")
}
response := responses.NewTx(tx)
return &response, nil
}
// SPDX-FileCopyrightText: 2023 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: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/uptrace/bun"
)
type AddressListFilter struct {
Limit int
Offset int
Sort storage.SortOrder
}
//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, fltrs AddressListFilter) ([]Address, 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"`
}
// TableName -
func (Address) TableName() string {
return "address"
}
func (address Address) String() string {
return address.Address
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"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"`
Total decimal.Decimal `bun:"total,type:numeric" comment:"Total account balance"`
}
func (Balance) TableName() string {
return "balance"
}
func (b Balance) IsEmpty() bool {
return b.Currency == "" && b.Total.IsZero()
}
func EmptyBalance() Balance {
return Balance{
Total: decimal.Zero,
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-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)
ListWithStats(ctx context.Context, limit, offset uint64, order storage.SortOrder) ([]*Block, 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:int8" 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"`
ProposerAddress pkgTypes.Hex `bun:"proposer_address" comment:"Proposer address"`
ChainId string `bun:"-"` // internal field for filling state
Addresses []Address `bun:"-"` // internal field for balance passing
Txs []Tx `bun:"rel:has-many"`
Events []Event `bun:"rel:has-many"`
Stats BlockStats `bun:"rel:has-one,join:height=height"`
}
// TableName -
func (Block) TableName() string {
return "block"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
"time"
pkgTypes "github.com/dipdup-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)
}
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"`
BlockTime uint64 `bun:"block_time" comment:"Time in milliseconds between current and previous block" stats:"func:min max avg sum"`
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"`
MessagesCounts map[types.MsgType]int64 `bun:"-"`
}
func (BlockStats) TableName() string {
return "block_stats"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-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"
}
// SPDX-FileCopyrightText: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/goccy/go-json"
"github.com/dipdup-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 IEvent interface {
storage.Table[*Event]
ByTxId(ctx context.Context, txId uint64) ([]Event, error)
ByBlock(ctx context.Context, height pkgTypes.Level) ([]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,type:jsonb" comment:"Event data"`
}
// TableName -
func (Event) TableName() string {
return "event"
}
func (e Event) Columns() []string {
return []string{
"height", "time", "position", "type",
"tx_id", "data",
}
}
func (e Event) Flat() []any {
data := []any{
e.Height, e.Time, e.Position, e.Type, e.TxId,
}
if len(data) > 0 {
raw, err := json.MarshalWithOption(e.Data, json.UnorderedMap(), json.DisableNormalizeUTF8())
if err == nil {
data = append(data, string(raw))
} else {
data = append(data, nil)
}
}
return data
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-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 IMessage interface {
storage.Table[*Message]
ByTxId(ctx context.Context, txId uint64) ([]Message, 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"`
Data map[string]any `bun:"data,type:jsonb" comment:"Message data"`
Namespace []Namespace `bun:"m2m:namespace_message,join:Message=Namespace"`
Validator *Validator `bun:"rel:belongs-to"`
Addresses []AddressWithType `bun:"-"`
}
// TableName -
func (Message) TableName() string {
return "message"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/dipdup-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"
}
type AddressWithType struct {
Address
Type types.MsgAddressType
}
// 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/dipdup-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) *IAddressByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockIAddress)(nil).ByHash), ctx, hash)
return &IAddressByHashCall{Call: call}
}
// IAddressByHashCall wrap *gomock.Call
type IAddressByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressByHashCall) Return(arg0 storage.Address, arg1 error) *IAddressByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressByHashCall) Do(f func(context.Context, []byte) (storage.Address, error)) *IAddressByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Address, error)) *IAddressByHashCall {
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) *IAddressCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIAddress)(nil).CursorList), ctx, id, limit, order, cmp)
return &IAddressCursorListCall{Call: call}
}
// IAddressCursorListCall wrap *gomock.Call
type IAddressCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressCursorListCall) Return(arg0 []*storage.Address, arg1 error) *IAddressCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Address, error)) *IAddressCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Address, error)) *IAddressCursorListCall {
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) *IAddressGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIAddress)(nil).GetByID), ctx, id)
return &IAddressGetByIDCall{Call: call}
}
// IAddressGetByIDCall wrap *gomock.Call
type IAddressGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressGetByIDCall) Return(arg0 *storage.Address, arg1 error) *IAddressGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressGetByIDCall) Do(f func(context.Context, uint64) (*storage.Address, error)) *IAddressGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Address, error)) *IAddressGetByIDCall {
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) *IAddressIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIAddress)(nil).IsNoRows), err)
return &IAddressIsNoRowsCall{Call: call}
}
// IAddressIsNoRowsCall wrap *gomock.Call
type IAddressIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressIsNoRowsCall) Return(arg0 bool) *IAddressIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressIsNoRowsCall) Do(f func(error) bool) *IAddressIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressIsNoRowsCall) DoAndReturn(f func(error) bool) *IAddressIsNoRowsCall {
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) *IAddressLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIAddress)(nil).LastID), ctx)
return &IAddressLastIDCall{Call: call}
}
// IAddressLastIDCall wrap *gomock.Call
type IAddressLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressLastIDCall) Return(arg0 uint64, arg1 error) *IAddressLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressLastIDCall) Do(f func(context.Context) (uint64, error)) *IAddressLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IAddressLastIDCall {
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) *IAddressListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIAddress)(nil).List), ctx, limit, offset, order)
return &IAddressListCall{Call: call}
}
// IAddressListCall wrap *gomock.Call
type IAddressListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressListCall) Return(arg0 []*storage.Address, arg1 error) *IAddressListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Address, error)) *IAddressListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Address, error)) *IAddressListCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ListWithBalance mocks base method.
func (m *MockIAddress) ListWithBalance(ctx context.Context, fltrs storage.AddressListFilter) ([]storage.Address, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListWithBalance", ctx, fltrs)
ret0, _ := ret[0].([]storage.Address)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListWithBalance indicates an expected call of ListWithBalance.
func (mr *MockIAddressMockRecorder) ListWithBalance(ctx, fltrs any) *IAddressListWithBalanceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithBalance", reflect.TypeOf((*MockIAddress)(nil).ListWithBalance), ctx, fltrs)
return &IAddressListWithBalanceCall{Call: call}
}
// IAddressListWithBalanceCall wrap *gomock.Call
type IAddressListWithBalanceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressListWithBalanceCall) Return(arg0 []storage.Address, arg1 error) *IAddressListWithBalanceCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressListWithBalanceCall) Do(f func(context.Context, storage.AddressListFilter) ([]storage.Address, error)) *IAddressListWithBalanceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressListWithBalanceCall) DoAndReturn(f func(context.Context, storage.AddressListFilter) ([]storage.Address, error)) *IAddressListWithBalanceCall {
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) *IAddressSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIAddress)(nil).Save), ctx, m)
return &IAddressSaveCall{Call: call}
}
// IAddressSaveCall wrap *gomock.Call
type IAddressSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressSaveCall) Return(arg0 error) *IAddressSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressSaveCall) Do(f func(context.Context, *storage.Address) error) *IAddressSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressSaveCall) DoAndReturn(f func(context.Context, *storage.Address) error) *IAddressSaveCall {
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) *IAddressUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIAddress)(nil).Update), ctx, m)
return &IAddressUpdateCall{Call: call}
}
// IAddressUpdateCall wrap *gomock.Call
type IAddressUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IAddressUpdateCall) Return(arg0 error) *IAddressUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IAddressUpdateCall) Do(f func(context.Context, *storage.Address) error) *IAddressUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IAddressUpdateCall) DoAndReturn(f func(context.Context, *storage.Address) error) *IAddressUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-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) *IBalanceCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBalance)(nil).CursorList), ctx, id, limit, order, cmp)
return &IBalanceCursorListCall{Call: call}
}
// IBalanceCursorListCall wrap *gomock.Call
type IBalanceCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceCursorListCall) Return(arg0 []*storage.Balance, arg1 error) *IBalanceCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Balance, error)) *IBalanceCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Balance, error)) *IBalanceCursorListCall {
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) *IBalanceGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBalance)(nil).GetByID), ctx, id)
return &IBalanceGetByIDCall{Call: call}
}
// IBalanceGetByIDCall wrap *gomock.Call
type IBalanceGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceGetByIDCall) Return(arg0 *storage.Balance, arg1 error) *IBalanceGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceGetByIDCall) Do(f func(context.Context, uint64) (*storage.Balance, error)) *IBalanceGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Balance, error)) *IBalanceGetByIDCall {
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) *IBalanceIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBalance)(nil).IsNoRows), err)
return &IBalanceIsNoRowsCall{Call: call}
}
// IBalanceIsNoRowsCall wrap *gomock.Call
type IBalanceIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceIsNoRowsCall) Return(arg0 bool) *IBalanceIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceIsNoRowsCall) Do(f func(error) bool) *IBalanceIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceIsNoRowsCall) DoAndReturn(f func(error) bool) *IBalanceIsNoRowsCall {
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) *IBalanceLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBalance)(nil).LastID), ctx)
return &IBalanceLastIDCall{Call: call}
}
// IBalanceLastIDCall wrap *gomock.Call
type IBalanceLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceLastIDCall) Return(arg0 uint64, arg1 error) *IBalanceLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceLastIDCall) Do(f func(context.Context) (uint64, error)) *IBalanceLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IBalanceLastIDCall {
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) *IBalanceListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBalance)(nil).List), ctx, limit, offset, order)
return &IBalanceListCall{Call: call}
}
// IBalanceListCall wrap *gomock.Call
type IBalanceListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceListCall) Return(arg0 []*storage.Balance, arg1 error) *IBalanceListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Balance, error)) *IBalanceListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Balance, error)) *IBalanceListCall {
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) *IBalanceSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBalance)(nil).Save), ctx, m)
return &IBalanceSaveCall{Call: call}
}
// IBalanceSaveCall wrap *gomock.Call
type IBalanceSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceSaveCall) Return(arg0 error) *IBalanceSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceSaveCall) Do(f func(context.Context, *storage.Balance) error) *IBalanceSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceSaveCall) DoAndReturn(f func(context.Context, *storage.Balance) error) *IBalanceSaveCall {
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) *IBalanceUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBalance)(nil).Update), ctx, m)
return &IBalanceUpdateCall{Call: call}
}
// IBalanceUpdateCall wrap *gomock.Call
type IBalanceUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBalanceUpdateCall) Return(arg0 error) *IBalanceUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBalanceUpdateCall) Do(f func(context.Context, *storage.Balance) error) *IBalanceUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBalanceUpdateCall) DoAndReturn(f func(context.Context, *storage.Balance) error) *IBalanceUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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"
storage "github.com/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-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) *IBlockByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockIBlock)(nil).ByHash), ctx, hash)
return &IBlockByHashCall{Call: call}
}
// IBlockByHashCall wrap *gomock.Call
type IBlockByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockByHashCall) Return(arg0 storage.Block, arg1 error) *IBlockByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockByHashCall) Do(f func(context.Context, []byte) (storage.Block, error)) *IBlockByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Block, error)) *IBlockByHashCall {
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) *IBlockByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeight", reflect.TypeOf((*MockIBlock)(nil).ByHeight), ctx, height)
return &IBlockByHeightCall{Call: call}
}
// IBlockByHeightCall wrap *gomock.Call
type IBlockByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockByHeightCall) Return(arg0 storage.Block, arg1 error) *IBlockByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockByHeightCall) Do(f func(context.Context, types.Level) (storage.Block, error)) *IBlockByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockByHeightCall) DoAndReturn(f func(context.Context, types.Level) (storage.Block, error)) *IBlockByHeightCall {
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) *IBlockByHeightWithStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeightWithStats", reflect.TypeOf((*MockIBlock)(nil).ByHeightWithStats), ctx, height)
return &IBlockByHeightWithStatsCall{Call: call}
}
// IBlockByHeightWithStatsCall wrap *gomock.Call
type IBlockByHeightWithStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockByHeightWithStatsCall) Return(arg0 storage.Block, arg1 error) *IBlockByHeightWithStatsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockByHeightWithStatsCall) Do(f func(context.Context, types.Level) (storage.Block, error)) *IBlockByHeightWithStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockByHeightWithStatsCall) DoAndReturn(f func(context.Context, types.Level) (storage.Block, error)) *IBlockByHeightWithStatsCall {
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) *IBlockByIdWithRelationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByIdWithRelations", reflect.TypeOf((*MockIBlock)(nil).ByIdWithRelations), ctx, id)
return &IBlockByIdWithRelationsCall{Call: call}
}
// IBlockByIdWithRelationsCall wrap *gomock.Call
type IBlockByIdWithRelationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockByIdWithRelationsCall) Return(arg0 storage.Block, arg1 error) *IBlockByIdWithRelationsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockByIdWithRelationsCall) Do(f func(context.Context, uint64) (storage.Block, error)) *IBlockByIdWithRelationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockByIdWithRelationsCall) DoAndReturn(f func(context.Context, uint64) (storage.Block, error)) *IBlockByIdWithRelationsCall {
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) *IBlockCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIBlock)(nil).CursorList), ctx, id, limit, order, cmp)
return &IBlockCursorListCall{Call: call}
}
// IBlockCursorListCall wrap *gomock.Call
type IBlockCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockCursorListCall) Return(arg0 []*storage.Block, arg1 error) *IBlockCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Block, error)) *IBlockCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Block, error)) *IBlockCursorListCall {
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) *IBlockGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIBlock)(nil).GetByID), ctx, id)
return &IBlockGetByIDCall{Call: call}
}
// IBlockGetByIDCall wrap *gomock.Call
type IBlockGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockGetByIDCall) Return(arg0 *storage.Block, arg1 error) *IBlockGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockGetByIDCall) Do(f func(context.Context, uint64) (*storage.Block, error)) *IBlockGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Block, error)) *IBlockGetByIDCall {
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) *IBlockIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIBlock)(nil).IsNoRows), err)
return &IBlockIsNoRowsCall{Call: call}
}
// IBlockIsNoRowsCall wrap *gomock.Call
type IBlockIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockIsNoRowsCall) Return(arg0 bool) *IBlockIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockIsNoRowsCall) Do(f func(error) bool) *IBlockIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockIsNoRowsCall) DoAndReturn(f func(error) bool) *IBlockIsNoRowsCall {
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) *IBlockLastCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Last", reflect.TypeOf((*MockIBlock)(nil).Last), ctx)
return &IBlockLastCall{Call: call}
}
// IBlockLastCall wrap *gomock.Call
type IBlockLastCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockLastCall) Return(arg0 storage.Block, arg1 error) *IBlockLastCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockLastCall) Do(f func(context.Context) (storage.Block, error)) *IBlockLastCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockLastCall) DoAndReturn(f func(context.Context) (storage.Block, error)) *IBlockLastCall {
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) *IBlockLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIBlock)(nil).LastID), ctx)
return &IBlockLastIDCall{Call: call}
}
// IBlockLastIDCall wrap *gomock.Call
type IBlockLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockLastIDCall) Return(arg0 uint64, arg1 error) *IBlockLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockLastIDCall) Do(f func(context.Context) (uint64, error)) *IBlockLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IBlockLastIDCall {
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) *IBlockListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIBlock)(nil).List), ctx, limit, offset, order)
return &IBlockListCall{Call: call}
}
// IBlockListCall wrap *gomock.Call
type IBlockListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockListCall) Return(arg0 []*storage.Block, arg1 error) *IBlockListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *IBlockListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *IBlockListCall {
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) *IBlockListWithStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithStats", reflect.TypeOf((*MockIBlock)(nil).ListWithStats), ctx, limit, offset, order)
return &IBlockListWithStatsCall{Call: call}
}
// IBlockListWithStatsCall wrap *gomock.Call
type IBlockListWithStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockListWithStatsCall) Return(arg0 []*storage.Block, arg1 error) *IBlockListWithStatsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockListWithStatsCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *IBlockListWithStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockListWithStatsCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Block, error)) *IBlockListWithStatsCall {
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) *IBlockSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIBlock)(nil).Save), ctx, m)
return &IBlockSaveCall{Call: call}
}
// IBlockSaveCall wrap *gomock.Call
type IBlockSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockSaveCall) Return(arg0 error) *IBlockSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockSaveCall) Do(f func(context.Context, *storage.Block) error) *IBlockSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockSaveCall) DoAndReturn(f func(context.Context, *storage.Block) error) *IBlockSaveCall {
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) *IBlockUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIBlock)(nil).Update), ctx, m)
return &IBlockUpdateCall{Call: call}
}
// IBlockUpdateCall wrap *gomock.Call
type IBlockUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockUpdateCall) Return(arg0 error) *IBlockUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockUpdateCall) Do(f func(context.Context, *storage.Block) error) *IBlockUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockUpdateCall) DoAndReturn(f func(context.Context, *storage.Block) error) *IBlockUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-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) *IBlockStatsByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHeight", reflect.TypeOf((*MockIBlockStats)(nil).ByHeight), ctx, height)
return &IBlockStatsByHeightCall{Call: call}
}
// IBlockStatsByHeightCall wrap *gomock.Call
type IBlockStatsByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IBlockStatsByHeightCall) Return(arg0 storage.BlockStats, arg1 error) *IBlockStatsByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IBlockStatsByHeightCall) Do(f func(context.Context, types.Level) (storage.BlockStats, error)) *IBlockStatsByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IBlockStatsByHeightCall) DoAndReturn(f func(context.Context, types.Level) (storage.BlockStats, error)) *IBlockStatsByHeightCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-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) *IConstantAllCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "All", reflect.TypeOf((*MockIConstant)(nil).All), ctx)
return &IConstantAllCall{Call: call}
}
// IConstantAllCall wrap *gomock.Call
type IConstantAllCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IConstantAllCall) Return(arg0 []storage.Constant, arg1 error) *IConstantAllCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IConstantAllCall) Do(f func(context.Context) ([]storage.Constant, error)) *IConstantAllCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IConstantAllCall) DoAndReturn(f func(context.Context) ([]storage.Constant, error)) *IConstantAllCall {
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) *IConstantByModuleCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByModule", reflect.TypeOf((*MockIConstant)(nil).ByModule), ctx, module)
return &IConstantByModuleCall{Call: call}
}
// IConstantByModuleCall wrap *gomock.Call
type IConstantByModuleCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IConstantByModuleCall) Return(arg0 []storage.Constant, arg1 error) *IConstantByModuleCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IConstantByModuleCall) Do(f func(context.Context, types.ModuleName) ([]storage.Constant, error)) *IConstantByModuleCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IConstantByModuleCall) DoAndReturn(f func(context.Context, types.ModuleName) ([]storage.Constant, error)) *IConstantByModuleCall {
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) *IConstantGetCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIConstant)(nil).Get), ctx, module, name)
return &IConstantGetCall{Call: call}
}
// IConstantGetCall wrap *gomock.Call
type IConstantGetCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IConstantGetCall) Return(arg0 storage.Constant, arg1 error) *IConstantGetCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IConstantGetCall) Do(f func(context.Context, types.ModuleName, string) (storage.Constant, error)) *IConstantGetCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IConstantGetCall) DoAndReturn(f func(context.Context, types.ModuleName, string) (storage.Constant, error)) *IConstantGetCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package mock
import (
models "github.com/dipdup-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
}
// 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/dipdup-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) *IDenomMetadataAllCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "All", reflect.TypeOf((*MockIDenomMetadata)(nil).All), ctx)
return &IDenomMetadataAllCall{Call: call}
}
// IDenomMetadataAllCall wrap *gomock.Call
type IDenomMetadataAllCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IDenomMetadataAllCall) Return(arg0 []storage.DenomMetadata, arg1 error) *IDenomMetadataAllCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IDenomMetadataAllCall) Do(f func(context.Context) ([]storage.DenomMetadata, error)) *IDenomMetadataAllCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IDenomMetadataAllCall) DoAndReturn(f func(context.Context) ([]storage.DenomMetadata, error)) *IDenomMetadataAllCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-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) ([]storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByBlock", ctx, height)
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 any) *IEventByBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByBlock", reflect.TypeOf((*MockIEvent)(nil).ByBlock), ctx, height)
return &IEventByBlockCall{Call: call}
}
// IEventByBlockCall wrap *gomock.Call
type IEventByBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventByBlockCall) Return(arg0 []storage.Event, arg1 error) *IEventByBlockCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventByBlockCall) Do(f func(context.Context, types.Level) ([]storage.Event, error)) *IEventByBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventByBlockCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Event, error)) *IEventByBlockCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// ByTxId mocks base method.
func (m *MockIEvent) ByTxId(ctx context.Context, txId uint64) ([]storage.Event, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByTxId", ctx, txId)
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 any) *IEventByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByTxId", reflect.TypeOf((*MockIEvent)(nil).ByTxId), ctx, txId)
return &IEventByTxIdCall{Call: call}
}
// IEventByTxIdCall wrap *gomock.Call
type IEventByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventByTxIdCall) Return(arg0 []storage.Event, arg1 error) *IEventByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventByTxIdCall) Do(f func(context.Context, uint64) ([]storage.Event, error)) *IEventByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventByTxIdCall) DoAndReturn(f func(context.Context, uint64) ([]storage.Event, error)) *IEventByTxIdCall {
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) *IEventCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIEvent)(nil).CursorList), ctx, id, limit, order, cmp)
return &IEventCursorListCall{Call: call}
}
// IEventCursorListCall wrap *gomock.Call
type IEventCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventCursorListCall) Return(arg0 []*storage.Event, arg1 error) *IEventCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Event, error)) *IEventCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Event, error)) *IEventCursorListCall {
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) *IEventGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIEvent)(nil).GetByID), ctx, id)
return &IEventGetByIDCall{Call: call}
}
// IEventGetByIDCall wrap *gomock.Call
type IEventGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventGetByIDCall) Return(arg0 *storage.Event, arg1 error) *IEventGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventGetByIDCall) Do(f func(context.Context, uint64) (*storage.Event, error)) *IEventGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Event, error)) *IEventGetByIDCall {
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) *IEventIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIEvent)(nil).IsNoRows), err)
return &IEventIsNoRowsCall{Call: call}
}
// IEventIsNoRowsCall wrap *gomock.Call
type IEventIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventIsNoRowsCall) Return(arg0 bool) *IEventIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventIsNoRowsCall) Do(f func(error) bool) *IEventIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventIsNoRowsCall) DoAndReturn(f func(error) bool) *IEventIsNoRowsCall {
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) *IEventLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIEvent)(nil).LastID), ctx)
return &IEventLastIDCall{Call: call}
}
// IEventLastIDCall wrap *gomock.Call
type IEventLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventLastIDCall) Return(arg0 uint64, arg1 error) *IEventLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventLastIDCall) Do(f func(context.Context) (uint64, error)) *IEventLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IEventLastIDCall {
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) *IEventListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIEvent)(nil).List), ctx, limit, offset, order)
return &IEventListCall{Call: call}
}
// IEventListCall wrap *gomock.Call
type IEventListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventListCall) Return(arg0 []*storage.Event, arg1 error) *IEventListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Event, error)) *IEventListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Event, error)) *IEventListCall {
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) *IEventSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIEvent)(nil).Save), ctx, m)
return &IEventSaveCall{Call: call}
}
// IEventSaveCall wrap *gomock.Call
type IEventSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventSaveCall) Return(arg0 error) *IEventSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventSaveCall) Do(f func(context.Context, *storage.Event) error) *IEventSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventSaveCall) DoAndReturn(f func(context.Context, *storage.Event) error) *IEventSaveCall {
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) *IEventUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIEvent)(nil).Update), ctx, m)
return &IEventUpdateCall{Call: call}
}
// IEventUpdateCall wrap *gomock.Call
type IEventUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IEventUpdateCall) Return(arg0 error) *IEventUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IEventUpdateCall) Do(f func(context.Context, *storage.Event) error) *IEventUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IEventUpdateCall) DoAndReturn(f func(context.Context, *storage.Event) error) *IEventUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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"
reflect "reflect"
storage "github.com/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-io/celestia-indexer/pkg/types"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
pq "github.com/lib/pq"
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) *NotificatorNotifyCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Notify", reflect.TypeOf((*MockNotificator)(nil).Notify), ctx, channel, payload)
return &NotificatorNotifyCall{Call: call}
}
// NotificatorNotifyCall wrap *gomock.Call
type NotificatorNotifyCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *NotificatorNotifyCall) Return(arg0 error) *NotificatorNotifyCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *NotificatorNotifyCall) Do(f func(context.Context, string, string) error) *NotificatorNotifyCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *NotificatorNotifyCall) DoAndReturn(f func(context.Context, string, string) error) *NotificatorNotifyCall {
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() *ListenerCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockListener)(nil).Close))
return &ListenerCloseCall{Call: call}
}
// ListenerCloseCall wrap *gomock.Call
type ListenerCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ListenerCloseCall) Return(arg0 error) *ListenerCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ListenerCloseCall) Do(f func() error) *ListenerCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ListenerCloseCall) DoAndReturn(f func() error) *ListenerCloseCall {
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() *ListenerListenCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Listen", reflect.TypeOf((*MockListener)(nil).Listen))
return &ListenerListenCall{Call: call}
}
// ListenerListenCall wrap *gomock.Call
type ListenerListenCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ListenerListenCall) Return(arg0 chan *pq.Notification) *ListenerListenCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ListenerListenCall) Do(f func() chan *pq.Notification) *ListenerListenCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ListenerListenCall) DoAndReturn(f func() chan *pq.Notification) *ListenerListenCall {
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) *ListenerSubscribeCall {
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 &ListenerSubscribeCall{Call: call}
}
// ListenerSubscribeCall wrap *gomock.Call
type ListenerSubscribeCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ListenerSubscribeCall) Return(arg0 error) *ListenerSubscribeCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ListenerSubscribeCall) Do(f func(context.Context, ...string) error) *ListenerSubscribeCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ListenerSubscribeCall) DoAndReturn(f func(context.Context, ...string) error) *ListenerSubscribeCall {
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() *ListenerFactoryCreateListenerCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateListener", reflect.TypeOf((*MockListenerFactory)(nil).CreateListener))
return &ListenerFactoryCreateListenerCall{Call: call}
}
// ListenerFactoryCreateListenerCall wrap *gomock.Call
type ListenerFactoryCreateListenerCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ListenerFactoryCreateListenerCall) Return(arg0 storage.Listener) *ListenerFactoryCreateListenerCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ListenerFactoryCreateListenerCall) Do(f func() storage.Listener) *ListenerFactoryCreateListenerCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ListenerFactoryCreateListenerCall) DoAndReturn(f func() storage.Listener) *ListenerFactoryCreateListenerCall {
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) *TransactionAddCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockTransaction)(nil).Add), ctx, model)
return &TransactionAddCall{Call: call}
}
// TransactionAddCall wrap *gomock.Call
type TransactionAddCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionAddCall) Return(arg0 error) *TransactionAddCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionAddCall) Do(f func(context.Context, any) error) *TransactionAddCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionAddCall) DoAndReturn(f func(context.Context, any) error) *TransactionAddCall {
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) *TransactionBulkSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BulkSave", reflect.TypeOf((*MockTransaction)(nil).BulkSave), ctx, models)
return &TransactionBulkSaveCall{Call: call}
}
// TransactionBulkSaveCall wrap *gomock.Call
type TransactionBulkSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionBulkSaveCall) Return(arg0 error) *TransactionBulkSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionBulkSaveCall) Do(f func(context.Context, []any) error) *TransactionBulkSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionBulkSaveCall) DoAndReturn(f func(context.Context, []any) error) *TransactionBulkSaveCall {
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) *TransactionCloseCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockTransaction)(nil).Close), ctx)
return &TransactionCloseCall{Call: call}
}
// TransactionCloseCall wrap *gomock.Call
type TransactionCloseCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionCloseCall) Return(arg0 error) *TransactionCloseCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionCloseCall) Do(f func(context.Context) error) *TransactionCloseCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionCloseCall) DoAndReturn(f func(context.Context) error) *TransactionCloseCall {
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) *TransactionCopyFromCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CopyFrom", reflect.TypeOf((*MockTransaction)(nil).CopyFrom), ctx, tableName, data)
return &TransactionCopyFromCall{Call: call}
}
// TransactionCopyFromCall wrap *gomock.Call
type TransactionCopyFromCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionCopyFromCall) Return(arg0 error) *TransactionCopyFromCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionCopyFromCall) Do(f func(context.Context, string, []storage0.Copiable) error) *TransactionCopyFromCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionCopyFromCall) DoAndReturn(f func(context.Context, string, []storage0.Copiable) error) *TransactionCopyFromCall {
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) *TransactionDeleteBalancesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBalances", reflect.TypeOf((*MockTransaction)(nil).DeleteBalances), ctx, ids)
return &TransactionDeleteBalancesCall{Call: call}
}
// TransactionDeleteBalancesCall wrap *gomock.Call
type TransactionDeleteBalancesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionDeleteBalancesCall) Return(arg0 error) *TransactionDeleteBalancesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionDeleteBalancesCall) Do(f func(context.Context, []uint64) error) *TransactionDeleteBalancesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionDeleteBalancesCall) DoAndReturn(f func(context.Context, []uint64) error) *TransactionDeleteBalancesCall {
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) *TransactionExecCall {
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 &TransactionExecCall{Call: call}
}
// TransactionExecCall wrap *gomock.Call
type TransactionExecCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionExecCall) Return(arg0 int64, arg1 error) *TransactionExecCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionExecCall) Do(f func(context.Context, string, ...any) (int64, error)) *TransactionExecCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionExecCall) DoAndReturn(f func(context.Context, string, ...any) (int64, error)) *TransactionExecCall {
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) *TransactionFlushCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Flush", reflect.TypeOf((*MockTransaction)(nil).Flush), ctx)
return &TransactionFlushCall{Call: call}
}
// TransactionFlushCall wrap *gomock.Call
type TransactionFlushCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionFlushCall) Return(arg0 error) *TransactionFlushCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionFlushCall) Do(f func(context.Context) error) *TransactionFlushCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionFlushCall) DoAndReturn(f func(context.Context) error) *TransactionFlushCall {
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) *TransactionHandleErrorCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleError", reflect.TypeOf((*MockTransaction)(nil).HandleError), ctx, err)
return &TransactionHandleErrorCall{Call: call}
}
// TransactionHandleErrorCall wrap *gomock.Call
type TransactionHandleErrorCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionHandleErrorCall) Return(arg0 error) *TransactionHandleErrorCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionHandleErrorCall) Do(f func(context.Context, error) error) *TransactionHandleErrorCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionHandleErrorCall) DoAndReturn(f func(context.Context, error) error) *TransactionHandleErrorCall {
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) *TransactionLastAddressActionCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAddressAction", reflect.TypeOf((*MockTransaction)(nil).LastAddressAction), ctx, address)
return &TransactionLastAddressActionCall{Call: call}
}
// TransactionLastAddressActionCall wrap *gomock.Call
type TransactionLastAddressActionCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionLastAddressActionCall) Return(arg0 uint64, arg1 error) *TransactionLastAddressActionCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionLastAddressActionCall) Do(f func(context.Context, []byte) (uint64, error)) *TransactionLastAddressActionCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionLastAddressActionCall) DoAndReturn(f func(context.Context, []byte) (uint64, error)) *TransactionLastAddressActionCall {
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) *TransactionLastBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastBlock", reflect.TypeOf((*MockTransaction)(nil).LastBlock), ctx)
return &TransactionLastBlockCall{Call: call}
}
// TransactionLastBlockCall wrap *gomock.Call
type TransactionLastBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionLastBlockCall) Return(block storage.Block, err error) *TransactionLastBlockCall {
c.Call = c.Call.Return(block, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionLastBlockCall) Do(f func(context.Context) (storage.Block, error)) *TransactionLastBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionLastBlockCall) DoAndReturn(f func(context.Context) (storage.Block, error)) *TransactionLastBlockCall {
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) *TransactionNamespaceCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Namespace", reflect.TypeOf((*MockTransaction)(nil).Namespace), ctx, id)
return &TransactionNamespaceCall{Call: call}
}
// TransactionNamespaceCall wrap *gomock.Call
type TransactionNamespaceCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionNamespaceCall) Return(ns storage.Namespace, err error) *TransactionNamespaceCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionNamespaceCall) Do(f func(context.Context, uint64) (storage.Namespace, error)) *TransactionNamespaceCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionNamespaceCall) DoAndReturn(f func(context.Context, uint64) (storage.Namespace, error)) *TransactionNamespaceCall {
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) *TransactionRollbackCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rollback", reflect.TypeOf((*MockTransaction)(nil).Rollback), ctx)
return &TransactionRollbackCall{Call: call}
}
// TransactionRollbackCall wrap *gomock.Call
type TransactionRollbackCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackCall) Return(arg0 error) *TransactionRollbackCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackCall) Do(f func(context.Context) error) *TransactionRollbackCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackCall) DoAndReturn(f func(context.Context) error) *TransactionRollbackCall {
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) *TransactionRollbackAddressesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackAddresses", reflect.TypeOf((*MockTransaction)(nil).RollbackAddresses), ctx, height)
return &TransactionRollbackAddressesCall{Call: call}
}
// TransactionRollbackAddressesCall wrap *gomock.Call
type TransactionRollbackAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackAddressesCall) Return(address []storage.Address, err error) *TransactionRollbackAddressesCall {
c.Call = c.Call.Return(address, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackAddressesCall) Do(f func(context.Context, types.Level) ([]storage.Address, error)) *TransactionRollbackAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackAddressesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Address, error)) *TransactionRollbackAddressesCall {
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) *TransactionRollbackBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlock", reflect.TypeOf((*MockTransaction)(nil).RollbackBlock), ctx, height)
return &TransactionRollbackBlockCall{Call: call}
}
// TransactionRollbackBlockCall wrap *gomock.Call
type TransactionRollbackBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackBlockCall) Return(arg0 error) *TransactionRollbackBlockCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackBlockCall) Do(f func(context.Context, types.Level) error) *TransactionRollbackBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackBlockCall) DoAndReturn(f func(context.Context, types.Level) error) *TransactionRollbackBlockCall {
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) *TransactionRollbackBlockStatsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackBlockStats", reflect.TypeOf((*MockTransaction)(nil).RollbackBlockStats), ctx, height)
return &TransactionRollbackBlockStatsCall{Call: call}
}
// TransactionRollbackBlockStatsCall wrap *gomock.Call
type TransactionRollbackBlockStatsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackBlockStatsCall) Return(stats storage.BlockStats, err error) *TransactionRollbackBlockStatsCall {
c.Call = c.Call.Return(stats, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackBlockStatsCall) Do(f func(context.Context, types.Level) (storage.BlockStats, error)) *TransactionRollbackBlockStatsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackBlockStatsCall) DoAndReturn(f func(context.Context, types.Level) (storage.BlockStats, error)) *TransactionRollbackBlockStatsCall {
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) *TransactionRollbackEventsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackEvents", reflect.TypeOf((*MockTransaction)(nil).RollbackEvents), ctx, height)
return &TransactionRollbackEventsCall{Call: call}
}
// TransactionRollbackEventsCall wrap *gomock.Call
type TransactionRollbackEventsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackEventsCall) Return(events []storage.Event, err error) *TransactionRollbackEventsCall {
c.Call = c.Call.Return(events, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackEventsCall) Do(f func(context.Context, types.Level) ([]storage.Event, error)) *TransactionRollbackEventsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackEventsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Event, error)) *TransactionRollbackEventsCall {
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) *TransactionRollbackMessageAddressesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackMessageAddresses", reflect.TypeOf((*MockTransaction)(nil).RollbackMessageAddresses), ctx, msgIds)
return &TransactionRollbackMessageAddressesCall{Call: call}
}
// TransactionRollbackMessageAddressesCall wrap *gomock.Call
type TransactionRollbackMessageAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackMessageAddressesCall) Return(err error) *TransactionRollbackMessageAddressesCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackMessageAddressesCall) Do(f func(context.Context, []uint64) error) *TransactionRollbackMessageAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackMessageAddressesCall) DoAndReturn(f func(context.Context, []uint64) error) *TransactionRollbackMessageAddressesCall {
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) *TransactionRollbackMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackMessages", reflect.TypeOf((*MockTransaction)(nil).RollbackMessages), ctx, height)
return &TransactionRollbackMessagesCall{Call: call}
}
// TransactionRollbackMessagesCall wrap *gomock.Call
type TransactionRollbackMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackMessagesCall) Return(msgs []storage.Message, err error) *TransactionRollbackMessagesCall {
c.Call = c.Call.Return(msgs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackMessagesCall) Do(f func(context.Context, types.Level) ([]storage.Message, error)) *TransactionRollbackMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackMessagesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Message, error)) *TransactionRollbackMessagesCall {
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) *TransactionRollbackNamespaceMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackNamespaceMessages", reflect.TypeOf((*MockTransaction)(nil).RollbackNamespaceMessages), ctx, height)
return &TransactionRollbackNamespaceMessagesCall{Call: call}
}
// TransactionRollbackNamespaceMessagesCall wrap *gomock.Call
type TransactionRollbackNamespaceMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackNamespaceMessagesCall) Return(msgs []storage.NamespaceMessage, err error) *TransactionRollbackNamespaceMessagesCall {
c.Call = c.Call.Return(msgs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackNamespaceMessagesCall) Do(f func(context.Context, types.Level) ([]storage.NamespaceMessage, error)) *TransactionRollbackNamespaceMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackNamespaceMessagesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.NamespaceMessage, error)) *TransactionRollbackNamespaceMessagesCall {
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) *TransactionRollbackNamespacesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackNamespaces", reflect.TypeOf((*MockTransaction)(nil).RollbackNamespaces), ctx, height)
return &TransactionRollbackNamespacesCall{Call: call}
}
// TransactionRollbackNamespacesCall wrap *gomock.Call
type TransactionRollbackNamespacesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackNamespacesCall) Return(ns []storage.Namespace, err error) *TransactionRollbackNamespacesCall {
c.Call = c.Call.Return(ns, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackNamespacesCall) Do(f func(context.Context, types.Level) ([]storage.Namespace, error)) *TransactionRollbackNamespacesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackNamespacesCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Namespace, error)) *TransactionRollbackNamespacesCall {
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) *TransactionRollbackSignersCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackSigners", reflect.TypeOf((*MockTransaction)(nil).RollbackSigners), ctx, txIds)
return &TransactionRollbackSignersCall{Call: call}
}
// TransactionRollbackSignersCall wrap *gomock.Call
type TransactionRollbackSignersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackSignersCall) Return(err error) *TransactionRollbackSignersCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackSignersCall) Do(f func(context.Context, []uint64) error) *TransactionRollbackSignersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackSignersCall) DoAndReturn(f func(context.Context, []uint64) error) *TransactionRollbackSignersCall {
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) *TransactionRollbackTxsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackTxs", reflect.TypeOf((*MockTransaction)(nil).RollbackTxs), ctx, height)
return &TransactionRollbackTxsCall{Call: call}
}
// TransactionRollbackTxsCall wrap *gomock.Call
type TransactionRollbackTxsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackTxsCall) Return(txs []storage.Tx, err error) *TransactionRollbackTxsCall {
c.Call = c.Call.Return(txs, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackTxsCall) Do(f func(context.Context, types.Level) ([]storage.Tx, error)) *TransactionRollbackTxsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackTxsCall) DoAndReturn(f func(context.Context, types.Level) ([]storage.Tx, error)) *TransactionRollbackTxsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// RollbackValidators mocks base method.
func (m *MockTransaction) RollbackValidators(ctx context.Context, height types.Level) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackValidators", ctx, height)
ret0, _ := ret[0].(error)
return ret0
}
// RollbackValidators indicates an expected call of RollbackValidators.
func (mr *MockTransactionMockRecorder) RollbackValidators(ctx, height any) *TransactionRollbackValidatorsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackValidators", reflect.TypeOf((*MockTransaction)(nil).RollbackValidators), ctx, height)
return &TransactionRollbackValidatorsCall{Call: call}
}
// TransactionRollbackValidatorsCall wrap *gomock.Call
type TransactionRollbackValidatorsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionRollbackValidatorsCall) Return(err error) *TransactionRollbackValidatorsCall {
c.Call = c.Call.Return(err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionRollbackValidatorsCall) Do(f func(context.Context, types.Level) error) *TransactionRollbackValidatorsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionRollbackValidatorsCall) DoAndReturn(f func(context.Context, types.Level) error) *TransactionRollbackValidatorsCall {
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) *TransactionSaveAddressesCall {
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 &TransactionSaveAddressesCall{Call: call}
}
// TransactionSaveAddressesCall wrap *gomock.Call
type TransactionSaveAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveAddressesCall) Return(arg0 int64, arg1 error) *TransactionSaveAddressesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveAddressesCall) Do(f func(context.Context, ...*storage.Address) (int64, error)) *TransactionSaveAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveAddressesCall) DoAndReturn(f func(context.Context, ...*storage.Address) (int64, error)) *TransactionSaveAddressesCall {
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) *TransactionSaveBalancesCall {
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 &TransactionSaveBalancesCall{Call: call}
}
// TransactionSaveBalancesCall wrap *gomock.Call
type TransactionSaveBalancesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveBalancesCall) Return(arg0 error) *TransactionSaveBalancesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveBalancesCall) Do(f func(context.Context, ...storage.Balance) error) *TransactionSaveBalancesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveBalancesCall) DoAndReturn(f func(context.Context, ...storage.Balance) error) *TransactionSaveBalancesCall {
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) *TransactionSaveConstantsCall {
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 &TransactionSaveConstantsCall{Call: call}
}
// TransactionSaveConstantsCall wrap *gomock.Call
type TransactionSaveConstantsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveConstantsCall) Return(arg0 error) *TransactionSaveConstantsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveConstantsCall) Do(f func(context.Context, ...storage.Constant) error) *TransactionSaveConstantsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveConstantsCall) DoAndReturn(f func(context.Context, ...storage.Constant) error) *TransactionSaveConstantsCall {
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) *TransactionSaveEventsCall {
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 &TransactionSaveEventsCall{Call: call}
}
// TransactionSaveEventsCall wrap *gomock.Call
type TransactionSaveEventsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveEventsCall) Return(arg0 error) *TransactionSaveEventsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveEventsCall) Do(f func(context.Context, ...storage.Event) error) *TransactionSaveEventsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveEventsCall) DoAndReturn(f func(context.Context, ...storage.Event) error) *TransactionSaveEventsCall {
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) *TransactionSaveMessagesCall {
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 &TransactionSaveMessagesCall{Call: call}
}
// TransactionSaveMessagesCall wrap *gomock.Call
type TransactionSaveMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveMessagesCall) Return(arg0 error) *TransactionSaveMessagesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveMessagesCall) Do(f func(context.Context, ...*storage.Message) error) *TransactionSaveMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveMessagesCall) DoAndReturn(f func(context.Context, ...*storage.Message) error) *TransactionSaveMessagesCall {
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) *TransactionSaveMsgAddressesCall {
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 &TransactionSaveMsgAddressesCall{Call: call}
}
// TransactionSaveMsgAddressesCall wrap *gomock.Call
type TransactionSaveMsgAddressesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveMsgAddressesCall) Return(arg0 error) *TransactionSaveMsgAddressesCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveMsgAddressesCall) Do(f func(context.Context, ...storage.MsgAddress) error) *TransactionSaveMsgAddressesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveMsgAddressesCall) DoAndReturn(f func(context.Context, ...storage.MsgAddress) error) *TransactionSaveMsgAddressesCall {
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) *TransactionSaveNamespaceMessageCall {
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 &TransactionSaveNamespaceMessageCall{Call: call}
}
// TransactionSaveNamespaceMessageCall wrap *gomock.Call
type TransactionSaveNamespaceMessageCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveNamespaceMessageCall) Return(arg0 error) *TransactionSaveNamespaceMessageCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveNamespaceMessageCall) Do(f func(context.Context, ...storage.NamespaceMessage) error) *TransactionSaveNamespaceMessageCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveNamespaceMessageCall) DoAndReturn(f func(context.Context, ...storage.NamespaceMessage) error) *TransactionSaveNamespaceMessageCall {
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) *TransactionSaveNamespacesCall {
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 &TransactionSaveNamespacesCall{Call: call}
}
// TransactionSaveNamespacesCall wrap *gomock.Call
type TransactionSaveNamespacesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveNamespacesCall) Return(arg0 int64, arg1 error) *TransactionSaveNamespacesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveNamespacesCall) Do(f func(context.Context, ...*storage.Namespace) (int64, error)) *TransactionSaveNamespacesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveNamespacesCall) DoAndReturn(f func(context.Context, ...*storage.Namespace) (int64, error)) *TransactionSaveNamespacesCall {
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) *TransactionSaveSignersCall {
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 &TransactionSaveSignersCall{Call: call}
}
// TransactionSaveSignersCall wrap *gomock.Call
type TransactionSaveSignersCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveSignersCall) Return(arg0 error) *TransactionSaveSignersCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveSignersCall) Do(f func(context.Context, ...storage.Signer) error) *TransactionSaveSignersCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveSignersCall) DoAndReturn(f func(context.Context, ...storage.Signer) error) *TransactionSaveSignersCall {
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) *TransactionSaveTransactionsCall {
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 &TransactionSaveTransactionsCall{Call: call}
}
// TransactionSaveTransactionsCall wrap *gomock.Call
type TransactionSaveTransactionsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveTransactionsCall) Return(arg0 error) *TransactionSaveTransactionsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveTransactionsCall) Do(f func(context.Context, ...storage.Tx) error) *TransactionSaveTransactionsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveTransactionsCall) DoAndReturn(f func(context.Context, ...storage.Tx) error) *TransactionSaveTransactionsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SaveValidators mocks base method.
func (m *MockTransaction) SaveValidators(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, "SaveValidators", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// SaveValidators indicates an expected call of SaveValidators.
func (mr *MockTransactionMockRecorder) SaveValidators(ctx any, validators ...any) *TransactionSaveValidatorsCall {
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 &TransactionSaveValidatorsCall{Call: call}
}
// TransactionSaveValidatorsCall wrap *gomock.Call
type TransactionSaveValidatorsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionSaveValidatorsCall) Return(arg0 error) *TransactionSaveValidatorsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionSaveValidatorsCall) Do(f func(context.Context, ...*storage.Validator) error) *TransactionSaveValidatorsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionSaveValidatorsCall) DoAndReturn(f func(context.Context, ...*storage.Validator) error) *TransactionSaveValidatorsCall {
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) *TransactionStateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "State", reflect.TypeOf((*MockTransaction)(nil).State), ctx, name)
return &TransactionStateCall{Call: call}
}
// TransactionStateCall wrap *gomock.Call
type TransactionStateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionStateCall) Return(state storage.State, err error) *TransactionStateCall {
c.Call = c.Call.Return(state, err)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionStateCall) Do(f func(context.Context, string) (storage.State, error)) *TransactionStateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionStateCall) DoAndReturn(f func(context.Context, string) (storage.State, error)) *TransactionStateCall {
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() *TransactionTxCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Tx", reflect.TypeOf((*MockTransaction)(nil).Tx))
return &TransactionTxCall{Call: call}
}
// TransactionTxCall wrap *gomock.Call
type TransactionTxCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionTxCall) Return(arg0 *bun.Tx) *TransactionTxCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionTxCall) Do(f func() *bun.Tx) *TransactionTxCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionTxCall) DoAndReturn(f func() *bun.Tx) *TransactionTxCall {
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) *TransactionUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockTransaction)(nil).Update), ctx, model)
return &TransactionUpdateCall{Call: call}
}
// TransactionUpdateCall wrap *gomock.Call
type TransactionUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *TransactionUpdateCall) Return(arg0 error) *TransactionUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *TransactionUpdateCall) Do(f func(context.Context, any) error) *TransactionUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *TransactionUpdateCall) DoAndReturn(f func(context.Context, any) error) *TransactionUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-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
}
// ByTxId mocks base method.
func (m *MockIMessage) ByTxId(ctx context.Context, txId uint64) ([]storage.Message, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ByTxId", ctx, txId)
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 any) *IMessageByTxIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByTxId", reflect.TypeOf((*MockIMessage)(nil).ByTxId), ctx, txId)
return &IMessageByTxIdCall{Call: call}
}
// IMessageByTxIdCall wrap *gomock.Call
type IMessageByTxIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageByTxIdCall) Return(arg0 []storage.Message, arg1 error) *IMessageByTxIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageByTxIdCall) Do(f func(context.Context, uint64) ([]storage.Message, error)) *IMessageByTxIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageByTxIdCall) DoAndReturn(f func(context.Context, uint64) ([]storage.Message, error)) *IMessageByTxIdCall {
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) *IMessageCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIMessage)(nil).CursorList), ctx, id, limit, order, cmp)
return &IMessageCursorListCall{Call: call}
}
// IMessageCursorListCall wrap *gomock.Call
type IMessageCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageCursorListCall) Return(arg0 []*storage.Message, arg1 error) *IMessageCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Message, error)) *IMessageCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Message, error)) *IMessageCursorListCall {
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) *IMessageGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIMessage)(nil).GetByID), ctx, id)
return &IMessageGetByIDCall{Call: call}
}
// IMessageGetByIDCall wrap *gomock.Call
type IMessageGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageGetByIDCall) Return(arg0 *storage.Message, arg1 error) *IMessageGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageGetByIDCall) Do(f func(context.Context, uint64) (*storage.Message, error)) *IMessageGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Message, error)) *IMessageGetByIDCall {
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) *IMessageIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIMessage)(nil).IsNoRows), err)
return &IMessageIsNoRowsCall{Call: call}
}
// IMessageIsNoRowsCall wrap *gomock.Call
type IMessageIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageIsNoRowsCall) Return(arg0 bool) *IMessageIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageIsNoRowsCall) Do(f func(error) bool) *IMessageIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageIsNoRowsCall) DoAndReturn(f func(error) bool) *IMessageIsNoRowsCall {
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) *IMessageLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIMessage)(nil).LastID), ctx)
return &IMessageLastIDCall{Call: call}
}
// IMessageLastIDCall wrap *gomock.Call
type IMessageLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageLastIDCall) Return(arg0 uint64, arg1 error) *IMessageLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageLastIDCall) Do(f func(context.Context) (uint64, error)) *IMessageLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IMessageLastIDCall {
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) *IMessageListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIMessage)(nil).List), ctx, limit, offset, order)
return &IMessageListCall{Call: call}
}
// IMessageListCall wrap *gomock.Call
type IMessageListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageListCall) Return(arg0 []*storage.Message, arg1 error) *IMessageListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Message, error)) *IMessageListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Message, error)) *IMessageListCall {
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) *IMessageSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIMessage)(nil).Save), ctx, m)
return &IMessageSaveCall{Call: call}
}
// IMessageSaveCall wrap *gomock.Call
type IMessageSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageSaveCall) Return(arg0 error) *IMessageSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageSaveCall) Do(f func(context.Context, *storage.Message) error) *IMessageSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageSaveCall) DoAndReturn(f func(context.Context, *storage.Message) error) *IMessageSaveCall {
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) *IMessageUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIMessage)(nil).Update), ctx, m)
return &IMessageUpdateCall{Call: call}
}
// IMessageUpdateCall wrap *gomock.Call
type IMessageUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IMessageUpdateCall) Return(arg0 error) *IMessageUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IMessageUpdateCall) Do(f func(context.Context, *storage.Message) error) *IMessageUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IMessageUpdateCall) DoAndReturn(f func(context.Context, *storage.Message) error) *IMessageUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-io/celestia-indexer/internal/storage"
types "github.com/dipdup-io/celestia-indexer/pkg/types"
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
}
// Active mocks base method.
func (m *MockINamespace) Active(ctx context.Context, top int) ([]storage.ActiveNamespace, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Active", ctx, top)
ret0, _ := ret[0].([]storage.ActiveNamespace)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Active indicates an expected call of Active.
func (mr *MockINamespaceMockRecorder) Active(ctx, top any) *INamespaceActiveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Active", reflect.TypeOf((*MockINamespace)(nil).Active), ctx, top)
return &INamespaceActiveCall{Call: call}
}
// INamespaceActiveCall wrap *gomock.Call
type INamespaceActiveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceActiveCall) Return(arg0 []storage.ActiveNamespace, arg1 error) *INamespaceActiveCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceActiveCall) Do(f func(context.Context, int) ([]storage.ActiveNamespace, error)) *INamespaceActiveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceActiveCall) DoAndReturn(f func(context.Context, int) ([]storage.ActiveNamespace, error)) *INamespaceActiveCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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) *INamespaceByNamespaceIdCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByNamespaceId", reflect.TypeOf((*MockINamespace)(nil).ByNamespaceId), ctx, namespaceId)
return &INamespaceByNamespaceIdCall{Call: call}
}
// INamespaceByNamespaceIdCall wrap *gomock.Call
type INamespaceByNamespaceIdCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceByNamespaceIdCall) Return(arg0 []storage.Namespace, arg1 error) *INamespaceByNamespaceIdCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceByNamespaceIdCall) Do(f func(context.Context, []byte) ([]storage.Namespace, error)) *INamespaceByNamespaceIdCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceByNamespaceIdCall) DoAndReturn(f func(context.Context, []byte) ([]storage.Namespace, error)) *INamespaceByNamespaceIdCall {
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) *INamespaceByNamespaceIdAndVersionCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByNamespaceIdAndVersion", reflect.TypeOf((*MockINamespace)(nil).ByNamespaceIdAndVersion), ctx, namespaceId, version)
return &INamespaceByNamespaceIdAndVersionCall{Call: call}
}
// INamespaceByNamespaceIdAndVersionCall wrap *gomock.Call
type INamespaceByNamespaceIdAndVersionCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceByNamespaceIdAndVersionCall) Return(arg0 storage.Namespace, arg1 error) *INamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceByNamespaceIdAndVersionCall) Do(f func(context.Context, []byte, byte) (storage.Namespace, error)) *INamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceByNamespaceIdAndVersionCall) DoAndReturn(f func(context.Context, []byte, byte) (storage.Namespace, error)) *INamespaceByNamespaceIdAndVersionCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// CountMessagesByHeight mocks base method.
func (m *MockINamespace) CountMessagesByHeight(ctx context.Context, height types.Level) (int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CountMessagesByHeight", ctx, height)
ret0, _ := ret[0].(int)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CountMessagesByHeight indicates an expected call of CountMessagesByHeight.
func (mr *MockINamespaceMockRecorder) CountMessagesByHeight(ctx, height any) *INamespaceCountMessagesByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountMessagesByHeight", reflect.TypeOf((*MockINamespace)(nil).CountMessagesByHeight), ctx, height)
return &INamespaceCountMessagesByHeightCall{Call: call}
}
// INamespaceCountMessagesByHeightCall wrap *gomock.Call
type INamespaceCountMessagesByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceCountMessagesByHeightCall) Return(arg0 int, arg1 error) *INamespaceCountMessagesByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceCountMessagesByHeightCall) Do(f func(context.Context, types.Level) (int, error)) *INamespaceCountMessagesByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceCountMessagesByHeightCall) DoAndReturn(f func(context.Context, types.Level) (int, error)) *INamespaceCountMessagesByHeightCall {
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) *INamespaceCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockINamespace)(nil).CursorList), ctx, id, limit, order, cmp)
return &INamespaceCursorListCall{Call: call}
}
// INamespaceCursorListCall wrap *gomock.Call
type INamespaceCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceCursorListCall) Return(arg0 []*storage.Namespace, arg1 error) *INamespaceCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Namespace, error)) *INamespaceCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Namespace, error)) *INamespaceCursorListCall {
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) *INamespaceGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockINamespace)(nil).GetByID), ctx, id)
return &INamespaceGetByIDCall{Call: call}
}
// INamespaceGetByIDCall wrap *gomock.Call
type INamespaceGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceGetByIDCall) Return(arg0 *storage.Namespace, arg1 error) *INamespaceGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceGetByIDCall) Do(f func(context.Context, uint64) (*storage.Namespace, error)) *INamespaceGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Namespace, error)) *INamespaceGetByIDCall {
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) *INamespaceIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockINamespace)(nil).IsNoRows), err)
return &INamespaceIsNoRowsCall{Call: call}
}
// INamespaceIsNoRowsCall wrap *gomock.Call
type INamespaceIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceIsNoRowsCall) Return(arg0 bool) *INamespaceIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceIsNoRowsCall) Do(f func(error) bool) *INamespaceIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceIsNoRowsCall) DoAndReturn(f func(error) bool) *INamespaceIsNoRowsCall {
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) *INamespaceLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockINamespace)(nil).LastID), ctx)
return &INamespaceLastIDCall{Call: call}
}
// INamespaceLastIDCall wrap *gomock.Call
type INamespaceLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceLastIDCall) Return(arg0 uint64, arg1 error) *INamespaceLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceLastIDCall) Do(f func(context.Context) (uint64, error)) *INamespaceLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *INamespaceLastIDCall {
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) *INamespaceListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockINamespace)(nil).List), ctx, limit, offset, order)
return &INamespaceListCall{Call: call}
}
// INamespaceListCall wrap *gomock.Call
type INamespaceListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceListCall) Return(arg0 []*storage.Namespace, arg1 error) *INamespaceListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Namespace, error)) *INamespaceListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Namespace, error)) *INamespaceListCall {
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) *INamespaceMessagesCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Messages", reflect.TypeOf((*MockINamespace)(nil).Messages), ctx, id, limit, offset)
return &INamespaceMessagesCall{Call: call}
}
// INamespaceMessagesCall wrap *gomock.Call
type INamespaceMessagesCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceMessagesCall) Return(arg0 []storage.NamespaceMessage, arg1 error) *INamespaceMessagesCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceMessagesCall) Do(f func(context.Context, uint64, int, int) ([]storage.NamespaceMessage, error)) *INamespaceMessagesCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceMessagesCall) DoAndReturn(f func(context.Context, uint64, int, int) ([]storage.NamespaceMessage, error)) *INamespaceMessagesCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// MessagesByHeight mocks base method.
func (m *MockINamespace) MessagesByHeight(ctx context.Context, height types.Level, limit, offset int) ([]storage.NamespaceMessage, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MessagesByHeight", ctx, height, limit, offset)
ret0, _ := ret[0].([]storage.NamespaceMessage)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// MessagesByHeight indicates an expected call of MessagesByHeight.
func (mr *MockINamespaceMockRecorder) MessagesByHeight(ctx, height, limit, offset any) *INamespaceMessagesByHeightCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MessagesByHeight", reflect.TypeOf((*MockINamespace)(nil).MessagesByHeight), ctx, height, limit, offset)
return &INamespaceMessagesByHeightCall{Call: call}
}
// INamespaceMessagesByHeightCall wrap *gomock.Call
type INamespaceMessagesByHeightCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceMessagesByHeightCall) Return(arg0 []storage.NamespaceMessage, arg1 error) *INamespaceMessagesByHeightCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceMessagesByHeightCall) Do(f func(context.Context, types.Level, int, int) ([]storage.NamespaceMessage, error)) *INamespaceMessagesByHeightCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceMessagesByHeightCall) DoAndReturn(f func(context.Context, types.Level, int, int) ([]storage.NamespaceMessage, error)) *INamespaceMessagesByHeightCall {
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) *INamespaceSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockINamespace)(nil).Save), ctx, m)
return &INamespaceSaveCall{Call: call}
}
// INamespaceSaveCall wrap *gomock.Call
type INamespaceSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceSaveCall) Return(arg0 error) *INamespaceSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceSaveCall) Do(f func(context.Context, *storage.Namespace) error) *INamespaceSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceSaveCall) DoAndReturn(f func(context.Context, *storage.Namespace) error) *INamespaceSaveCall {
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) *INamespaceUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockINamespace)(nil).Update), ctx, m)
return &INamespaceUpdateCall{Call: call}
}
// INamespaceUpdateCall wrap *gomock.Call
type INamespaceUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *INamespaceUpdateCall) Return(arg0 error) *INamespaceUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *INamespaceUpdateCall) Do(f func(context.Context, *storage.Namespace) error) *INamespaceUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *INamespaceUpdateCall) DoAndReturn(f func(context.Context, *storage.Namespace) error) *INamespaceUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-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) *IStateByNameCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByName", reflect.TypeOf((*MockIState)(nil).ByName), ctx, name)
return &IStateByNameCall{Call: call}
}
// IStateByNameCall wrap *gomock.Call
type IStateByNameCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateByNameCall) Return(arg0 storage.State, arg1 error) *IStateByNameCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateByNameCall) Do(f func(context.Context, string) (storage.State, error)) *IStateByNameCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateByNameCall) DoAndReturn(f func(context.Context, string) (storage.State, error)) *IStateByNameCall {
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) *IStateCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIState)(nil).CursorList), ctx, id, limit, order, cmp)
return &IStateCursorListCall{Call: call}
}
// IStateCursorListCall wrap *gomock.Call
type IStateCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateCursorListCall) Return(arg0 []*storage.State, arg1 error) *IStateCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.State, error)) *IStateCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.State, error)) *IStateCursorListCall {
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) *IStateGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIState)(nil).GetByID), ctx, id)
return &IStateGetByIDCall{Call: call}
}
// IStateGetByIDCall wrap *gomock.Call
type IStateGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateGetByIDCall) Return(arg0 *storage.State, arg1 error) *IStateGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateGetByIDCall) Do(f func(context.Context, uint64) (*storage.State, error)) *IStateGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.State, error)) *IStateGetByIDCall {
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) *IStateIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIState)(nil).IsNoRows), err)
return &IStateIsNoRowsCall{Call: call}
}
// IStateIsNoRowsCall wrap *gomock.Call
type IStateIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateIsNoRowsCall) Return(arg0 bool) *IStateIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateIsNoRowsCall) Do(f func(error) bool) *IStateIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateIsNoRowsCall) DoAndReturn(f func(error) bool) *IStateIsNoRowsCall {
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) *IStateLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIState)(nil).LastID), ctx)
return &IStateLastIDCall{Call: call}
}
// IStateLastIDCall wrap *gomock.Call
type IStateLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateLastIDCall) Return(arg0 uint64, arg1 error) *IStateLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateLastIDCall) Do(f func(context.Context) (uint64, error)) *IStateLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IStateLastIDCall {
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) *IStateListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIState)(nil).List), ctx, limit, offset, order)
return &IStateListCall{Call: call}
}
// IStateListCall wrap *gomock.Call
type IStateListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateListCall) Return(arg0 []*storage.State, arg1 error) *IStateListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.State, error)) *IStateListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.State, error)) *IStateListCall {
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) *IStateSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIState)(nil).Save), ctx, m)
return &IStateSaveCall{Call: call}
}
// IStateSaveCall wrap *gomock.Call
type IStateSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateSaveCall) Return(arg0 error) *IStateSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateSaveCall) Do(f func(context.Context, *storage.State) error) *IStateSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateSaveCall) DoAndReturn(f func(context.Context, *storage.State) error) *IStateSaveCall {
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) *IStateUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIState)(nil).Update), ctx, m)
return &IStateUpdateCall{Call: call}
}
// IStateUpdateCall wrap *gomock.Call
type IStateUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStateUpdateCall) Return(arg0 error) *IStateUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStateUpdateCall) Do(f func(context.Context, *storage.State) error) *IStateUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStateUpdateCall) DoAndReturn(f func(context.Context, *storage.State) error) *IStateUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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"
storage "github.com/dipdup-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
}
// 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) *IStatsCountCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Count", reflect.TypeOf((*MockIStats)(nil).Count), ctx, req)
return &IStatsCountCall{Call: call}
}
// IStatsCountCall wrap *gomock.Call
type IStatsCountCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStatsCountCall) Return(arg0 string, arg1 error) *IStatsCountCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStatsCountCall) Do(f func(context.Context, storage.CountRequest) (string, error)) *IStatsCountCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStatsCountCall) DoAndReturn(f func(context.Context, storage.CountRequest) (string, error)) *IStatsCountCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// Histogram mocks base method.
func (m *MockIStats) Histogram(ctx context.Context, req storage.HistogramRequest) ([]storage.HistogramItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Histogram", ctx, req)
ret0, _ := ret[0].([]storage.HistogramItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Histogram indicates an expected call of Histogram.
func (mr *MockIStatsMockRecorder) Histogram(ctx, req any) *IStatsHistogramCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Histogram", reflect.TypeOf((*MockIStats)(nil).Histogram), ctx, req)
return &IStatsHistogramCall{Call: call}
}
// IStatsHistogramCall wrap *gomock.Call
type IStatsHistogramCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStatsHistogramCall) Return(arg0 []storage.HistogramItem, arg1 error) *IStatsHistogramCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStatsHistogramCall) Do(f func(context.Context, storage.HistogramRequest) ([]storage.HistogramItem, error)) *IStatsHistogramCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStatsHistogramCall) DoAndReturn(f func(context.Context, storage.HistogramRequest) ([]storage.HistogramItem, error)) *IStatsHistogramCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// HistogramCount mocks base method.
func (m *MockIStats) HistogramCount(ctx context.Context, req storage.HistogramCountRequest) ([]storage.HistogramItem, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HistogramCount", ctx, req)
ret0, _ := ret[0].([]storage.HistogramItem)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// HistogramCount indicates an expected call of HistogramCount.
func (mr *MockIStatsMockRecorder) HistogramCount(ctx, req any) *IStatsHistogramCountCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HistogramCount", reflect.TypeOf((*MockIStats)(nil).HistogramCount), ctx, req)
return &IStatsHistogramCountCall{Call: call}
}
// IStatsHistogramCountCall wrap *gomock.Call
type IStatsHistogramCountCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStatsHistogramCountCall) Return(arg0 []storage.HistogramItem, arg1 error) *IStatsHistogramCountCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStatsHistogramCountCall) Do(f func(context.Context, storage.HistogramCountRequest) ([]storage.HistogramItem, error)) *IStatsHistogramCountCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStatsHistogramCountCall) DoAndReturn(f func(context.Context, storage.HistogramCountRequest) ([]storage.HistogramItem, error)) *IStatsHistogramCountCall {
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) *IStatsSummaryCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockIStats)(nil).Summary), ctx, req)
return &IStatsSummaryCall{Call: call}
}
// IStatsSummaryCall wrap *gomock.Call
type IStatsSummaryCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IStatsSummaryCall) Return(arg0 string, arg1 error) *IStatsSummaryCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IStatsSummaryCall) Do(f func(context.Context, storage.SummaryRequest) (string, error)) *IStatsSummaryCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IStatsSummaryCall) DoAndReturn(f func(context.Context, storage.SummaryRequest) (string, error)) *IStatsSummaryCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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"
storage "github.com/dipdup-io/celestia-indexer/internal/storage"
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) *ITxByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockITx)(nil).ByAddress), ctx, addressId, fltrs)
return &ITxByAddressCall{Call: call}
}
// ITxByAddressCall wrap *gomock.Call
type ITxByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxByAddressCall) Return(arg0 []storage.Tx, arg1 error) *ITxByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxByAddressCall) Do(f func(context.Context, uint64, storage.TxFilter) ([]storage.Tx, error)) *ITxByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxByAddressCall) DoAndReturn(f func(context.Context, uint64, storage.TxFilter) ([]storage.Tx, error)) *ITxByAddressCall {
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) *ITxByHashCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByHash", reflect.TypeOf((*MockITx)(nil).ByHash), ctx, hash)
return &ITxByHashCall{Call: call}
}
// ITxByHashCall wrap *gomock.Call
type ITxByHashCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxByHashCall) Return(arg0 storage.Tx, arg1 error) *ITxByHashCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxByHashCall) Do(f func(context.Context, []byte) (storage.Tx, error)) *ITxByHashCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxByHashCall) DoAndReturn(f func(context.Context, []byte) (storage.Tx, error)) *ITxByHashCall {
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) *ITxByIdWithRelationsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByIdWithRelations", reflect.TypeOf((*MockITx)(nil).ByIdWithRelations), ctx, id)
return &ITxByIdWithRelationsCall{Call: call}
}
// ITxByIdWithRelationsCall wrap *gomock.Call
type ITxByIdWithRelationsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxByIdWithRelationsCall) Return(arg0 storage.Tx, arg1 error) *ITxByIdWithRelationsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxByIdWithRelationsCall) Do(f func(context.Context, uint64) (storage.Tx, error)) *ITxByIdWithRelationsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxByIdWithRelationsCall) DoAndReturn(f func(context.Context, uint64) (storage.Tx, error)) *ITxByIdWithRelationsCall {
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) *ITxCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockITx)(nil).CursorList), ctx, id, limit, order, cmp)
return &ITxCursorListCall{Call: call}
}
// ITxCursorListCall wrap *gomock.Call
type ITxCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxCursorListCall) Return(arg0 []*storage.Tx, arg1 error) *ITxCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Tx, error)) *ITxCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Tx, error)) *ITxCursorListCall {
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) *ITxFilterCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Filter", reflect.TypeOf((*MockITx)(nil).Filter), ctx, fltrs)
return &ITxFilterCall{Call: call}
}
// ITxFilterCall wrap *gomock.Call
type ITxFilterCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxFilterCall) Return(arg0 []storage.Tx, arg1 error) *ITxFilterCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxFilterCall) Do(f func(context.Context, storage.TxFilter) ([]storage.Tx, error)) *ITxFilterCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxFilterCall) DoAndReturn(f func(context.Context, storage.TxFilter) ([]storage.Tx, error)) *ITxFilterCall {
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) *ITxGenesisCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockITx)(nil).Genesis), ctx, limit, offset, sortOrder)
return &ITxGenesisCall{Call: call}
}
// ITxGenesisCall wrap *gomock.Call
type ITxGenesisCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxGenesisCall) Return(arg0 []storage.Tx, arg1 error) *ITxGenesisCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxGenesisCall) Do(f func(context.Context, int, int, storage0.SortOrder) ([]storage.Tx, error)) *ITxGenesisCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxGenesisCall) DoAndReturn(f func(context.Context, int, int, storage0.SortOrder) ([]storage.Tx, error)) *ITxGenesisCall {
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) *ITxGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockITx)(nil).GetByID), ctx, id)
return &ITxGetByIDCall{Call: call}
}
// ITxGetByIDCall wrap *gomock.Call
type ITxGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxGetByIDCall) Return(arg0 *storage.Tx, arg1 error) *ITxGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxGetByIDCall) Do(f func(context.Context, uint64) (*storage.Tx, error)) *ITxGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Tx, error)) *ITxGetByIDCall {
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) *ITxIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockITx)(nil).IsNoRows), err)
return &ITxIsNoRowsCall{Call: call}
}
// ITxIsNoRowsCall wrap *gomock.Call
type ITxIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxIsNoRowsCall) Return(arg0 bool) *ITxIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxIsNoRowsCall) Do(f func(error) bool) *ITxIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxIsNoRowsCall) DoAndReturn(f func(error) bool) *ITxIsNoRowsCall {
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) *ITxLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockITx)(nil).LastID), ctx)
return &ITxLastIDCall{Call: call}
}
// ITxLastIDCall wrap *gomock.Call
type ITxLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxLastIDCall) Return(arg0 uint64, arg1 error) *ITxLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxLastIDCall) Do(f func(context.Context) (uint64, error)) *ITxLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *ITxLastIDCall {
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) *ITxListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockITx)(nil).List), ctx, limit, offset, order)
return &ITxListCall{Call: call}
}
// ITxListCall wrap *gomock.Call
type ITxListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxListCall) Return(arg0 []*storage.Tx, arg1 error) *ITxListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Tx, error)) *ITxListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Tx, error)) *ITxListCall {
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) *ITxSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockITx)(nil).Save), ctx, m)
return &ITxSaveCall{Call: call}
}
// ITxSaveCall wrap *gomock.Call
type ITxSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxSaveCall) Return(arg0 error) *ITxSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxSaveCall) Do(f func(context.Context, *storage.Tx) error) *ITxSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxSaveCall) DoAndReturn(f func(context.Context, *storage.Tx) error) *ITxSaveCall {
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) *ITxUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockITx)(nil).Update), ctx, m)
return &ITxUpdateCall{Call: call}
}
// ITxUpdateCall wrap *gomock.Call
type ITxUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ITxUpdateCall) Return(arg0 error) *ITxUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ITxUpdateCall) Do(f func(context.Context, *storage.Tx) error) *ITxUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ITxUpdateCall) DoAndReturn(f func(context.Context, *storage.Tx) error) *ITxUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// 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/dipdup-io/celestia-indexer/internal/storage"
storage0 "github.com/dipdup-net/indexer-sdk/pkg/storage"
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) *IValidatorByAddressCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ByAddress", reflect.TypeOf((*MockIValidator)(nil).ByAddress), ctx, address)
return &IValidatorByAddressCall{Call: call}
}
// IValidatorByAddressCall wrap *gomock.Call
type IValidatorByAddressCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorByAddressCall) Return(arg0 storage.Validator, arg1 error) *IValidatorByAddressCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorByAddressCall) Do(f func(context.Context, string) (storage.Validator, error)) *IValidatorByAddressCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorByAddressCall) DoAndReturn(f func(context.Context, string) (storage.Validator, error)) *IValidatorByAddressCall {
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) *IValidatorCursorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CursorList", reflect.TypeOf((*MockIValidator)(nil).CursorList), ctx, id, limit, order, cmp)
return &IValidatorCursorListCall{Call: call}
}
// IValidatorCursorListCall wrap *gomock.Call
type IValidatorCursorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorCursorListCall) Return(arg0 []*storage.Validator, arg1 error) *IValidatorCursorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorCursorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Validator, error)) *IValidatorCursorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorCursorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder, storage0.Comparator) ([]*storage.Validator, error)) *IValidatorCursorListCall {
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) *IValidatorGetByIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByID", reflect.TypeOf((*MockIValidator)(nil).GetByID), ctx, id)
return &IValidatorGetByIDCall{Call: call}
}
// IValidatorGetByIDCall wrap *gomock.Call
type IValidatorGetByIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorGetByIDCall) Return(arg0 *storage.Validator, arg1 error) *IValidatorGetByIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorGetByIDCall) Do(f func(context.Context, uint64) (*storage.Validator, error)) *IValidatorGetByIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorGetByIDCall) DoAndReturn(f func(context.Context, uint64) (*storage.Validator, error)) *IValidatorGetByIDCall {
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) *IValidatorIsNoRowsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsNoRows", reflect.TypeOf((*MockIValidator)(nil).IsNoRows), err)
return &IValidatorIsNoRowsCall{Call: call}
}
// IValidatorIsNoRowsCall wrap *gomock.Call
type IValidatorIsNoRowsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorIsNoRowsCall) Return(arg0 bool) *IValidatorIsNoRowsCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorIsNoRowsCall) Do(f func(error) bool) *IValidatorIsNoRowsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorIsNoRowsCall) DoAndReturn(f func(error) bool) *IValidatorIsNoRowsCall {
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) *IValidatorLastIDCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastID", reflect.TypeOf((*MockIValidator)(nil).LastID), ctx)
return &IValidatorLastIDCall{Call: call}
}
// IValidatorLastIDCall wrap *gomock.Call
type IValidatorLastIDCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorLastIDCall) Return(arg0 uint64, arg1 error) *IValidatorLastIDCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorLastIDCall) Do(f func(context.Context) (uint64, error)) *IValidatorLastIDCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorLastIDCall) DoAndReturn(f func(context.Context) (uint64, error)) *IValidatorLastIDCall {
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) *IValidatorListCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockIValidator)(nil).List), ctx, limit, offset, order)
return &IValidatorListCall{Call: call}
}
// IValidatorListCall wrap *gomock.Call
type IValidatorListCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorListCall) Return(arg0 []*storage.Validator, arg1 error) *IValidatorListCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorListCall) Do(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Validator, error)) *IValidatorListCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorListCall) DoAndReturn(f func(context.Context, uint64, uint64, storage0.SortOrder) ([]*storage.Validator, error)) *IValidatorListCall {
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) *IValidatorSaveCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockIValidator)(nil).Save), ctx, m)
return &IValidatorSaveCall{Call: call}
}
// IValidatorSaveCall wrap *gomock.Call
type IValidatorSaveCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorSaveCall) Return(arg0 error) *IValidatorSaveCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorSaveCall) Do(f func(context.Context, *storage.Validator) error) *IValidatorSaveCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorSaveCall) DoAndReturn(f func(context.Context, *storage.Validator) error) *IValidatorSaveCall {
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) *IValidatorUpdateCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockIValidator)(nil).Update), ctx, m)
return &IValidatorUpdateCall{Call: call}
}
// IValidatorUpdateCall wrap *gomock.Call
type IValidatorUpdateCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *IValidatorUpdateCall) Return(arg0 error) *IValidatorUpdateCall {
c.Call = c.Call.Return(arg0)
return c
}
// Do rewrite *gomock.Call.Do
func (c *IValidatorUpdateCall) Do(f func(context.Context, *storage.Validator) error) *IValidatorUpdateCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *IValidatorUpdateCall) DoAndReturn(f func(context.Context, *storage.Validator) error) *IValidatorUpdateCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"encoding/base64"
"fmt"
"time"
"github.com/dipdup-io/celestia-indexer/pkg/types"
pkgTypes "github.com/dipdup-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 INamespace interface {
storage.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)
MessagesByHeight(ctx context.Context, height pkgTypes.Level, limit, offset int) ([]NamespaceMessage, error)
CountMessagesByHeight(ctx context.Context, height pkgTypes.Level) (int, error)
Active(ctx context.Context, top int) ([]ActiveNamespace, 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"`
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"`
Reserved bool `bun:"reserved,default:false" comment:"If namespace is reserved flag is true"`
}
// 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...))
}
type ActiveNamespace struct {
Namespace
Height pkgTypes.Level `bun:"height"`
Time time.Time `bun:"time"`
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"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" comment:"Message time"`
Height types.Level `bun:"height" comment:"Message block height"`
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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// 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) {
err = a.DB().NewSelect().Model(&address).
Where("hash = ?", hash).
Relation("Balance").
Scan(ctx)
return
}
func (a *Address) ListWithBalance(ctx context.Context, fltrs storage.AddressListFilter) (result []storage.Address, err error) {
query := a.DB().NewSelect().Model(&result).
Offset(fltrs.Offset).
Relation("Balance")
query = addressListFilter(query, fltrs)
err = query.Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-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).
Limit(1).
Scan(ctx)
return
}
type typeCount struct {
Type storageTypes.MsgType `bun:"type"`
Count int64 `bun:"count"`
}
// ByHeightWithStats -
func (b *Blocks) ByHeightWithStats(ctx context.Context, height types.Level) (block storage.Block, err error) {
err = b.DB().NewSelect().Model(&block).
Where("block.height = ?", height).
Relation("Stats").
Limit(1).
Scan(ctx)
if err != nil {
return
}
var msgsStats []typeCount
err = b.DB().NewSelect().Model((*storage.Message)(nil)).
ColumnExpr("message.type, count(*)").
Where("message.height = ?", height).
Group("message.type").
Scan(ctx, &msgsStats)
if err != nil {
return
}
block.Stats.MessagesCounts = make(map[storageTypes.MsgType]int64)
for _, stat := range msgsStats {
block.Stats.MessagesCounts[stat.Type] = stat.Count
}
return
}
// ByIdWithRelations -
func (b *Blocks) ByIdWithRelations(ctx context.Context, id uint64) (block storage.Block, err error) {
err = b.DB().NewSelect().Model(&block).
Where("block.id = ?", id).
Relation("Stats").
Limit(1).
Scan(ctx)
if err != nil {
return
}
var msgsStats []typeCount
err = b.DB().NewSelect().Model((*storage.Message)(nil)).
ColumnExpr("message.type, count(*)").
Where("message.height = ?", block.Height).
Group("message.type").
Scan(ctx, &msgsStats)
if err != nil {
return
}
block.Stats.MessagesCounts = make(map[storageTypes.MsgType]int64)
for _, stat := range msgsStats {
block.Stats.MessagesCounts[stat.Type] = stat.Count
}
return
}
// Last -
func (b *Blocks) Last(ctx context.Context) (block storage.Block, err error) {
err = b.DB().NewSelect().Model(&block).Order("id desc").Limit(1).Scan(ctx)
return
}
// ByHash -
func (b *Blocks) ByHash(ctx context.Context, hash []byte) (block storage.Block, err error) {
err = b.DB().NewSelect().
Model(&block).
Where("hash = ?", hash).
Relation("Stats").
Limit(1).
Scan(ctx)
return
}
type listTypeCount struct {
Height types.Level `bun:"height"`
Type storageTypes.MsgType `bun:"type"`
Count int64 `bun:"count"`
}
// 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)
subQuery = postgres.Pagination(subQuery, limit, offset, order)
query := 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_size AS stats__blobs_size, stats.block_time AS stats__block_time, stats.supply_change AS stats__supply_change, stats.inflation_rate AS stats__inflation_rate, stats.fee AS stats__fee").
TableExpr("(?) as block", subQuery).
Join("LEFT JOIN block_stats as stats").
JoinOn("stats.height = block.height")
query = sortScope(query, "block.id", order)
err = query.Scan(ctx, &blocks)
if err != nil {
return
}
heights := make([]types.Level, len(blocks))
blocksHeightMap := make(map[types.Level]*storage.Block)
for i, b := range blocks {
heights[i] = b.Height
blocksHeightMap[b.Height] = b
}
var listTypeCounts []listTypeCount
queryMsgsCounts := b.DB().NewSelect().Model((*storage.Message)(nil)).
ColumnExpr("message.height, message.type, count(*)").
Where("message.height IN (?)", bun.In(heights)).
Group("message.type").
Group("message.height")
queryMsgsCounts = sortScope(queryMsgsCounts, "message.height", order)
err = queryMsgsCounts.Scan(ctx, &listTypeCounts)
if err != nil {
return
}
for _, stat := range listTypeCounts {
if blocksHeightMap[stat.Height].Stats.MessagesCounts == nil {
blocksHeightMap[stat.Height].Stats.MessagesCounts = make(map[storageTypes.MsgType]int64)
}
blocksHeightMap[stat.Height].Stats.MessagesCounts[stat.Type] = stat.Count
}
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-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)
if err != nil {
return
}
var msgsStats []typeCount
err = b.db.DB().NewSelect().Model((*storage.Message)(nil)).
ColumnExpr("message.type, count(*)").
Where("message.height = ?", height).
Group("message.type").
Scan(ctx, &msgsStats)
if err != nil {
return
}
stats.MessagesCounts = make(map[storageTypes.MsgType]int64)
for _, stat := range msgsStats {
stats.MessagesCounts[stat.Type] = stat.Count
}
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/stats"
models "github.com/dipdup-io/celestia-indexer/internal/storage"
"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"
)
// Storage -
type Storage struct {
*postgres.Storage
cfg config.Database
Blocks models.IBlock
BlockStats models.IBlockStats
Constants models.IConstant
DenomMetadata models.IDenomMetadata
Tx models.ITx
Message models.IMessage
Event models.IEvent
Address models.IAddress
Namespace models.INamespace
State models.IState
Stats models.IStats
Validator models.IValidator
Notificator *Notificator
}
// Create -
func Create(ctx context.Context, cfg config.Database) (Storage, error) {
strg, err := postgres.Create(ctx, cfg, initDatabase)
if err != nil {
return Storage{}, err
}
s := Storage{
cfg: cfg,
Storage: strg,
Blocks: NewBlocks(strg.Connection()),
BlockStats: NewBlockStats(strg.Connection()),
Constants: NewConstant(strg.Connection()),
DenomMetadata: NewDenomMetadata(strg.Connection()),
Message: NewMessage(strg.Connection()),
Event: NewEvent(strg.Connection()),
Address: NewAddress(strg.Connection()),
Tx: NewTx(strg.Connection()),
State: NewState(strg.Connection()),
Namespace: NewNamespace(strg.Connection()),
Stats: NewStats(strg.Connection()),
Validator: NewValidator(strg.Connection()),
Notificator: NewNotificator(cfg, strg.Connection().DB()),
}
return s, nil
}
func initDatabase(ctx context.Context, conn *database.Bun) error {
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.Signer)(nil),
(*models.MsgAddress)(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 (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{},
} {
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
})
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
"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 {
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
}
return nil
})
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"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) (events []storage.Event, err error) {
err = e.DB().NewSelect().Model(&events).
Where("tx_id = ?", txId).
Scan(ctx)
return
}
// ByBlock -
func (e *Event) ByBlock(ctx context.Context, height pkgTypes.Level) (events []storage.Event, err error) {
err = e.DB().NewSelect().Model(&events).
Where("height = ?", height).
Where("tx_id IS NULL").
Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"database/sql"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"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.Address)(nil)).
Index("block_height_idx").
Column("height").
Using("BRIN").
Exec(ctx); err != nil {
return err
}
// BlockStats
if _, err := tx.NewCreateIndex().
IfNotExists().
Model((*storage.Address)(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
}
// 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
}
// 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
}
return nil
})
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// 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) (messages []storage.Message, err error) {
err = m.DB().NewSelect().Model(&messages).
Where("tx_id = ?", txId).
Scan(ctx)
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"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) {
query := n.DB().NewSelect().Model(&msgs).
Where("namespace_message.namespace_id = ?", id).
Order("namespace_message.time desc").
Relation("Namespace").
Relation("Message").
Relation("Tx")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = query.Scan(ctx)
return
}
// MessagesByHeight -
func (n *Namespace) MessagesByHeight(ctx context.Context, height pkgTypes.Level, limit, offset int) (msgs []storage.NamespaceMessage, err error) {
query := n.DB().NewSelect().Model(&msgs).
Where("namespace_message.height = ?", height).
Order("namespace_message.time desc").
Relation("Namespace").
Relation("Message").
Relation("Tx")
query = limitScope(query, limit)
if offset > 0 {
query = query.Offset(offset)
}
err = query.Scan(ctx)
return
}
func (n *Namespace) CountMessagesByHeight(ctx context.Context, height pkgTypes.Level) (int, error) {
return n.DB().NewSelect().Model((*storage.NamespaceMessage)(nil)).
Where("namespace_message.height = ?", height).
Count(ctx)
}
func (n *Namespace) Active(ctx context.Context, top int) (ns []storage.ActiveNamespace, err error) {
subQuery := n.DB().NewSelect().
ColumnExpr("namespace_id, max(msg_id) as msg_id, max(height) as height, max(time) as time").
Model((*storage.NamespaceMessage)(nil)).
Group("namespace_id").
Order("msg_id desc")
subQuery = limitScope(subQuery, top)
err = n.DB().NewSelect().
ColumnExpr("action.time as time, action.height as height, namespace.*").
TableExpr("(?) as action", subQuery).
Join("LEFT JOIN namespace").
JoinOn("namespace.id = action.namespace_id").
Order("msg_id desc").
Scan(ctx, &ns)
return
}
// SPDX-FileCopyrightText: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
sdk "github.com/dipdup-net/indexer-sdk/pkg/storage"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
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 timeframeScope(q *bun.SelectQuery, tf storage.Timeframe) (*bun.SelectQuery, error) {
switch tf {
case storage.TimeframeHour:
return q.ColumnExpr("time_bucket('1 hour', time) as bucket"), nil
case storage.TimeframeDay:
return q.ColumnExpr("time_bucket('1 day', time) as bucket"), nil
case storage.TimeframeWeek:
return q.ColumnExpr("time_bucket('1 week', time) as bucket"), nil
case storage.TimeframeMonth:
return q.ColumnExpr("time_bucket('1 month', time) as bucket"), nil
case storage.TimeframeYear:
return q.ColumnExpr("time_bucket('1 year', time) as bucket"), nil
default:
return nil, errors.Errorf("unexpected timeframe %s", tf)
}
}
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("message_types & ? > 0", fltrs.MessageTypes)
}
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 > 0 {
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 = sortScope(query, "id", fltrs.Sort)
return query
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"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) HistogramCount(ctx context.Context, req storage.HistogramCountRequest) (response []storage.HistogramItem, err error) {
if err := req.Validate(); err != nil {
return nil, err
}
query := s.db.DB().NewSelect().Table(req.Table).
ColumnExpr(`COUNT(*) as value`).
Group("bucket").
Order("bucket desc")
query, err = timeframeScope(query, req.Timeframe)
if err != nil {
return
}
if req.From > 0 {
query = query.Where("time >= to_timestamp(?)", req.From)
}
if req.To > 0 {
query = query.Where("time < to_timestamp(?)", req.To)
}
err = query.Scan(ctx, &response)
return
}
func (s Stats) Histogram(ctx context.Context, req storage.HistogramRequest) (response []storage.HistogramItem, err error) {
if err := req.Validate(); err != nil {
return nil, err
}
query := s.db.DB().NewSelect().Table(req.Table).
ColumnExpr(`? (?) as value`, bun.Safe(req.Function), bun.Safe(req.Column)).
Group("bucket").
Order("bucket desc")
query, err = timeframeScope(query, req.Timeframe)
if err != nil {
return
}
if req.From > 0 {
query = query.Where("time >= to_timestamp(?)", req.From)
}
if req.To > 0 {
query = query.Where("time < to_timestamp(?)", req.To)
}
err = query.Scan(ctx, &response)
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/uptrace/bun"
models "github.com/dipdup-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").
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").
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", "total").
On("CONFLICT (id, currency) DO UPDATE").
Set("total = EXCLUDED.total + balance.total").
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:
data := make([]any, len(events))
for i := range events {
data[i] = &events[i]
}
return tx.BulkSave(ctx, data)
default:
copiable := make([]storage.Copiable, len(events))
for i := range events {
copiable[i] = events[i]
}
return tx.CopyFrom(ctx, "event", copiable)
}
}
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) 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) SaveValidators(ctx context.Context, validators ...*models.Validator) error {
if len(validators) == 0 {
return nil
}
_, err := tx.Tx().NewInsert().Model(&validators).
On("CONFLICT ON CONSTRAINT address_validator DO UPDATE").
Set("moniker = EXCLUDED.moniker").
Set("website = EXCLUDED.website").
Set("identity = EXCLUDED.identity").
Set("contacts = EXCLUDED.contacts").
Set("details = EXCLUDED.details").
Set("rate = EXCLUDED.rate").
Set("min_self_delegation = EXCLUDED.min_self_delegation").
Returning("id").
Exec(ctx)
return err
}
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) (err error) {
_, err = tx.Tx().NewDelete().Model((*models.Validator)(nil)).Where("height = ?", height).Returning("*").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) 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) 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
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-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"
)
// 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) ByHash(ctx context.Context, hash []byte) (transaction storage.Tx, err error) {
err = tx.DB().NewSelect().Model(&transaction).
Where("hash = ?", hash).
Scan(ctx)
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)
err = query.Scan(ctx)
return
}
func (tx *Tx) ByIdWithRelations(ctx context.Context, id uint64) (transaction storage.Tx, err error) {
err = tx.DB().NewSelect().Model(&transaction).
Where("id = ?", id).
Relation("Messages").
Scan(ctx)
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")
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
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package postgres
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-net/go-lib/database"
"github.com/dipdup-net/indexer-sdk/pkg/storage/postgres"
)
// 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
}
// SPDX-FileCopyrightText: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"time"
"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"`
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"`
}
// TableName -
func (State) TableName() string {
return "state"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
"github.com/dipdup-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.Errorf("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.Errorf("unknown table '%s' for stats computing", req.Table)
}
column, ok := table.Columns[req.Column]
if !ok {
return errors.Errorf("unknown column '%s' in table '%s' for stats computing", req.Column, req.Table)
}
if _, ok := column.Functions[req.Function]; !ok {
return errors.Errorf("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"`
}
//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)
HistogramCount(ctx context.Context, req HistogramCountRequest) ([]HistogramItem, error)
Histogram(ctx context.Context, req HistogramRequest) ([]HistogramItem, error)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"time"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-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)
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)
}
type TxFilter struct {
Limit int
Offset int
Sort storage.SortOrder
Status []string
MessageTypes 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:int8" 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:"m2m:signer,join:Tx=Address"`
BlobsSize int64 `bun:"-"`
}
// TableName -
func (Tx) TableName() string {
return "tx"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
type Bits uint64
func (b *Bits) Set(flag Bits) { *b |= flag }
func (b *Bits) Clear(flag Bits) { *b &^= flag }
func (b Bits) Has(flag Bits) bool { return b&flag != 0 }
func (b Bits) CountBits() int {
var count int
for b != 0 {
count += int(b & 1)
b >>= 1
}
return count
}
func (b Bits) Empty() bool { return b == 0 }
// 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 (
// 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"
// 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"
)
var ErrInvalidEventType = errors.New("not a valid EventType")
// 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,
EventTypeUseFeegrant,
EventTypeRevokeFeegrant,
EventTypeSetFeegrant,
EventTypeUpdateFeegrant,
EventTypeSlash,
EventTypeProposalVote,
EventTypeProposalDeposit,
EventTypeSubmitProposal,
EventTypeCosmosauthzv1beta1EventGrant,
EventTypeSendPacket,
EventTypeIbcTransfer,
}
}
// 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,
"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,
}
// 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
}
// 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"
)
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,
}
}
// 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,
}
// 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
}
// 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"
)
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,
}
}
// 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,
}
// 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"database/sql"
"database/sql/driver"
"github.com/pkg/errors"
)
type MsgTypeBits struct {
Bits
}
const (
MsgTypeBitsUnknown uint64 = 1 << 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
)
func NewMsgTypeBitMask(values ...MsgType) MsgTypeBits {
var mask MsgTypeBits
for i := range values {
mask.SetBit(values[i])
}
return mask
}
func (mask *MsgTypeBits) SetBit(value MsgType) {
switch value {
case MsgUnknown:
mask.Set(Bits(MsgTypeBitsUnknown))
case MsgSetWithdrawAddress:
mask.Set(Bits(MsgTypeBitsSetWithdrawAddress))
case MsgWithdrawDelegatorReward:
mask.Set(Bits(MsgTypeBitsWithdrawDelegatorReward))
case MsgWithdrawValidatorCommission:
mask.Set(Bits(MsgTypeBitsWithdrawValidatorCommission))
case MsgFundCommunityPool:
mask.Set(Bits(MsgTypeBitsFundCommunityPool))
case MsgCreateValidator:
mask.Set(Bits(MsgTypeBitsCreateValidator))
case MsgEditValidator:
mask.Set(Bits(MsgTypeBitsEditValidator))
case MsgDelegate:
mask.Set(Bits(MsgTypeBitsDelegate))
case MsgBeginRedelegate:
mask.Set(Bits(MsgTypeBitsBeginRedelegate))
case MsgUndelegate:
mask.Set(Bits(MsgTypeBitsUndelegate))
case MsgCancelUnbondingDelegation:
mask.Set(Bits(MsgTypeBitsCancelUnbondingDelegation))
case MsgUnjail:
mask.Set(Bits(MsgTypeBitsUnjail))
case MsgSend:
mask.Set(Bits(MsgTypeBitsSend))
case MsgMultiSend:
mask.Set(Bits(MsgTypeBitsMultiSend))
case MsgCreateVestingAccount:
mask.Set(Bits(MsgTypeBitsCreateVestingAccount))
case MsgCreatePermanentLockedAccount:
mask.Set(Bits(MsgTypeBitsCreatePermanentLockedAccount))
case MsgCreatePeriodicVestingAccount:
mask.Set(Bits(MsgTypeBitsCreatePeriodicVestingAccount))
case MsgPayForBlobs:
mask.Set(Bits(MsgTypeBitsPayForBlobs))
case MsgGrant:
mask.Set(Bits(MsgTypeBitsGrant))
case MsgExec:
mask.Set(Bits(MsgTypeBitsExec))
case MsgRevoke:
mask.Set(Bits(MsgTypeBitsRevoke))
case MsgGrantAllowance:
mask.Set(Bits(MsgTypeBitsGrantAllowance))
case MsgRevokeAllowance:
mask.Set(Bits(MsgTypeBitsRevokeAllowance))
case MsgRegisterEVMAddress:
mask.Set(Bits(MsgTypeBitsRegisterEVMAddress))
case MsgSubmitProposal:
mask.Set(Bits(MsgTypeBitsSubmitProposal))
case MsgExecLegacyContent:
mask.Set(Bits(MsgTypeBitsExecLegacyContent))
case MsgVote:
mask.Set(Bits(MsgTypeBitsVote))
case MsgVoteWeighted:
mask.Set(Bits(MsgTypeBitsVoteWeighted))
case MsgDeposit:
mask.Set(Bits(MsgTypeBitsDeposit))
}
}
func (mask MsgTypeBits) Names() []MsgType {
names := make([]MsgType, mask.CountBits())
var i int
if mask.Has(Bits(MsgTypeBitsUnknown)) {
names[i] = MsgUnknown
i++
}
if mask.Has(Bits(MsgTypeBitsSetWithdrawAddress)) {
names[i] = MsgSetWithdrawAddress
}
if mask.Has(Bits(MsgTypeBitsWithdrawDelegatorReward)) {
names[i] = MsgWithdrawDelegatorReward
i++
}
if mask.Has(Bits(MsgTypeBitsWithdrawValidatorCommission)) {
names[i] = MsgWithdrawValidatorCommission
i++
}
if mask.Has(Bits(MsgTypeBitsFundCommunityPool)) {
names[i] = MsgFundCommunityPool
i++
}
if mask.Has(Bits(MsgTypeBitsCreateValidator)) {
names[i] = MsgCreateValidator
i++
}
if mask.Has(Bits(MsgTypeBitsEditValidator)) {
names[i] = MsgEditValidator
i++
}
if mask.Has(Bits(MsgTypeBitsDelegate)) {
names[i] = MsgDelegate
i++
}
if mask.Has(Bits(MsgTypeBitsBeginRedelegate)) {
names[i] = MsgBeginRedelegate
i++
}
if mask.Has(Bits(MsgTypeBitsUndelegate)) {
names[i] = MsgUndelegate
i++
}
if mask.Has(Bits(MsgTypeBitsCancelUnbondingDelegation)) {
names[i] = MsgCancelUnbondingDelegation
i++
}
if mask.Has(Bits(MsgTypeBitsUnjail)) {
names[i] = MsgUnjail
i++
}
if mask.Has(Bits(MsgTypeBitsSend)) {
names[i] = MsgSend
i++
}
if mask.Has(Bits(MsgTypeBitsMultiSend)) {
names[i] = MsgMultiSend
i++
}
if mask.Has(Bits(MsgTypeBitsCreateVestingAccount)) {
names[i] = MsgCreateVestingAccount
i++
}
if mask.Has(Bits(MsgTypeBitsCreatePermanentLockedAccount)) {
names[i] = MsgCreatePermanentLockedAccount
i++
}
if mask.Has(Bits(MsgTypeBitsCreatePeriodicVestingAccount)) {
names[i] = MsgCreatePeriodicVestingAccount
i++
}
if mask.Has(Bits(MsgTypeBitsPayForBlobs)) {
names[i] = MsgPayForBlobs
i++
}
if mask.Has(Bits(MsgTypeBitsGrant)) {
names[i] = MsgGrant
i++
}
if mask.Has(Bits(MsgTypeBitsExec)) {
names[i] = MsgExec
i++
}
if mask.Has(Bits(MsgTypeBitsRevoke)) {
names[i] = MsgRevoke
i++
}
if mask.Has(Bits(MsgTypeBitsGrantAllowance)) {
names[i] = MsgGrantAllowance
i++
}
if mask.Has(Bits(MsgTypeBitsRevokeAllowance)) {
names[i] = MsgRevokeAllowance
i++
}
if mask.Has(Bits(MsgTypeBitsRegisterEVMAddress)) {
names[i] = MsgRegisterEVMAddress
i++
}
if mask.Has(Bits(MsgTypeBitsSubmitProposal)) {
names[i] = MsgSubmitProposal
i++
}
if mask.Has(Bits(MsgTypeBitsExecLegacyContent)) {
names[i] = MsgExecLegacyContent
i++
}
if mask.Has(Bits(MsgTypeBitsVote)) {
names[i] = MsgVote
i++
}
if mask.Has(Bits(MsgTypeBitsVoteWeighted)) {
names[i] = MsgVoteWeighted
i++
}
if mask.Has(Bits(MsgTypeBitsDeposit)) {
names[i] = MsgDeposit
// i++
}
return names
}
func (mask MsgTypeBits) HasOne(value MsgTypeBits) bool {
return mask.Bits&value.Bits > 0
}
var _ sql.Scanner = (*MsgTypeBits)(nil)
func (mask *MsgTypeBits) Scan(src interface{}) (err error) {
switch val := src.(type) {
case int64:
mask.Bits = Bits(val)
case nil:
mask.Bits = 0
default:
return errors.Errorf("unknown bits database type: %T", src)
}
return nil
}
var _ driver.Valuer = (*MsgTypeBits)(nil)
func (mask MsgTypeBits) Value() (driver.Value, error) {
return uint64(mask.Bits), nil
}
// 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 (
// 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"
)
var ErrInvalidMsgType = errors.New("not a valid MsgType")
// 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,
}
}
// 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,
}
// 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
}
// 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 (
// StatusSuccess is a Status of type success.
StatusSuccess Status = "success"
// StatusFailed is a Status of type failed.
StatusFailed Status = "failed"
)
var ErrInvalidStatus = errors.New("not a valid Status")
// 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
pkgTypes "github.com/dipdup-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)
}
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"`
Address string `bun:"address,unique:address_validator,type:text" comment:"Validator address"`
Moniker string `bun:"moniker,type:text" comment:"Human-readable name for the validator"`
Website string `bun:"website,type:text" comment:"Website link"`
Identity string `bun:"identity,type:text" comment:"Optional identity signature"`
Contacts string `bun:"contacts,type:text" comment:"Contacts"`
Details string `bun:"details,type:text" comment:"Detailed information about validator"`
Rate decimal.Decimal `bun:"rate,type:numeric" comment:"Commission rate charged to delegators, as a fraction"`
MaxRate decimal.Decimal `bun:"max_rate,type:numeric" comment:"Maximum commission rate which validator can ever charge, as a fraction"`
MaxChangeRate decimal.Decimal `bun:"max_change_rate,type:numeric" comment:"Maximum daily increase of the validator commission, as a fraction"`
MinSelfDelegation decimal.Decimal `bun:"min_self_delegation,type:numeric" comment:""`
MsgId uint64 `bun:"msg_id" comment:"Message id when validator was created"`
Height pkgTypes.Level `bun:"height" comment:"Height when validator was created"`
}
func (Validator) TableName() string {
return "validator"
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package testsuite
import (
"time"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package testsuite
import "encoding/hex"
// 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
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package config
import (
"github.com/dipdup-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"`
}
// Substitute -
func (c *Config) Substitute() error {
if err := c.Config.Substitute(); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"github.com/cosmos/cosmos-sdk/types"
"github.com/pkg/errors"
)
type CoinReceived struct {
Amount *types.Coin
Receiver string
}
func NewCoinReceived(m map[string]any) (body CoinReceived, err error) {
body.Receiver = StringFromMap(m, "receiver")
if body.Receiver == "" {
err = errors.Errorf("receiver key not found in %##v", m)
return
}
body.Amount, err = BalanceFromMap(m, "amount")
return
}
type CoinSpent struct {
Amount *types.Coin
Spender string
}
func NewCoinSpent(m map[string]any) (body CoinSpent, err error) {
body.Spender = StringFromMap(m, "spender")
if body.Spender == "" {
err = errors.Errorf("spender key not found in %##v", m)
return
}
body.Amount, err = BalanceFromMap(m, "amount")
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/cosmos/cosmos-sdk/x/authz"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// 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(level types.Level, m *authz.MsgGrant) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgGrant
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, level)
return msgType, addresses, 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(level types.Level, m *authz.MsgExec) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgExec
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, level)
// 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.
return msgType, addresses, err
}
// 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(level types.Level, m *authz.MsgRevoke) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRevoke
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosBankTypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgSend represents a message to send coins from one account to another.
func MsgSend(level types.Level, m *cosmosBankTypes.MsgSend) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSend
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, level)
return msgType, addresses, err
}
// MsgMultiSend represents an arbitrary multi-in, multi-out send message.
func MsgMultiSend(level types.Level, 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(aData, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/celestiaorg/celestia-app/pkg/namespace"
appBlobTypes "github.com/celestiaorg/celestia-app/x/blob/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
)
// MsgPayForBlobs pays for the inclusion of a blob in the block.
func MsgPayForBlobs(level types.Level, m *appBlobTypes.MsgPayForBlobs) (storageTypes.MsgType, []storage.AddressWithType, []storage.Namespace, int64, error) {
var blobsSize int64
namespaces := make([]storage.Namespace, len(m.Namespaces))
for nsI, ns := range m.Namespaces {
if len(m.BlobSizes) < nsI {
return storageTypes.MsgUnknown, nil, nil, 0, errors.Errorf(
"blob sizes length=%d is less then namespaces index=%d", len(m.BlobSizes), nsI)
}
appNS := namespace.Namespace{Version: ns[0], ID: ns[1:]}
size := int64(m.BlobSizes[nsI])
blobsSize += size
namespaces[nsI] = storage.Namespace{
FirstHeight: level,
Version: appNS.Version,
NamespaceID: appNS.ID,
Size: size,
PfbCount: 1,
Reserved: appNS.IsReserved(),
}
}
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeSigner, address: m.Signer},
}, level)
return storageTypes.MsgPayForBlobs, addresses, namespaces, blobsSize, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
type addressData struct {
t storageTypes.MsgAddressType
address string
}
type addressesData []addressData
func createAddresses(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
}
addresses[i] = storage.AddressWithType{
Type: d.t,
Address: storage.Address{
Hash: hash,
Height: level,
LastHeight: level,
Address: d.address,
Balance: storage.EmptyBalance(),
},
}
}
return addresses, nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosDistributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgSetWithdrawAddress sets the withdrawal address for
// a delegator (or validator self-delegation).
func MsgSetWithdrawAddress(level types.Level, m *cosmosDistributionTypes.MsgSetWithdrawAddress) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSetWithdrawAddress
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeWithdraw, address: m.WithdrawAddress},
}, level)
return msgType, addresses, err
}
// MsgWithdrawDelegatorReward represents delegation withdrawal to a delegator
// from a single validator.
func MsgWithdrawDelegatorReward(level types.Level, m *cosmosDistributionTypes.MsgWithdrawDelegatorReward) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgWithdrawDelegatorReward
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
return msgType, addresses, err
}
// MsgWithdrawValidatorCommission withdraws the full commission to the validator
// address.
func MsgWithdrawValidatorCommission(level types.Level, m *cosmosDistributionTypes.MsgWithdrawValidatorCommission) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgWithdrawValidatorCommission
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
return msgType, addresses, err
}
// MsgFundCommunityPool allows an account to directly
// fund the community pool.
func MsgFundCommunityPool(level types.Level, m *cosmosDistributionTypes.MsgFundCommunityPool) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgFundCommunityPool
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDepositor, address: m.Depositor},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
"github.com/cosmos/cosmos-sdk/x/feegrant"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgGrantAllowance adds permission for Grantee to spend up to Allowance
// of fees from the account of Granter.
func MsgGrantAllowance(level types.Level, m *feegrant.MsgGrantAllowance) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgGrantAllowance
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, level)
return msgType, addresses, err
}
// MsgRevokeAllowance removes any existing Allowance from Granter to Grantee.
func MsgRevokeAllowance(level types.Level, m *feegrant.MsgRevokeAllowance) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRevokeAllowance
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeGranter, address: m.Granter},
{t: storageTypes.MsgAddressTypeGrantee, address: m.Grantee},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosGovTypesV1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgSubmitProposal defines a sdk.Msg type that supports submitting arbitrary
// proposal Content.
func MsgSubmitProposal(level types.Level, proposerAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgSubmitProposal
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeProposer, address: proposerAddress},
}, level)
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(level types.Level, m *cosmosGovTypesV1.MsgExecLegacyContent) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgExecLegacyContent
addresses, err := createAddresses(
addressesData{
{t: storageTypes.MsgAddressTypeAuthority, address: m.Authority},
}, level)
return msgType, addresses, err
}
// MsgVote defines a message to cast a vote.
func MsgVote(level types.Level, voterAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVote
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeVoter, address: voterAddress},
}, level)
return msgType, addresses, err
}
// MsgVoteWeighted defines a message to cast a vote.
func MsgVoteWeighted(level types.Level, voterAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgVoteWeighted
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeVoter, address: voterAddress},
}, level)
return msgType, addresses, err
}
// MsgDeposit defines a message to submit a deposit to an existing proposal.
func MsgDeposit(level types.Level, depositorAddress string) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgDeposit
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDepositor, address: depositorAddress},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
ibcTypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/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(level types.Level, m *ibcTypes.MsgTransfer) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.IBCTransfer
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeSender, address: m.Sender},
// {t: storageTypes.MsgAddressTypeReceiver,
// address: m.Receiver}, // TODO: is it data to do IBC Transfer on cosmos network?
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
qgbTypes "github.com/celestiaorg/celestia-app/x/qgb/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgRegisterEVMAddress registers an evm address to a validator.
func MsgRegisterEVMAddress(level types.Level, m *qgbTypes.MsgRegisterEVMAddress) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgRegisterEVMAddress
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
// TODO: think about EVM addresses
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosSlashingTypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgUnjail defines the Msg/Unjail request type
func MsgUnjail(level types.Level, m *cosmosSlashingTypes.MsgUnjail) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUnjail
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddr},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosStakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/shopspring/decimal"
)
// MsgCreateValidator defines an SDK message for creating a new validator.
func MsgCreateValidator(level types.Level, status storageTypes.Status, m *cosmosStakingTypes.MsgCreateValidator) (storageTypes.MsgType, []storage.AddressWithType, *storage.Validator, error) {
msgType := storageTypes.MsgCreateValidator
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
if status == storageTypes.StatusFailed {
return msgType, addresses, nil, nil
}
validator := storage.Validator{
Delegator: m.DelegatorAddress,
Address: m.ValidatorAddress,
Moniker: m.Description.Moniker,
Identity: m.Description.Identity,
Website: m.Description.Website,
Details: m.Description.Details,
Contacts: m.Description.SecurityContact,
Height: level,
Rate: decimal.Zero,
MaxRate: decimal.Zero,
MaxChangeRate: decimal.Zero,
MinSelfDelegation: decimal.Zero,
}
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())
}
return msgType, addresses, &validator, err
}
// MsgEditValidator defines a SDK message for editing an existing validator.
func MsgEditValidator(level types.Level, status storageTypes.Status, m *cosmosStakingTypes.MsgEditValidator) (storageTypes.MsgType, []storage.AddressWithType, *storage.Validator, error) {
msgType := storageTypes.MsgEditValidator
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
if status == storageTypes.StatusFailed {
return msgType, addresses, nil, 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: level,
Rate: decimal.Zero,
MinSelfDelegation: 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())
}
return msgType, addresses, &validator, err
}
// MsgDelegate defines a SDK message for performing a delegation of coins
// from a delegator to a validator.
func MsgDelegate(level types.Level, m *cosmosStakingTypes.MsgDelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgDelegate
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
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(level types.Level, m *cosmosStakingTypes.MsgBeginRedelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgBeginRedelegate
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidatorSrc, address: m.ValidatorSrcAddress},
{t: storageTypes.MsgAddressTypeValidatorDst, address: m.ValidatorDstAddress},
}, level)
return msgType, addresses, err
}
// MsgUndelegate defines a SDK message for performing an undelegation from a
// delegate and a validator.
func MsgUndelegate(level types.Level, m *cosmosStakingTypes.MsgUndelegate) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgUndelegate
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
return msgType, addresses, err
}
// MsgCancelUnbondingDelegation defines the SDK message for performing a cancel unbonding delegation for delegator
//
// Since: cosmos-sdk 0.46
func MsgCancelUnbondingDelegation(level types.Level, m *cosmosStakingTypes.MsgCancelUnbondingDelegation) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCancelUnbondingDelegation
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeDelegator, address: m.DelegatorAddress},
{t: storageTypes.MsgAddressTypeValidator, address: m.ValidatorAddress},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package handle
import (
cosmosVestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
// MsgCreateVestingAccount defines a message that enables creating a vesting
// account.
func MsgCreateVestingAccount(level types.Level, m *cosmosVestingTypes.MsgCreateVestingAccount) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreateVestingAccount
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, level)
return msgType, addresses, err
}
// MsgCreatePermanentLockedAccount defines a message that enables creating a permanent
// locked account.
//
// Since: cosmos-sdk 0.46
func MsgCreatePermanentLockedAccount(level types.Level, m *cosmosVestingTypes.MsgCreatePermanentLockedAccount) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreatePermanentLockedAccount
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, level)
return msgType, addresses, err
}
// MsgCreateVestingAccount defines a message that enables creating a vesting
// account.
//
// Since: cosmos-sdk 0.46
func MsgCreatePeriodicVestingAccount(level types.Level, m *cosmosVestingTypes.MsgCreatePeriodicVestingAccount) (storageTypes.MsgType, []storage.AddressWithType, error) {
msgType := storageTypes.MsgCreatePeriodicVestingAccount
addresses, err := createAddresses(addressesData{
{t: storageTypes.MsgAddressTypeFromAddress, address: m.FromAddress},
{t: storageTypes.MsgAddressTypeToAddress, address: m.ToAddress},
}, level)
return msgType, addresses, err
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"strings"
"github.com/cosmos/cosmos-sdk/types"
"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
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"github.com/cosmos/cosmos-sdk/x/authz"
ibcTypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode/handle"
"time"
"github.com/rs/zerolog/log"
appBlobTypes "github.com/celestiaorg/celestia-app/x/blob/types"
qgbTypes "github.com/celestiaorg/celestia-app/x/qgb/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/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/fatih/structs"
"github.com/pkg/errors"
)
type DecodedMsg struct {
Msg storage.Message
BlobsSize int64
Addresses []storage.AddressWithType
}
func Message(
msg cosmosTypes.Msg,
height types.Level,
time time.Time,
position int,
status storageTypes.Status,
) (d DecodedMsg, err error) {
d.Msg.Height = height
d.Msg.Time = time
d.Msg.Position = int64(position)
d.Msg.Data = structs.Map(msg)
switch typedMsg := msg.(type) {
// distribution module
case *cosmosDistributionTypes.MsgSetWithdrawAddress:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSetWithdrawAddress(height, typedMsg)
case *cosmosDistributionTypes.MsgWithdrawDelegatorReward:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgWithdrawDelegatorReward(height, typedMsg)
case *cosmosDistributionTypes.MsgWithdrawValidatorCommission:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgWithdrawValidatorCommission(height, typedMsg)
case *cosmosDistributionTypes.MsgFundCommunityPool:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgFundCommunityPool(height, typedMsg)
// staking module
case *cosmosStakingTypes.MsgCreateValidator:
d.Msg.Type, d.Msg.Addresses, d.Msg.Validator, err = handle.MsgCreateValidator(height, status, typedMsg)
case *cosmosStakingTypes.MsgEditValidator:
d.Msg.Type, d.Msg.Addresses, d.Msg.Validator, err = handle.MsgEditValidator(height, status, typedMsg)
case *cosmosStakingTypes.MsgDelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDelegate(height, typedMsg)
case *cosmosStakingTypes.MsgBeginRedelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgBeginRedelegate(height, typedMsg)
case *cosmosStakingTypes.MsgUndelegate:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUndelegate(height, typedMsg)
case *cosmosStakingTypes.MsgCancelUnbondingDelegation:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCancelUnbondingDelegation(height, typedMsg)
// slashing module
case *cosmosSlashingTypes.MsgUnjail:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgUnjail(height, typedMsg)
// bank module
case *cosmosBankTypes.MsgSend:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSend(height, typedMsg)
case *cosmosBankTypes.MsgMultiSend:
log.Warn().Msg("MsgMultiSend detected")
d.Msg.Type, d.Msg.Addresses, err = handle.MsgMultiSend(height, typedMsg)
// vesting module
case *cosmosVestingTypes.MsgCreateVestingAccount:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreateVestingAccount(height, typedMsg)
case *cosmosVestingTypes.MsgCreatePermanentLockedAccount:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreatePermanentLockedAccount(height, typedMsg)
case *cosmosVestingTypes.MsgCreatePeriodicVestingAccount:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgCreatePeriodicVestingAccount(height, typedMsg)
// blob module
case *appBlobTypes.MsgPayForBlobs:
d.Msg.Type, d.Msg.Addresses, d.Msg.Namespace, d.BlobsSize, err = handle.MsgPayForBlobs(height, typedMsg)
// feegrant module
case *cosmosFeegrant.MsgGrantAllowance:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgGrantAllowance(height, typedMsg)
case *cosmosFeegrant.MsgRevokeAllowance:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRevokeAllowance(height, typedMsg)
// qgb module
case *qgbTypes.MsgRegisterEVMAddress:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRegisterEVMAddress(height, typedMsg)
// authz module
case *authz.MsgGrant:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgGrant(height, typedMsg)
case *authz.MsgExec:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgExec(height, typedMsg)
case *authz.MsgRevoke:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgRevoke(height, typedMsg)
// gov module
case *cosmosGovTypesV1.MsgSubmitProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitProposal(height, typedMsg.Proposer)
case *cosmosGovTypesV1Beta1.MsgSubmitProposal:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgSubmitProposal(height, typedMsg.Proposer)
case *cosmosGovTypesV1.MsgExecLegacyContent:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgExecLegacyContent(height, typedMsg)
case *cosmosGovTypesV1.MsgVote:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVote(height, typedMsg.Voter)
case *cosmosGovTypesV1Beta1.MsgVote:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVote(height, typedMsg.Voter)
case *cosmosGovTypesV1.MsgVoteWeighted:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVoteWeighted(height, typedMsg.Voter)
case *cosmosGovTypesV1Beta1.MsgVoteWeighted:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgVoteWeighted(height, typedMsg.Voter)
case *cosmosGovTypesV1.MsgDeposit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDeposit(height, typedMsg.Depositor)
case *cosmosGovTypesV1Beta1.MsgDeposit:
d.Msg.Type, d.Msg.Addresses, err = handle.MsgDeposit(height, typedMsg.Depositor)
// ibc module
case *ibcTypes.MsgTransfer:
d.Msg.Type, d.Msg.Addresses, err = handle.IBCTransfer(height, typedMsg)
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)
}
d.Addresses = append(d.Addresses, d.Msg.Addresses...)
return
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package decode
import (
"github.com/celestiaorg/celestia-app/app"
"github.com/celestiaorg/celestia-app/app/encoding"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/dipdup-io/celestia-indexer/internal/consts"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
tmTypes "github.com/tendermint/tendermint/types"
)
type DecodedTx struct {
AuthInfo tx.AuthInfo
TimeoutHeight uint64
Memo string
Messages []cosmosTypes.Msg
Fee decimal.Decimal
Signers map[string]struct{}
}
var (
cfg, decoder = 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.AuthInfo, d.Fee, err = decodeAuthInfo(cfg, raw)
if err != nil {
return
}
d.TimeoutHeight, d.Memo, d.Messages, err = decodeCosmosTx(decoder, raw)
if err != nil {
return
}
d.Signers = make(map[string]struct{})
for i := range d.Messages {
for _, signer := range d.Messages[i].GetSigners() {
d.Signers[signer.String()] = struct{}{}
}
}
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, consts.Utia)
if !ok {
if fee, ok = getFeeInDenom(amount, consts.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 consts.Denom) (decimal.Decimal, bool) {
ok, utiaCoin := amount.Find(string(denom))
if !ok {
return decimal.Zero, false
}
switch denom {
case consts.Utia:
fee := decimal.NewFromBigInt(utiaCoin.Amount.BigInt(), 0)
return fee, true
case consts.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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"strconv"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/node/types"
)
func (module *Module) parseConstants(appState types.AppState, data *parsedData) {
// 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.Auth.Params.TxSigLimit,
})
// 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage/postgres"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/config"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"strings"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode"
"github.com/dipdup-io/celestia-indexer/pkg/node/types"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
type parsedData struct {
block storage.Block
addresses map[string]*storage.Address
constants []storage.Constant
denomMetadata []storage.DenomMetadata
}
func newParsedData() parsedData {
return parsedData{
addresses: make(map[string]*storage.Address),
constants: make([]storage.Constant, 0),
denomMetadata: make([]storage.DenomMetadata, 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,
},
}
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(msg, block.Height, block.Time, msgIndex, storageTypes.StatusSuccess)
if err != nil {
return data, errors.Wrap(err, "decode genesis message")
}
tx.Messages[msgIndex] = decoded.Msg
tx.MessageTypes.SetBit(decoded.Msg.Type)
tx.BlobsSize += decoded.BlobsSize
}
block.Txs = append(block.Txs, tx)
}
module.parseDenomMetadata(genesis.AppState.Bank.DenomMetadata, &data)
module.parseConstants(genesis.AppState, &data)
module.parseTotalSupply(genesis.AppState.Bank.Supply, &block)
if err := module.parseAccounts(genesis.AppState.Auth.Accounts, block.Height, &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.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, height pkgTypes.Level, data *parsedData) error {
for i := range accounts {
address := storage.Address{
Height: height,
LastHeight: height,
Balance: storage.Balance{
Total: decimal.Zero,
Currency: data.denomMetadata[0].Base,
},
}
var readableAddress string
switch {
case strings.Contains(accounts[i].Type, "PeriodicVestingAccount"):
readableAddress = accounts[i].BaseVestingAccount.BaseAccount.Address
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
case strings.Contains(accounts[i].Type, "DelayedVestingAccount"):
readableAddress = accounts[i].BaseVestingAccount.BaseAccount.Address
default:
return errors.Errorf("unknown account type: %s", accounts[i].Type)
}
_, 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{
Total: decimal.Zero,
Currency: balances[i].Coins[0].Denom,
},
}
if balance, err := decimal.NewFromString(balances[i].Coins[0].Amount); err == nil {
address.Balance.Total = address.Balance.Total.Add(balance)
}
if addr, ok := data.addresses[address.String()]; ok {
addr.Balance.Total = addr.Balance.Total.Add(address.Balance.Total)
} else {
data.addresses[address.String()] = &address
}
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package genesis
import (
"context"
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/postgres"
)
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.Total = addr.Balance.Total.Add(data.block.Txs[i].Signers[j].Balance.Total)
}
}
}
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)
}
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,
})
}
}
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,
}); 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"github.com/dipdup-io/celestia-indexer/internal/consts"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode"
pkgTypes "github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func parseCoinSpent(data map[string]any, height pkgTypes.Level) (*storage.Address, error) {
coinSpent, err := decode.NewCoinSpent(data)
if err != nil {
return nil, err
}
if coinSpent.Spender == "" {
return nil, nil
}
_, hash, err := pkgTypes.Address(coinSpent.Spender).Decode()
if err != nil {
return nil, errors.Wrapf(err, "decode spender: %s", coinSpent.Spender)
}
address := &storage.Address{
Address: coinSpent.Spender,
Hash: hash,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Currency: consts.DefaultCurrency,
Total: decimal.Zero,
},
}
if coinSpent.Amount != nil {
address.Balance.Currency = coinSpent.Amount.Denom
address.Balance.Total = decimal.NewFromBigInt(coinSpent.Amount.Amount.Neg().BigInt(), 0)
}
return address, nil
}
func parseCoinReceived(data map[string]any, height pkgTypes.Level) (*storage.Address, error) {
coinReceived, err := decode.NewCoinReceived(data)
if err != nil {
return nil, err
}
if coinReceived.Receiver == "" {
return nil, nil
}
_, hash, err := pkgTypes.Address(coinReceived.Receiver).Decode()
if err != nil {
return nil, errors.Wrapf(err, "decode receiver: %s", coinReceived.Receiver)
}
address := &storage.Address{
Address: coinReceived.Receiver,
Hash: hash,
Height: height,
LastHeight: height,
Balance: storage.Balance{
Currency: consts.DefaultCurrency,
Total: decimal.Zero,
},
}
if coinReceived.Amount != nil {
address.Balance.Currency = coinReceived.Amount.Denom
address.Balance.Total = decimal.NewFromBigInt(coinReceived.Amount.Amount.BigInt(), 0) // TODO: unit test
}
return address, nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
type eventsResult struct {
SupplyChange decimal.Decimal
InflationRate decimal.Decimal
Addresses []storage.Address
}
func (er *eventsResult) Fill(events []storage.Event) error {
er.Addresses = make([]storage.Address, 0)
for i := range events {
switch events[i].Type {
case types.EventTypeBurn:
amount := decode.Amount(events[i].Data)
er.SupplyChange = er.SupplyChange.Sub(amount)
case types.EventTypeMint:
er.InflationRate = decode.DecimalFromMap(events[i].Data, "inflation_rate")
amount := decode.Amount(events[i].Data)
er.SupplyChange = er.SupplyChange.Add(amount)
case types.EventTypeCoinReceived:
address, err := parseCoinReceived(events[i].Data, events[i].Height)
if err != nil {
return errors.Wrap(err, "parse coin received")
}
if address != nil {
er.Addresses = append(er.Addresses, *address)
}
case types.EventTypeCoinSpent:
address, err := parseCoinSpent(events[i].Data, events[i].Height)
if err != nil {
return errors.Wrap(err, "parse coin spent")
}
if address != nil {
er.Addresses = append(er.Addresses, *address)
}
}
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"context"
"github.com/dipdup-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(ctx, block); err != nil {
p.Log.Err(err).
Uint64("height", uint64(block.Height)).
Msg("block parsing error")
p.MustOutput(StopOutput).Push(struct{}{})
continue
}
}
}
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"context"
"time"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func (p *Module) parse(ctx context.Context, b types.BlockData) error {
start := time.Now()
p.Log.Info().
Int64("height", b.Block.Height).
Msg("parsing block...")
txs, err := parseTxs(b)
if err != nil {
return errors.Wrapf(err, "while parsing block on level=%d", b.Height)
}
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,
ChainId: b.Block.ChainID,
Txs: txs,
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,
},
}
allEvents := make([]storage.Event, 0)
block.Events = parseEvents(b, b.ResultBlockResults.BeginBlockEvents)
allEvents = append(allEvents, block.Events...)
for _, tx := range txs {
block.Stats.Fee = block.Stats.Fee.Add(tx.Fee)
block.MessageTypes.Set(tx.MessageTypes.Bits)
block.Stats.BlobsSize += tx.BlobsSize
allEvents = append(allEvents, tx.Events...)
}
endEvents := parseEvents(b, b.ResultBlockResults.EndBlockEvents)
block.Events = append(block.Events, endEvents...)
allEvents = append(allEvents, endEvents...)
var eventsResult eventsResult
if err := eventsResult.Fill(allEvents); err != nil {
return err
}
block.Stats.InflationRate = eventsResult.InflationRate
block.Stats.SupplyChange = eventsResult.SupplyChange
block.Addresses = eventsResult.Addresses
p.Log.Info().
Uint64("height", uint64(block.Height)).
Int64("ms", time.Since(start).Milliseconds()).
Msg("block parsed")
output := p.MustOutput(OutputName)
output.Push(block)
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"encoding/base64"
"github.com/rs/zerolog/log"
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
func parseEvents(b types.BlockData, events []types.Event) []storage.Event {
result := make([]storage.Event, len(events))
for i, eN := range events {
eS := parseEvent(b, eN, i)
result[i] = eS
}
return result
}
func parseEvent(b types.BlockData, eN types.Event, index int) storage.Event {
eventType, err := storageTypes.ParseEventType(eN.Type)
if err != nil {
log.Err(err).Msgf("got type %v", eN.Type)
eventType = storageTypes.EventTypeUnknown
}
event := storage.Event{
Height: b.Height,
Time: b.Block.Time,
Position: int64(index),
Type: eventType,
Data: make(map[string]any),
}
for _, attr := range eN.Attributes {
key := decodeEventAttribute(attr.Key)
value := decodeEventAttribute(attr.Value)
event.Data[key] = value
}
return event
}
var b64 = base64.StdEncoding
func decodeEventAttribute(data string) string {
dst, err := b64.DecodeString(data)
if err != nil {
return data
}
return string(dst)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
storageTypes "github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
func parseTxs(b types.BlockData) ([]storage.Tx, error) {
txs := make([]storage.Tx, len(b.TxsResults))
for i, txRes := range b.TxsResults {
t, err := parseTx(b, i, txRes)
if err != nil {
return nil, err
}
txs[i] = t
}
return txs, nil
}
func parseTx(b types.BlockData, index int, txRes *types.ResponseDeliverTx) (storage.Tx, error) {
d, err := decode.Tx(b, index)
if err != nil {
return storage.Tx{}, errors.Wrapf(err, "while parsing Tx on index %d", index)
}
t := storage.Tx{
Height: b.Height,
Time: b.Block.Time,
Position: int64(index),
GasWanted: txRes.GasWanted,
GasUsed: txRes.GasUsed,
TimeoutHeight: d.TimeoutHeight,
EventsCount: int64(len(txRes.Events)),
MessagesCount: int64(len(d.Messages)),
Fee: d.Fee,
Status: storageTypes.StatusSuccess,
Codespace: txRes.Codespace,
Hash: b.Block.Txs[index].Hash(),
Memo: d.Memo,
MessageTypes: storageTypes.NewMsgTypeBitMask(),
Messages: make([]storage.Message, len(d.Messages)),
Events: nil,
Signers: make([]storage.Address, 0),
BlobsSize: 0,
}
for signer := range d.Signers {
_, hash, err := types.Address(signer).Decode()
if err != nil {
return t, errors.Wrapf(err, "decode signer: %s", signer)
}
t.Signers = append(t.Signers, storage.Address{
Address: signer,
Height: t.Height,
LastHeight: t.Height,
Hash: hash,
Balance: storage.Balance{
Total: decimal.Zero,
},
})
}
if txRes.IsFailed() {
t.Status = storageTypes.StatusFailed
t.Error = txRes.Log
}
t.Events = parseEvents(b, txRes.Events)
for position, sdkMsg := range d.Messages {
dm, err := decode.Message(sdkMsg, b.Height, b.Block.Time, position, t.Status)
if err != nil {
return storage.Tx{}, errors.Wrapf(err, "while parsing tx=%v on index=%d", t.Hash, t.Position)
}
if txRes.IsFailed() {
dm.Msg.Namespace = nil
dm.BlobsSize = 0
}
t.Messages[position] = dm.Msg
t.MessageTypes.SetBit(dm.Msg.Type)
t.BlobsSize += dm.BlobsSize
}
return t, nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package parser
import (
"context"
"github.com/dipdup-net/indexer-sdk/pkg/modules"
)
type Module struct {
modules.BaseModule
}
var _ modules.Module = (*Module)(nil)
const (
InputName = "blocks"
OutputName = "data"
StopOutput = "stop"
)
func NewModule() Module {
m := Module{
BaseModule: modules.New("parser"),
}
m.CreateInput(InputName)
m.CreateOutput(OutputName)
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: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"sync"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/config"
"github.com/dipdup-io/celestia-indexer/pkg/node"
"github.com/dipdup-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"
)
const (
BlocksOutput = "blocks"
RollbackOutput = "signal"
RollbackInput = "state"
GenesisOutput = "genesis"
GenesisDoneInput = "genesis_done"
StopOutput = "stop"
)
// Module - runs through a chain with aim ti catch-up head and identifies either block is 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
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, 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,
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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"bytes"
"context"
"encoding/hex"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/pkg/errors"
"time"
)
func (r *Module) sync(ctx context.Context) {
var blocksCtx context.Context
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")
r.stopAll()
return
}
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) readBlocks(ctx context.Context) error {
headLevel, err := r.headLevel(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
level, _ := r.Level()
level += 1
for ; level <= headLevel; level++ {
select {
case <-ctx.Done():
return nil
default:
if _, ok := r.taskQueue.Get(level); !ok {
r.taskQueue.Set(level, struct{}{})
r.pool.AddTask(level)
}
}
}
return nil
}
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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package receiver
import (
"context"
"time"
"github.com/dipdup-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:
}
block, err := r.api.BlockData(ctx, level)
if err != nil {
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
break
}
r.Log.Info().
Uint64("height", uint64(result.Height)).
Int64("ms", time.Since(start).Milliseconds()).
Msg("received block")
r.blocks <- result
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/consts"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/types"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/decode"
pkgTypes "github.com/dipdup-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.Total = addr.Balance.Total.Add(address.Balance.Total)
} else {
lastHeight, err := tx.LastAddressAction(ctx, address.Hash)
if err != nil {
return nil, err
}
address.LastHeight = pkgTypes.Level(lastHeight)
updates[address.Address] = address
}
}
result := make([]*storage.Address, 0, len(updates))
for _, addr := range updates {
result = append(result, addr)
}
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: consts.DefaultCurrency,
Total: decimal.Zero,
}
if coinSpent.Amount != nil {
balance.Total = 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: consts.DefaultCurrency,
Total: decimal.Zero,
}
if coinReceived.Amount != nil {
balance.Total = 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"encoding/base64"
"encoding/hex"
"github.com/dipdup-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 {
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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"bytes"
"context"
"github.com/dipdup-io/celestia-indexer/pkg/node"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/config"
"github.com/dipdup-io/celestia-indexer/pkg/types"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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)
}
if err := tx.RollbackValidators(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.TotalFee = state.TotalFee.Sub(blockStats.Fee)
state.TotalSupply = state.TotalSupply.Sub(blockStats.SupplyChange)
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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package rollback
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
)
func saveAddresses(
ctx context.Context,
tx storage.Transaction,
addresses map[string]*storage.Address,
) (map[string]uint64, int64, error) {
if len(addresses) == 0 {
return nil, 0, nil
}
data := make([]*storage.Address, 0, len(addresses))
for key := range addresses {
data = append(data, addresses[key])
}
totalAccounts, err := tx.SaveAddresses(ctx, data...)
if err != nil {
return nil, 0, err
}
addToId := make(map[string]uint64)
balances := make([]storage.Balance, 0)
for i := range data {
addToId[data[i].Address] = data[i].Id
data[i].Balance.Id = data[i].Id
balances = append(balances, data[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 _, transaction := range txs {
for _, signer := range transaction.Signers {
if addrId, ok := addrToId[signer.Address]; ok {
txAddresses = append(txAddresses, storage.Signer{
TxId: transaction.Id,
AddressId: addrId,
})
}
}
}
return tx.SaveSigners(ctx, txAddresses...)
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import "github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-io/celestia-indexer/internal/storage"
)
func 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
validators = make([]*storage.Validator, 0)
namespaces = make(map[string]uint64)
addedMsgId = make(map[uint64]struct{})
)
for i := range messages {
for _, ns := range messages[i].Namespace {
nsId := ns.Id
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[ns.String()]
if !ok {
continue
}
nsId = id
} else {
namespaces[ns.String()] = 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,
})
}
if messages[i].Validator != nil {
messages[i].Validator.MsgId = messages[i].Id
validators = append(validators, messages[i].Validator)
}
for j := range messages[i].Addresses {
id, ok := addrToId[messages[i].Addresses[j].String()]
if !ok {
continue
}
msgAddress = append(msgAddress, storage.MsgAddress{
MsgId: messages[i].Id,
AddressId: id,
Type: messages[i].Addresses[j].Type,
})
}
}
if err := tx.SaveNamespaceMessage(ctx, namespaceMsgs...); err != nil {
return err
}
if err := tx.SaveValidators(ctx, validators...); err != nil {
return err
}
if err := tx.SaveMsgAddresses(ctx, msgAddress...); err != nil {
return err
}
return nil
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"github.com/dipdup-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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/pkg/types"
)
func updateState(block *storage.Block, totalAccounts int64, totalNamespaces int64, state *storage.State) {
if types.Level(block.Id) <= 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.TotalFee = state.TotalFee.Add(block.Stats.Fee)
state.TotalSupply = state.TotalSupply.Add(block.Stats.SupplyChange)
state.ChainId = block.ChainId
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package storage
import (
"context"
"strconv"
"time"
"github.com/dipdup-io/celestia-indexer/pkg/indexer/config"
"github.com/dipdup-io/celestia-indexer/internal/storage"
"github.com/dipdup-io/celestia-indexer/internal/storage/postgres"
"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
notificator storage.Notificator
indexerName string
}
var _ modules.Module = (*Module)(nil)
// NewModule -
func NewModule(
storage sdk.Transactable,
notificator storage.Notificator,
cfg config.Indexer,
) Module {
m := Module{
BaseModule: modules.New("storage"),
storage: storage,
notificator: notificator,
indexerName: cfg.Name,
}
m.CreateInput(InputName)
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")
module.MustOutput(StopOutput).Push(struct{}{})
continue
}
block, ok := msg.(storage.Block)
if !ok {
module.Log.Warn().Msgf("invalid message type: %T", msg)
continue
}
if err := module.saveBlock(ctx, &block); err != nil {
module.Log.Err(err).
Uint64("height", uint64(block.Height)).
Msg("block saving error")
module.MustOutput(StopOutput).Push(struct{}{})
continue
}
if err := module.notify(ctx, 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, block *storage.Block) error {
start := time.Now()
module.Log.Info().Uint64("height", uint64(block.Height)).Msg("saving block...")
tx, err := postgres.BeginTransaction(ctx, module.storage)
if err != nil {
return err
}
defer tx.Close(ctx)
if err := module.processBlockInTransaction(ctx, tx, block); err != nil {
return tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
return tx.HandleError(ctx, err)
}
module.Log.Info().
Uint64("height", uint64(block.Height)).
Time("block_time", block.Time).
Int64("block_ns_size", block.Stats.BlobsSize).
Str("block_fee", block.Stats.Fee.String()).
Int64("ms", time.Since(start).Milliseconds()).
Msg("block saved")
return nil
}
func (module *Module) processBlockInTransaction(ctx context.Context, tx storage.Transaction, block *storage.Block) error {
state, err := tx.State(ctx, module.indexerName)
if err != nil {
return err
}
block.Stats.BlockTime = uint64(block.Time.Sub(state.LastTime).Milliseconds())
if err := tx.Add(ctx, block); err != nil {
return err
}
if err := tx.Add(ctx, &block.Stats); err != nil {
return err
}
if err := tx.SaveTransactions(ctx, block.Txs...); err != nil {
return err
}
var (
messages = make([]*storage.Message, 0)
events = make([]storage.Event, 0)
namespaces = make(map[string]*storage.Namespace, 0)
addresses = make(map[string]*storage.Address, 0)
)
for i := range block.Addresses {
key := block.Addresses[i].String()
if addr, ok := addresses[key]; !ok {
addresses[key] = &block.Addresses[i]
} else {
addr.Balance.Total = addr.Balance.Total.Add(block.Addresses[i].Balance.Total)
}
}
events = append(events, block.Events...)
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[j])
}
for j := range block.Txs[i].Signers {
key := block.Txs[i].Signers[j].String()
if _, ok := addresses[key]; !ok {
addresses[key] = &block.Txs[i].Signers[j]
}
}
}
addrToId, totalAccounts, err := saveAddresses(ctx, tx, addresses)
if err != nil {
return err
}
if err := saveSigners(ctx, tx, addrToId, block.Txs); err != nil {
return err
}
if err := tx.SaveEvents(ctx, events...); err != nil {
return err
}
totalNamespaces, err := saveNamespaces(ctx, tx, namespaces)
if err != nil {
return err
}
if err := saveMessages(ctx, tx, messages, addrToId); err != nil {
return err
}
updateState(block, totalAccounts, totalNamespaces, &state)
if err := tx.Update(ctx, &state); err != nil {
return err
}
return nil
}
func (module *Module) notify(ctx context.Context, block storage.Block) error {
blockId := strconv.FormatUint(block.Id, 10)
if err := module.notificator.Notify(ctx, storage.ChannelHead, blockId); err != nil {
return err
}
for i := range block.Txs {
txId := strconv.FormatUint(block.Txs[i].Id, 10)
if err := module.notificator.Notify(ctx, storage.ChannelTx, txId); err != nil {
return err
}
}
return nil
}
// 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/dipdup-io/celestia-indexer/pkg/node/types"
types0 "github.com/dipdup-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) *ApiBlockCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Block", reflect.TypeOf((*MockApi)(nil).Block), ctx, level)
return &ApiBlockCall{Call: call}
}
// ApiBlockCall wrap *gomock.Call
type ApiBlockCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiBlockCall) Return(arg0 types0.ResultBlock, arg1 error) *ApiBlockCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiBlockCall) Do(f func(context.Context, types0.Level) (types0.ResultBlock, error)) *ApiBlockCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiBlockCall) DoAndReturn(f func(context.Context, types0.Level) (types0.ResultBlock, error)) *ApiBlockCall {
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) *ApiBlockDataCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockData", reflect.TypeOf((*MockApi)(nil).BlockData), ctx, level)
return &ApiBlockDataCall{Call: call}
}
// ApiBlockDataCall wrap *gomock.Call
type ApiBlockDataCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiBlockDataCall) Return(arg0 types0.BlockData, arg1 error) *ApiBlockDataCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiBlockDataCall) Do(f func(context.Context, types0.Level) (types0.BlockData, error)) *ApiBlockDataCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiBlockDataCall) DoAndReturn(f func(context.Context, types0.Level) (types0.BlockData, error)) *ApiBlockDataCall {
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) *ApiBlockResultsCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockResults", reflect.TypeOf((*MockApi)(nil).BlockResults), ctx, level)
return &ApiBlockResultsCall{Call: call}
}
// ApiBlockResultsCall wrap *gomock.Call
type ApiBlockResultsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiBlockResultsCall) Return(arg0 types0.ResultBlockResults, arg1 error) *ApiBlockResultsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiBlockResultsCall) Do(f func(context.Context, types0.Level) (types0.ResultBlockResults, error)) *ApiBlockResultsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiBlockResultsCall) DoAndReturn(f func(context.Context, types0.Level) (types0.ResultBlockResults, error)) *ApiBlockResultsCall {
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) *ApiGenesisCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Genesis", reflect.TypeOf((*MockApi)(nil).Genesis), ctx)
return &ApiGenesisCall{Call: call}
}
// ApiGenesisCall wrap *gomock.Call
type ApiGenesisCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiGenesisCall) Return(arg0 types.Genesis, arg1 error) *ApiGenesisCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiGenesisCall) Do(f func(context.Context) (types.Genesis, error)) *ApiGenesisCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiGenesisCall) DoAndReturn(f func(context.Context) (types.Genesis, error)) *ApiGenesisCall {
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) *ApiHeadCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Head", reflect.TypeOf((*MockApi)(nil).Head), ctx)
return &ApiHeadCall{Call: call}
}
// ApiHeadCall wrap *gomock.Call
type ApiHeadCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiHeadCall) Return(arg0 types0.ResultBlock, arg1 error) *ApiHeadCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiHeadCall) Do(f func(context.Context) (types0.ResultBlock, error)) *ApiHeadCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiHeadCall) DoAndReturn(f func(context.Context) (types0.ResultBlock, error)) *ApiHeadCall {
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) *ApiStatusCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockApi)(nil).Status), ctx)
return &ApiStatusCall{Call: call}
}
// ApiStatusCall wrap *gomock.Call
type ApiStatusCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *ApiStatusCall) Return(arg0 types.Status, arg1 error) *ApiStatusCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *ApiStatusCall) Do(f func(context.Context) (types.Status, error)) *ApiStatusCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *ApiStatusCall) DoAndReturn(f func(context.Context) (types.Status, error)) *ApiStatusCall {
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) *DalApiBlobCall {
mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Blob", reflect.TypeOf((*MockDalApi)(nil).Blob), ctx, height, namespace, commitment)
return &DalApiBlobCall{Call: call}
}
// DalApiBlobCall wrap *gomock.Call
type DalApiBlobCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *DalApiBlobCall) Return(arg0 types.Blob, arg1 error) *DalApiBlobCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *DalApiBlobCall) Do(f func(context.Context, types0.Level, string, string) (types.Blob, error)) *DalApiBlobCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *DalApiBlobCall) DoAndReturn(f func(context.Context, types0.Level, string, string) (types.Blob, error)) *DalApiBlobCall {
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) *DalApiBlobsCall {
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 &DalApiBlobsCall{Call: call}
}
// DalApiBlobsCall wrap *gomock.Call
type DalApiBlobsCall struct {
*gomock.Call
}
// Return rewrite *gomock.Call.Return
func (c *DalApiBlobsCall) Return(arg0 []types.Blob, arg1 error) *DalApiBlobsCall {
c.Call = c.Call.Return(arg0, arg1)
return c
}
// Do rewrite *gomock.Call.Do
func (c *DalApiBlobsCall) Do(f func(context.Context, types0.Level, ...string) ([]types.Blob, error)) *DalApiBlobsCall {
c.Call = c.Call.Do(f)
return c
}
// DoAndReturn rewrite *gomock.Call.DoAndReturn
func (c *DalApiBlobsCall) DoAndReturn(f func(context.Context, types0.Level, ...string) ([]types.Blob, error)) *DalApiBlobsCall {
c.Call = c.Call.DoAndReturn(f)
return c
}
// SPDX-FileCopyrightText: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"encoding/json"
"fmt"
"time"
"github.com/dipdup-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 string `json:"end_time"`
}
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"`
}
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: 2023 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: 2023 PK Lab AG <contact@pklab.io>
// SPDX-License-Identifier: MIT
package types
import (
"encoding/hex"
"math/big"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
// celestia prefixes
const (
AddressPrefixCelestia = "celestia"
AddressPrefixValoper = "celestiavaloper"
)
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)
}
// SPDX-FileCopyrightText: 2023 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 string `json:"key,omitempty" protobuf:"bytes,1,opt,name=key,proto3"`
Value string `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 any `json:"pub_key" protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3"` // crypto.PublicKey
Power int64 `json:"power,omitempty,string" protobuf:"varint,2,opt,name=power,proto3"`
}
// 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: 2023 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 lenght: %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: 2023 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)
}