historydb

package
v1.3.0-rc1 Latest Latest
Warning

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

Go to latest
Published: May 20, 2021 License: AGPL-3.0 Imports: 18 Imported by: 2

Documentation

Overview

Package historydb is responsible for storing and retrieving the historic data of the Hermez network. It's mostly but not exclusively used by the API and the synchronizer.

Apart from the logic defined in this package, it's important to notice that there are some triggers defined in the migration files that have to be taken into consideration to understanding the results of some queries. This is especially true for reorgs: all the data is directly or indirectly related to a block, this makes handling reorgs as easy as deleting the reorged blocks from the block table, and all related items will be dropped in cascade. This is not the only case, in general functions defined in this package that get affected somehow by the SQL level defined logic has a special mention on the function description.

Some of the database tooling used in this package such as meddler and migration tools is explained in the db package.

This package is spitted in different files following these ideas: - historydb.go: constructor and functions used by packages other than the api. - apiqueries.go: functions used by the API, the queries implemented in this functions use a semaphore to restrict the maximum concurrent connections to the database. - views.go: structs used to retrieve/store data from/to the database. When possible, the common structs are used, however most of the time there is no 1:1 relation between the struct fields and the tables of the schema, especially when joining tables. In some cases, some of the structs defined in this file also include custom Marshallers to easily match the expected api formats. - nodeinfo.go: used to handle the interfaces and structs that allow communication across running in different machines/process but sharing the same database.

Index

Constants

