Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
giansalex committed Apr 18, 2022
0 parents commit 3456160
Show file tree
Hide file tree
Showing 7 changed files with 412 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/make -f

export GO111MODULE = on

BUILD_FLAGS := -ldflags '-w -s' -trimpath

all: install

install: go.sum
go install -mod=readonly $(BUILD_FLAGS) ./cmd

build:
go build $(BUILD_FLAGS) -o build/gnoapi ./cmd

.PHONY: all install build
123 changes: 123 additions & 0 deletions cmd/handler/query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package handler

import (
"encoding/json"
"fmt"
"net/http"
"strings"

"github.com/gnolang/gno/pkgs/bft/rpc/client"

"github.com/gorilla/mux"
)

type Coin struct {
Denom string `json:"denom"`
Amount string `json:"amount"`
}

type PaginationInfo struct {
NextKey []byte `json:"next_key"`
Total string `json:"total"`
}

type BankResult struct {
Balances []Coin `json:"balances"`
Pagination PaginationInfo `json:"pagination"`
}

func AuthQueryHandler(cli client.ABCIClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
authPath := fmt.Sprintf("auth/accounts/%s", vars["address"])
res, err := cli.ABCIQuery(authPath, nil)
if err != nil {
writeError(w, err)
return
}

if res.Response.Error != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(res.Response.Data))
}
}

func BankQueryHandler(cli client.ABCIClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
denom := "gnot"

authPath := fmt.Sprintf("bank/balances/%s", vars["address"])
res, err := cli.ABCIQuery(authPath, nil)
if err != nil {
writeError(w, err)
return
}

if res.Response.Error != nil {
writeError(w, err)
return
}

var balance string
err = json.Unmarshal(res.Response.Data, &balance)
if err != nil {
writeError(w, err)
return
}

result := BankResult{
Balances: []Coin{
{Denom: denom, Amount: strings.TrimRight(balance, denom)},
},
Pagination: PaginationInfo{
NextKey: nil,
Total: "1",
},
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(result)
}
}

func StakingQueryHandler(cli client.ABCIClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
template := `{
"delegation_responses": [
],
"pagination": {
"next_key": null,
"total": "0"
}
}`
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, template)
}
}

func StakingUnbondingQueryHandler(cli client.ABCIClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
template := `{
"unbonding_responses": [
],
"pagination": {
"next_key": null,
"total": "0"
}
}`
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, template)
}
}

func writeError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Error: %s", err.Error())
}
71 changes: 71 additions & 0 deletions cmd/handler/tx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package handler

import (
"encoding/json"
"fmt"
"net/http"

"github.com/gnolang/gno/pkgs/amino"
"github.com/gnolang/gno/pkgs/bft/rpc/client"
ctypes "github.com/gnolang/gno/pkgs/bft/rpc/core/types"
"github.com/gnolang/gno/pkgs/std"
)

func TxsHandler(cli client.ABCIClient) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var params map[string]json.RawMessage
err := json.NewDecoder(r.Body).Decode(&params)
if err != nil {
writeError(w, fmt.Errorf("%s, %s", "unmarshaling json params", err.Error()))
return
}

txData, ok := params["tx"]
if !ok {
writeError(w, fmt.Errorf("%s, %s", "Missing tx param", err.Error()))
return
}

txBz, _ := txData.MarshalJSON()
var tx std.Tx
err = amino.UnmarshalJSON(txBz, &tx)
if err != nil {
writeError(w, fmt.Errorf("%s, %s", "unmarshaling tx json bytes", err.Error()))
return
}

res, err := BroadcastHandler(cli, tx)
if err != nil {
writeError(w, err)
return
}

if res.CheckTx.IsErr() {
writeError(w, fmt.Errorf("transaction failed %#v\nlog %s", res, res.CheckTx.Log))
return
}

if res.DeliverTx.IsErr() {
writeError(w, fmt.Errorf("transaction failed %#v\nlog %s", res, res.DeliverTx.Log))
return
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res.DeliverTx)
}
}

func BroadcastHandler(cli client.ABCIClient, tx std.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
bz, err := amino.Marshal(tx)
if err != nil {
return nil, fmt.Errorf("%s, %s", err.Error(), "remarshaling tx binary bytes")
}

bres, err := cli.BroadcastTxCommit(bz)
if err != nil {
return nil, fmt.Errorf("%s, %s", err.Error(), "broadcasting bytes")
}

return bres, nil
}
44 changes: 44 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"flag"
"fmt"
"log"
"net/http"

"github.com/gnolang/gno/pkgs/bft/rpc/client"

"github.com/gorilla/mux"

"github.com/disperze/gno-api/cmd/handler"
)

var (
remotePtr = flag.String("remote", "http://gno.land:36657", "Remote rpc")
apiPortPtr = flag.String("port", "8888", "Api port")
)

func main() {
flag.Parse()

if remotePtr == nil || *remotePtr == "" {
log.Fatal("remote url is required")
}

if apiPortPtr == nil || *apiPortPtr == "" {
log.Fatal("api port is required")
}

apiPort := *apiPortPtr
cli := client.NewHTTP(*remotePtr, "/websocket")

r := mux.NewRouter()
r.HandleFunc("/cosmos/auth/v1beta1/accounts/{address}", handler.AuthQueryHandler(cli))
r.HandleFunc("/cosmos/bank/v1beta1/balances/{address}", handler.BankQueryHandler(cli))
r.HandleFunc("/cosmos/staking/v1beta1/delegations/{address}", handler.StakingQueryHandler(cli))
r.HandleFunc("/cosmos/staking/v1beta1/delegators/{address}/unbonding_delegations", handler.StakingUnbondingQueryHandler(cli))
r.HandleFunc("/txs", handler.TxsHandler(cli)).Methods(http.MethodPost)

fmt.Println("Running on port", apiPort)
log.Fatal(http.ListenAndServe(":"+apiPort, r))
}
28 changes: 28 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module github.com/disperze/gno-api

go 1.17

require (
github.com/gnolang/gno v0.0.0-20220415050405-655769291a16
github.com/gorilla/mux v1.8.0
)

require (
github.com/btcsuite/btcutil v1.0.2 // indirect
github.com/gnolang/cors v1.8.1 // indirect
github.com/gnolang/overflow v0.0.0-20170615021017-4d914c927216 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect
github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d // indirect
golang.org/x/mod v0.4.2 // indirect
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 // indirect
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect
google.golang.org/protobuf v1.27.1 // indirect
)
Loading

0 comments on commit 3456160

Please sign in to comment.