From 2ee13b9f20afc54eaf1c917cb467ec60d535e496 Mon Sep 17 00:00:00 2001 From: Robert Zaremba Date: Thu, 21 Sep 2023 22:40:46 +0200 Subject: [PATCH 1/2] feat(client): unify and refactore client package (#2256) * add metoken client * refactore tx client * metoken queries * add proto.Message validator * use umee client in e2e tests * nil check * add QueryMetokenIndexPrices * lint * rollback change to 20s * fix metoken e2e --------- Co-authored-by: Egor Kostetskiy --- client/metoken.go | 58 +++++++++++++++++++++++++++++++++ sdkclient/client.go | 7 ++-- sdkclient/query/client.go | 7 ++-- sdkclient/tx/bank.go | 8 +++-- sdkclient/tx/client.go | 18 +++++++--- sdkclient/tx/gov.go | 24 ++++++-------- sdkclient/tx/key.go | 9 +++++ sdkclient/tx/sign.go | 1 - sdkclient/tx/wasm.go | 51 +++++++++++------------------ tests/e2e/e2e_metoken_test.go | 20 +++--------- tests/e2e/setup/metoken.go | 23 ------------- tests/e2e/setup/utils.go | 2 +- tests/grpc/gov.go | 12 +++---- tests/util/cw_util.go | 10 +++--- util/sdkutil/msg.go | 15 +++++++++ x/oracle/keeper/historic_avg.go | 2 +- 16 files changed, 158 insertions(+), 109 deletions(-) create mode 100644 client/metoken.go diff --git a/client/metoken.go b/client/metoken.go new file mode 100644 index 0000000000..50d2cb6121 --- /dev/null +++ b/client/metoken.go @@ -0,0 +1,58 @@ +package client + +import ( + "github.com/umee-network/umee/v6/util/sdkutil" + "github.com/umee-network/umee/v6/x/metoken" +) + +func (c Client) MetokenQClient() metoken.QueryClient { + return metoken.NewQueryClient(c.Query.GrpcConn) +} + +func (c Client) QueryMetokenParams() (metoken.Params, error) { + ctx, cancel := c.NewQCtx() + defer cancel() + + resp, err := c.MetokenQClient().Params(ctx, &metoken.QueryParams{}) + if err != nil { + return metoken.Params{}, err + } + return resp.Params, err +} + +func (c Client) QueryMetokenIndexBalances(denom string) (*metoken.QueryIndexBalancesResponse, error) { + ctx, cancel := c.NewQCtx() + defer cancel() + + msg := &metoken.QueryIndexBalances{MetokenDenom: denom} + if err := sdkutil.ValidateProtoMsg(msg); err != nil { + return nil, err + } + return c.MetokenQClient().IndexBalances(ctx, msg) +} + +func (c Client) QueryMetokenIndexes(denom string) (*metoken.QueryIndexesResponse, error) { + ctx, cancel := c.NewQCtx() + defer cancel() + + msg := &metoken.QueryIndexes{MetokenDenom: denom} + if err := sdkutil.ValidateProtoMsg(msg); err != nil { + return nil, err + } + return c.MetokenQClient().Indexes(ctx, msg) +} + +func (c Client) QueryMetokenIndexPrices(denom string) (*metoken.QueryIndexPricesResponse, error) { + ctx, cancel := c.NewQCtx() + defer cancel() + + msg := &metoken.QueryIndexPrices{MetokenDenom: denom} + if err := sdkutil.ValidateProtoMsg(msg); err != nil { + return nil, err + } + return c.MetokenQClient().IndexPrices(ctx, msg) +} + +// +// Tx +// diff --git a/sdkclient/client.go b/sdkclient/client.go index 79736d6163..907c54f17c 100644 --- a/sdkclient/client.go +++ b/sdkclient/client.go @@ -2,6 +2,8 @@ package sdkclient import ( "context" + "log" + "os" "time" sdkparams "github.com/cosmos/cosmos-sdk/simapp/params" @@ -32,11 +34,12 @@ func NewClient( encCfg sdkparams.EncodingConfig, ) (uc Client, err error) { uc = Client{} - uc.Query, err = query.NewClient(grpcEndpoint, 15*time.Second) + logger := log.New(os.Stderr, "chain-client", log.LstdFlags) + uc.Query, err = query.NewClient(logger, grpcEndpoint, 15*time.Second) if err != nil { return Client{}, err } - uc.Tx, err = tx.NewClient(chainDataDir, chainID, tmrpcEndpoint, mnemonics, gasAdjustment, encCfg) + uc.Tx, err = tx.NewClient(logger, chainDataDir, chainID, tmrpcEndpoint, mnemonics, gasAdjustment, encCfg) return uc, err } diff --git a/sdkclient/query/client.go b/sdkclient/query/client.go index dc24c1574c..e3317300b8 100644 --- a/sdkclient/query/client.go +++ b/sdkclient/query/client.go @@ -2,6 +2,7 @@ package query import ( "context" + "log" "net" "strings" "time" @@ -14,10 +15,12 @@ type Client struct { GrpcConn *grpc.ClientConn grpcEndpoint string QueryTimeout time.Duration + + logger *log.Logger } -func NewClient(grpcEndpoint string, queryTimeout time.Duration) (*Client, error) { - qc := &Client{grpcEndpoint: grpcEndpoint, QueryTimeout: queryTimeout} +func NewClient(logger *log.Logger, grpcEndpoint string, queryTimeout time.Duration) (*Client, error) { + qc := &Client{logger: logger, grpcEndpoint: grpcEndpoint, QueryTimeout: queryTimeout} return qc, qc.dialGrpcConn() } diff --git a/sdkclient/tx/bank.go b/sdkclient/tx/bank.go index 8082b71f3b..788fd20226 100644 --- a/sdkclient/tx/bank.go +++ b/sdkclient/tx/bank.go @@ -5,11 +5,13 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) -func (c *Client) TxSend(fromAddress, toAddress string, amount sdk.Coins) (*sdk.TxResponse, error) { +// BankSend creates and broadcasts bank send tx. `fromIdx` is an account index in the client +// keyring. +func (c *Client) BankSend(fromIdx int, toAddress string, amount sdk.Coins) (*sdk.TxResponse, error) { msg := &banktypes.MsgSend{ - FromAddress: fromAddress, + FromAddress: c.KeyringAddress(fromIdx).String(), ToAddress: toAddress, Amount: amount, } - return c.BroadcastTx(msg) + return c.BroadcastTx(fromIdx, msg) } diff --git a/sdkclient/tx/client.go b/sdkclient/tx/client.go index c074c4bde3..64d673da6b 100644 --- a/sdkclient/tx/client.go +++ b/sdkclient/tx/client.go @@ -1,6 +1,7 @@ package tx import ( + "log" "os" "github.com/cosmos/cosmos-sdk/client" @@ -26,12 +27,15 @@ type Client struct { keyringRecord []*keyring.Record txFactory *tx.Factory encCfg sdkparams.EncodingConfig + + logger *log.Logger } // Initializes a cosmos sdk client context and transaction factory for // signing and broadcasting transactions by passing chainDataDir and remaining func arguments // Note: For signing the transactions accounts are created by names like this val0, val1.... func NewClient( + logger *log.Logger, chainDataDir, chainID, tmrpcEndpoint string, @@ -44,6 +48,7 @@ func NewClient( TMRPCEndpoint: tmrpcEndpoint, gasAdjustment: gasAdjustment, encCfg: encCfg, + logger: logger, } c.keyringKeyring, err = keyring.New(keyringAppName, keyring.BackendTest, chainDataDir, nil, encCfg.Codec) @@ -120,10 +125,15 @@ func (c *Client) initTxFactory() { c.txFactory = &f } -func (c *Client) BroadcastTx(msgs ...sdk.Msg) (*sdk.TxResponse, error) { - c.ClientContext.From = c.keyringRecord[0].Name - c.ClientContext.FromName = c.keyringRecord[0].Name - c.ClientContext.FromAddress, _ = c.keyringRecord[0].GetAddress() +func (c *Client) BroadcastTx(idx int, msgs ...sdk.Msg) (*sdk.TxResponse, error) { + var err error + r := c.keyringRecord[idx] + c.ClientContext.From = r.Name + c.ClientContext.FromName = r.Name + c.ClientContext.FromAddress, err = r.GetAddress() + if err != nil { + c.logger.Fatalln("can't get keyring record, idx=", idx, err) + } return BroadcastTx(*c.ClientContext, *c.txFactory, msgs...) } diff --git a/sdkclient/tx/gov.go b/sdkclient/tx/gov.go index fbdd5f2e7e..890e831982 100644 --- a/sdkclient/tx/gov.go +++ b/sdkclient/tx/gov.go @@ -21,10 +21,10 @@ func (c *Client) GovParamChange(title, description string, changes []proposal.Pa return nil, err } - return c.BroadcastTx(msg) + return c.BroadcastTx(0, msg) } -func (c *Client) GovSubmitProposal(changes []proposal.ParamChange, deposit sdk.Coins) (*sdk.TxResponse, error) { +func (c *Client) GovSubmitParamProposal(changes []proposal.ParamChange, deposit sdk.Coins) (*sdk.TxResponse, error) { content := proposal.NewParameterChangeProposal( "update historic stamp period", "auto grpc proposal", @@ -40,10 +40,10 @@ func (c *Client) GovSubmitProposal(changes []proposal.ParamChange, deposit sdk.C return nil, err } - return c.BroadcastTx(msg) + return c.BroadcastTx(0, msg) } -func (c *Client) TxSubmitProposalWithMsg(msgs []sdk.Msg) (*sdk.TxResponse, error) { +func (c *Client) GovSubmitProposal(msgs []sdk.Msg) (*sdk.TxResponse, error) { deposit, err := sdk.ParseCoinsNormalized("1000uumee") if err != nil { return nil, err @@ -59,11 +59,11 @@ func (c *Client) TxSubmitProposalWithMsg(msgs []sdk.Msg) (*sdk.TxResponse, error return nil, err } - return c.BroadcastTx(submitProposal) + return c.BroadcastTx(0, submitProposal) } -// TxGovVoteYesAll creates transactions (one for each registered account) to approve a given proposal. -func (c *Client) TxGovVoteYesAll(proposalID uint64) error { +// GovVoteAllYes creates transactions (one for each account in the keyring) to approve a given proposal. +func (c *Client) GovVoteAllYes(proposalID uint64) error { for index := range c.keyringRecord { voter, err := c.keyringRecord[index].GetAddress() if err != nil { @@ -80,16 +80,12 @@ func (c *Client) TxGovVoteYesAll(proposalID uint64) error { proposalID, voteType, ) - - c.ClientContext.From = c.keyringRecord[index].Name - c.ClientContext.FromName = c.keyringRecord[index].Name - c.ClientContext.FromAddress, _ = c.keyringRecord[index].GetAddress() - - for retry := 0; retry < 5; retry++ { + for retry := 0; retry < 3; retry++ { // retry if txs fails, because sometimes account sequence mismatch occurs due to txs pending - if _, err = BroadcastTx(*c.ClientContext, *c.txFactory, []sdk.Msg{msg}...); err == nil { + if _, err = c.BroadcastTx(index, msg); err == nil { break } + c.logger.Println("Tx broadcast failed. RETRYING. Err: ", err) time.Sleep(time.Millisecond * 300) } diff --git a/sdkclient/tx/key.go b/sdkclient/tx/key.go index aea24dd4c3..c9facaa102 100644 --- a/sdkclient/tx/key.go +++ b/sdkclient/tx/key.go @@ -25,3 +25,12 @@ func CreateAccountFromMnemonic(kb keyring.Keyring, name, mnemonic string) (*keyr return account, nil } + +// Returns account address stored at give index +func (c *Client) KeyringAddress(idx int) sdk.AccAddress { + addr, err := c.keyringRecord[idx].GetAddress() + if err != nil { + c.logger.Fatalln("can't get keyring record, idx=", idx, err) + } + return addr +} diff --git a/sdkclient/tx/sign.go b/sdkclient/tx/sign.go index 343f17be09..3292dec6ca 100644 --- a/sdkclient/tx/sign.go +++ b/sdkclient/tx/sign.go @@ -52,7 +52,6 @@ func BroadcastTx(clientCtx client.Context, txf tx.Factory, msgs ...sdk.Msg) (*sd // the updated fields will be returned. func prepareFactory(clientCtx client.Context, txf tx.Factory) (tx.Factory, error) { from := clientCtx.GetFromAddress() - if err := txf.AccountRetriever().EnsureExists(clientCtx, from); err != nil { return txf, err } diff --git a/sdkclient/tx/wasm.go b/sdkclient/tx/wasm.go index 40e417517e..a85b00c8db 100644 --- a/sdkclient/tx/wasm.go +++ b/sdkclient/tx/wasm.go @@ -12,28 +12,21 @@ import ( "github.com/umee-network/umee/v6/util/coin" ) -func (c *Client) TxSubmitWasmContract(contractPath string) (*sdk.TxResponse, error) { - fromAddr, err := c.keyringRecord[0].GetAddress() +func (c *Client) WasmDeployContract(contractPath string) (*sdk.TxResponse, error) { + fromIdx := 0 + msg, err := readWasmCode(contractPath, c.KeyringAddress(fromIdx)) if err != nil { return nil, err } - msg, err := readWasmCode(contractPath, fromAddr) - if err != nil { - return nil, err - } - - return c.BroadcastTx(&msg) + return c.BroadcastTx(fromIdx, &msg) } -func (c *Client) TxWasmInstantiateContract(storeCode uint64, initMsg []byte) (*sdk.TxResponse, error) { - fromAddr, err := c.keyringRecord[0].GetAddress() - if err != nil { - return nil, err - } +func (c *Client) WasmInitContract(storeCode uint64, initMsg []byte) (*sdk.TxResponse, error) { + fromIdx := 0 amount := sdk.NewCoins(sdk.NewCoin(appparams.BondDenom, sdk.NewInt(1))) msg := types.MsgInstantiateContract{ - Sender: fromAddr.String(), + Sender: c.KeyringAddress(fromIdx).String(), CodeID: storeCode, Label: "label", Funds: amount, @@ -41,31 +34,27 @@ func (c *Client) TxWasmInstantiateContract(storeCode uint64, initMsg []byte) (*s Admin: "", } - return c.BroadcastTx(&msg) + return c.BroadcastTx(fromIdx, &msg) } -func (c *Client) TxWasmExecuteContractByAccSeq(contractAddr string, execMsg []byte, - accSeq uint64, +func (c *Client) WasmExecContractWithAccSeq(contractAddr string, execMsg []byte, accSeq uint64, ) (*sdk.TxResponse, error) { - fromAddr, err := c.keyringRecord[0].GetAddress() - if err != nil { - return nil, err - } + fromIdx := 0 amount := sdk.NewCoins(coin.Umee1) msg := types.MsgExecuteContract{ - Sender: fromAddr.String(), + Sender: c.KeyringAddress(fromIdx).String(), Contract: contractAddr, Funds: amount, Msg: execMsg, } if accSeq != 0 { - return c.WithAccSeq(accSeq).WithAsyncBlock().BroadcastTx(&msg) + return c.WithAccSeq(accSeq).WithAsyncBlock().BroadcastTx(fromIdx, &msg) } - return c.WithAsyncBlock().BroadcastTx(&msg) + return c.WithAsyncBlock().BroadcastTx(fromIdx, &msg) } -func (c *Client) TxWasmExecuteContract(contractAddr string, execMsg []byte) (*sdk.TxResponse, error) { - return c.TxWasmExecuteContractByAccSeq(contractAddr, execMsg, 0) +func (c *Client) WasmExecuteContract(contractAddr string, execMsg []byte) (*sdk.TxResponse, error) { + return c.WasmExecContractWithAccSeq(contractAddr, execMsg, 0) } // Prepares MsgStoreCode object from flags with gzipped wasm byte code field @@ -75,21 +64,19 @@ func readWasmCode(file string, sender sdk.AccAddress) (types.MsgStoreCode, error return types.MsgStoreCode{}, err } - // gzip the wasm file if ioutils.IsWasm(wasm) { wasm, err = ioutils.GzipIt(wasm) - if err != nil { return types.MsgStoreCode{}, err } } else if !ioutils.IsGzip(wasm) { - return types.MsgStoreCode{}, fmt.Errorf("invalid input file. Use wasm binary or gzip") + return types.MsgStoreCode{}, + fmt.Errorf("invalid input file. Wasm file must be a binary or gzip of a binary") } - msg := types.MsgStoreCode{ + return types.MsgStoreCode{ Sender: sender.String(), WASMByteCode: wasm, InstantiatePermission: &types.AllowEverybody, - } - return msg, nil + }, nil } diff --git a/tests/e2e/e2e_metoken_test.go b/tests/e2e/e2e_metoken_test.go index 69b8b44e0c..6a10c5fafa 100644 --- a/tests/e2e/e2e_metoken_test.go +++ b/tests/e2e/e2e_metoken_test.go @@ -124,7 +124,7 @@ func (s *E2ETest) TestMetokenSwapAndRedeem() { func (s *E2ETest) checkMetokenBalance(valAddr, denom string) { s.Require().Eventually( func() bool { - resp, err := s.QueryMetokenBalances(denom) + resp, err := s.Umee.QueryMetokenIndexBalances(denom) if err != nil { return false } @@ -175,7 +175,7 @@ func (s *E2ETest) getPrices(denom string) []metoken.IndexPrices { var prices []metoken.IndexPrices s.Require().Eventually( func() bool { - resp, err := s.QueryMetokenPrices(denom) + resp, err := s.Umee.QueryMetokenIndexPrices(denom) if err != nil { return false } @@ -193,7 +193,7 @@ func (s *E2ETest) getMetokenIndex(denom string) metoken.Index { index := metoken.Index{} s.Require().Eventually( func() bool { - resp, err := s.QueryMetokenIndexes(denom) + resp, err := s.Umee.QueryMetokenIndexes(denom) if err != nil { return false } @@ -220,12 +220,7 @@ func (s *E2ETest) getMetokenIndex(denom string) metoken.Index { func (s *E2ETest) executeSwap(umeeAddr string, asset sdk.Coin, meTokenDenom string) { s.Require().Eventually( func() bool { - err := s.TxMetokenSwap(umeeAddr, asset, meTokenDenom) - if err != nil { - return false - } - - return true + return s.TxMetokenSwap(umeeAddr, asset, meTokenDenom) == nil }, 30*time.Second, 500*time.Millisecond, @@ -235,12 +230,7 @@ func (s *E2ETest) executeSwap(umeeAddr string, asset sdk.Coin, meTokenDenom stri func (s *E2ETest) executeRedeemSuccess(umeeAddr string, meToken sdk.Coin, assetDenom string) { s.Require().Eventually( func() bool { - err := s.TxMetokenRedeem(umeeAddr, meToken, assetDenom) - if err != nil { - return false - } - - return true + return s.TxMetokenRedeem(umeeAddr, meToken, assetDenom) == nil }, 30*time.Second, 500*time.Millisecond, diff --git a/tests/e2e/setup/metoken.go b/tests/e2e/setup/metoken.go index 4ab5564819..c7cfe11a55 100644 --- a/tests/e2e/setup/metoken.go +++ b/tests/e2e/setup/metoken.go @@ -1,34 +1,11 @@ package setup import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/umee-network/umee/v6/x/metoken" ) -func (s *E2ETestSuite) QueryMetokenBalances(denom string) (metoken.QueryIndexBalancesResponse, error) { - endpoint := fmt.Sprintf("%s/umee/metoken/v1/index_balances?metoken_denom=%s", s.UmeeREST(), denom) - var resp metoken.QueryIndexBalancesResponse - - return resp, s.QueryREST(endpoint, &resp) -} - -func (s *E2ETestSuite) QueryMetokenIndexes(denom string) (metoken.QueryIndexesResponse, error) { - endpoint := fmt.Sprintf("%s/umee/metoken/v1/indexes?metoken_denom=%s", s.UmeeREST(), denom) - var resp metoken.QueryIndexesResponse - - return resp, s.QueryREST(endpoint, &resp) -} - -func (s *E2ETestSuite) QueryMetokenPrices(denom string) (metoken.QueryIndexPricesResponse, error) { - endpoint := fmt.Sprintf("%s/umee/metoken/v1/index_prices?metoken_denom=%s", s.UmeeREST(), denom) - var resp metoken.QueryIndexPricesResponse - - return resp, s.QueryREST(endpoint, &resp) -} - func (s *E2ETestSuite) TxMetokenSwap(umeeAddr string, asset sdk.Coin, meTokenDenom string) error { req := &metoken.MsgSwap{ User: umeeAddr, diff --git a/tests/e2e/setup/utils.go b/tests/e2e/setup/utils.go index e643ebf65e..ec371259e0 100644 --- a/tests/e2e/setup/utils.go +++ b/tests/e2e/setup/utils.go @@ -235,7 +235,7 @@ func (s *E2ETestSuite) BroadcastTxWithRetry(msg sdk.Msg) error { var err error for retry := 0; retry < 3; retry++ { // retry if txs fails, because sometimes account sequence mismatch occurs due to txs pending - _, err = s.Umee.Client.Tx.BroadcastTx(msg) + _, err = s.Umee.Tx.BroadcastTx(0, msg) if err == nil { return nil } diff --git a/tests/grpc/gov.go b/tests/grpc/gov.go index 9fb353ba7b..45796175bc 100644 --- a/tests/grpc/gov.go +++ b/tests/grpc/gov.go @@ -26,7 +26,7 @@ func init() { } func SubmitAndPassProposal(umee client.Client, changes []proposal.ParamChange) error { - resp, err := umee.Tx.GovSubmitProposal(changes, govDeposit) + resp, err := umee.Tx.GovSubmitParamProposal(changes, govDeposit) if err != nil { return err } @@ -65,7 +65,7 @@ func UIBCIBCTransferSatusUpdate(umeeClient client.Client, status uibc.IBCTransfe IbcStatus: status, } - resp, err := umeeClient.Tx.TxSubmitProposalWithMsg([]sdk.Msg{&msg}) + resp, err := umeeClient.Tx.GovSubmitProposal([]sdk.Msg{&msg}) if err != nil { return err } @@ -86,7 +86,7 @@ func LeverageRegistryUpdate(umeeClient client.Client, addTokens, updateTokens [] UpdateTokens: updateTokens, } - resp, err := umeeClient.Tx.TxSubmitProposalWithMsg([]sdk.Msg{&msg}) + resp, err := umeeClient.Tx.GovSubmitProposal([]sdk.Msg{&msg}) if err != nil { return err } @@ -112,7 +112,7 @@ func LeverageSpecialPairsUpdate( Pairs: pairs, } - resp, err := umeeClient.Tx.TxSubmitProposalWithMsg([]sdk.Msg{&msg}) + resp, err := umeeClient.Tx.GovSubmitProposal([]sdk.Msg{&msg}) if err != nil { return err } @@ -132,7 +132,7 @@ func MetokenRegistryUpdate(umeeClient client.Client, addIndexes, updateIndexes [ UpdateIndex: updateIndexes, } - resp, err := umeeClient.Tx.TxSubmitProposalWithMsg([]sdk.Msg{&msg}) + resp, err := umeeClient.Tx.GovSubmitProposal([]sdk.Msg{&msg}) if err != nil { return err } @@ -165,7 +165,7 @@ func MakeVoteAndCheckProposal(umeeClient client.Client, resp sdk.TxResponse) err return err } - err = umeeClient.Tx.TxGovVoteYesAll(proposalIDInt) + err = umeeClient.Tx.GovVoteAllYes(proposalIDInt) if err != nil { return err } diff --git a/tests/util/cw_util.go b/tests/util/cw_util.go index 62c6825c18..0818ea4a9b 100644 --- a/tests/util/cw_util.go +++ b/tests/util/cw_util.go @@ -33,7 +33,7 @@ func NewCosmwasmTestSuite(t *testing.T, umee client.Client) *Cosmwasm { func (cw *Cosmwasm) DeployWasmContract(path string) { cw.T.Logf("ℹ️ deploying smart contract %s", path) - resp, err := cw.umee.Tx.TxSubmitWasmContract(path) + resp, err := cw.umee.Tx.WasmDeployContract(path) assert.NilError(cw.T, err) storeCode := cw.GetAttributeValue(*resp, "store_code", "code_id") cw.StoreCode, err = strconv.ParseUint(storeCode, 10, 64) @@ -49,7 +49,7 @@ func (cw *Cosmwasm) MarshalAny(any interface{}) []byte { func (cw *Cosmwasm) InstantiateContract(initMsg []byte) { cw.T.Log("ℹ️ smart contract is instantiating...") - resp, err := cw.umee.Tx.TxWasmInstantiateContract(cw.StoreCode, initMsg) + resp, err := cw.umee.Tx.WasmInitContract(cw.StoreCode, initMsg) assert.NilError(cw.T, err) cw.ContractAddr = cw.GetAttributeValue(*resp, "instantiate", "_contract_address") assert.Equal(cw.T, SucceessRespCode, resp.Code) @@ -64,19 +64,19 @@ func (cw *Cosmwasm) CWQuery(query []byte) wasmtypes.QuerySmartContractStateRespo } func (cw *Cosmwasm) CWExecute(execMsg []byte) { - resp, err := cw.umee.Tx.TxWasmExecuteContract(cw.ContractAddr, execMsg) + resp, err := cw.umee.Tx.WasmExecuteContract(cw.ContractAddr, execMsg) assert.NilError(cw.T, err) assert.Equal(cw.T, SucceessRespCode, resp.Code) } func (cw *Cosmwasm) CWExecuteWithSeqAndAsync(execMsg []byte, accSeq uint64) { - resp, err := cw.umee.Tx.TxWasmExecuteContractByAccSeq(cw.ContractAddr, execMsg, accSeq) + resp, err := cw.umee.Tx.WasmExecContractWithAccSeq(cw.ContractAddr, execMsg, accSeq) assert.NilError(cw.T, err) assert.Equal(cw.T, SucceessRespCode, resp.Code) } func (cw *Cosmwasm) CWExecuteWithSeqAndAsyncResp(execMsg []byte, accSeq uint64) (*sdk.TxResponse, error) { - return cw.umee.Tx.TxWasmExecuteContractByAccSeq(cw.ContractAddr, execMsg, accSeq) + return cw.umee.Tx.WasmExecContractWithAccSeq(cw.ContractAddr, execMsg, accSeq) } func (cw *Cosmwasm) GetAttributeValue(resp sdk.TxResponse, eventName, attrKey string) string { diff --git a/util/sdkutil/msg.go b/util/sdkutil/msg.go index 7400c4e510..e08b95f11d 100644 --- a/util/sdkutil/msg.go +++ b/util/sdkutil/msg.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/gogo/protobuf/proto" ) // StartMsg unpacks sdk.Context and validates msg. @@ -22,3 +23,17 @@ func StartMsg(ctx context.Context, msg sdk.Msg) (sdk.Context, error) { type fullValidate interface { Validate(*sdk.Context) error } + +type validateBasic interface { + ValidateBasic() error +} + +// ValidateProtoMsg tries to run msg.ValidateBasic +func ValidateProtoMsg(msg proto.Message) error { + if vm, ok := msg.(validateBasic); ok { + if err := vm.ValidateBasic(); err != nil { + return err + } + } + return nil +} diff --git a/x/oracle/keeper/historic_avg.go b/x/oracle/keeper/historic_avg.go index 8e354e0b4a..820da66ee5 100644 --- a/x/oracle/keeper/historic_avg.go +++ b/x/oracle/keeper/historic_avg.go @@ -153,7 +153,7 @@ func (k Keeper) SetHistoricAvgCounterParams(ctx sdk.Context, acp types.AvgCounte } // GetHistoricAvgCounterParams gets the avg period and avg shift time duration from store -func (k Keeper) GetHistoricAvgCounterParams(ctx sdk.Context) types.AvgCounterParams { +func (k Keeper) GetHistoricAvgCounterParams(_ sdk.Context) types.AvgCounterParams { return types.DefaultAvgCounterParams() // TODO: investigate why we don't have record! // kvs := ctx.KVStore(k.storeKey) From e1cb4521d2ae9a62f3735a573cce95cc6ebfb2a2 Mon Sep 17 00:00:00 2001 From: Robert Zaremba Date: Fri, 22 Sep 2023 03:22:23 +0200 Subject: [PATCH 2/2] fix(oracle): avg params storage. (#2260) * fix(oracle): v6.1 upgrade with setting missing oracle avg price params * oracle: use avg params from the store * set correct AvgParams prefix key * fix * review * changelog --- CHANGELOG.md | 4 ++++ app/upgrades.go | 15 +++++++++++++++ x/oracle/keeper/historic_avg.go | 13 +++++-------- x/oracle/keeper/migrations.go | 6 ------ x/oracle/types/keys.go | 22 ++++++++++++---------- x/oracle/types/params.go | 1 - 6 files changed, 36 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2eb0c40fe..5183aabada 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [Unreleased] +### Bug Fixes + +- [2260](https://github.com/umee-network/umee/pull/2260) fix(oracle): avg params storage. + ## [v6.0.2](https://github.com/umee-network/umee/releases/tag/v6.0.2) - 2023-09-20 ### BugFix diff --git a/app/upgrades.go b/app/upgrades.go index 46e7dd8d45..a51a37de18 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -57,6 +57,21 @@ func (app UmeeApp) RegisterUpgradeHandlers() { app.registerUpgrade5_1(upgradeInfo) app.registerUpgrade("v5.2", upgradeInfo) // v5.2 migration is not compatible with v6, so leaving default here. app.registerUpgrade6(upgradeInfo) + app.registerUpgrade6_1("v6.1", upgradeInfo) +} + +func (app *UmeeApp) registerUpgrade6_1(planName string, _ upgradetypes.Plan) { + app.UpgradeKeeper.SetUpgradeHandler(planName, + func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + ctx.Logger().Info("-----------------------------\n-----------------------------") + err := app.OracleKeeper.SetHistoricAvgCounterParams(ctx, oracletypes.DefaultAvgCounterParams()) + if err != nil { + return fromVM, err + } + + return app.mm.RunMigrations(ctx, app.configurator, fromVM) + }, + ) } func (app *UmeeApp) registerUpgrade6(upgradeInfo upgradetypes.Plan) { diff --git a/x/oracle/keeper/historic_avg.go b/x/oracle/keeper/historic_avg.go index 820da66ee5..2fd0069bfb 100644 --- a/x/oracle/keeper/historic_avg.go +++ b/x/oracle/keeper/historic_avg.go @@ -149,14 +149,11 @@ func (k AvgKeeper) getCounter(denom string, idx byte) (types.AvgCounter, error) // SetHistoricAvgCounterParams sets avg period and avg shift time duration func (k Keeper) SetHistoricAvgCounterParams(ctx sdk.Context, acp types.AvgCounterParams) error { kvs := ctx.KVStore(k.storeKey) - return store.SetValue(kvs, types.KeyHistoricAvgCounterParams, &acp, "historic avg counter params") + return store.SetValue(kvs, types.KeyAvgCounterParams, &acp, "historic avg counter params") } -// GetHistoricAvgCounterParams gets the avg period and avg shift time duration from store -func (k Keeper) GetHistoricAvgCounterParams(_ sdk.Context) types.AvgCounterParams { - return types.DefaultAvgCounterParams() - // TODO: investigate why we don't have record! - // kvs := ctx.KVStore(k.storeKey) - // return *store.GetValue[*types.AvgCounterParams](kvs, types.KeyHistoricAvgCounterParams, - // "historic avg counter params") +func (k Keeper) GetHistoricAvgCounterParams(ctx sdk.Context) types.AvgCounterParams { + kvs := ctx.KVStore(k.storeKey) + return *store.GetValue[*types.AvgCounterParams](kvs, types.KeyAvgCounterParams, + "historic avg counter params") } diff --git a/x/oracle/keeper/migrations.go b/x/oracle/keeper/migrations.go index 53774de819..c26c90b9b0 100644 --- a/x/oracle/keeper/migrations.go +++ b/x/oracle/keeper/migrations.go @@ -35,12 +35,6 @@ func (m Migrator) HistoracleParams3x4(ctx sdk.Context) error { return nil } -// SetAvgPeriodAndShift updates the avg shift and period params -func (m Migrator) SetAvgPeriodAndShift(ctx sdk.Context) error { - p := types.DefaultAvgCounterParams() - return m.keeper.SetHistoricAvgCounterParams(ctx, p) -} - // MigrateBNB fixes the BNB base denom for the 4.1 upgrade without using leverage hooks func (m Migrator) MigrateBNB(ctx sdk.Context) { badDenom := "ibc/77BCD42E49E5B7E0FC6B269FEBF0185B15044F13F6F38CA285DF0AF883459F40" diff --git a/x/oracle/types/keys.go b/x/oracle/types/keys.go index 53359f0f36..3ef456f483 100644 --- a/x/oracle/types/keys.go +++ b/x/oracle/types/keys.go @@ -19,16 +19,18 @@ const ( // KVStore key prefixes var ( - KeyPrefixExchangeRate = []byte{0x01} // prefix for each key to a rate - KeyPrefixFeederDelegation = []byte{0x02} // prefix for each key to a feeder delegation - KeyPrefixMissCounter = []byte{0x03} // prefix for each key to a miss counter - KeyPrefixAggregateExchangeRatePrevote = []byte{0x04} // prefix for each key to a aggregate prevote - KeyPrefixAggregateExchangeRateVote = []byte{0x05} // prefix for each key to a aggregate vote - KeyPrefixMedian = []byte{0x06} // prefix for each key to a price median - KeyPrefixMedianDeviation = []byte{0x07} // prefix for each key to a price median standard deviation - KeyPrefixHistoricPrice = []byte{0x08} // prefix for each key to a historic price - KeyPrefixAvgCounter = []byte{0x09} // prefix for each key to a historic avg price counter - KeyLatestAvgCounter = []byte{0x10} // key where we store the latest avg price counter + KeyPrefixExchangeRate = []byte{1} // prefix for each key to a rate + KeyPrefixFeederDelegation = []byte{2} // prefix for each key to a feeder delegation + KeyPrefixMissCounter = []byte{3} // prefix for each key to a miss counter + KeyPrefixAggregateExchangeRatePrevote = []byte{4} // prefix for each key to a aggregate prevote + KeyPrefixAggregateExchangeRateVote = []byte{5} // prefix for each key to a aggregate vote + KeyPrefixMedian = []byte{6} // prefix for each key to a price median + KeyPrefixMedianDeviation = []byte{7} // prefix for each key to a price median standard deviation + KeyPrefixHistoricPrice = []byte{8} // prefix for each key to a historic price + KeyPrefixAvgCounter = []byte{9} // prefix for each key to a historic avg price counter + KeyAvgCounterParams = []byte{10} + + KeyLatestAvgCounter = []byte{16} // it was set as 0x10 and breaking the order ) // KeyExchangeRate - stored by *denom* diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 69fad2c690..50ad4a49e1 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -37,7 +37,6 @@ var ( KeyMedianStampPeriod = []byte("MedianStampPeriod") KeyMaximumPriceStamps = []byte("MaximumPriceStamps") KeyMaximumMedianStamps = []byte("MedianStampAmount") - KeyHistoricAvgCounterParams = []byte("HistoricAvgCounterParams") ) var _ paramstypes.ParamSet = &Params{}