View Source
const (
	// CreateAccountExtraFeePercentage is the multiplication factor over
	// the average fee for CreateAccount that is applied to obtain the
	// recommended fee for CreateAccount
	CreateAccountExtraFeePercentage float64 = 2.5
	// CreateAccountInternalExtraFeePercentage is the multiplication factor
	// over the average fee for CreateAccountInternal that is applied to
	// obtain the recommended fee for CreateAccountInternal
	CreateAccountInternalExtraFeePercentage float64 = 2.0
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountAPI

type AccountAPI struct {
	ItemID           uint64              `meddler:"item_id"`
	Idx              apitypes.HezIdx     `meddler:"idx"`
	BatchNum         common.BatchNum     `meddler:"batch_num"`
	PublicKey        apitypes.HezBJJ     `meddler:"bjj"`
	EthAddr          apitypes.HezEthAddr `meddler:"eth_addr"`
	Nonce            common.Nonce        `meddler:"nonce"`   // max of 40 bits used
	Balance          *apitypes.BigIntStr `meddler:"balance"` // max of 192 bits used
	TotalItems       uint64              `meddler:"total_items"`
	FirstItem        uint64              `meddler:"first_item"`
	LastItem         uint64              `meddler:"last_item"`
	TokenID          common.TokenID      `meddler:"token_id"`
	TokenItemID      int                 `meddler:"token_item_id"`
	TokenEthBlockNum int64               `meddler:"token_block"`
	TokenEthAddr     ethCommon.Address   `meddler:"token_eth_addr"`
	TokenName        string              `meddler:"name"`
	TokenSymbol      string              `meddler:"symbol"`
	TokenDecimals    uint64              `meddler:"decimals"`
	TokenUSD         *float64            `meddler:"usd"`
	TokenUSDUpdate   *time.Time          `meddler:"usd_update"`
}

AccountAPI is a representation of a account with additional information required by the API

func (AccountAPI) MarshalJSON

func (account AccountAPI) MarshalJSON() ([]byte, error)

MarshalJSON is used to neast some of the fields of AccountAPI without the need of auxiliar structs

type AuctionVariablesAPI

type AuctionVariablesAPI struct {
	EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
	// DonationAddress Address where the donations will be sent
	DonationAddress ethCommon.Address `json:"donationAddress" meddler:"donation_address" validate:"required"`
	// BootCoordinator Address of the boot coordinator
	BootCoordinator ethCommon.Address `json:"bootCoordinator" meddler:"boot_coordinator" validate:"required"`
	// BootCoordinatorURL URL of the boot coordinator
	BootCoordinatorURL string `json:"bootCoordinatorUrl" meddler:"boot_coordinator_url" validate:"required"`
	// DefaultSlotSetBid The minimum bid value in a series of 6 slots
	DefaultSlotSetBid [6]*apitypes.BigIntStr `json:"defaultSlotSetBid" meddler:"default_slot_set_bid,json" validate:"required"`
	// DefaultSlotSetBidSlotNum SlotNum at which the new default_slot_set_bid applies
	DefaultSlotSetBidSlotNum int64 `json:"defaultSlotSetBidSlotNum" meddler:"default_slot_set_bid_slot_num"`
	// ClosedAuctionSlots Distance (#slots) to the closest slot to which you can bid ( 2 Slots = 2 * 40 Blocks = 20 min )
	ClosedAuctionSlots uint16 `json:"closedAuctionSlots" meddler:"closed_auction_slots" validate:"required"`
	// OpenAuctionSlots Distance (#slots) to the farthest slot to which you can bid (30 days = 4320 slots )
	OpenAuctionSlots uint16 `json:"openAuctionSlots" meddler:"open_auction_slots" validate:"required"`
	// AllocationRatio How the HEZ tokens deposited by the slot winner are distributed (Burn: 40% - Donation: 40% - HGT: 20%)
	AllocationRatio [3]uint16 `json:"allocationRatio" meddler:"allocation_ratio,json" validate:"required"`
	// Outbidding Minimum outbid (percentage) over the previous one to consider it valid
	Outbidding uint16 `json:"outbidding" meddler:"outbidding" validate:"required"`
	// SlotDeadline Number of blocks at the end of a slot in which any coordinator can forge if the winner has not forged one before
	SlotDeadline uint8 `json:"slotDeadline" meddler:"slot_deadline" validate:"required"`
}

AuctionVariablesAPI are the variables of the Auction Smart Contract

func NewAuctionVariablesAPI

func NewAuctionVariablesAPI(auctionVariables *common.AuctionVariables) *AuctionVariablesAPI

NewAuctionVariablesAPI creates a AuctionVariablesAPI from common.AuctionVariables

type BatchAPI

type BatchAPI struct {
	ItemID           uint64                      `json:"itemId" meddler:"item_id"`
	BatchNum         common.BatchNum             `json:"batchNum" meddler:"batch_num"`
	EthereumTxHash   ethCommon.Hash              `json:"ethereumTxHash" meddler:"eth_tx_hash"`
	EthBlockNum      int64                       `json:"ethereumBlockNum" meddler:"eth_block_num"`
	EthBlockHash     ethCommon.Hash              `json:"ethereumBlockHash" meddler:"hash"`
	Timestamp        time.Time                   `json:"timestamp" meddler:"timestamp,utctime"`
	ForgerAddr       ethCommon.Address           `json:"forgerAddr" meddler:"forger_addr"`
	CollectedFeesDB  map[common.TokenID]*big.Int `json:"-" meddler:"fees_collected,json"`
	CollectedFeesAPI apitypes.CollectedFeesAPI   `json:"collectedFees" meddler:"-"`
	TotalFeesUSD     *float64                    `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
	StateRoot        apitypes.BigIntStr          `json:"stateRoot" meddler:"state_root"`
	NumAccounts      int                         `json:"numAccounts" meddler:"num_accounts"`
	ExitRoot         apitypes.BigIntStr          `json:"exitRoot" meddler:"exit_root"`
	ForgeL1TxsNum    *int64                      `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
	SlotNum          int64                       `json:"slotNum" meddler:"slot_num"`
	ForgedTxs        int                         `json:"forgedTransactions" meddler:"forged_txs"`
	TotalItems       uint64                      `json:"-" meddler:"total_items"`
	FirstItem        uint64                      `json:"-" meddler:"first_item"`
	LastItem         uint64                      `json:"-" meddler:"last_item"`
}

BatchAPI is a representation of a batch with additional information required by the API, and extracted by joining block table

type BidAPI

type BidAPI struct {
	ItemID      uint64             `json:"itemId" meddler:"item_id"`
	SlotNum     int64              `json:"slotNum" meddler:"slot_num"`
	BidValue    apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
	EthBlockNum int64              `json:"ethereumBlockNum" meddler:"eth_block_num"`
	Bidder      ethCommon.Address  `json:"bidderAddr" meddler:"bidder_addr"`
	Forger      ethCommon.Address  `json:"forgerAddr" meddler:"forger_addr"`
	URL         string             `json:"URL" meddler:"url"`
	Timestamp   time.Time          `json:"timestamp" meddler:"timestamp,utctime"`
	TotalItems  uint64             `json:"-" meddler:"total_items"`
	FirstItem   uint64             `json:"-" meddler:"first_item"`
	LastItem    uint64             `json:"-" meddler:"last_item"`
}

BidAPI is a representation of a bid with additional information required by the API

type BucketParamsAPI

type BucketParamsAPI struct {
	CeilUSD         *apitypes.BigIntStr `json:"ceilUSD"`
	BlockStamp      *apitypes.BigIntStr `json:"blockStamp"`
	Withdrawals     *apitypes.BigIntStr `json:"withdrawals"`
	RateBlocks      *apitypes.BigIntStr `json:"rateBlocks"`
	RateWithdrawals *apitypes.BigIntStr `json:"rateWithdrawals"`
	MaxWithdrawals  *apitypes.BigIntStr `json:"maxWithdrawals"`
}

BucketParamsAPI are the parameter variables of each Bucket of Rollup Smart Contract

type BucketUpdateAPI

type BucketUpdateAPI struct {
	EthBlockNum int64               `json:"ethereumBlockNum" meddler:"eth_block_num"`
	NumBucket   int                 `json:"numBucket" meddler:"num_bucket"`
	BlockStamp  int64               `json:"blockStamp" meddler:"block_stamp"`
	Withdrawals *apitypes.BigIntStr `json:"withdrawals" meddler:"withdrawals"`
}

BucketUpdateAPI are the bucket updates (tracking the withdrawals value changes) in Rollup Smart Contract

type Constants

type Constants struct {
	common.SCConsts
	ChainID       uint16
	HermezAddress ethCommon.Address
}

Constants contains network constants

type CoordinatorAPI

type CoordinatorAPI struct {
	ItemID      uint64            `json:"itemId" meddler:"item_id"`
	Bidder      ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
	Forger      ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
	EthBlockNum int64             `json:"ethereumBlock" meddler:"eth_block_num"`
	URL         string            `json:"URL" meddler:"url"`
	TotalItems  uint64            `json:"-" meddler:"total_items"`
	FirstItem   uint64            `json:"-" meddler:"first_item"`
	LastItem    uint64            `json:"-" meddler:"last_item"`
}

CoordinatorAPI is a representation of a coordinator with additional information required by the API

type ExitAPI

type ExitAPI struct {
	ItemID                 uint64                          `meddler:"item_id"`
	BatchNum               common.BatchNum                 `meddler:"batch_num"`
	AccountIdx             apitypes.HezIdx                 `meddler:"account_idx"`
	EthAddr                *apitypes.HezEthAddr            `meddler:"eth_addr"`
	BJJ                    *apitypes.HezBJJ                `meddler:"bjj"`
	MerkleProof            *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
	Balance                apitypes.BigIntStr              `meddler:"balance"`
	InstantWithdrawn       *int64                          `meddler:"instant_withdrawn"`
	DelayedWithdrawRequest *int64                          `meddler:"delayed_withdraw_request"`
	DelayedWithdrawn       *int64                          `meddler:"delayed_withdrawn"`
	TotalItems             uint64                          `meddler:"total_items"`
	FirstItem              uint64                          `meddler:"first_item"`
	LastItem               uint64                          `meddler:"last_item"`
	TokenID                common.TokenID                  `meddler:"token_id"`
	TokenItemID            uint64                          `meddler:"token_item_id"`
	TokenEthBlockNum       int64                           `meddler:"token_block"`
	TokenEthAddr           ethCommon.Address               `meddler:"token_eth_addr"`
	TokenName              string                          `meddler:"name"`
	TokenSymbol            string                          `meddler:"symbol"`
	TokenDecimals          uint64                          `meddler:"decimals"`
	TokenUSD               *float64                        `meddler:"usd"`
	TokenUSDUpdate         *time.Time                      `meddler:"usd_update"`
}

ExitAPI is a representation of a exit with additional information required by the API, and extracted by joining token table

func (ExitAPI) MarshalJSON

func (e ExitAPI) MarshalJSON() ([]byte, error)

MarshalJSON is used to neast some of the fields of ExitAPI without the need of auxiliar structs

type GetAccountsAPIRequest added in v1.2.0

type GetAccountsAPIRequest struct {
	TokenIDs []common.TokenID
	EthAddr  *ethCommon.Address
	Bjj      *babyjub.PublicKeyComp

	FromItem *uint
	Limit    *uint
	Order    string
}

GetAccountsAPIRequest is an API request struct for getting accounts

type GetBatchesAPIRequest added in v1.2.0

type GetBatchesAPIRequest struct {
	MinBatchNum *uint
	MaxBatchNum *uint
	SlotNum     *uint
	ForgerAddr  *ethCommon.Address

	FromItem *uint
	Limit    *uint
	Order    string
}

GetBatchesAPIRequest is an API request struct for getting batches

type GetBestBidsAPIRequest added in v1.2.0

type GetBestBidsAPIRequest struct {
	MinSlotNum *int64
	MaxSlotNum *int64
	BidderAddr *ethCommon.Address

	Limit *uint
	Order string
}

GetBestBidsAPIRequest is an API request struct for getting best bids

type GetBidsAPIRequest added in v1.2.0

type GetBidsAPIRequest struct {
	SlotNum    *int64
	BidderAddr *ethCommon.Address

	FromItem *uint
	Limit    *uint
	Order    string
}

GetBidsAPIRequest is an API request struct for getting bids

type GetCoordinatorsAPIRequest added in v1.2.0

type GetCoordinatorsAPIRequest struct {
	BidderAddr *ethCommon.Address
	ForgerAddr *ethCommon.Address

	FromItem *uint
	Limit    *uint
	Order    string
}

GetCoordinatorsAPIRequest is an API request struct for getting coordinators

type GetExitsAPIRequest added in v1.2.0

type GetExitsAPIRequest struct {
	EthAddr              *ethCommon.Address
	Bjj                  *babyjub.PublicKeyComp
	TokenID              *common.TokenID
	Idx                  *common.Idx
	BatchNum             *uint
	OnlyPendingWithdraws *bool

	FromItem *uint
	Limit    *uint
	Order    string
}

GetExitsAPIRequest is an API request struct for getting exits

type GetTokensAPIRequest added in v1.2.0

type GetTokensAPIRequest struct {
	Ids     []common.TokenID
	Symbols []string
	Name    string

	FromItem *uint
	Limit    *uint
	Order    string
}

GetTokensAPIRequest is an API request struct for getting tokens

type GetTxsAPIRequest added in v1.2.0

type GetTxsAPIRequest struct {
	EthAddr           *ethCommon.Address
	FromEthAddr       *ethCommon.Address
	ToEthAddr         *ethCommon.Address
	Bjj               *babyjub.PublicKeyComp
	FromBjj           *babyjub.PublicKeyComp
	ToBjj             *babyjub.PublicKeyComp
	TokenID           *common.TokenID
	Idx               *common.Idx
	FromIdx           *common.Idx
	ToIdx             *common.Idx
	BatchNum          *uint
	TxType            *common.TxType
	IncludePendingL1s *bool

	FromItem *uint
	Limit    *uint
	Order    string
}

GetTxsAPIRequest is an API request struct for getting txs

type HistoryDB

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

HistoryDB persist the historic of the rollup

func NewHistoryDB

func NewHistoryDB(dbRead, dbWrite *sqlx.DB, apiConnCon *db.APIConnectionController) *HistoryDB

NewHistoryDB initialize the DB

func (*HistoryDB) AddAccountUpdates

func (hdb *HistoryDB) AddAccountUpdates(accUpdates []common.AccountUpdate) error

AddAccountUpdates inserts accUpdates into the DB

func (*HistoryDB) AddAccounts

func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error

AddAccounts insert accounts into the DB

func (*HistoryDB) AddAuctionVars

func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error

AddAuctionVars insert auction vars into the DB

func (*HistoryDB) AddBatch

func (hdb *HistoryDB) AddBatch(batch *common.Batch) error

AddBatch insert a Batch into the DB

func (*HistoryDB) AddBatches

func (hdb *HistoryDB) AddBatches(batches []common.Batch) error

AddBatches insert Bids into the DB

func (*HistoryDB) AddBids

func (hdb *HistoryDB) AddBids(bids []common.Bid) error

AddBids insert Bids into the DB

func (*HistoryDB) AddBlock

func (hdb *HistoryDB) AddBlock(block *common.Block) error

AddBlock insert a block into the DB

func (*HistoryDB) AddBlockSCData

func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error)

