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