Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat get detail evm tx #2

Merged
merged 9 commits into from
Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bootstrap/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type HTTPService struct {
Enable bool `yaml:"enable" toml:"enable" xml:"enable" json:"enable,omitempty"`
ListeningAddress string `yaml:"listening_address" toml:"listening_address" xml:"listening_address" json:"listening_address,omitempty"`
RoutePrefix string `yaml:"route_prefix" toml:"route_prefix" xml:"route_prefix" json:"route_prefix,omitempty"`
BlockscoutUrl string `yaml:"blockscout_url" toml:"blockscout_url" xml:"blockscout_url" json:"blockscout_url,omitempty"`
CorsAllowedOrigins []string `yaml:"cors_allowed_origins" toml:"cors_allowed_origins" xml:"cors_allowed_origins" json:"cors_allowed_origins,omitempty"`
CorsAllowedMethods []string `yaml:"cors_allowed_methods" toml:"cors_allowed_methods" xml:"cors_allowed_methods" json:"cors_allowed_methods,omitempty"`
CorsAllowedHeaders []string `yaml:"cors_allowed_headers" toml:"cors_allowed_headers" xml:"cors_allowed_headers" json:"cors_allowed_headers,omitempty"`
Expand Down
8 changes: 6 additions & 2 deletions cmd/astra-indexing/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/AstraProtocol/astra-indexing/bootstrap"
"github.com/AstraProtocol/astra-indexing/bootstrap/config"
applogger "github.com/AstraProtocol/astra-indexing/external/logger"
blockscout_infrastructure "github.com/AstraProtocol/astra-indexing/infrastructure/blockscout"
cosmosapp_infrastructure "github.com/AstraProtocol/astra-indexing/infrastructure/cosmosapp"
httpapi_handlers "github.com/AstraProtocol/astra-indexing/infrastructure/httpapi/handlers"
tendermint_infrastructure "github.com/AstraProtocol/astra-indexing/infrastructure/tendermint"
Expand All @@ -18,7 +19,6 @@ func InitRouteRegistry(
config *config.Config,
) bootstrap.RouteRegistry {
var cosmosAppClient cosmosapp.Client

cosmosAppClient = cosmosapp_infrastructure.NewHTTPClient(
config.CosmosApp.HTTPRPCUrl,
config.Blockchain.BondingDenom,
Expand All @@ -30,6 +30,10 @@ func InitRouteRegistry(
config.TendermintApp.StrictGenesisParsing,
)

blockscoutClient := blockscout_infrastructure.NewHTTPClient(
config.HTTPService.BlockscoutUrl,
)

validatorAddressPrefix := config.Blockchain.ValidatorAddressPrefix
conNodeAddressPrefix := config.Blockchain.ConNodeAddressPrefix

Expand Down Expand Up @@ -108,7 +112,7 @@ func InitRouteRegistry(
},
)

transactionHandler := httpapi_handlers.NewTransactions(logger, rdbConn.ToHandle())
transactionHandler := httpapi_handlers.NewTransactions(logger, *blockscoutClient, rdbConn.ToHandle())
routes = append(routes,
Route{
Method: GET,
Expand Down
5 changes: 3 additions & 2 deletions cmd/astra-indexing/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package main

import (
"fmt"
"github.com/AstraProtocol/astra-indexing/cmd/astra-indexing/routes"
"github.com/urfave/cli/v2"
"os"
"path/filepath"

"github.com/AstraProtocol/astra-indexing/cmd/astra-indexing/routes"
"github.com/urfave/cli/v2"

"github.com/AstraProtocol/astra-indexing/bootstrap"
configuration "github.com/AstraProtocol/astra-indexing/bootstrap/config"
applogger "github.com/AstraProtocol/astra-indexing/external/logger"
Expand Down
1 change: 1 addition & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ http_service:
enable: true
listening_address: "0.0.0.0:8080"
route_prefix: "/"
blockscout_url: "https://explorer.astranaut.dev"
# A list of origins a cross-domain request is allowed to be requested from
# Default value '[]' disables CORS support
# Use '["*"]' to allow request from any origin
Expand Down
56 changes: 56 additions & 0 deletions infrastructure/blockscout/detail_tx_response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package blockscout

import "github.com/AstraProtocol/astra-indexing/external/utctime"

type Log struct {
Address string `json:"address"`
Data string `json:"data"`
Index string `json:"index"`
Topics []string `json:"topics"`
}

type TokenTransfer struct {
Amount string `json:"amount"`
FromAddress string `json:"fromAddress"`
ToAddress string `json:"toAddress"`
TokenContractAddress string `json:"tokenContractAddress"`
TokenName string `json:"tokenName"`
TokenSymbol string `json:"tokenSymbol"`
}

type TransactionEvm struct {
BlockHeight int64 `json:"blockHeight"`
BlockHash string `json:"blockHash"`
BlockTime utctime.UTCTime `json:"blockTime"`
Confirmations int64 `json:"confirmations"`
Hash string `json:"hash"`
CosmosHash string `json:"cosmosHash"`
Index int `json:"index"`
Success bool `json:"success"`
Error string `json:"error"`
RevertReason string `json:"revertReason"`
CreatedContractCodeIndexedAt utctime.UTCTime `json:"createdContractCodeIndexedAt"`
From string `json:"from"`
To string `json:"to"`
Value string `json:"value"`
CumulativeGasUsed string `json:"cumulativeGasUsed"`
GasLimit string `json:"gasLimit"`
GasPrice string `json:"gasPrice"`
GasUsed string `json:"gasUsed"`
MaxFeePerGas string `json:"maxFeePerGas"`
MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas"`
Input string `json:"input"`
Nonce int `json:"nonce"`
R string `json:"r"`
S string `json:"s"`
V string `json:"v"`
Type int `json:"type"`
Logs []Log `json:"logs"`
TokenTransfers []TokenTransfer `json:"tokenTransfers"`
}

type TxResp struct {
Message string `json:"message"`
Result TransactionEvm `json:"result"`
Status string `json:"status"`
}
127 changes: 127 additions & 0 deletions infrastructure/blockscout/httpclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package blockscout

import (
"context"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"

"github.com/AstraProtocol/astra-indexing/external/cache"
"github.com/hashicorp/go-retryablehttp"
jsoniter "github.com/json-iterator/go"
)

const GET_DETAIL_EVM_TX = "/api/v1?module=transaction&action=getTxCosmosInfo&txhash="

type HTTPClient struct {
httpClient *retryablehttp.Client
url string
httpCache *cache.AstraCache
}

var (
redirectsErrorRe = regexp.MustCompile(`stopped after \d+ redirects\z`)
schemeErrorRe = regexp.MustCompile(`unsupported protocol scheme`)
notTrustedErrorRe = regexp.MustCompile(`certificate is not trusted`)
)

func defaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
if ctx.Err() != nil {
return false, ctx.Err()
}
shouldRetry, _ := baseRetryPolicy(resp, err)
return shouldRetry, nil
}

func baseRetryPolicy(resp *http.Response, err error) (bool, error) {
if err != nil {
if v, ok := err.(*url.Error); ok {
if redirectsErrorRe.MatchString(v.Error()) {
return false, v
}
if schemeErrorRe.MatchString(v.Error()) {
return false, v
}
if notTrustedErrorRe.MatchString(v.Error()) {
return false, v
}
if _, ok := v.Err.(x509.UnknownAuthorityError); ok {
return false, v
}
}
return true, nil
}
if resp.StatusCode == http.StatusTooManyRequests {
return true, nil
}
if resp.StatusCode == http.StatusNotFound {
return true, nil
}
if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != http.StatusNotImplemented) {
return true, fmt.Errorf("unexpected HTTP status %s", resp.Status)
}
return false, nil
}

func (client *HTTPClient) getUrl(action string, param string) string {
return fmt.Sprintf("%s%s%s", client.url, action, param)
}

func (client *HTTPClient) request(endpoint string, queryParams ...string) (io.ReadCloser, error) {
var err error
queryUrl := endpoint

if len(queryParams[0]) > 0 {
for _, v := range queryParams {
queryUrl += "?" + v
}
}

req, err := retryablehttp.NewRequestWithContext(context.Background(), http.MethodGet, queryUrl, nil)
if err != nil {
return nil, fmt.Errorf("error creating HTTP request with context: %v", err)
}
rawResp, err := client.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error requesting blockscout %s endpoint: %v", queryUrl, err)
}

if rawResp.StatusCode != 200 {
rawResp.Body.Close()
return nil, fmt.Errorf("error requesting blockscout %s endpoint: %s", queryUrl, rawResp.Status)
}

return rawResp.Body, nil
}

func NewHTTPClient(url string) *HTTPClient {
httpClient := retryablehttp.NewClient()
httpClient.Logger = nil
httpClient.CheckRetry = defaultRetryPolicy

return &HTTPClient{
httpClient,
strings.TrimSuffix(url, "/"),
cache.NewCache("blockscout"),
}
}

func (client *HTTPClient) GetDetailEvmTx(txHash string) (*TransactionEvm, error) {
rawRespBody, err := client.request(
client.getUrl(GET_DETAIL_EVM_TX, txHash), "",
)
if err != nil {
return nil, err
}
defer rawRespBody.Close()

var txResp TxResp
if err := jsoniter.NewDecoder(rawRespBody).Decode(&txResp); err != nil {
return nil, err
}
return &txResp.Result, nil
}
40 changes: 27 additions & 13 deletions infrastructure/httpapi/handlers/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package handlers

import (
"errors"
"time"

"github.com/AstraProtocol/astra-indexing/appinterface/pagination"
"github.com/AstraProtocol/astra-indexing/external/cache"
transactionView "github.com/AstraProtocol/astra-indexing/projection/transaction/view"
"time"

applogger "github.com/AstraProtocol/astra-indexing/external/logger"
blockscout_infrastructure "github.com/AstraProtocol/astra-indexing/infrastructure/blockscout"
"github.com/valyala/fasthttp"

"github.com/AstraProtocol/astra-indexing/appinterface/projection/view"
Expand All @@ -18,6 +20,7 @@ import (
type Transactions struct {
logger applogger.Logger
transactionsView transactionView.BlockTransactions
blockscoutClient blockscout_infrastructure.HTTPClient
astraCache *cache.AstraCache
}

Expand All @@ -34,13 +37,16 @@ func NewTransactionsPaginationResult(transactionRows []transactionView.Transacti
}
}

func NewTransactions(logger applogger.Logger, rdbHandle *rdb.Handle) *Transactions {
func NewTransactions(
logger applogger.Logger,
blockscoutClient blockscout_infrastructure.HTTPClient,
rdbHandle *rdb.Handle) *Transactions {
return &Transactions{
logger.WithFields(applogger.LogFields{
"module": "TransactionsHandler",
}),

transactionView.NewTransactionsView(rdbHandle),
blockscoutClient,
cache.NewCache("transactions"),
}
}
Expand All @@ -50,19 +56,27 @@ func (handler *Transactions) FindByHash(ctx *fasthttp.RequestCtx) {
if !hashParamOk {
return
}

transaction, err := handler.transactionsView.FindByHash(hashParam)
if err != nil {
if errors.Is(err, rdb.ErrNoRows) {
httpapi.NotFound(ctx)
if string(ctx.QueryArgs().Peek("type")) == "evm" {
transaction, err := handler.blockscoutClient.GetDetailEvmTx(hashParam)
if err != nil {
handler.logger.Errorf("error parsing tx response from blockscout: %v", err)
httpapi.InternalServerError(ctx)
return
}
handler.logger.Errorf("error finding transactions by hash: %v", err)
httpapi.InternalServerError(ctx)
return
httpapi.Success(ctx, transaction)
} else {
transaction, err := handler.transactionsView.FindByHash(hashParam)
if err != nil {
if errors.Is(err, rdb.ErrNoRows) {
httpapi.NotFound(ctx)
return
}
handler.logger.Errorf("error finding transactions by hash: %v", err)
httpapi.InternalServerError(ctx)
return
}
httpapi.Success(ctx, transaction)
}

httpapi.Success(ctx, transaction)
}

func (handler *Transactions) List(ctx *fasthttp.RequestCtx) {
Expand Down