AddBlockSCData stores all the information of a block retrieved by the Synchronizer. Blocks should be inserted in order, leaving no gaps because the pagination system of the API/DB depends on this. Within blocks, all items should also be in the correct order (Accounts, Tokens, Txs, etc.)

func (*HistoryDB) AddBlocks

func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error

AddBlocks inserts blocks into the DB

func (*HistoryDB) AddBucketUpdatesTest

func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error

AddBucketUpdatesTest allows call to unexported method only for internal testing purposes

func (*HistoryDB) AddCoordinators

func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error

AddCoordinators insert Coordinators into the DB

func (*HistoryDB) AddExitTree

func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error

AddExitTree insert Exit tree into the DB

func (*HistoryDB) AddL1Txs

func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error

AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx. If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user, BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx. EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.

func (*HistoryDB) AddL2Txs

func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error

AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.

func (*HistoryDB) AddToken

func (hdb *HistoryDB) AddToken(token *common.Token) error

AddToken insert a token into the DB

func (*HistoryDB) AddTokens

func (hdb *HistoryDB) AddTokens(tokens []common.Token) error

AddTokens insert tokens into the DB

func (*HistoryDB) CanSendToEthAddr added in v1.1.0

func (hdb *HistoryDB) CanSendToEthAddr(ethAddr ethCommon.Address, tokenID common.TokenID) (bool, error)

