arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/api/account.go
api/account.goRaw
 1package api
 2
 3import (
 4	"net/http"
 5
 6	"github.com/gin-gonic/gin"
 7	"github.com/hermeznetwork/hermez-node/apitypes"
 8	"github.com/hermeznetwork/hermez-node/db/historydb"
 9)
10
11func (a *API) getAccount(c *gin.Context) {
12	// Get Addr
13	idx, err := parseParamIdx(c)
14	if err != nil {
15		retBadReq(err, c)
16		return
17	}
18	apiAccount, err := a.h.GetAccountAPI(*idx)
19	if err != nil {
20		retSQLErr(err, c)
21		return
22	}
23
24	// Get balance from stateDB
25	account, err := a.s.GetAccount(*idx)
26	if err != nil {
27		retSQLErr(err, c)
28		return
29	}
30
31	apiAccount.Balance = apitypes.NewBigIntStr(account.Balance)
32	apiAccount.Nonce = account.Nonce
33
34	c.JSON(http.StatusOK, apiAccount)
35}
36
37func (a *API) getAccounts(c *gin.Context) {
38	// Account filters
39	tokenIDs, addr, bjj, err := parseAccountFilters(c)
40	if err != nil {
41		retBadReq(err, c)
42		return
43	}
44	// Pagination
45	fromItem, order, limit, err := parsePagination(c)
46	if err != nil {
47		retBadReq(err, c)
48		return
49	}
50
51	// Fetch Accounts from historyDB
52	apiAccounts, pendingItems, err := a.h.GetAccountsAPI(tokenIDs, addr, bjj, fromItem, limit, order)
53	if err != nil {
54		retSQLErr(err, c)
55		return
56	}
57
58	// Get balances from stateDB
59	for x, apiAccount := range apiAccounts {
60		idx, err := stringToIdx(string(apiAccount.Idx), "Account Idx")
61		if err != nil {
62			retSQLErr(err, c)
63			return
64		}
65		account, err := a.s.GetAccount(*idx)
66		if err != nil {
67			retSQLErr(err, c)
68			return
69		}
70		apiAccounts[x].Balance = apitypes.NewBigIntStr(account.Balance)
71		apiAccounts[x].Nonce = account.Nonce
72	}
73
74	// Build succesfull response
75	type accountResponse struct {
76		Accounts     []historydb.AccountAPI `json:"accounts"`
77		PendingItems uint64                 `json:"pendingItems"`
78	}
79	c.JSON(http.StatusOK, &accountResponse{
80		Accounts:     apiAccounts,
81		PendingItems: pendingItems,
82	})
83}