Skip to content

Commit

Permalink
add ut and query cli for wasm extra propsal (#3093)
Browse files Browse the repository at this point in the history
* add wasm proposal ut

* add wasm proposal ut

* add query api

* update max value

* fix ut

* fix cli display

* optimized code

* optimized code

* optimized code

* optimized code
  • Loading branch information
zjg555543 authored Apr 12, 2023
1 parent 9fc23a8 commit ab28f14
Show file tree
Hide file tree
Showing 13 changed files with 547 additions and 41 deletions.
2 changes: 1 addition & 1 deletion x/wasm/client/cli/gov_custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ Where proposal.json contains like these:
"title":"modify wasm gas factor",
"description":"modify wasm gas factor",
"action": "GasFactor",
"extra": "{\"factor\":240000000}",
"extra": "{\"factor\":\"14\"}",
"deposit":[
{
"denom":"%s",
Expand Down
24 changes: 24 additions & 0 deletions x/wasm/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func NewQueryCmd(cdc *codec.CodecProxy, reg codectypes.InterfaceRegistry) *cobra
NewCmdLibVersion(cdc, reg),
NewCmdListContractBlockedMethod(cdc),
NewCmdGetParams(cdc, reg),
NewCmdGetExtraParams(cdc, reg),
NewCmdGetAddressWhitelist(cdc, reg),
)

Expand Down Expand Up @@ -133,6 +134,29 @@ func NewCmdGetParams(m *codec.CodecProxy, reg codectypes.InterfaceRegistry) *cob
return cmd
}

func NewCmdGetExtraParams(m *codec.CodecProxy, reg codectypes.InterfaceRegistry) *cobra.Command {
cmd := &cobra.Command{
Use: "extra-params",
Short: "Get wasm extra parameters on the chain",
Long: "Get wasm extra parameters on the chain",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := clientCtx.NewCLIContext().WithProxy(m).WithInterfaceRegistry(reg)
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryExtraParams)

res, _, err := clientCtx.Query(route)
if err != nil {
return err
}

var params types.QueryExtraParams
m.GetCdc().MustUnmarshalJSON(res, &params)
return clientCtx.PrintOutput(params)
},
}
return cmd
}

func NewCmdGetAddressWhitelist(m *codec.CodecProxy, reg codectypes.InterfaceRegistry) *cobra.Command {
cmd := &cobra.Command{
Use: "get-address-whitelist",
Expand Down
21 changes: 21 additions & 0 deletions x/wasm/client/rest/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func registerQueryRoutes(cliCtx clientCtx.CLIContext, r *mux.Router) {
r.HandleFunc("/wasm/contract/{contractAddr}/raw/{key}", queryContractStateRawHandlerFn(cliCtx)).Queries("encoding", "{encoding}").Methods("GET")
r.HandleFunc("/wasm/contract/{contractAddr}/blocked_methods", queryContractBlockedMethodsHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/params", queryParamsHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/extra_params", queryExtraParamsHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/whitelist", queryContractWhitelistHandlerFn(cliCtx)).Methods("GET")
}

Expand All @@ -55,6 +56,26 @@ func queryParamsHandlerFn(cliCtx clientCtx.CLIContext) http.HandlerFunc {
}
}

func queryExtraParamsHandlerFn(cliCtx clientCtx.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}

route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryExtraParams)

res, height, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}

cliCtx = cliCtx.WithHeight(height)
rest.PostProcessResponse(w, cliCtx, res)
}
}