CanSendToEthAddr returns true if it's possible to send a tx to an Eth addr either because there is an idx associated to the Eth addr and token or the cordinator has an authorization to create a valid account

func (*HistoryDB) DB

func (hdb *HistoryDB) DB() *sqlx.DB

DB returns a pointer to the L2DB.db. This method should be used only for internal testing purposes.

func (*HistoryDB) GetAccountAPI

func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error)

GetAccountAPI returns an account by its index

func (*HistoryDB) GetAccountsAPI

func (hdb *HistoryDB) GetAccountsAPI(
	request GetAccountsAPIRequest,
) ([]AccountAPI, uint64, error)

GetAccountsAPI returns a list of accounts from the DB and pagination info

func (*HistoryDB) GetAllAccountUpdates

func (hdb *HistoryDB) GetAllAccountUpdates() ([]common.AccountUpdate, error)

GetAllAccountUpdates returns all the AccountUpdate from the DB

func (*HistoryDB) GetAllAccounts

func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error)

GetAllAccounts returns a list of accounts from the DB

func (*HistoryDB) GetAllBatches

func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error)

GetAllBatches retrieve all batches from the DB

func (*HistoryDB) GetAllBids

func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error)

GetAllBids retrieve all bids from the DB

func (*HistoryDB) GetAllBlocks

