arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/api/api.go
api/api.goRaw
 1package api
 2
 3import (
 4	"errors"
 5
 6	ethCommon "github.com/ethereum/go-ethereum/common"
 7	"github.com/gin-gonic/gin"
 8	"github.com/hermeznetwork/hermez-node/db/historydb"
 9	"github.com/hermeznetwork/hermez-node/db/l2db"
10	"github.com/hermeznetwork/tracerr"
11)
12
13// API serves HTTP requests to allow external interaction with the Hermez node
14type API struct {
15	h             *historydb.HistoryDB
16	cg            *configAPI
17	l2            *l2db.L2DB
18	chainID       uint16
19	hermezAddress ethCommon.Address
20}
21
22// NewAPI sets the endpoints and the appropriate handlers, but doesn't start the server
23func NewAPI(
24	coordinatorEndpoints, explorerEndpoints bool,
25	server *gin.Engine,
26	hdb *historydb.HistoryDB,
27	l2db *l2db.L2DB,
28) (*API, error) {
29	// Check input
30	// TODO: is stateDB only needed for explorer endpoints or for both?
31	if coordinatorEndpoints && l2db == nil {
32		return nil, tracerr.Wrap(errors.New("cannot serve Coordinator endpoints without L2DB"))
33	}
34	if explorerEndpoints && hdb == nil {
35		return nil, tracerr.Wrap(errors.New("cannot serve Explorer endpoints without HistoryDB"))
36	}
37	consts, err := hdb.GetConstants()
38	if err != nil {
39		return nil, err
40	}
41	a := &API{
42		h: hdb,
43		cg: &configAPI{
44			RollupConstants:   *newRollupConstants(consts.Rollup),
45			AuctionConstants:  consts.Auction,
46			WDelayerConstants: consts.WDelayer,
47		},
48		l2:            l2db,
49		chainID:       consts.ChainID,
50		hermezAddress: consts.HermezAddress,
51	}
52
53	server.NoRoute(a.noRoute)
54
55	v1 := server.Group("/v1")
56
57	// Add coordinator endpoints
58	if coordinatorEndpoints {
59		// Account
60		v1.POST("/account-creation-authorization", a.postAccountCreationAuth)
61		v1.GET("/account-creation-authorization/:hezEthereumAddress", a.getAccountCreationAuth)
62		// Transaction
63		v1.POST("/transactions-pool", a.postPoolTx)
64		v1.GET("/transactions-pool/:id", a.getPoolTx)
65	}
66
67	// Add explorer endpoints
68	if explorerEndpoints {
69		// Account
70		v1.GET("/accounts", a.getAccounts)
71		v1.GET("/accounts/:accountIndex", a.getAccount)
72		v1.GET("/exits", a.getExits)
73		v1.GET("/exits/:batchNum/:accountIndex", a.getExit)
74		// Transaction
75		v1.GET("/transactions-history", a.getHistoryTxs)
76		v1.GET("/transactions-history/:id", a.getHistoryTx)
77		// Status
78		v1.GET("/batches", a.getBatches)
79		v1.GET("/batches/:batchNum", a.getBatch)
80		v1.GET("/full-batches/:batchNum", a.getFullBatch)
81		v1.GET("/slots", a.getSlots)
82		v1.GET("/slots/:slotNum", a.getSlot)
83		v1.GET("/bids", a.getBids)
84		v1.GET("/state", a.getState)
85		v1.GET("/config", a.getConfig)
86		v1.GET("/tokens", a.getTokens)
87		v1.GET("/tokens/:id", a.getToken)
88		v1.GET("/coordinators", a.getCoordinators)
89	}
90
91	return a, nil
92}