func queryContractWhitelistHandlerFn(cliCtx clientCtx.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
Expand Down
14 changes: 7 additions & 7 deletions x/wasm/keeper/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,10 +458,10 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
"code_id": "1",
"code_info": {
"code_hash": %q,
"creator": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx",
"creator": "ex190227rqaps5nplhg2tg8hww7slvvquzy0qa0l0",
"instantiate_config": {
"permission": "OnlyAddress",
"address": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx"
"address": "ex190227rqaps5nplhg2tg8hww7slvvquzy0qa0l0"
}
},
"code_bytes": %q
Expand All @@ -472,8 +472,8 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
"contract_address": "0x5A8D648DEE57b2fc90D98DC17fa887159b69638b",
"contract_info": {
"code_id": "1",
"creator": "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x",
"admin": "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn",
"creator": "ex1fsfwwvl93qv6r56jpu084hxxzn9zphnyxhske5",
"admin": "ex1s0vrf96rrsknl64jj65lhf89ltwj7lksr7m3r9",
"label": "ȀĴnZV芢毤"
}
}
Expand Down Expand Up @@ -513,7 +513,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
// verify code info
gotCodeInfo := keeper.GetCodeInfo(ctx, 1)
require.NotNil(t, gotCodeInfo)
codeCreatorAddr := "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx"
codeCreatorAddr := "ex190227rqaps5nplhg2tg8hww7slvvquzy0qa0l0"
expCodeInfo := types.CodeInfo{
CodeHash: wasmCodeHash[:],
Creator: codeCreatorAddr,
Expand All @@ -528,8 +528,8 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
contractAddr, _ := sdk.WasmAddressFromBech32("0x5A8D648DEE57b2fc90D98DC17fa887159b69638b")
gotContractInfo := keeper.GetContractInfo(ctx, contractAddr)
require.NotNil(t, gotContractInfo)
contractCreatorAddr := "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x"
adminAddr := "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn"
contractCreatorAddr := "ex1fsfwwvl93qv6r56jpu084hxxzn9zphnyxhske5"
adminAddr := "ex1s0vrf96rrsknl64jj65lhf89ltwj7lksr7m3r9"

expContractInfo := types.ContractInfo{
CodeID: firstCodeID,
Expand Down
10 changes: 10 additions & 0 deletions x/wasm/keeper/legacy_querier.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const (
QueryContractHistory = "contract-history"
QueryListContractBlockedMethod = "list-contract-blocked-method"
QueryParams = "params"
QueryExtraParams = "extra-params"
)

const (
Expand Down Expand Up @@ -76,6 +77,8 @@ func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier {
rsp = queryListContractBlockedMethod(ctx, contractAddr, keeper)
case QueryParams:
rsp = queryParams(ctx, keeper)
case QueryExtraParams:
rsp = queryExtraParams(ctx, keeper)
default:
return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint")
}
Expand Down Expand Up @@ -171,3 +174,10 @@ func queryParams(ctx sdk.Context, keeper types.ViewKeeper) *types.Params {
params := keeper.GetParams(ctx)
return &params
}

func queryExtraParams(ctx sdk.Context, keeper types.ViewKeeper) *types.QueryExtraParams {
params := types.QueryExtraParams{
GasFactor: strconv.FormatUint(keeper.GetGasFactor(ctx), 10),
}
return &params
}
94 changes: 93 additions & 1 deletion x/wasm/keeper/proposal_integration_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
package keeper
package keeper_test

import (
"github.com/okex/exchain/x/wasm"
"github.com/okex/exchain/x/wasm/keeper"
"testing"
"time"

"github.com/okex/exchain/app"
"github.com/okex/exchain/libs/cosmos-sdk/codec"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
abci "github.com/okex/exchain/libs/tendermint/abci/types"
tmtypes "github.com/okex/exchain/libs/tendermint/types"
govtypes "github.com/okex/exchain/x/gov/types"
"github.com/okex/exchain/x/wasm/types"
"github.com/stretchr/testify/suite"
)

//import (
// "bytes"
Expand Down Expand Up @@ -841,3 +857,79 @@ package keeper
// })
// }
//}

func (suite *ProposalTestSuite) SetupTest() {
checkTx := false

suite.app = app.Setup(checkTx)
suite.ctx = suite.app.BaseApp.NewContext(checkTx, abci.Header{Height: 1, ChainID: "ethermint-3", Time: time.Now().UTC()})
suite.wasmHandler = keeper.NewWasmProposalHandler(&suite.app.WasmKeeper, wasm.NecessaryProposals)
suite.codec = codec.New()
}

func TestSuite(t *testing.T) {
suite.Run(t, new(ProposalTestSuite))
}

type ProposalTestSuite struct {
suite.Suite

ctx sdk.Context
wasmHandler govtypes.Handler
app *app.OKExChainApp
codec *codec.Codec
}

func (suite *ProposalTestSuite) TestModifyNextBlockUpdateProposal() {
suite.ctx.SetBlockHeight(1000)

proposal := types.ExtraProposal{
Title: types.ActionModifyGasFactor,
Description: "Description",
Action: types.ActionModifyGasFactor,
Extra: "",
}

govProposal := govtypes.Proposal{
Content: &proposal,
}

testCases := []struct {
msg string
extra string
gasFactor uint64
expectError error
}{
{"1", "", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse json error, expect like {\"factor\":\"14\"}, but get:")},
{"1", "{}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, decimal string cannot be empty")},
{"1", "{\"\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse json error, expect like {\"factor\":\"14\"}, but get:{\"\"}")},
{"1", "{\"df\", \"\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse json error, expect like {\"factor\":\"14\"}, but get:{\"df\", \"\"}")},
{"1", "{\"factor\":19.7}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse json error, expect like {\"factor\":\"14\"}, but get:{\"factor\":19.7}")},
{"1", "{\"factor\":19}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse json error, expect like {\"factor\":\"14\"}, but get:{\"factor\":19}")},
{"1", "{\"factor\": \"adfasd\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, failed to set decimal string: adfasd000000000000000000")},
{"1", "{\"factor\": \"-1\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, expect factor positive and 18 precision, but get -1")},
{"2", "{\"factor\": \"0\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, expect factor positive and 18 precision, but get 0")},
{"3", "{\"factor\": \"0.0000000000000000000000001\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, invalid precision; max: 18, got: 25")},
{"4", "{\"factor\": \"0.000000000000000001\"}", keeper.DefaultGasMultiplier, types.ErrCodeInvalidGasFactor},
{"4", "{\"factor\":\"19.7a\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, failed to set decimal string: 197a0000000000000000")},
{"4", "{\"factor\":\"a19.7\"}", keeper.DefaultGasMultiplier, types.ErrExtraProposalParams("parse factor error, failed to set decimal string: a19700000000000000000")},
{"4", "{\"factor\": \"10000000\"}", (uint64(types.MaxGasFactor)) * keeper.BaseGasMultiplier, nil},
{"4", "{\"factor\":\"19.7\"}", 197 * keeper.BaseGasMultiplier / 10, nil},
}

