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

Deepanshutr/chore #436

Merged
merged 21 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3ceec50
fix(supplement):Update auxiliary_keeper to handle invalid requests
deepanshutr Apr 15, 2024
df05554
Remove unnecessary assertions in auxiliary_request_test
deepanshutr Apr 15, 2024
2270f48
Refactor(supplement):removed dependency on the govalidator in auxilia…
deepanshutr Apr 15, 2024
c5c7dd2
test(supplement): adding test cases
deepanshutr Apr 15, 2024
f626f8e
refactor(errors): moving errors to modules
deepanshutr Apr 17, 2024
5f6a76e
feat(transactions_request): replacing go validator with native valida…
deepanshutr Apr 22, 2024
ad29185
code cleanup(aux req test): unused test cases
deepanshutr Apr 22, 2024
adf272d
refactor(auxiliary_request): replacing go validator with native valid…
deepanshutr Apr 22, 2024
9723446
feat(auxiliary keeper):adding request validation
deepanshutr Apr 22, 2024
a55eff6
refactor(genesis): updating error messages
deepanshutr Apr 22, 2024
6553add
refactor: updating error messages
deepanshutr Apr 22, 2024
33dc248
feat(key):adding validateBasic method to key interface
deepanshutr Apr 22, 2024
aa4cead
refactor(query_request):updating validation logic away from go validator
deepanshutr Apr 22, 2024
026a19f
feat(query_keeper):adding request validation logic
deepanshutr Apr 22, 2024
cf31f89
refactor(utilities):updating request validation logic
deepanshutr Apr 22, 2024
6d72faf
feat(errors): adding invalid key error
deepanshutr Apr 22, 2024
616a963
fix(renumerate): auxiliary request type
deepanshutr Apr 23, 2024
cb4de6e
fix(assets): modifying parameter unwrap allowed coins for easier testing
deepanshutr Apr 23, 2024
0eb6ef4
fix(name): disallowing empty name issuance
deepanshutr Apr 23, 2024
55b7b1b
fix(legacy_codec): adding error, Error and Request interfaces
deepanshutr Apr 23, 2024
424ae50
fix(member): allowing requests with nil immutables or mutables
deepanshutr Apr 23, 2024
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
12 changes: 12 additions & 0 deletions helpers/base/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package base

import (
"github.com/AssetMantle/modules/helpers"
sdkErrors "github.com/cosmos/cosmos-sdk/types/errors"
)

var _ helpers.Error = (*sdkErrors.Error)(nil)

func NewError(codeSpace string, code uint32, description string) helpers.Error {
return sdkErrors.Register(codeSpace, code, description)
}
13 changes: 6 additions & 7 deletions helpers/base/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"math/rand"

errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/cosmos/cosmos-sdk/client"
sdkCodec "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
Expand Down Expand Up @@ -153,15 +152,15 @@ func (module module) RegisterInvariants(invariantRegistry sdkTypes.InvariantRegi
func (module module) Route() sdkTypes.Route {
return sdkTypes.NewRoute(module.Name(), func(context sdkTypes.Context, msg sdkTypes.Msg) (*sdkTypes.Result, error) {
if module.transactions == nil {
panic(errorConstants.UninitializedUsage.Wrapf("transactions for module %s not initialized", module.Name()))
panic(fmt.Errorf("transactions for module %s not initialized", module.Name()))
}

if message, ok := msg.(helpers.Message); ok {
if transaction := module.transactions.GetTransaction(message.Type()); transaction != nil {
return transaction.HandleMessage(sdkTypes.WrapSDKContext(context.WithEventManager(sdkTypes.NewEventManager())), message)
}
}
return nil, errorConstants.InvalidMessage.Wrapf("message type %T is not supported by module %s", msg, module.Name())
return nil, fmt.Errorf("message type %T is not supported by module %s", msg, module.Name())
})
}
func (module module) QuerierRoute() string {
Expand All @@ -170,7 +169,7 @@ func (module module) QuerierRoute() string {
func (module module) LegacyQuerierHandler(_ *sdkCodec.LegacyAmino) sdkTypes.Querier {
return func(context sdkTypes.Context, path []string, requestQuery abciTypes.RequestQuery) ([]byte, error) {
if module.queries == nil {
panic(errorConstants.UninitializedUsage.Wrapf("queries for module %s not initialized", module.Name()))
panic(fmt.Errorf("queries for module %s not initialized", module.Name()))
}

if query := module.queries.GetQuery(path[0]); query != nil {
Expand Down Expand Up @@ -200,7 +199,7 @@ func (module module) InitGenesis(context sdkTypes.Context, jsonCodec sdkCodec.JS
genesisState := module.genesisPrototype().Decode(jsonCodec, rawMessage)

if module.mapper == nil || module.parameterManager == nil {
panic(errorConstants.UninitializedUsage.Wrapf("mapper or parameter manager for module %s not initialized", module.Name()))
panic(fmt.Errorf("mapper or parameter manager for module %s not initialized", module.Name()))
}

genesisState.Import(sdkTypes.WrapSDKContext(context), module.mapper, module.parameterManager)
Expand All @@ -209,7 +208,7 @@ func (module module) InitGenesis(context sdkTypes.Context, jsonCodec sdkCodec.JS
}
func (module module) ExportGenesis(context sdkTypes.Context, jsonCodec sdkCodec.JSONCodec) json.RawMessage {
if module.mapper == nil || module.parameterManager == nil {
panic(errorConstants.UninitializedUsage.Wrapf("mapper or parameter manager for module %s not initialized", module.Name()))
panic(fmt.Errorf("mapper or parameter manager for module %s not initialized", module.Name()))
}

return module.genesisPrototype().Export(sdkTypes.WrapSDKContext(context), module.mapper, module.parameterManager).Encode(jsonCodec)
Expand All @@ -235,7 +234,7 @@ func (module module) DecodeModuleTransactionRequest(transactionName string, rawM
return transaction.DecodeTransactionRequest(rawMessage)
}

return nil, errorConstants.InvalidMessage.Wrapf("transaction %s is not supported by module %s", transactionName, module.Name())
return nil, fmt.Errorf("transaction %s is not supported by module %s", transactionName, module.Name())
}
func (module module) Initialize(kvStoreKey *sdkTypes.KVStoreKey, paramsSubspace paramsTypes.Subspace, auxiliaryKeepers ...interface{}) helpers.Module {
module.mapper = module.mapperPrototype().Initialize(kvStoreKey)
Expand Down
7 changes: 3 additions & 4 deletions helpers/base/parameter_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"net/http"

errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/AssetMantle/schema/go/ids"
"github.com/AssetMantle/schema/go/lists"
baseLists "github.com/AssetMantle/schema/go/lists/base"
Expand Down Expand Up @@ -51,15 +50,15 @@ func (parameterManager parameterManager) GetValidatableParameter(propertyID ids.
return nil
}
func (parameterManager parameterManager) ValidateParameter(parameter parameters.Parameter) error {
validator := parameterManager.GetValidatableParameter(parameter.GetMetaProperty().GetID())
if validator != nil {
if validator := parameterManager.GetValidatableParameter(parameter.GetMetaProperty().GetID()); validator != nil {
if err := parameter.ValidateBasic(); err != nil {
return err
}

return validator.GetValidator()(parameter.GetMetaProperty().GetData().Get().AsString())
}
return errorConstants.EntityNotFound.Wrapf("parameter with id %s not found", parameter.GetMetaProperty().GetID().AsString())

return fmt.Errorf("validator not found for parameter %s", parameter.GetMetaProperty().GetID().AsString())
}
func (parameterManager parameterManager) Fetch(context context.Context) helpers.ParameterManager {
for _, validatableParameter := range parameterManager.validatableParameters {
Expand Down
4 changes: 2 additions & 2 deletions helpers/base/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
package base

import (
"fmt"
"net/http"

errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/cosmos/cosmos-sdk/client"
sdkModuleTypes "github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/types/rest"
Expand Down Expand Up @@ -35,7 +35,7 @@ var _ helpers.Query = (*query)(nil)

func (query query) RegisterService(configurator sdkModuleTypes.Configurator) {
if query.queryKeeper == nil {
panic(errorConstants.UninitializedUsage.Wrapf("query keeper for query %s not initialized", query.name))
panic(fmt.Errorf("query keeper for query %s not initialized", query.name))
}
query.serviceRegistrar(configurator.QueryServer(), query.queryKeeper)
}
Expand Down
21 changes: 10 additions & 11 deletions helpers/base/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@ package base
import (
"context"
"encoding/json"
"github.com/AssetMantle/modules/utilities/rest/queuing"
"net/http"
"reflect"

"fmt"
"github.com/AssetMantle/modules/helpers"
errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/AssetMantle/modules/utilities/rest/queuing"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
sdkCodec "github.com/cosmos/cosmos-sdk/codec"
Expand All @@ -22,6 +19,8 @@ import (
"github.com/gogo/protobuf/grpc"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
"net/http"
"reflect"
)

type transaction struct {
Expand All @@ -40,12 +39,12 @@ var _ helpers.Transaction = (*transaction)(nil)
func (transaction transaction) GetName() string { return transaction.name }
func (transaction transaction) Command() *cobra.Command {
runE := func(command *cobra.Command, args []string) error {
context, err := client.GetClientTxContext(command)
Context, err := client.GetClientTxContext(command)
if err != nil {
return err
}

transactionRequest, err := transaction.requestPrototype().FromCLI(transaction.cliCommand, context)
transactionRequest, err := transaction.requestPrototype().FromCLI(transaction.cliCommand, Context)
if err != nil {
return err
}
Expand All @@ -63,7 +62,7 @@ func (transaction transaction) Command() *cobra.Command {
return err
}

return tx.GenerateOrBroadcastTxCLI(context, command.Flags(), msg)
return tx.GenerateOrBroadcastTxCLI(Context, command.Flags(), msg)
}

return transaction.cliCommand.CreateCommand(runE)
Expand All @@ -81,15 +80,15 @@ func (transaction transaction) RESTRequestHandler(context client.Context) http.H
if !rest.ReadRESTReq(responseWriter, httpRequest, context.LegacyAmino, &transactionRequest) {
return
} else if reflect.TypeOf(transaction.requestPrototype()) != reflect.TypeOf(transactionRequest) {
rest.CheckBadRequestError(responseWriter, errorConstants.InvalidRequest.Wrapf("expected %s, got %s", reflect.TypeOf(transaction.requestPrototype()), reflect.TypeOf(transactionRequest)))
rest.CheckBadRequestError(responseWriter, fmt.Errorf("expected %s, got %s", reflect.TypeOf(transaction.requestPrototype()), reflect.TypeOf(transactionRequest)))
return
} else if rest.CheckBadRequestError(responseWriter, transactionRequest.Validate()) {
return
}

baseReq := transactionRequest.GetBaseReq().Sanitize()
if !baseReq.ValidateBasic(responseWriter) {
rest.CheckBadRequestError(responseWriter, errorConstants.InvalidRequest.Wrapf("invalid base request"))
rest.CheckBadRequestError(responseWriter, fmt.Errorf("invalid base request"))
}

msg, err := transactionRequest.MakeMsg()
Expand All @@ -112,7 +111,7 @@ func (transaction transaction) RegisterInterfaces(interfaceRegistry codecTypes.I
}
func (transaction transaction) RegisterService(configurator sdkModuleTypes.Configurator) {
if transaction.keeper == nil {
panic(errorConstants.UninitializedUsage.Wrapf("keeper for transaction %s is not initialized", transaction.name))
panic(fmt.Errorf("keeper for transaction %s is not initialized", transaction.name))
}
transaction.serviceRegistrar(configurator.MsgServer(), transaction.keeper)
}
Expand Down
25 changes: 25 additions & 0 deletions helpers/constants/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors
// SPDX-License-Identifier: Apache-2.0

package constants

import (
"github.com/AssetMantle/modules/helpers/base"
)

const projectRoute = "/AssetMantle"

var (
MockError = base.NewError(projectRoute, 100, "mock error")
EntityAlreadyExists = base.NewError(projectRoute, 102, "entity already exists")
EntityNotFound = base.NewError(projectRoute, 103, "entity not found")
IncorrectFormat = base.NewError(projectRoute, 104, "incorrect format")
InvalidMessage = base.NewError(projectRoute, 105, "invalid message")
InsufficientBalance = base.NewError(projectRoute, 106, "insufficient balance")
InvalidParameter = base.NewError(projectRoute, 107, "invalid parameter")
InvalidRequest = base.NewError(projectRoute, 108, "invalid request")
MetaDataError = base.NewError(projectRoute, 109, "meta data error")
NotAuthorized = base.NewError(projectRoute, 110, "not authorized")
UninitializedUsage = base.NewError(projectRoute, 111, "uninitialized usage")
InvalidKey = base.NewError(projectRoute, 112, "invalid key")
)
3 changes: 3 additions & 0 deletions helpers/constants/queryRequest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package constants

const PaginationLimit = 100
7 changes: 7 additions & 0 deletions helpers/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package helpers

type Error interface {
Wrapf(string, ...interface{}) error
Is(error) bool
error
}
1 change: 1 addition & 0 deletions helpers/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package helpers

// Key SHOULD be derivable from the object it is referencing and SHOULD not be totally arbitrary or sequential
type Key interface {
ValidateBasic() error
GenerateStorePrefixBytes() []byte
GenerateStoreKeyBytes() []byte
GeneratePrefixedStoreKeyBytes() []byte
Expand Down
3 changes: 3 additions & 0 deletions helpers/legacy_codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ func RegisterLegacyAminoCodec(legacyAmino *codec.LegacyAmino) {
legacyAmino.RegisterInterface((*QueryResponse)(nil), nil)
legacyAmino.RegisterInterface((*QueryRequest)(nil), nil)
legacyAmino.RegisterInterface((*TransactionRequest)(nil), nil)
legacyAmino.RegisterInterface((*Request)(nil), nil)
legacyAmino.RegisterInterface((*Error)(nil), nil)
legacyAmino.RegisterInterface((*error)(nil), nil)
}
6 changes: 3 additions & 3 deletions utilities/rest/id_getters/docs/identity.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package docs

import (
"fmt"
"net/http"

baseData "github.com/AssetMantle/schema/go/data/base"
baseDocuments "github.com/AssetMantle/schema/go/documents/base"
errorConstants "github.com/AssetMantle/schema/go/errors/constants"
baseIDs "github.com/AssetMantle/schema/go/ids/base"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/rest"
Expand All @@ -15,11 +15,11 @@ func nameIdentityIDHandler(context client.Context) http.HandlerFunc {
return func(responseWriter http.ResponseWriter, httpRequest *http.Request) {
transactionRequest := Prototype()
if !rest.ReadRESTReq(responseWriter, httpRequest, context.LegacyAmino, &transactionRequest) {
panic(errorConstants.IncorrectFormat)
panic(fmt.Errorf("failed to read request"))
}

if rest.CheckBadRequestError(responseWriter, transactionRequest.Validate()) {
panic(errorConstants.IncorrectFormat)
panic(fmt.Errorf("failed to validate request"))
}

rest.PostProcessResponse(responseWriter, context, newResponse(baseDocuments.NewNameIdentity(baseIDs.NewStringID(transactionRequest.(request).Name), baseData.PrototypeListData()).GetNameIdentityID().AsString(), nil))
Expand Down
33 changes: 3 additions & 30 deletions utilities/rest/id_getters/docs/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@
package docs

import (
"encoding/json"

"github.com/asaskevich/govalidator"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdkTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"

"github.com/AssetMantle/modules/helpers"
Expand All @@ -34,37 +28,16 @@ type request struct {
Coins string `json:"coins" valid:"optional"`
}

var _ helpers.TransactionRequest = &request{}

func (request request) FromCLI(command helpers.CLICommand, context client.Context) (helpers.TransactionRequest, error) {
// TODO implement me
panic("implement me")
}

func (request) RegisterLegacyAminoCodec(legacyAmino *codec.LegacyAmino) {
// TODO implement me
panic("implement me")
}

func (request request) FromJSON(message json.RawMessage) (helpers.TransactionRequest, error) {
// TODO implement me
panic("implement me")
}

func (request request) MakeMsg() (sdkTypes.Msg, error) {
// TODO implement me
panic("implement me")
}
var _ helpers.Request = &request{}

func (request request) Validate() error {
_, err := govalidator.ValidateStruct(request)
return err
return nil
}

func (request request) GetBaseReq() rest.BaseReq {
return request.BaseReq
}

func Prototype() helpers.TransactionRequest {
func Prototype() helpers.Request {
return request{}
}
9 changes: 4 additions & 5 deletions utilities/rest/id_getters/docs/split.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
package docs

import (
"net/http"

"fmt"
baseDocuments "github.com/AssetMantle/schema/go/documents/base"
errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/AssetMantle/schema/go/ids"
baseIDs "github.com/AssetMantle/schema/go/ids/base"
"github.com/cosmos/cosmos-sdk/client"
sdkTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"net/http"
)

func splitIDHandler(context client.Context) http.HandlerFunc {
return func(responseWriter http.ResponseWriter, httpRequest *http.Request) {
transactionRequest := Prototype()
if !rest.ReadRESTReq(responseWriter, httpRequest, context.LegacyAmino, &transactionRequest) {
panic(errorConstants.IncorrectFormat)
panic(fmt.Errorf("failed to read request"))
}

if rest.CheckBadRequestError(responseWriter, transactionRequest.Validate()) {
panic(errorConstants.IncorrectFormat)
panic(fmt.Errorf("failed to validate request"))
}

req := transactionRequest.(request)
Expand Down
2 changes: 1 addition & 1 deletion utilities/wasm/custom_encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ package wasm

import (
"encoding/json"
errorConstants "github.com/AssetMantle/modules/helpers/constants"
"strings"

errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/CosmWasm/wasmd/x/wasm"
sdkTypes "github.com/cosmos/cosmos-sdk/types"

Expand Down
6 changes: 3 additions & 3 deletions x/assets/genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package genesis

import (
"context"
errorConstants "github.com/AssetMantle/modules/helpers/constants"

errorConstants "github.com/AssetMantle/schema/go/errors/constants"
"github.com/AssetMantle/schema/go/lists"
"github.com/AssetMantle/schema/go/lists/base"
sdkCodec "github.com/cosmos/cosmos-sdk/codec"
Expand Down Expand Up @@ -34,11 +34,11 @@ func (genesis *Genesis) ValidateBasic(parameterManager helpers.ParameterManager)
}

if !isPresent {
return errorConstants.IncorrectFormat.Wrapf("expected parameter %s not found", parameter.GetMetaProperty().GetKey().AsString())
return errorConstants.EntityNotFound.Wrapf("expected parameter %s not found", parameter.GetMetaProperty().GetKey().AsString())
}

if err := parameterManager.ValidateParameter(parameter); err != nil {
return err
return errorConstants.InvalidParameter.Wrapf("parameter %s: %s", parameter.GetMetaProperty().GetKey().AsString(), err.Error())
}
}

Expand Down
Loading
Loading