add: (wip) balances query API

This commit is contained in:
Mohamed Sohail 2022-05-14 11:15:45 +03:00
parent 352b89332f
commit 7d431f1c8f
Signed by: kamikazechaser
GPG Key ID: 7DD45520C01CD85D
6 changed files with 75 additions and 0 deletions

View File

@ -34,6 +34,7 @@ type config struct {
type queries struct {
core goyesql.Queries
dashboard goyesql.Queries
public goyesql.Queries
}
func loadConfig(configFilePath string, k *koanf.Koanf) error {
@ -97,9 +98,15 @@ func loadQueries(sqlFilesPath string) error {
return err
}
publicQueries, err := goyesql.ParseFile(fmt.Sprintf("%s/public.sql", sqlFilesPath))
if err != nil {
return err
}
preparedQueries = &queries{
core: coreQueries,
dashboard: dashboardQueries,
public: publicQueries,
}
return nil

View File

@ -2,6 +2,7 @@ package main
import (
"cic-dw/internal/dashboard"
"cic-dw/internal/public"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
@ -18,6 +19,7 @@ func initHTTPServer() *echo.Echo {
}))
dashboard.InitDashboardApi(server, db, preparedQueries.dashboard)
public.InitPublicApi(server, db, preparedQueries.public)
return server
}

View File

@ -13,6 +13,7 @@ cors = [
[chain]
index = "0x5A1EB529438D8b3cA943A45a48744f4c73d1f098"
balances_resolver = "0x9C48FF0888A747Ba0108E7205Cae2EeB0C76c948"
rpc = "http://127.0.0.1:8545"
[syncers]

28
internal/public/api.go Normal file
View File

@ -0,0 +1,28 @@
package public
import (
"github.com/jackc/pgx/v4/pgxpool"
"github.com/labstack/echo/v4"
"github.com/nleof/goyesql"
)
type api struct {
db *pgxpool.Pool
q goyesql.Queries
}
func InitPublicApi(e *echo.Echo, db *pgxpool.Pool, queries goyesql.Queries) {
g := e.Group("/public")
g.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set("api", &api{
db: db,
q: queries,
})
return next(c)
}
})
g.GET("/balances/:address", handleBalancesQuery)
}

View File

@ -0,0 +1,31 @@
package public
import (
"context"
"github.com/georgysavva/scany/pgxscan"
"github.com/labstack/echo/v4"
"net/http"
)
type dbRes struct {
TokenSymbol string `db:"token_symbol"`
TokenAddress string `db:"token_address"`
}
func handleBalancesQuery(c echo.Context) error {
var (
api = c.Get("api").(*api)
data []dbRes
)
rows, err := api.db.Query(context.Background(), api.q["all-known-tokens"], c.Param("address"))
if err != nil {
return err
}
if err := pgxscan.ScanAll(&data, rows); err != nil {
return err
}
return c.JSON(http.StatusOK, data)
}

6
queries/public.sql Normal file
View File

@ -0,0 +1,6 @@
-- name: all-known-tokens
-- Looks up all known tokens from the transactions records
SELECT DISTINCT tokens.token_symbol, tokens.token_address FROM transactions
INNER JOIN tokens on transactions.token_address = tokens.token_address
WHERE transactions.sender_address = $1
OR transactions.recipient_address = $1;