func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error)

GetAllBlocks retrieve all blocks from the DB

func (*HistoryDB) GetAllBucketUpdates

func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error)

GetAllBucketUpdates retrieves all the bucket updates

func (*HistoryDB) GetAllEscapeHatchWithdrawals

func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error)

GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals

func (*HistoryDB) GetAllExits

func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error)

GetAllExits returns all exit from the DB

func (*HistoryDB) GetAllL1CoordinatorTxs

func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error)

GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB

func (*HistoryDB) GetAllL1UserTxs

func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error)

GetAllL1UserTxs returns all L1UserTxs from the DB

func (*HistoryDB) GetAllL2Txs

func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error)

GetAllL2Txs returns all L2Txs from the DB

func (*HistoryDB) GetAllTokenExchanges

func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error)

GetAllTokenExchanges retrieves all the token exchanges

func (*HistoryDB) GetAllTokens

func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error)

GetAllTokens returns all tokens from the DB

func (*HistoryDB) GetAuctionVarsAPI

func (hdb *HistoryDB) GetAuctionVarsAPI() (*common.AuctionVariables, error)

GetAuctionVarsAPI returns auction variables

func (*HistoryDB) GetBatch

func (hdb *HistoryDB) GetBatch(batchNum common.BatchNum) (*common.Batch, error)

GetBatch returns the batch with the given batchNum

func (*HistoryDB) GetBatchAPI

func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error)

GetBatchAPI return the batch with the given batchNum

func (*HistoryDB) GetBatchInternalAPI

func (hdb *HistoryDB) GetBatchInternalAPI(batchNum common.BatchNum) (*BatchAPI, error)

GetBatchInternalAPI return the batch with the given batchNum

func (*HistoryDB) GetBatches

func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error)

GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to

func (*HistoryDB) GetBatchesAPI

func (hdb *HistoryDB) GetBatchesAPI(
	request GetBatchesAPIRequest,
) ([]BatchAPI, uint64, error)

GetBatchesAPI return the batches applying the given filters

func (*HistoryDB) GetBestBidAPI

func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error)

GetBestBidAPI returns the best bid in specific slot by slotNum

func (*HistoryDB) GetBestBidCoordinator

func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error)

GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum

func (*HistoryDB) GetBestBidsAPI

func (hdb *HistoryDB) GetBestBidsAPI(request GetBestBidsAPIRequest) ([]BidAPI, uint64, error)

GetBestBidsAPI returns the best bid in specific slot by slotNum

func (*HistoryDB) GetBidsAPI

func (hdb *HistoryDB) GetBidsAPI(request GetBidsAPIRequest) ([]BidAPI, uint64, error)

GetBidsAPI return the bids applying the given filters

func (*HistoryDB) GetBlock

func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error)

GetBlock retrieve a block from the DB, given a block number

func (*HistoryDB) GetBucketUpdatesInternalAPI

func (hdb *HistoryDB) GetBucketUpdatesInternalAPI() ([]BucketUpdateAPI, error)

GetBucketUpdatesInternalAPI returns the latest bucket updates

func (*HistoryDB) GetCommonAccountAPI

func (hdb *HistoryDB) GetCommonAccountAPI(idx common.Idx) (*common.Account, error)

GetCommonAccountAPI returns the account associated to an account idx

func (*HistoryDB) GetConstants

func (hdb *HistoryDB) GetConstants() (*Constants, error)

GetConstants returns the Constats

func (*HistoryDB) GetCoordinatorAPI

func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error)

GetCoordinatorAPI returns a coordinator by its bidderAddr

func (*HistoryDB) GetCoordinatorsAPI

func (hdb *HistoryDB) GetCoordinatorsAPI(
	request GetCoordinatorsAPIRequest,
) ([]CoordinatorAPI, uint64, error)

GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info

func (*HistoryDB) GetExitAPI

func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error)

GetExitAPI returns a exit from the DB

func (*HistoryDB) GetExitsAPI

func (hdb *HistoryDB) GetExitsAPI(
	request GetExitsAPIRequest,
) ([]ExitAPI, uint64, error)

GetExitsAPI returns a list of exits from the DB and pagination info

func (*HistoryDB) GetFirstBatchBlockNumBySlot

func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error)

GetFirstBatchBlockNumBySlot returns the ethereum block number of the first batch within a slot

func (*HistoryDB) GetLastBatch

func (hdb *HistoryDB) GetLastBatch() (*common.Batch, error)

GetLastBatch returns the last forged batch

func (*HistoryDB) GetLastBatchNum

func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error)

GetLastBatchNum returns the BatchNum of the latest forged batch

func (*HistoryDB) GetLastBlock

func (hdb *HistoryDB) GetLastBlock() (*common.Block, error)

