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
33	c.JSON(http.StatusOK, apiAccount)
34}
35
36func (a *API) getAccounts(c *gin.Context) {
37	// Account filters
38	tokenIDs, addr, bjj, err := parseAccountFilters(c)
39	if err != nil {
40		retBadReq(err, c)
41		return
42	}
43	// Pagination
44	fromItem, order, limit, err := parsePagination(c)
45	if err != nil {
46		retBadReq(err, c)
47		return
48	}
49
50	// Fetch Accounts from historyDB
51	apiAccounts, pendingItems, err := a.h.GetAccountsAPI(tokenIDs, addr, bjj, fromItem, limit, order)
52	if err != nil {
53		retSQLErr(err, c)
54		return
55	}
56
57	// Get balances from stateDB
58	for x, apiAccount := range apiAccounts {
59		idx, err := stringToIdx(string(apiAccount.Idx), "Account Idx")
60		if err != nil {
61			retSQLErr(err, c)
62			return
63		}
64		account, err := a.s.GetAccount(*idx)
65		if err != nil {
66			retSQLErr(err, c)
67			return
68		}
69		apiAccounts[x].Balance = apitypes.NewBigIntStr(account.Balance)
70	}
71
72	// Build succesfull response
73	type accountResponse struct {
74		Accounts     []historydb.AccountAPI `json:"accounts"`
75		PendingItems uint64                 `json:"pendingItems"`
76	}
77	c.JSON(http.StatusOK, &accountResponse{
78		Accounts:     apiAccounts,
79		PendingItems: pendingItems,
80	})
81}