tmtypes.UnittestOnlySetMilestoneEarthHeight(-1)

for _, tc := range testCases {
suite.Run(tc.msg, func() {
proposal.Extra = tc.extra
govProposal.Content = &proposal

err := suite.wasmHandler(suite.ctx, &govProposal)
suite.app.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{ChainID: "exchain-67", Height: 1, Time: time.Now()}})
suite.Require().Equal(tc.expectError, err)

gasFactor := suite.app.WasmKeeper.GetGasFactor(suite.ctx)
suite.Require().Equal(tc.gasFactor, gasFactor)
})
}
}
4 changes: 2 additions & 2 deletions x/wasm/keeper/querier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ func TestQueryCodeInfo(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, SupportedFeatures)
keeper := keepers.WasmKeeper

anyAddress, err := sdk.WasmAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz")
anyAddress, err := sdk.WasmAddressFromBech32("ex190227rqaps5nplhg2tg8hww7slvvquzy0qa0l0")
require.NoError(t, err)
specs := map[string]struct {
codeId uint64
Expand Down Expand Up @@ -714,7 +714,7 @@ func TestQueryCodeInfoList(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, SupportedFeatures)
keeper := keepers.WasmKeeper

anyAddress, err := sdk.WasmAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz")
anyAddress, err := sdk.WasmAddressFromBech32("ex190227rqaps5nplhg2tg8hww7slvvquzy0qa0l0")
require.NoError(t, err)
codeInfoWithConfig := func(accessConfig types.AccessConfig) types.CodeInfo {
codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode))
Expand Down
4 changes: 4 additions & 0 deletions x/wasm/proto/proposal_custom.proto
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ message ExtraProposal {
string action = 3;
string extra = 4;
}

message QueryExtraParams {
string gas_factor = 1;
}
4 changes: 2 additions & 2 deletions x/wasm/types/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ var (
// ErrExceedMaxQueryStackSize error if max query stack size is exceeded
ErrExceedMaxQueryStackSize = sdkErrors.Register(DefaultCodespace, 27, "max query stack size exceeded")

ErrCodeInvalidGasFactor = sdkErrors.Register(ModuleName, 29, "invalid gas factor")
ErrCodeInvalidGasFactor = sdkErrors.Register(DefaultCodespace, 29, "invalid gas factor")
ErrHandleExtraProposal = sdkErrors.Register(DefaultCodespace, 30, "handle extra proposal error")
ErrUnknownExtraProposalAction = sdkErrors.Register(DefaultCodespace, 31, "extra proposal's action unknown")

ErrProposerMustBeValidator = sdkErrors.Register(ModuleName, 32, "the proposal of proposer must be validator")
ErrProposerMustBeValidator = sdkErrors.Register(DefaultCodespace, 32, "the proposal of proposer must be validator")
)

type ErrNoSuchContract struct {
Expand Down
1 change: 1 addition & 0 deletions x/wasm/types/exported_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type ViewKeeper interface {
IsPinnedCode(ctx sdk.Context, codeID uint64) bool
GetContractMethodBlockedList(ctx sdk.Context, contractAddr string) *ContractMethods
GetParams(ctx sdk.Context) Params
GetGasFactor(ctx sdk.Context) uint64
}

// ContractOpsKeeper contains mutable operations on a contract.
Expand Down
15 changes: 10 additions & 5 deletions x/wasm/types/proposal_custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import (
)

const (
maxAddressListLength = 100
maxMethodListLength = 100
maxAddressListLength = 100
maxMethodListLength = 100
MaxGasFactor int64 = 10000000
)

// ProposalRoute returns the routing key of a parameter change proposal.
Expand Down Expand Up @@ -223,16 +224,20 @@ func NewActionModifyGasFactor(data string) (sdk.Dec, error) {
var param GasFactor
err := json.Unmarshal([]byte(data), &param)
if err != nil {
return sdk.Dec{}, ErrExtraProposalParams("parse json error")
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("parse json error, expect like {\"factor\":\"14\"}, but get:%s", data))
}

result, err := sdk.NewDecFromStr(param.Factor)
if err != nil {
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("parse factor error:%s", param.Factor))
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("parse factor error, %s", err.Error()))
}

if result.IsNil() || result.IsNegative() || result.IsZero() {
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("parse factor error:%s", param.Factor))
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("parse factor error, expect factor positive and 18 precision, but get %s", param.Factor))
}

if result.GT(sdk.NewDec(MaxGasFactor)) {
return sdk.Dec{}, ErrExtraProposalParams(fmt.Sprintf("max gas factor:%v, but get:%s", MaxGasFactor, param.Factor))
}

return result, nil
Expand Down
Loading

0 comments on commit ab28f14

Please sign in to comment.