GetLastBlock retrieve the block with the highest block number from the DB

func (*HistoryDB) GetLastBlockAPI

func (hdb *HistoryDB) GetLastBlockAPI() (*common.Block, error)

GetLastBlockAPI retrieve the block with the highest block number from the DB

func (*HistoryDB) GetLastL1BatchBlockNum

func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error)

GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch

func (*HistoryDB) GetLastL1TxsNum

func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error)

GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged batches. If there's no batch in the DB (nil, nil) is returned.

func (*HistoryDB) GetLastTxsPosition

func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error)

GetLastTxsPosition for a given to_forge_l1_txs_num

func (*HistoryDB) GetMetricsInternalAPI

func (hdb *HistoryDB) GetMetricsInternalAPI(lastBatchNum common.BatchNum) (metrics *MetricsAPI, poolLoad int64, err error)

GetMetricsInternalAPI returns the MetricsAPI

func (*HistoryDB) GetNextForgersInternalAPI

func (hdb *HistoryDB) GetNextForgersInternalAPI(auctionVars *common.AuctionVariables,
	auctionConsts *common.AuctionConstants,
	lastBlock common.Block, currentSlot, lastClosedSlot int64) ([]NextForgerAPI, error)

GetNextForgersInternalAPI returns next forgers

func (*HistoryDB) GetNodeConfig

func (hdb *HistoryDB) GetNodeConfig() (*NodeConfig, error)

GetNodeConfig returns the NodeConfig

func (*HistoryDB) GetNodeInfo

func (hdb *HistoryDB) GetNodeInfo() (*NodeInfo, error)

GetNodeInfo returns the NodeInfo

func (*HistoryDB) GetNodeInfoAPI

func (hdb *HistoryDB) GetNodeInfoAPI() (*NodeInfo, error)

GetNodeInfoAPI retusnt he NodeInfo

func (*HistoryDB) GetRecommendedFee

func (hdb *HistoryDB) GetRecommendedFee(minFeeUSD, maxFeeUSD float64) (*common.RecommendedFee, error)

GetRecommendedFee returns the RecommendedFee information

func (*HistoryDB) GetSCVars

GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.

func (*HistoryDB) GetStateAPI

func (hdb *HistoryDB) GetStateAPI() (*StateAPI, error)

GetStateAPI returns the StateAPI

func (*HistoryDB) GetStateInternalAPI

func (hdb *HistoryDB) GetStateInternalAPI() (*StateAPI, error)

GetStateInternalAPI returns the StateAPI

func (*HistoryDB) GetToken

func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error)

GetToken returns a token from the DB given a TokenID

func (*HistoryDB) GetTokenAPI

func (hdb *HistoryDB) GetTokenAPI(tokenID common.TokenID) (*TokenWithUSD, error)

GetTokenAPI returns a token from the DB given a TokenID

func (*HistoryDB) GetTokenSymbolsAndAddrs

func (hdb *HistoryDB) GetTokenSymbolsAndAddrs() ([]TokenSymbolAndAddr, error)

GetTokenSymbolsAndAddrs returns all the token symbols and addresses from the DB

func (*HistoryDB) GetTokensAPI

func (hdb *HistoryDB) GetTokensAPI(
	request GetTokensAPIRequest,
) ([]TokenWithUSD, uint64, error)

GetTokensAPI returns a list of tokens from the DB

func (*HistoryDB) GetTokensTest

func (hdb *HistoryDB) GetTokensTest() ([]TokenWithUSD, error)

GetTokensTest used to get tokens in a testing context

func (*HistoryDB) GetTxAPI

func (hdb *HistoryDB) GetTxAPI(txID common.TxID) (*TxAPI, error)

GetTxAPI returns a tx from the DB given a TxID

func (*HistoryDB) GetTxsAPI

func (hdb *HistoryDB) GetTxsAPI(
	request GetTxsAPIRequest,
) ([]TxAPI, uint64, error)

GetTxsAPI returns a list of txs from the DB using the HistoryTx struct and pagination info

func (*HistoryDB) GetUnforgedL1UserFutureTxs added in v1.1.0

func (hdb *HistoryDB) GetUnforgedL1UserFutureTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error)

GetUnforgedL1UserFutureTxs gets L1 User Txs to be forged after the L1Batch with toForgeL1TxsNum (in one of the future batches, not in the next one).

func (*HistoryDB) GetUnforgedL1UserTxs

func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error)

GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.

func (*HistoryDB) GetUnforgedL1UserTxsCount

func (hdb *HistoryDB) GetUnforgedL1UserTxsCount() (int, error)

GetUnforgedL1UserTxsCount returns the count of unforged L1Txs (either in open or frozen queues that are not yet forged)

func (*HistoryDB) Reorg

func (hdb *HistoryDB) Reorg(lastValidBlock int64) error

Reorg deletes all the information that was added into the DB after the lastValidBlock. If lastValidBlock is negative, all block information is deleted.

