Skip to content

Commit

Permalink
fix: fix errors reporting (#37)
Browse files Browse the repository at this point in the history
* fix: do not query coingecko if no coins specified

* feat: fail queries on unsuccessful responses

* feat: fail rewards query if it errors

* chore: balance -> amount

* chore: removed unused fields

* chore: moved tendermint types to a separate file

* fix: fail commission query if it is not supported

* chore: fix linting

* fix: fail staking params query if it is not supported

* chore: cleanup
  • Loading branch information
freak12techno authored Dec 10, 2023
1 parent 43052d8 commit baa6581
Show file tree
Hide file tree
Showing 5 changed files with 206 additions and 257 deletions.
6 changes: 3 additions & 3 deletions pkg/price_fetchers/coingecko/coingecko.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func NewCoingecko(appConfig *config.Config, logger *zerolog.Logger) *Coingecko {
}
}

func (c *Coingecko) FetchPrices(currencies []string) (map[string]float64, types.QueryInfo) {
func (c *Coingecko) FetchPrices(currencies []string) (map[string]float64, *types.QueryInfo) {
ids := strings.Join(currencies, ",")
url := fmt.Sprintf("https://api.coingecko.com/api/v3/simple/price?ids=%s&vs_currencies=usd", ids)

Expand All @@ -35,7 +35,7 @@ func (c *Coingecko) FetchPrices(currencies []string) (map[string]float64, types.

if err != nil {
c.Logger.Error().Err(err).Msg("Could not get rate")
return nil, queryInfo
return nil, &queryInfo
}

prices := map[string]float64{}
Expand All @@ -46,5 +46,5 @@ func (c *Coingecko) FetchPrices(currencies []string) (map[string]float64, types.
}
}

return prices, queryInfo
return prices, &queryInfo
}
16 changes: 14 additions & 2 deletions pkg/queriers/price.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,19 @@ func NewPriceQuerier(

func (q *PriceQuerier) GetMetrics() ([]prometheus.Collector, []*types.QueryInfo) {
currenciesList := q.Config.GetCoingeckoCurrencies()
currenciesRates, query := q.Coingecko.FetchPrices(currenciesList)

var currenciesRates map[string]float64
var currenciesQuery *types.QueryInfo

var queries []*types.QueryInfo

if len(currenciesList) > 0 {
currenciesRates, currenciesQuery = q.Coingecko.FetchPrices(currenciesList)
}

if currenciesQuery != nil {
queries = append(queries, currenciesQuery)
}

currenciesRatesToChains := map[string]map[string]float64{}
for _, chain := range q.Config.Chains {
Expand Down Expand Up @@ -73,5 +85,5 @@ func (q *PriceQuerier) GetMetrics() ([]prometheus.Collector, []*types.QueryInfo)
}
}

return []prometheus.Collector{tokenPriceGauge}, []*types.QueryInfo{&query}
return []prometheus.Collector{tokenPriceGauge}, queries
}
71 changes: 39 additions & 32 deletions pkg/tendermint/tendermint.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"main/pkg/types"
"main/pkg/utils"

cosmosTypes "github.com/cosmos/cosmos-sdk/types"
distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/rs/zerolog"
)

Expand Down Expand Up @@ -46,6 +44,7 @@ func (rpc *RPC) GetValidator(address string) (*types.ValidatorResponse, *types.Q
}

if response.Code != 0 {
info.Success = false
return &types.ValidatorResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

Expand All @@ -70,6 +69,7 @@ func (rpc *RPC) GetDelegationsCount(address string) (*types.PaginationResponse,
}

if response.Code != 0 {
info.Success = false
return &types.PaginationResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

Expand All @@ -94,13 +94,14 @@ func (rpc *RPC) GetUnbondsCount(address string) (*types.PaginationResponse, *typ
}

if response.Code != 0 {
info.Success = false
return &types.PaginationResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

return response, &info, nil
}

func (rpc *RPC) GetSingleDelegation(validator, wallet string) (*types.Balance, *types.QueryInfo, error) {
func (rpc *RPC) GetSingleDelegation(validator, wallet string) (*types.Amount, *types.QueryInfo, error) {
if !rpc.Chain.QueryEnabled("self-delegation") {
return nil, nil, nil
}
Expand All @@ -115,17 +116,16 @@ func (rpc *RPC) GetSingleDelegation(validator, wallet string) (*types.Balance, *
var response types.SingleDelegationResponse
info, err := rpc.Client.Get(url, &response)
if err != nil {
return &types.Balance{}, &info, err
return &types.Amount{}, &info, err
}

if response.Code != 0 {
return &types.Balance{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
info.Success = false
return &types.Amount{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

return &types.Balance{
Amount: utils.StrToFloat64(response.DelegationResponse.Balance.Amount),
Denom: response.DelegationResponse.Balance.Denom,
}, &info, nil
amount := response.DelegationResponse.Balance.ToAmount()
return &amount, &info, nil
}

func (rpc *RPC) GetAllValidators() (*types.ValidatorsResponse, *types.QueryInfo, error) {
Expand All @@ -141,10 +141,15 @@ func (rpc *RPC) GetAllValidators() (*types.ValidatorsResponse, *types.QueryInfo,
return nil, &info, err
}

if response.Code != 0 {
info.Success = false
return &types.ValidatorsResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

return response, &info, nil
}

func (rpc *RPC) GetValidatorCommission(address string) ([]types.Balance, *types.QueryInfo, error) {
func (rpc *RPC) GetValidatorCommission(address string) ([]types.Amount, *types.QueryInfo, error) {
if !rpc.Chain.QueryEnabled("commission") {
return nil, nil, nil
}
Expand All @@ -155,21 +160,18 @@ func (rpc *RPC) GetValidatorCommission(address string) ([]types.Balance, *types.
address,
)

var response *distributionTypes.QueryValidatorCommissionResponse
var response *types.CommissionResponse
info, err := rpc.Client.Get(url, &response)
if err != nil {
return []types.Balance{}, &info, err
return []types.Amount{}, &info, err
}

return utils.Map(response.Commission.Commission, func(balance cosmosTypes.DecCoin) types.Balance {
return types.Balance{
Amount: balance.Amount.MustFloat64(),
Denom: balance.Denom,
}
return utils.Map(response.Commission.Commission, func(amount types.ResponseAmount) types.Amount {
return amount.ToAmount()
}), &info, nil
}

func (rpc *RPC) GetDelegatorRewards(validator, wallet string) ([]types.Balance, *types.QueryInfo, error) {
func (rpc *RPC) GetDelegatorRewards(validator, wallet string) ([]types.Amount, *types.QueryInfo, error) {
if !rpc.Chain.QueryEnabled("rewards") {
return nil, nil, nil
}
Expand All @@ -181,21 +183,23 @@ func (rpc *RPC) GetDelegatorRewards(validator, wallet string) ([]types.Balance,
validator,
)

var response *distributionTypes.QueryDelegationRewardsResponse
var response *types.RewardsResponse
info, err := rpc.Client.Get(url, &response)
if err != nil {
return []types.Balance{}, &info, err
return []types.Amount{}, &info, err
}

return utils.Map(response.Rewards, func(balance cosmosTypes.DecCoin) types.Balance {
return types.Balance{
Amount: balance.Amount.MustFloat64(),
Denom: balance.Denom,
}
if response.Code != 0 {
info.Success = false
return []types.Amount{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

return utils.Map(response.Rewards, func(amount types.ResponseAmount) types.Amount {
return amount.ToAmount()
}), &info, nil
}

func (rpc *RPC) GetWalletBalance(wallet string) ([]types.Balance, *types.QueryInfo, error) {
func (rpc *RPC) GetWalletBalance(wallet string) ([]types.Amount, *types.QueryInfo, error) {
if !rpc.Chain.QueryEnabled("balance") {
return nil, nil, nil
}
Expand All @@ -209,14 +213,11 @@ func (rpc *RPC) GetWalletBalance(wallet string) ([]types.Balance, *types.QueryIn
var response types.BalancesResponse
info, err := rpc.Client.Get(url, &response)
if err != nil {
return []types.Balance{}, &info, err
return []types.Amount{}, &info, err
}

return utils.Map(response.Balances, func(balance types.BalanceInResponse) types.Balance {
return types.Balance{
Amount: utils.StrToFloat64(balance.Amount),
Denom: balance.Denom,
}
return utils.Map(response.Balances, func(amount types.ResponseAmount) types.Amount {
return amount.ToAmount()
}), &info, nil
}

Expand All @@ -234,6 +235,7 @@ func (rpc *RPC) GetSigningInfo(valcons string) (*types.SigningInfoResponse, *typ
}

if response.Code != 0 {
info.Success = false
return &types.SigningInfoResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

Expand Down Expand Up @@ -269,5 +271,10 @@ func (rpc *RPC) GetStakingParams() (*types.StakingParamsResponse, *types.QueryIn
return nil, &info, err
}

if response.Code != 0 {
info.Success = false
return &types.StakingParamsResponse{}, &info, fmt.Errorf("expected code 0, but got %d", response.Code)
}

return response, &info, nil
}
149 changes: 149 additions & 0 deletions pkg/types/tendermint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package types

import (
b64 "encoding/base64"
"main/pkg/utils"
"time"

codecTypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptoTypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/types"
)

type ValidatorResponse struct {
Code int `json:"code"`
Validator Validator `json:"validator"`
}

type Validator struct {
OperatorAddress string `json:"operator_address"`
ConsensusPubkey ConsensusPubkey `json:"consensus_pubkey"`
Jailed bool `json:"jailed"`
Status string `json:"status"`
Tokens string `json:"tokens"`
DelegatorShares string `json:"delegator_shares"`
Description struct {
Moniker string `json:"moniker"`
Identity string `json:"identity"`
Website string `json:"website"`
SecurityContact string `json:"security_contact"`
Details string `json:"details"`
} `json:"description"`
UnbondingHeight string `json:"unbonding_height"`
UnbondingTime time.Time `json:"unbonding_time"`
Commission struct {
CommissionRates struct {
Rate string `json:"rate"`
MaxRate string `json:"max_rate"`
MaxChangeRate string `json:"max_change_rate"`
} `json:"commission_rates"`
UpdateTime time.Time `json:"update_time"`
} `json:"commission"`
MinSelfDelegation string `json:"min_self_delegation"`
}

type ConsensusPubkey struct {
Type string `json:"@type"`
Key string `json:"key"`
}

func (key *ConsensusPubkey) GetValConsAddress(prefix string) (string, error) {
encCfg := simapp.MakeTestEncodingConfig()
interfaceRegistry := encCfg.InterfaceRegistry

sDec, _ := b64.StdEncoding.DecodeString(key.Key)
pk := codecTypes.Any{
TypeUrl: key.Type,
Value: append([]byte{10, 32}, sDec...),
}

var pkProto cryptoTypes.PubKey
if err := interfaceRegistry.UnpackAny(&pk, &pkProto); err != nil {
return "", err
}

cosmosValCons := types.ConsAddress(pkProto.Address()).String()
properValCons, err := utils.ChangeBech32Prefix(cosmosValCons, prefix)
if err != nil {
return "", err
}

return properValCons, nil
}

type PaginationResponse struct {
Code int `json:"code"`
Pagination Pagination `json:"pagination"`
}

type Pagination struct {
Total string `json:"total"`
}

type ValidatorsResponse struct {
Code int `json:"code"`
Validators []Validator `json:"validators"`
}

type BalancesResponse struct {
Balances []ResponseAmount `json:"balances"`
}

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

func (a ResponseAmount) ToAmount() Amount {
return Amount{
Amount: utils.StrToFloat64(a.Amount),
Denom: a.Denom,
}
}

type SigningInfoResponse struct {
Code int `json:"code"`
ValSigningInfo struct {
Address string `json:"address"`
StartHeight string `json:"start_height"`
IndexOffset string `json:"index_offset"`
JailedUntil time.Time `json:"jailed_until"`
Tombstoned bool `json:"tombstoned"`
MissedBlocksCounter string `json:"missed_blocks_counter"`
} `json:"val_signing_info"`
}

type SlashingParamsResponse struct {
SlashingParams struct {
SignedBlocksWindow string `json:"signed_blocks_window"`
} `json:"params"`
}

type SingleDelegationResponse struct {
Code int `json:"code"`
DelegationResponse DelegationResponse `json:"delegation_response"`
}

type DelegationResponse struct {
Balance ResponseAmount `json:"balance"`
}

type RewardsResponse struct {
Code int `json:"code"`
Rewards []ResponseAmount `json:"rewards"`
}

type StakingParamsResponse struct {
Code int `json:"code"`
StakingParams struct {
MaxValidators int `json:"max_validators"`
} `json:"params"`
}

type CommissionResponse struct {
Code int `json:"code"`
Commission struct {
Commission []ResponseAmount `json:"commission"`
} `json:"commission"`
}
Loading

0 comments on commit baa6581

Please sign in to comment.