func (*HistoryDB) SetConstants

func (hdb *HistoryDB) SetConstants(constants *Constants) error

SetConstants sets the Constants

func (*HistoryDB) SetInitialSCVars

func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
	auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error

SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart contract variables. This initial state is stored linked to block 0, which always exist in the DB and is used to store initialization data that always exist in the smart contracts.

func (*HistoryDB) SetNodeConfig

func (hdb *HistoryDB) SetNodeConfig(nodeConfig *NodeConfig) error

SetNodeConfig sets the NodeConfig

func (*HistoryDB) SetStateInternalAPI

func (hdb *HistoryDB) SetStateInternalAPI(stateAPI *StateAPI) error

SetStateInternalAPI sets the StateAPI

func (*HistoryDB) UpdateTokenValue

func (hdb *HistoryDB) UpdateTokenValue(tokenAddr ethCommon.Address, value float64) error

UpdateTokenValue updates the USD value of a token. Value is the price in USD of a normalized token (1 token = 10^decimals units)

type MetricsAPI

type MetricsAPI struct {
	TransactionsPerBatch   float64 `json:"transactionsPerBatch"`
	BatchFrequency         float64 `json:"batchFrequency"`
	TransactionsPerSecond  float64 `json:"transactionsPerSecond"`
	TokenAccounts          int64   `json:"tokenAccounts"`
	Wallets                int64   `json:"wallets"`
	AvgTransactionFee      float64 `json:"avgTransactionFee"`
	EstimatedTimeToForgeL1 float64 `json:"estimatedTimeToForgeL1" meddler:"estimated_time_to_forge_l1"`
}

MetricsAPI define metrics of the network

type MinBidInfo

type MinBidInfo struct {
	DefaultSlotSetBid        [6]*big.Int `json:"defaultSlotSetBid" meddler:"default_slot_set_bid,json" validate:"required"`
	DefaultSlotSetBidSlotNum int64       `json:"-" meddler:"default_slot_set_bid_slot_num"`
}

MinBidInfo gives information of the minum bid for specific slot(s)

type NetworkAPI

type NetworkAPI struct {
	LastEthBlock  int64           `json:"lastEthereumBlock"`
	LastSyncBlock int64           `json:"lastSynchedBlock"`
	LastBatch     *BatchAPI       `json:"lastBatch"`
	CurrentSlot   int64           `json:"currentSlot"`
	NextForgers   []NextForgerAPI `json:"nextForgers"`
	PendingL1Txs  int             `json:"pendingL1Transactions"`
}

NetworkAPI is the network state exposed via the API

type NextForgerAPI

type NextForgerAPI struct {
	Coordinator CoordinatorAPI `json:"coordinator"`
	Period      Period         `json:"period"`
}

NextForgerAPI represents the next forger exposed via the API

type NodeConfig

type NodeConfig struct {
	MaxPoolTxs uint32
	MinFeeUSD  float64
	MaxFeeUSD  float64
	ForgeDelay float64
}

NodeConfig contains the node config exposed in the API

type NodeInfo

type NodeInfo struct {
	ItemID     int         `meddler:"item_id,pk"`
	StateAPI   *StateAPI   `meddler:"state,json"`
	NodeConfig *NodeConfig `meddler:"config,json"`
	Constants  *Constants  `meddler:"constants,json"`
}

NodeInfo contains information about he node used when serving the API

type NodePublicInfo

type NodePublicInfo struct {
	// ForgeDelay in seconds
	ForgeDelay float64 `json:"forgeDelay"`
	// PoolLoad amount of transactions in the pool
	PoolLoad int64 `json:"poolLoad"`
}

NodePublicInfo is the configuration and metrics of the node that is exposed via API

type Period

type Period struct {
	SlotNum       int64     `json:"slotNum"`
	FromBlock     int64     `json:"fromBlock"`
	ToBlock       int64     `json:"toBlock"`
	FromTimestamp time.Time `json:"fromTimestamp"`
	ToTimestamp   time.Time `json:"toTimestamp"`
}

Period represents a time period in ethereum

type RollupVariablesAPI

type RollupVariablesAPI struct {
	EthBlockNum           int64               `json:"ethereumBlockNum" meddler:"eth_block_num"`
	FeeAddToken           *apitypes.BigIntStr `json:"feeAddToken" meddler:"fee_add_token" validate:"required"`
	ForgeL1L2BatchTimeout int64               `json:"forgeL1L2BatchTimeout" meddler:"forge_l1_timeout" validate:"required"`
	WithdrawalDelay       uint64              `json:"withdrawalDelay" meddler:"withdrawal_delay" validate:"required"`
	Buckets               []BucketParamsAPI   `json:"buckets" meddler:"buckets,json"`
	SafeMode              bool                `json:"safeMode" meddler:"safe_mode"`
}

RollupVariablesAPI are the variables of the Rollup Smart Contract

func NewRollupVariablesAPI

func NewRollupVariablesAPI(rollupVariables *common.RollupVariables) *RollupVariablesAPI

NewRollupVariablesAPI creates a RollupVariablesAPI from common.RollupVariables

type StateAPI

type StateAPI struct {
	NodePublicInfo    NodePublicInfo           `json:"node"`
	Network           NetworkAPI               `json:"network"`
	Metrics           MetricsAPI               `json:"metrics"`
	Rollup            RollupVariablesAPI       `json:"rollup"`
	Auction           AuctionVariablesAPI      `json:"auction"`
	WithdrawalDelayer common.WDelayerVariables `json:"withdrawalDelayer"`
	RecommendedFee    common.RecommendedFee    `json:"recommendedFee"`
}

StateAPI is an object representing the node and network state exposed via the API

type TokenSymbolAndAddr

type TokenSymbolAndAddr struct {
	Symbol string            `meddler:"symbol"`
	Addr   ethCommon.Address `meddler:"eth_addr"`
}

TokenSymbolAndAddr token representation with only Eth addr and symbol

type TokenWithUSD

type TokenWithUSD struct {
	ItemID      uint64            `json:"itemId" meddler:"item_id"`
	TokenID     common.TokenID    `json:"id" meddler:"token_id"`
	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
	EthAddr     ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
	Name        string            `json:"name" meddler:"name"`
	Symbol      string            `json:"symbol" meddler:"symbol"`
	Decimals    uint64            `json:"decimals" meddler:"decimals"`
	USD         *float64          `json:"USD" meddler:"usd"`
	USDUpdate   *time.Time        `json:"fiatUpdate" meddler:"usd_update,utctime"`
	TotalItems  uint64            `json:"-" meddler:"total_items"`
	FirstItem   uint64            `json:"-" meddler:"first_item"`
	LastItem    uint64            `json:"-" meddler:"last_item"`
}

TokenWithUSD add USD info to common.Token

type TxAPI

type TxAPI struct {
	// Generic
	IsL1        bool                 `meddler:"is_l1"`
	TxID        common.TxID          `meddler:"id"`
	ItemID      uint64               `meddler:"item_id"`
	Type        common.TxType        `meddler:"type"`
	Position    int                  `meddler:"position"`
	FromIdx     *apitypes.HezIdx     `meddler:"from_idx"`
	FromEthAddr *apitypes.HezEthAddr `meddler:"from_eth_addr"`
	FromBJJ     *apitypes.HezBJJ     `meddler:"from_bjj"`
	ToIdx       apitypes.HezIdx      `meddler:"to_idx"`
	ToEthAddr   *apitypes.HezEthAddr `meddler:"to_eth_addr"`
	ToBJJ       *apitypes.HezBJJ     `meddler:"to_bjj"`
	Amount      apitypes.BigIntStr   `meddler:"amount"`
	HistoricUSD *float64             `meddler:"amount_usd"`
	BatchNum    *common.BatchNum     `meddler:"batch_num"`     // batchNum in which this tx was forged. If the tx is L2, this must be != 0
	EthBlockNum int64                `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
	// L1
	ToForgeL1TxsNum          *int64              `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
	UserOrigin               *bool               `meddler:"user_origin"`         // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
	DepositAmount            *apitypes.BigIntStr `meddler:"deposit_amount"`
	HistoricDepositAmountUSD *float64            `meddler:"deposit_amount_usd"`
	AmountSuccess            bool                `meddler:"amount_success"`
	DepositAmountSuccess     bool                `meddler:"deposit_amount_success"`
	// L2
	Fee            *common.FeeSelector `meddler:"fee"`
	HistoricFeeUSD *float64            `meddler:"fee_usd"`
	Nonce          *common.Nonce       `meddler:"nonce"`
	// API extras
	Timestamp        time.Time         `meddler:"timestamp,utctime"`
	TotalItems       uint64            `meddler:"total_items"`
	FirstItem        uint64            `meddler:"first_item"`
	LastItem         uint64            `meddler:"last_item"`
	TokenID          common.TokenID    `meddler:"token_id"`
	TokenItemID      uint64            `meddler:"token_item_id"`
	TokenEthBlockNum int64             `meddler:"token_block"`
	TokenEthAddr     ethCommon.Address `meddler:"eth_addr"`
	TokenName        string            `meddler:"name"`
	TokenSymbol      string            `meddler:"symbol"`
	TokenDecimals    uint64            `meddler:"decimals"`
	TokenUSD         *float64          `meddler:"usd"`
	TokenUSDUpdate   *time.Time        `meddler:"usd_update"`
}

TxAPI is a representation of a generic Tx with additional information required by the API, and extracted by joining block and token tables

func (TxAPI) MarshalJSON

func (tx TxAPI) MarshalJSON() ([]byte, error)

MarshalJSON is used to neast some of the fields of TxAPI without the need of auxiliar structs

Jump to

Keyboard shortcuts

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