From 747fdfc12629b00cd434f0c0691f1901c1763ffc Mon Sep 17 00:00:00 2001 From: lumtis Date: Sun, 19 May 2024 18:30:22 +0200 Subject: [PATCH] run new line tool --- app/ante/authz.go | 7 +- app/ante/fees.go | 31 +- app/ante/handler_options.go | 45 ++- app/app.go | 50 ++- app/config.go | 56 ++- app/export.go | 6 +- app/mempool/priority_nonce_mempool.go | 7 +- app/setup_handlers.go | 23 +- cmd/zetaclientd-supervisor/lib.go | 16 +- cmd/zetaclientd/debug.go | 3 +- cmd/zetaclientd/hsm.go | 3 +- cmd/zetaclientd/init.go | 27 +- cmd/zetaclientd/keygen_tss.go | 12 +- cmd/zetaclientd/main.go | 6 +- cmd/zetaclientd/p2p_diagnostics.go | 20 +- cmd/zetaclientd/start.go | 21 +- cmd/zetaclientd/utils.go | 6 +- cmd/zetacore_utils/main.go | 47 ++- cmd/zetacored/genaccounts.go | 3 +- cmd/zetacored/observer_accounts.go | 12 +- cmd/zetacored/parse_genesis.go | 12 +- cmd/zetacored/parsers_test.go | 6 +- cmd/zetacored/root.go | 20 +- cmd/zetae2e/config/clients.go | 4 +- cmd/zetae2e/init.go | 6 +- cmd/zetae2e/stress.go | 47 ++- cmd/zetatool/filterdeposit/filterdeposit.go | 3 +- contrib/rpctest/main.go | 14 +- e2e/e2etests/helper_bitcoin.go | 6 +- ...est_bitcoin_withdraw_restricted_address.go | 5 +- e2e/e2etests/test_crosschain_swap.go | 14 +- e2e/e2etests/test_erc20_deposit_refund.go | 8 +- e2e/e2etests/test_erc20_multiple_deposits.go | 9 +- e2e/e2etests/test_erc20_multiple_withdraws.go | 13 +- e2e/e2etests/test_eth_deposit_call.go | 12 +- e2e/e2etests/test_eth_deposit_refund.go | 8 +- .../test_message_passing_evm_to_zevm.go | 5 +- ...test_message_passing_evm_to_zevm_revert.go | 9 +- .../test_message_passing_external_chains.go | 5 +- ...age_passing_external_chains_revert_fail.go | 13 +- .../test_message_passing_zevm_to_evm.go | 5 +- ...test_message_passing_zevm_to_evm_revert.go | 5 +- ...message_passing_zevm_to_evm_revert_fail.go | 4 +- e2e/e2etests/test_migrate_chain_support.go | 5 +- e2e/e2etests/test_rate_limiter.go | 8 +- e2e/e2etests/test_stress_btc_withdraw.go | 4 +- e2e/e2etests/test_stress_eth_withdraw.go | 4 +- e2e/runner/accounting.go | 6 +- e2e/runner/bitcoin.go | 53 ++- e2e/runner/e2etest.go | 5 +- e2e/runner/evm.go | 6 +- e2e/runner/setup_evm.go | 19 +- e2e/runner/setup_zeta.go | 33 +- e2e/runner/zeta.go | 8 +- e2e/txserver/zeta_tx_server.go | 22 +- pkg/chains/address_taproot_test.go | 6 +- pkg/chains/address_test.go | 24 +- pkg/chains/chains_test.go | 62 +++- pkg/chains/utils_test.go | 16 +- pkg/crypto/tss.go | 5 +- pkg/proofs/proof_test.go | 19 +- rpc/backend/account_info.go | 18 +- rpc/backend/backend.go | 46 ++- rpc/backend/blocks.go | 47 ++- rpc/backend/call_tx.go | 21 +- rpc/backend/chain_info.go | 4 +- rpc/backend/sign_tx.go | 12 +- rpc/backend/tracing.go | 10 +- rpc/backend/tx_info.go | 41 ++- rpc/backend/utils.go | 13 +- rpc/namespaces/ethereum/debug/api.go | 5 +- rpc/namespaces/ethereum/eth/api.go | 56 ++- rpc/namespaces/ethereum/eth/filters/api.go | 30 +- .../ethereum/eth/filters/filters.go | 16 +- rpc/namespaces/ethereum/eth/filters/utils.go | 7 +- rpc/namespaces/ethereum/personal/api.go | 19 +- rpc/namespaces/ethereum/web3/api.go | 8 +- rpc/types/block.go | 6 +- rpc/types/block_test.go | 16 +- rpc/types/events.go | 29 +- rpc/websockets.go | 23 +- server/flags/flags.go | 15 +- server/start.go | 97 +++-- testutil/keeper/crosschain.go | 73 +++- testutil/keeper/fungible.go | 5 +- testutil/keeper/keeper.go | 39 +- testutil/keeper/lightclient.go | 5 +- testutil/keeper/observer.go | 5 +- testutil/network/genesis_state.go | 51 ++- testutil/network/network_setup.go | 8 +- testutil/network/util.go | 7 +- testutil/sample/crosschain.go | 15 +- testutil/sample/sample.go | 4 +- testutil/simapp/simapp.go | 43 ++- x/authority/keeper/grpc_query_policies.go | 5 +- .../keeper/msg_server_update_policies.go | 5 +- x/authority/types/policies.go | 3 +- x/crosschain/client/cli/cli_gas_price.go | 8 +- x/crosschain/keeper/abci_test.go | 29 +- x/crosschain/keeper/cctx.go | 3 +- x/crosschain/keeper/cctx_test.go | 28 +- x/crosschain/keeper/cctx_utils.go | 23 +- x/crosschain/keeper/cctx_utils_test.go | 23 +- x/crosschain/keeper/evm_deposit.go | 10 +- x/crosschain/keeper/evm_deposit_test.go | 332 +++++++++--------- x/crosschain/keeper/evm_hooks.go | 46 ++- x/crosschain/keeper/evm_hooks_test.go | 155 ++++++-- .../keeper/finalized_inbounds_test.go | 6 +- x/crosschain/keeper/gas_payment.go | 85 +++-- x/crosschain/keeper/gas_payment_test.go | 42 ++- x/crosschain/keeper/grpc_query_cctx.go | 28 +- .../keeper/grpc_query_cctx_rate_limit.go | 38 +- .../keeper/grpc_query_cctx_rate_limit_test.go | 292 ++++++++++++--- x/crosschain/keeper/grpc_query_gas_price.go | 10 +- .../keeper/grpc_query_in_tx_hash_to_cctx.go | 10 +- .../grpc_query_in_tx_hash_to_cctx_test.go | 5 +- .../keeper/grpc_query_in_tx_tracker.go | 10 +- .../keeper/grpc_query_last_block_height.go | 10 +- .../keeper/grpc_query_last_zeta_height.go | 5 +- .../keeper/grpc_query_out_tx_tracker.go | 15 +- .../keeper/grpc_query_rate_limiter_flags.go | 5 +- .../keeper/grpc_query_zeta_conversion_rate.go | 10 +- x/crosschain/keeper/in_tx_tracker.go | 12 +- x/crosschain/keeper/in_tx_tracker_test.go | 12 +- x/crosschain/keeper/migrator.go | 7 +- .../keeper/msg_server_add_to_intx_tracker.go | 5 +- .../msg_server_add_to_intx_tracker_test.go | 24 +- .../keeper/msg_server_add_to_outtx_tracker.go | 12 +- .../msg_server_add_to_outtx_tracker_test.go | 15 +- .../keeper/msg_server_migrate_tss_funds.go | 56 ++- .../msg_server_migrate_tss_funds_test.go | 76 ++-- .../keeper/msg_server_refund_aborted_tx.go | 5 +- .../msg_server_refund_aborted_tx_test.go | 40 ++- .../msg_server_remove_out_tx_tracker.go | 5 +- .../msg_server_update_rate_limiter_flags.go | 5 +- x/crosschain/keeper/msg_server_update_tss.go | 22 +- .../keeper/msg_server_update_tss_test.go | 42 ++- .../keeper/msg_server_vote_gas_price.go | 5 +- .../keeper/msg_server_vote_inbound_tx.go | 12 +- .../keeper/msg_server_vote_inbound_tx_test.go | 28 +- .../keeper/msg_server_vote_outbound_tx.go | 45 ++- .../msg_server_vote_outbound_tx_test.go | 77 +++- .../keeper/msg_server_whitelist_erc20.go | 22 +- x/crosschain/keeper/process_inbound.go | 7 + x/crosschain/keeper/process_inbound_test.go | 307 ++++++++-------- x/crosschain/keeper/process_outbound.go | 13 +- x/crosschain/keeper/process_outbound_test.go | 73 +++- x/crosschain/keeper/rate_limiter_flags.go | 4 +- .../keeper/rate_limiter_flags_test.go | 30 +- x/crosschain/keeper/refund.go | 30 +- x/crosschain/keeper/refund_test.go | 20 +- x/crosschain/migrations/v4/migrate_test.go | 5 +- x/crosschain/migrations/v5/migrate.go | 8 +- x/crosschain/migrations/v5/migrate_test.go | 15 +- x/crosschain/types/cctx.go | 22 +- x/crosschain/types/errors.go | 30 +- x/crosschain/types/expected_keepers.go | 39 +- x/crosschain/types/keys.go | 8 +- .../types/message_add_to_in_tx_tracker.go | 6 +- .../message_add_to_in_tx_tracker_test.go | 6 +- .../types/message_refund_aborted_test.go | 6 +- x/crosschain/types/status.go | 7 +- x/crosschain/types/status_test.go | 106 +++++- x/crosschain/types/validate_test.go | 88 ++++- x/emissions/abci.go | 19 +- x/emissions/abci_test.go | 129 +++++-- .../keeper/grpc_query_get_emmisons_factors.go | 5 +- .../grpc_query_get_emmisons_factors_test.go | 5 +- .../keeper/grpc_query_list_balances.go | 13 +- .../grpc_query_show_available_emissions.go | 5 +- .../keeper/msg_server_update_params.go | 12 +- .../keeper/msg_server_withdraw_emissions.go | 24 +- .../msg_server_withdraw_emissions_test.go | 100 ++++-- x/emissions/types/errors.go | 10 +- x/emissions/types/events.go | 5 +- x/emissions/types/expected_keepers.go | 7 +- x/emissions/types/params_legacy.go | 27 +- x/emissions/types/params_test.go | 16 +- .../client/cli/query_gas_stability_pool.go | 10 +- x/fungible/keeper/evm.go | 46 ++- x/fungible/keeper/evm_test.go | 34 +- x/fungible/keeper/gas_coin_and_pool.go | 91 ++++- x/fungible/keeper/gas_price.go | 42 ++- x/fungible/keeper/gas_price_test.go | 26 +- x/fungible/keeper/grpc_query_foreign_coins.go | 10 +- .../keeper/grpc_query_system_contract.go | 5 +- .../msg_server_deploy_fungible_coin_zrc20.go | 19 +- .../msg_server_deploy_system_contract.go | 10 +- .../keeper/msg_server_remove_foreign_coin.go | 10 +- .../msg_server_udpate_zrc20_liquidity_cap.go | 10 +- ..._server_udpate_zrc20_liquidity_cap_test.go | 7 +- .../msg_server_update_contract_bytecode.go | 16 +- .../msg_server_update_system_contract.go | 75 +++- .../msg_server_update_system_contract_test.go | 12 +- .../msg_server_update_zrc20_paused_status.go | 5 +- ..._server_update_zrc20_paused_status_test.go | 7 +- .../msg_server_update_zrc20_withdraw_fee.go | 34 +- x/fungible/keeper/system_contract.go | 130 +++++-- x/fungible/keeper/system_contract_test.go | 87 ++++- .../keeper/zevm_message_passing_test.go | 95 ++++- x/fungible/keeper/zevm_msg_passing.go | 21 +- x/fungible/types/expected_keepers.go | 7 +- .../message_deploy_fungible_coin_zrc20.go | 11 +- .../types/message_update_system_contract.go | 6 +- .../message_update_zrc20_paused_status.go | 6 +- .../message_update_zrc20_withdraw_fee.go | 7 +- x/lightclient/genesis_test.go | 6 +- x/lightclient/keeper/block_header_test.go | 79 +++-- .../keeper/block_header_verification_test.go | 18 +- .../keeper/grpc_query_block_header.go | 10 +- .../keeper/grpc_query_chain_state.go | 10 +- .../grpc_query_header_enabled_chains.go | 18 +- x/lightclient/keeper/grpc_query_prove.go | 5 +- ...erver_disable_block_header_verification.go | 5 +- x/lightclient/keeper/proof.go | 21 +- x/lightclient/keeper/proof_test.go | 6 +- .../types/block_header_verification_test.go | 33 +- .../message_disable_verification_flags.go | 6 +- ...message_disable_verification_flags_test.go | 6 +- .../message_enable_verification_flags.go | 6 +- .../message_enable_verification_flags_test.go | 6 +- x/observer/abci.go | 8 +- x/observer/client/cli/tx_permission_flags.go | 6 +- x/observer/genesis.go | 5 +- x/observer/keeper/blame.go | 11 +- x/observer/keeper/events.go | 6 +- x/observer/keeper/grpc_query_ballot.go | 5 +- x/observer/keeper/grpc_query_blame.go | 15 +- .../keeper/grpc_query_crosschain_flags.go | 5 +- x/observer/keeper/grpc_query_node_account.go | 10 +- x/observer/keeper/grpc_query_nonces.go | 20 +- x/observer/keeper/grpc_query_observer.go | 10 +- .../keeper/grpc_query_supported_chain.go | 5 +- x/observer/keeper/grpc_query_tss.go | 10 +- x/observer/keeper/hooks.go | 6 +- .../keeper/msg_server_add_blame_vote.go | 10 +- x/observer/keeper/msg_server_add_observer.go | 13 +- .../keeper/msg_server_remove_chain_params.go | 5 +- .../keeper/msg_server_reset_chain_nonces.go | 5 +- .../keeper/msg_server_update_chain_params.go | 5 +- .../msg_server_update_crosschain_flags.go | 5 +- ...msg_server_update_crosschain_flags_test.go | 6 +- x/observer/keeper/msg_server_update_keygen.go | 5 +- .../keeper/msg_server_update_observer.go | 27 +- .../keeper/msg_server_vote_block_header.go | 5 +- x/observer/keeper/msg_server_vote_tss.go | 5 +- x/observer/keeper/nonce_to_cctx.go | 7 +- x/observer/keeper/nonce_to_cctx_test.go | 7 +- x/observer/keeper/pending_nonces.go | 5 +- x/observer/keeper/pending_nonces_test.go | 5 +- x/observer/keeper/tss.go | 5 +- x/observer/keeper/utils.go | 7 +- x/observer/types/ballot.go | 5 +- x/observer/types/ballot_test.go | 94 ++++- x/observer/types/chain_params.go | 36 +- x/observer/types/errors.go | 30 +- x/observer/types/expected_keepers.go | 6 +- x/observer/types/message_add_observer.go | 7 +- .../types/message_reset_chain_nonces.go | 7 +- x/observer/types/message_update_observer.go | 7 +- x/observer/types/message_vote_block_header.go | 8 +- zetaclient/chains/bitcoin/fee.go | 7 +- zetaclient/chains/bitcoin/fee_test.go | 4 +- zetaclient/chains/bitcoin/observer/inbound.go | 59 +++- .../chains/bitcoin/observer/inbound_test.go | 30 +- .../chains/bitcoin/observer/live_test.go | 34 +- .../chains/bitcoin/observer/observer.go | 32 +- .../chains/bitcoin/observer/outbound.go | 111 ++++-- .../chains/bitcoin/observer/outbound_test.go | 26 +- zetaclient/chains/bitcoin/signer/signer.go | 50 ++- .../bitcoin/signer/signer_keysign_test.go | 21 +- .../chains/bitcoin/signer/signer_test.go | 28 +- zetaclient/chains/evm/observer/inbound.go | 135 +++++-- .../chains/evm/observer/inbound_test.go | 26 +- zetaclient/chains/evm/observer/observer.go | 34 +- .../chains/evm/observer/observer_test.go | 5 +- zetaclient/chains/evm/observer/outbound.go | 48 ++- .../chains/evm/observer/outbound_test.go | 227 ++++++++++-- .../chains/evm/signer/outbound_tx_data.go | 12 +- zetaclient/chains/evm/signer/signer.go | 118 +++++-- zetaclient/chains/evm/signer/signer_test.go | 9 +- zetaclient/chains/interfaces/interfaces.go | 12 +- zetaclient/compliance/compliance.go | 16 +- zetaclient/config/types.go | 6 +- zetaclient/context/zetacore_context_test.go | 199 +++++------ zetaclient/hsm/hsm_signer.go | 6 +- zetaclient/keys/keys.go | 10 +- zetaclient/keys/keys_test.go | 8 +- zetaclient/orchestrator/orchestrator.go | 49 ++- zetaclient/orchestrator/orchestrator_test.go | 49 ++- zetaclient/outtxprocessor/out_tx_processor.go | 3 +- zetaclient/ratelimiter/rate_limiter_test.go | 70 +++- zetaclient/supplychecker/validate.go | 5 +- .../supplychecker/zeta_supply_checker.go | 18 +- .../supplychecker/zeta_supply_checker_test.go | 13 +- zetaclient/testutils/evm.go | 10 +- zetaclient/testutils/mocks/btc_rpc.go | 11 +- zetaclient/testutils/mocks/evm_rpc.go | 18 +- zetaclient/testutils/mocks/keyring.go | 7 +- zetaclient/testutils/mocks/tss_signer.go | 5 +- zetaclient/testutils/mocks/zetacore_client.go | 37 +- zetaclient/testutils/testdata.go | 7 +- zetaclient/tss/tss_signer.go | 31 +- zetaclient/zetacore/broadcast.go | 14 +- zetaclient/zetacore/broadcast_test.go | 20 +- zetaclient/zetacore/client.go | 11 +- zetaclient/zetacore/query.go | 59 +++- zetaclient/zetacore/query_test.go | 24 +- zetaclient/zetacore/tx.go | 43 ++- 309 files changed, 6280 insertions(+), 1728 deletions(-) diff --git a/app/ante/authz.go b/app/ante/authz.go index c81dcf97b5..5c8a58c534 100644 --- a/app/ante/authz.go +++ b/app/ante/authz.go @@ -27,7 +27,12 @@ func NewAuthzLimiterDecorator(disabledMsgTypes ...string) AuthzLimiterDecorator } } -func (ald AuthzLimiterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { +func (ald AuthzLimiterDecorator) AnteHandle( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, + next sdk.AnteHandler, +) (newCtx sdk.Context, err error) { if err := ald.checkDisabledMsgs(tx.GetMsgs(), false, 1); err != nil { return ctx, errorsmod.Wrapf(errortypes.ErrUnauthorized, err.Error()) } diff --git a/app/ante/fees.go b/app/ante/fees.go index 912ed8e0e2..054cca7c4f 100644 --- a/app/ante/fees.go +++ b/app/ante/fees.go @@ -83,7 +83,12 @@ func NewEthMempoolFeeDecorator(ek EVMKeeper) EthMempoolFeeDecorator { } } -func (mpd MinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { +func (mpd MinGasPriceDecorator) AnteHandle( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, + next sdk.AnteHandler, +) (newCtx sdk.Context, err error) { feeTx, ok := tx.(sdk.FeeTx) if !ok { return ctx, errorsmod.Wrapf(errortypes.ErrInvalidType, "invalid transaction type %T, expected sdk.FeeTx", tx) @@ -143,7 +148,12 @@ func (mpd MinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate // AnteHandle ensures that the that the effective fee from the transaction is greater than the // minimum global fee, which is defined by the MinGasPrice (parameter) * GasLimit (tx argument). -func (empd EthMinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { +func (empd EthMinGasPriceDecorator) AnteHandle( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, + next sdk.AnteHandler, +) (newCtx sdk.Context, err error) { minGasPrice := empd.feesKeeper.GetParams(ctx).MinGasPrice // short-circuit if min gas price is 0 @@ -195,7 +205,8 @@ func (empd EthMinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul return ctx, errorsmod.Wrapf( errortypes.ErrInsufficientFee, "provided fee < minimum global fee (%d < %d). Please increase the priority tip (for EIP-1559 txs) or the gas prices (for access list or legacy txs)", //nolint:lll - fee.TruncateInt().Int64(), requiredFee.TruncateInt().Int64(), + fee.TruncateInt().Int64(), + requiredFee.TruncateInt().Int64(), ) } } @@ -206,7 +217,12 @@ func (empd EthMinGasPriceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul // AnteHandle ensures that the provided fees meet a minimum threshold for the validator. // This check only for local mempool purposes, and thus it is only run on (Re)CheckTx. // The logic is also skipped if the London hard fork and EIP-1559 are enabled. -func (mfd EthMempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { +func (mfd EthMempoolFeeDecorator) AnteHandle( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, + next sdk.AnteHandler, +) (newCtx sdk.Context, err error) { if !ctx.IsCheckTx() || simulate { return next(ctx, tx, simulate) } @@ -226,7 +242,12 @@ func (mfd EthMempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulat for _, msg := range tx.GetMsgs() { ethMsg, ok := msg.(*evmtypes.MsgEthereumTx) if !ok { - return ctx, errorsmod.Wrapf(errortypes.ErrUnknownRequest, "invalid message type %T, expected %T", msg, (*evmtypes.MsgEthereumTx)(nil)) + return ctx, errorsmod.Wrapf( + errortypes.ErrUnknownRequest, + "invalid message type %T, expected %T", + msg, + (*evmtypes.MsgEthereumTx)(nil), + ) } fee := sdk.NewDecFromBigInt(ethMsg.GetFee()) diff --git a/app/ante/handler_options.go b/app/ante/handler_options.go index 9ae24bf56e..cb9a587445 100644 --- a/app/ante/handler_options.go +++ b/app/ante/handler_options.go @@ -63,7 +63,12 @@ func NewLegacyCosmosAnteHandlerEip712(options HandlerOptions) sdk.AnteHandler { ethante.NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), + ante.NewDeductFeeDecorator( + options.AccountKeeper, + options.BankKeeper, + options.FeegrantKeeper, + options.TxFeeChecker, + ), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewSetPubKeyDecorator(options.AccountKeeper), ante.NewValidateSigCountDecorator(options.AccountKeeper), @@ -78,9 +83,16 @@ func NewLegacyCosmosAnteHandlerEip712(options HandlerOptions) sdk.AnteHandler { func newEthAnteHandler(options HandlerOptions) sdk.AnteHandler { return sdk.ChainAnteDecorators( - ethante.NewEthSetUpContextDecorator(options.EvmKeeper), // outermost AnteDecorator. SetUpContext must be called first - ethante.NewEthMempoolFeeDecorator(options.EvmKeeper), // Check eth effective gas price against minimal-gas-prices - ethante.NewEthMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper), // Check eth effective gas price against the global MinGasPrice + ethante.NewEthSetUpContextDecorator( + options.EvmKeeper, + ), // outermost AnteDecorator. SetUpContext must be called first + ethante.NewEthMempoolFeeDecorator( + options.EvmKeeper, + ), // Check eth effective gas price against minimal-gas-prices + ethante.NewEthMinGasPriceDecorator( + options.FeeMarketKeeper, + options.EvmKeeper, + ), // Check eth effective gas price against the global MinGasPrice ethante.NewEthValidateBasicDecorator(options.EvmKeeper), ethante.NewEthSigVerificationDecorator(options.EvmKeeper), ethante.NewEthAccountVerificationDecorator(options.AccountKeeper, options.EvmKeeper), @@ -88,7 +100,9 @@ func newEthAnteHandler(options HandlerOptions) sdk.AnteHandler { ethante.NewEthGasConsumeDecorator(options.EvmKeeper, options.MaxTxGasWanted), ethante.NewEthIncrementSenderSequenceDecorator(options.AccountKeeper), // innermost AnteDecorator. ethante.NewGasWantedDecorator(options.EvmKeeper, options.FeeMarketKeeper), - ethante.NewEthEmitEventDecorator(options.EvmKeeper), // emit eth tx hash and index at the very last ante handler. + ethante.NewEthEmitEventDecorator( + options.EvmKeeper, + ), // emit eth tx hash and index at the very last ante handler. ) } @@ -104,7 +118,12 @@ func newCosmosAnteHandler(options HandlerOptions) sdk.AnteHandler { ethante.NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), + ante.NewDeductFeeDecorator( + options.AccountKeeper, + options.BankKeeper, + options.FeegrantKeeper, + options.TxFeeChecker, + ), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewSetPubKeyDecorator(options.AccountKeeper), ante.NewValidateSigCountDecorator(options.AccountKeeper), @@ -129,7 +148,12 @@ func newCosmosAnteHandlerForSystemTx(options HandlerOptions) sdk.AnteHandler { NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), + ante.NewDeductFeeDecorator( + options.AccountKeeper, + options.BankKeeper, + options.FeegrantKeeper, + options.TxFeeChecker, + ), NewSystemPriorityDecorator(), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewSetPubKeyDecorator(options.AccountKeeper), @@ -160,7 +184,12 @@ func NewSetUpContextDecorator() SetUpContextDecorator { return SetUpContextDecorator{} } -func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { +func (sud SetUpContextDecorator) AnteHandle( + ctx sdk.Context, + tx sdk.Tx, + simulate bool, + next sdk.AnteHandler, +) (newCtx sdk.Context, err error) { // all transactions must implement GasTx gasTx, ok := tx.(GasTx) if !ok { diff --git a/app/app.go b/app/app.go index b88d2c01a7..fa899febc2 100644 --- a/app/app.go +++ b/app/app.go @@ -526,7 +526,11 @@ func New( // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks(), app.ObserverKeeper.Hooks()), + stakingtypes.NewMultiStakingHooks( + app.DistrKeeper.Hooks(), + app.SlashingKeeper.Hooks(), + app.ObserverKeeper.Hooks(), + ), ) app.AuthzKeeper = authzkeeper.NewKeeper( @@ -685,10 +689,36 @@ func New( bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), - gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + gov.NewAppModule( + appCodec, + &app.GovKeeper, + app.AccountKeeper, + app.BankKeeper, + app.GetSubspace(govtypes.ModuleName), + ), + slashing.NewAppModule( + appCodec, + app.SlashingKeeper, + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.GetSubspace(slashingtypes.ModuleName), + ), + distr.NewAppModule( + appCodec, + app.DistrKeeper, + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.GetSubspace(distrtypes.ModuleName), + ), + staking.NewAppModule( + appCodec, + app.StakingKeeper, + app.AccountKeeper, + app.BankKeeper, + app.GetSubspace(stakingtypes.ModuleName), + ), upgrade.NewAppModule(app.UpgradeKeeper), evidence.NewAppModule(app.EvidenceKeeper), params.NewAppModule(app.ParamsKeeper), @@ -803,7 +833,9 @@ func New( SigGasConsumer: evmante.DefaultSigVerificationGasConsumer, MaxTxGasWanted: maxGasWanted, DisabledAuthzMsgs: []string{ - sdk.MsgTypeURL(&evmtypes.MsgEthereumTx{}), // disable the Msg types that cannot be included on an authz.MsgExec msgs field + sdk.MsgTypeURL( + &evmtypes.MsgEthereumTx{}, + ), // disable the Msg types that cannot be included on an authz.MsgExec msgs field sdk.MsgTypeURL(&vestingtypes.MsgCreateVestingAccount{}), sdk.MsgTypeURL(&vestingtypes.MsgCreatePermanentLockedAccount{}), sdk.MsgTypeURL(&vestingtypes.MsgCreatePeriodicVestingAccount{}), @@ -980,7 +1012,11 @@ func GetMaccPerms() map[string][]string { } // initParamsKeeper init params keeper and its subspaces -func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { +func initParamsKeeper( + appCodec codec.BinaryCodec, + legacyAmino *codec.LegacyAmino, + key, tkey storetypes.StoreKey, +) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) paramsKeeper.Subspace(authtypes.ModuleName) diff --git a/app/config.go b/app/config.go index 5e8062fce8..8f50ff8b7b 100644 --- a/app/config.go +++ b/app/config.go @@ -32,12 +32,42 @@ var ( // GetSimulatorFlags gets the values of all the available simulation flags func GetSimulatorFlags() { // config fields - flag.StringVar(&FlagGenesisFileValue, "Genesis", "", "custom simulation genesis file; cannot be used with params file") - flag.StringVar(&FlagParamsFileValue, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") - flag.StringVar(&FlagExportParamsPathValue, "ExportParamsPath", "", "custom file path to save the exported params JSON") - flag.IntVar(&FlagExportParamsHeightValue, "ExportParamsHeight", 0, "height to which export the randomly generated params") - flag.StringVar(&FlagExportStatePathValue, "ExportStatePath", "", "custom file path to save the exported app state JSON") - flag.StringVar(&FlagExportStatsPathValue, "ExportStatsPath", "", "custom file path to save the exported simulation statistics JSON") + flag.StringVar( + &FlagGenesisFileValue, + "Genesis", + "", + "custom simulation genesis file; cannot be used with params file", + ) + flag.StringVar( + &FlagParamsFileValue, + "Params", + "", + "custom simulation params file which overrides any random params; cannot be used with genesis", + ) + flag.StringVar( + &FlagExportParamsPathValue, + "ExportParamsPath", + "", + "custom file path to save the exported params JSON", + ) + flag.IntVar( + &FlagExportParamsHeightValue, + "ExportParamsHeight", + 0, + "height to which export the randomly generated params", + ) + flag.StringVar( + &FlagExportStatePathValue, + "ExportStatePath", + "", + "custom file path to save the exported app state JSON", + ) + flag.StringVar( + &FlagExportStatsPathValue, + "ExportStatsPath", + "", + "custom file path to save the exported simulation statistics JSON", + ) flag.Int64Var(&FlagSeedValue, "Seed", 42, "simulation random seed") flag.IntVar(&FlagInitialBlockHeightValue, "InitialBlockHeight", 1, "initial block to start the simulation") flag.IntVar(&FlagNumBlocksValue, "NumBlocks", 500, "number of new blocks to simulate from the initial block height") @@ -45,13 +75,23 @@ func GetSimulatorFlags() { flag.BoolVar(&FlagLeanValue, "Lean", false, "lean simulation log output") flag.BoolVar(&FlagCommitValue, "Commit", false, "have the simulation commit") flag.BoolVar(&FlagOnOperationValue, "SimulateEveryOperation", false, "run slow invariants every operation") - flag.BoolVar(&FlagAllInvariantsValue, "PrintAllInvariants", false, "print all invariants if a broken invariant is found") + flag.BoolVar( + &FlagAllInvariantsValue, + "PrintAllInvariants", + false, + "print all invariants if a broken invariant is found", + ) // simulation flags flag.BoolVar(&FlagEnabledValue, "Enabled", false, "enable the simulation") flag.BoolVar(&FlagVerboseValue, "Verbose", false, "verbose log output") flag.UintVar(&FlagPeriodValue, "Period", 0, "run slow invariants only once every period assertions") - flag.Int64Var(&FlagGenesisTimeValue, "GenesisTime", 0, "override genesis UNIX time instead of using a random UNIX time") + flag.Int64Var( + &FlagGenesisTimeValue, + "GenesisTime", + 0, + "override genesis UNIX time instead of using a random UNIX time", + ) } // NewConfigFromFlags creates a simulation from the retrieved values of the flags. diff --git a/app/export.go b/app/export.go index feea997869..16362daafd 100644 --- a/app/export.go +++ b/app/export.go @@ -87,7 +87,11 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // withdraw all delegator rewards dels := app.StakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { - _, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr()) + _, err := app.DistrKeeper.WithdrawDelegationRewards( + ctx, + delegation.GetDelegatorAddr(), + delegation.GetValidatorAddr(), + ) if err != nil { panic(err) } diff --git a/app/mempool/priority_nonce_mempool.go b/app/mempool/priority_nonce_mempool.go index cb6ed8748f..6e3365c7a2 100644 --- a/app/mempool/priority_nonce_mempool.go +++ b/app/mempool/priority_nonce_mempool.go @@ -103,7 +103,9 @@ func PriorityNonceWithOnRead(onRead func(tx sdk.Tx)) PriorityNonceMempoolOption // PriorityNonceWithTxReplacement sets a callback to be called when duplicated // transaction nonce detected during mempool insert. An application can define a // transaction replacement rule based on tx priority or certain transaction fields. -func PriorityNonceWithTxReplacement(txReplacementRule func(op, np int64, oTx, nTx sdk.Tx) bool) PriorityNonceMempoolOption { +func PriorityNonceWithTxReplacement( + txReplacementRule func(op, np int64, oTx, nTx sdk.Tx) bool, +) PriorityNonceMempoolOption { return func(mp *PriorityNonceMempool) { mp.txReplacement = txReplacementRule } @@ -203,7 +205,8 @@ func (mp *PriorityNonceMempool) Insert(ctx context.Context, tx sdk.Tx) error { // changes. sk := txMeta{nonce: nonce, sender: sender} if oldScore, txExists := mp.scores[sk]; txExists { - if mp.txReplacement != nil && !mp.txReplacement(oldScore.priority, priority, senderIndex.Get(key).Value.(sdk.Tx), tx) { + if mp.txReplacement != nil && + !mp.txReplacement(oldScore.priority, priority, senderIndex.Get(key).Value.(sdk.Tx), tx) { return fmt.Errorf( "tx doesn't fit the replacement rule, oldPriority: %v, newPriority: %v, oldTx: %v, newTx: %v", oldScore.priority, diff --git a/app/setup_handlers.go b/app/setup_handlers.go index d178f5a599..ced966307f 100644 --- a/app/setup_handlers.go +++ b/app/setup_handlers.go @@ -127,19 +127,22 @@ func SetupHandlers(app *App) { upgradeHandlerFns, storeUpgrades = allUpgrades.mergeAllUpgrades() } - app.UpgradeKeeper.SetUpgradeHandler(constant.Version, func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { - app.Logger().Info("Running upgrade handler for " + constant.Version) + app.UpgradeKeeper.SetUpgradeHandler( + constant.Version, + func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { + app.Logger().Info("Running upgrade handler for " + constant.Version) - var err error - for _, upgradeHandler := range upgradeHandlerFns { - vm, err = upgradeHandler(ctx, vm) - if err != nil { - return vm, err + var err error + for _, upgradeHandler := range upgradeHandlerFns { + vm, err = upgradeHandler(ctx, vm) + if err != nil { + return vm, err + } } - } - return app.mm.RunMigrations(ctx, app.configurator, vm) - }) + return app.mm.RunMigrations(ctx, app.configurator, vm) + }, + ) upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() if err != nil { diff --git a/cmd/zetaclientd-supervisor/lib.go b/cmd/zetaclientd-supervisor/lib.go index cb943b4557..9ab96026b6 100644 --- a/cmd/zetaclientd-supervisor/lib.go +++ b/cmd/zetaclientd-supervisor/lib.go @@ -46,7 +46,11 @@ func getLogger(cfg config.Config, out io.Writer) zerolog.Logger { case "json": logger = zerolog.New(out).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() case "text": - logger = zerolog.New(zerolog.ConsoleWriter{Out: out, TimeFormat: time.RFC3339}).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() + logger = zerolog.New(zerolog.ConsoleWriter{Out: out, TimeFormat: time.RFC3339}). + Level(zerolog.Level(cfg.LogLevel)). + With(). + Timestamp(). + Logger() default: logger = zerolog.New(zerolog.ConsoleWriter{Out: out, TimeFormat: time.RFC3339}) } @@ -63,7 +67,11 @@ type zetaclientdSupervisor struct { enableAutoDownload bool } -func newZetaclientdSupervisor(zetaCoreURL string, logger zerolog.Logger, enableAutoDownload bool) (*zetaclientdSupervisor, error) { +func newZetaclientdSupervisor( + zetaCoreURL string, + logger zerolog.Logger, + enableAutoDownload bool, +) (*zetaclientdSupervisor, error) { logger = logger.With().Str("module", "zetaclientdSupervisor").Logger() conn, err := grpc.Dial( fmt.Sprintf("%s:9090", zetaCoreURL), @@ -151,7 +159,9 @@ func (s *zetaclientdSupervisor) watchForVersionChanges(ctx context.Context) { err = atomicSymlink(newVersionDir, currentLinkPath) if err != nil { - s.logger.Error().Err(err).Msgf("unable to update current symlink (%s -> %s)", newVersionDir, currentLinkPath) + s.logger.Error(). + Err(err). + Msgf("unable to update current symlink (%s -> %s)", newVersionDir, currentLinkPath) return } s.reloadSignals <- true diff --git a/cmd/zetaclientd/debug.go b/cmd/zetaclientd/debug.go index c466ad744b..ee99b6e56d 100644 --- a/cmd/zetaclientd/debug.go +++ b/cmd/zetaclientd/debug.go @@ -38,7 +38,8 @@ type debugArguments struct { func init() { RootCmd.AddCommand(DebugCmd()) - DebugCmd().Flags().StringVar(&debugArgs.zetaCoreHome, "core-home", "/Users/tanmay/.zetacored", "peer address, e.g. /dns/tss1/tcp/6668/ipfs/16Uiu2HAmACG5DtqmQsHtXg4G2sLS65ttv84e7MrL4kapkjfmhxAp") + DebugCmd().Flags(). + StringVar(&debugArgs.zetaCoreHome, "core-home", "/Users/tanmay/.zetacored", "peer address, e.g. /dns/tss1/tcp/6668/ipfs/16Uiu2HAmACG5DtqmQsHtXg4G2sLS65ttv84e7MrL4kapkjfmhxAp") DebugCmd().Flags().StringVar(&debugArgs.zetaNode, "node", "46.4.15.110", "public ip address") DebugCmd().Flags().StringVar(&debugArgs.zetaChainID, "chain-id", "athens_7001-1", "pre-params file path") } diff --git a/cmd/zetaclientd/hsm.go b/cmd/zetaclientd/hsm.go index 578d7909cb..eeb6246594 100644 --- a/cmd/zetaclientd/hsm.go +++ b/cmd/zetaclientd/hsm.go @@ -49,7 +49,8 @@ func init() { HsmCmd.PersistentFlags().StringVar(&hsmArgs.label, "key-label", "", "label used to identify key on HSM") // HSM key gen arguments - GenerateHsmKeyCmd.Flags().IntVar(&hsmKeyGenArgs.algorithm, "algorithm", 0, "key algo; 0=SECP256K1, 1=SECP256R1, 2=ED25519") + GenerateHsmKeyCmd.Flags(). + IntVar(&hsmKeyGenArgs.algorithm, "algorithm", 0, "key algo; 0=SECP256K1, 1=SECP256R1, 2=ED25519") } func GetHsmAddress(_ *cobra.Command, _ []string) error { diff --git a/cmd/zetaclientd/init.go b/cmd/zetaclientd/init.go index 4af5a437b3..4b36cb6b43 100644 --- a/cmd/zetaclientd/init.go +++ b/cmd/zetaclientd/init.go @@ -41,24 +41,33 @@ func init() { RootCmd.AddCommand(InitCmd) RootCmd.AddCommand(VersionCmd) - InitCmd.Flags().StringVar(&initArgs.peer, "peer", "", "peer address, e.g. /dns/tss1/tcp/6668/ipfs/16Uiu2HAmACG5DtqmQsHtXg4G2sLS65ttv84e7MrL4kapkjfmhxAp") + InitCmd.Flags(). + StringVar(&initArgs.peer, "peer", "", "peer address, e.g. /dns/tss1/tcp/6668/ipfs/16Uiu2HAmACG5DtqmQsHtXg4G2sLS65ttv84e7MrL4kapkjfmhxAp") InitCmd.Flags().StringVar(&initArgs.publicIP, "public-ip", "", "public ip address") InitCmd.Flags().StringVar(&initArgs.preParamsPath, "pre-params", "~/preParams.json", "pre-params file path") InitCmd.Flags().StringVar(&initArgs.chainID, "chain-id", "athens_7001-1", "chain id") InitCmd.Flags().StringVar(&initArgs.zetacoreURL, "zetacore-url", "127.0.0.1", "zetacore node URL") - InitCmd.Flags().StringVar(&initArgs.authzGranter, "operator", "", "granter for the authorization , this should be operator address") - InitCmd.Flags().StringVar(&initArgs.authzHotkey, "hotkey", "hotkey", "hotkey for zetaclient this key is used for TSS and ZetaClient operations") - InitCmd.Flags().Int8Var(&initArgs.level, "log-level", int8(zerolog.InfoLevel), "log level (0:debug, 1:info, 2:warn, 3:error, 4:fatal, 5:panic , 6: NoLevel , 7: Disable)") + InitCmd.Flags(). + StringVar(&initArgs.authzGranter, "operator", "", "granter for the authorization , this should be operator address") + InitCmd.Flags(). + StringVar(&initArgs.authzHotkey, "hotkey", "hotkey", "hotkey for zetaclient this key is used for TSS and ZetaClient operations") + InitCmd.Flags(). + Int8Var(&initArgs.level, "log-level", int8(zerolog.InfoLevel), "log level (0:debug, 1:info, 2:warn, 3:error, 4:fatal, 5:panic , 6: NoLevel , 7: Disable)") InitCmd.Flags().StringVar(&initArgs.logFormat, "log-format", "json", "log format (json, test)") InitCmd.Flags().BoolVar(&initArgs.logSampler, "log-sampler", false, "set to to true to turn on log sampling") InitCmd.Flags().BoolVar(&initArgs.p2pDiagnostic, "p2p-diagnostic", false, "enable p2p diagnostic") - InitCmd.Flags().Uint64Var(&initArgs.p2pDiagnosticTicker, "p2p-diagnostic-ticker", 30, "p2p diagnostic ticker (default: 0 means no ticker)") - InitCmd.Flags().Uint64Var(&initArgs.configUpdateTicker, "config-update-ticker", 5, "config update ticker (default: 0 means no ticker)") + InitCmd.Flags(). + Uint64Var(&initArgs.p2pDiagnosticTicker, "p2p-diagnostic-ticker", 30, "p2p diagnostic ticker (default: 0 means no ticker)") + InitCmd.Flags(). + Uint64Var(&initArgs.configUpdateTicker, "config-update-ticker", 5, "config update ticker (default: 0 means no ticker)") InitCmd.Flags().StringVar(&initArgs.TssPath, "tss-path", "~/.tss", "path to tss location") - InitCmd.Flags().BoolVar(&initArgs.TestTssKeysign, "test-tss", false, "set to to true to run a check for TSS keysign on startup") - InitCmd.Flags().StringVar(&initArgs.KeyringBackend, "keyring-backend", string(config.KeyringBackendTest), "keyring backend to use (test, file)") + InitCmd.Flags(). + BoolVar(&initArgs.TestTssKeysign, "test-tss", false, "set to to true to run a check for TSS keysign on startup") + InitCmd.Flags(). + StringVar(&initArgs.KeyringBackend, "keyring-backend", string(config.KeyringBackendTest), "keyring backend to use (test, file)") InitCmd.Flags().BoolVar(&initArgs.HsmMode, "hsm-mode", false, "enable hsm signer, default disabled") - InitCmd.Flags().StringVar(&initArgs.HsmHotKey, "hsm-hotkey", "hsm-hotkey", "name of hotkey associated with hardware security module") + InitCmd.Flags(). + StringVar(&initArgs.HsmHotKey, "hsm-hotkey", "hsm-hotkey", "name of hotkey associated with hardware security module") } func Initialize(_ *cobra.Command, _ []string) error { diff --git a/cmd/zetaclientd/keygen_tss.go b/cmd/zetaclientd/keygen_tss.go index b07d7f6106..461d8ebec7 100644 --- a/cmd/zetaclientd/keygen_tss.go +++ b/cmd/zetaclientd/keygen_tss.go @@ -99,7 +99,8 @@ func GenerateTss( if currentBlock != keyGen.BlockNumber { if currentBlock > lastBlock { lastBlock = currentBlock - keygenLogger.Info().Msgf("Waiting For Keygen Block to arrive or new keygen block to be set. Keygen Block : %d Current Block : %d ChainID %s ", keyGen.BlockNumber, currentBlock, appContext.Config().ChainID) + keygenLogger.Info(). + Msgf("Waiting For Keygen Block to arrive or new keygen block to be set. Keygen Block : %d Current Block : %d ChainID %s ", keyGen.BlockNumber, currentBlock, appContext.Config().ChainID) } continue } @@ -126,7 +127,11 @@ func GenerateTss( } // If TSS is successful , broadcast the vote to zetacore and set Pubkey - tssSuccessVoteHash, err := client.SetTSS(newTss.CurrentPubkey, keyGen.BlockNumber, chains.ReceiveStatus_success) + tssSuccessVoteHash, err := client.SetTSS( + newTss.CurrentPubkey, + keyGen.BlockNumber, + chains.ReceiveStatus_success, + ) if err != nil { keygenLogger.Error().Err(err).Msg("TSS successful but unable to broadcast vote to zeta-core") return nil, err @@ -143,7 +148,8 @@ func GenerateTss( continue } } - keygenLogger.Debug().Msgf("Waiting for TSS to be generated or Current Keygen to be be finalized. Keygen Block : %d ", keyGen.BlockNumber) + keygenLogger.Debug(). + Msgf("Waiting for TSS to be generated or Current Keygen to be be finalized. Keygen Block : %d ", keyGen.BlockNumber) } return nil, errors.New("unexpected state for TSS generation") } diff --git a/cmd/zetaclientd/main.go b/cmd/zetaclientd/main.go index 9502c438f9..5558138ede 100644 --- a/cmd/zetaclientd/main.go +++ b/cmd/zetaclientd/main.go @@ -73,7 +73,11 @@ func InitLogger(cfg config.Config) (clientcommon.ClientLogger, error) { logger = zerolog.New(os.Stdout).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() loggerCompliance = zerolog.New(file).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() case "text": - logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() + logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}). + Level(zerolog.Level(cfg.LogLevel)). + With(). + Timestamp(). + Logger() loggerCompliance = zerolog.New(file).Level(zerolog.Level(cfg.LogLevel)).With().Timestamp().Logger() default: logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}) diff --git a/cmd/zetaclientd/p2p_diagnostics.go b/cmd/zetaclientd/p2p_diagnostics.go index 8794be30d1..bfbc58748f 100644 --- a/cmd/zetaclientd/p2p_diagnostics.go +++ b/cmd/zetaclientd/p2p_diagnostics.go @@ -26,7 +26,12 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/config" ) -func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, hotkeyPk cryptotypes.PrivKey, cfg config.Config) error { +func RunDiagnostics( + startLogger zerolog.Logger, + peers p2p.AddrList, + hotkeyPk cryptotypes.PrivKey, + cfg config.Config, +) error { startLogger.Warn().Msg("P2P Diagnostic mode enabled") startLogger.Warn().Msgf("seed peer: %s", peers) @@ -177,7 +182,12 @@ func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, hotkeyPk cry startLogger.Error().Err(err).Msgf("fail to create stream to peer %s", peer) continue } - message := fmt.Sprintf("round %d %s => %s", round, host.ID().String()[len(host.ID().String())-5:], peer.ID.String()[len(peer.ID.String())-5:]) + message := fmt.Sprintf( + "round %d %s => %s", + round, + host.ID().String()[len(host.ID().String())-5:], + peer.ID.String()[len(peer.ID.String())-5:], + ) _, err = stream.Write([]byte(message)) if err != nil { startLogger.Error().Err(err).Msgf("fail to write to stream to peer %s", peer) @@ -206,13 +216,15 @@ func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, hotkeyPk cry } if string(buf[:nr]) != message { - startLogger.Error().Msgf("ping-pong failed with peer #(%d): %s; want %s got %s", peerCount, peer, message, string(buf[:nr])) + startLogger.Error(). + Msgf("ping-pong failed with peer #(%d): %s; want %s got %s", peerCount, peer, message, string(buf[:nr])) continue } startLogger.Info().Msgf("ping-pong success with peer #(%d): %s;", peerCount, peer) okPingPongCount++ } - startLogger.Info().Msgf("Expect %d peers in total; successful pings (%d/%d)", peerCount, okPingPongCount, peerCount-1) + startLogger.Info(). + Msgf("Expect %d peers in total; successful pings (%d/%d)", peerCount, okPingPongCount, peerCount-1) } } } diff --git a/cmd/zetaclientd/start.go b/cmd/zetaclientd/start.go index b16b9b7888..e3840f58b6 100644 --- a/cmd/zetaclientd/start.go +++ b/cmd/zetaclientd/start.go @@ -108,7 +108,8 @@ func start(_ *cobra.Command, _ []string) error { } if strings.Compare(res.GetDefaultNodeInfo().Network, cfg.ChainID) != 0 { - startLogger.Warn().Msgf("chain id mismatch, zeta-core chain id %s, zeta client chain id %s; reset zeta client chain id", res.GetDefaultNodeInfo().Network, cfg.ChainID) + startLogger.Warn(). + Msgf("chain id mismatch, zeta-core chain id %s, zeta client chain id %s; reset zeta client chain id", res.GetDefaultNodeInfo().Network, cfg.ChainID) cfg.ChainID = res.GetDefaultNodeInfo().Network err := zetacoreClient.UpdateChainID(cfg.ChainID) if err != nil { @@ -179,7 +180,17 @@ func start(_ *cobra.Command, _ []string) error { } telemetryServer.SetIPAddress(cfg.PublicIP) - tss, err := GenerateTss(appContext, masterLogger, zetacoreClient, peers, priKey, telemetryServer, tssHistoricalList, tssKeyPass, hotkeyPass) + tss, err := GenerateTss( + appContext, + masterLogger, + zetacoreClient, + peers, + priKey, + telemetryServer, + tssHistoricalList, + tssKeyPass, + hotkeyPass, + ) if err != nil { return err } @@ -216,7 +227,8 @@ func start(_ *cobra.Command, _ []string) error { if tss.EVMAddress() == (ethcommon.Address{}) || tss.BTCAddress() == "" { startLogger.Error().Msg("TSS address is not set in zetacore") } - startLogger.Info().Msgf("Current TSS address \n ETH : %s \n BTC : %s \n PubKey : %s ", tss.EVMAddress(), tss.BTCAddress(), tss.CurrentPubkey) + startLogger.Info(). + Msgf("Current TSS address \n ETH : %s \n BTC : %s \n PubKey : %s ", tss.EVMAddress(), tss.BTCAddress(), tss.CurrentPubkey) if len(appContext.ZetacoreContext().GetEnabledChains()) == 0 { startLogger.Error().Msgf("No chains enabled in updated config %s ", cfg.String()) } @@ -256,7 +268,8 @@ func start(_ *cobra.Command, _ []string) error { } if !isNodeActive { - startLogger.Error().Msgf("Node %s is not an active observer external chain observers will not be started", zetacoreClient.GetKeys().GetOperatorAddress().String()) + startLogger.Error(). + Msgf("Node %s is not an active observer external chain observers will not be started", zetacoreClient.GetKeys().GetOperatorAddress().String()) } else { startLogger.Debug().Msgf("Node %s is an active observer starting external chain observers", zetacoreClient.GetKeys().GetOperatorAddress().String()) for _, observer := range observerMap { diff --git a/cmd/zetaclientd/utils.go b/cmd/zetaclientd/utils.go index 7f4ec66ce0..b51f7adbcb 100644 --- a/cmd/zetaclientd/utils.go +++ b/cmd/zetaclientd/utils.go @@ -21,7 +21,11 @@ func CreateAuthzSigner(granter string, grantee sdk.AccAddress) { authz.SetupAuthZSignerList(granter, grantee) } -func CreateZetaCoreClient(cfg config.Config, telemetry *metrics.TelemetryServer, hotkeyPassword string) (*zetacore.Client, error) { +func CreateZetaCoreClient( + cfg config.Config, + telemetry *metrics.TelemetryServer, + hotkeyPassword string, +) (*zetacore.Client, error) { hotKey := cfg.AuthzHotkey if cfg.HsmMode { hotKey = cfg.HsmHotKey diff --git a/cmd/zetacore_utils/main.go b/cmd/zetacore_utils/main.go index f7dcff1e67..f2cd31a1b8 100644 --- a/cmd/zetacore_utils/main.go +++ b/cmd/zetacore_utils/main.go @@ -55,7 +55,19 @@ func main() { distributionList := make([]TokenDistribution, len(addresses)) for i, address := range addresses { // #nosec G204 - cmd := exec.Command("zetacored", "q", "bank", "balances", address, "--output", "json", "--denom", "azeta", "--node", node) + cmd := exec.Command( + "zetacored", + "q", + "bank", + "balances", + address, + "--output", + "json", + "--denom", + "azeta", + "--node", + node, + ) output, err := cmd.CombinedOutput() if err != nil { fmt.Println(cmd.String()) @@ -83,8 +95,23 @@ func main() { args = append(args, address) } - args = append(args, []string{distributionList[0].TokensDistributed.String(), "--keyring-backend", "test", "--chain-id", chainID, "--yes", - "--broadcast-mode", broadcastMode, "--gas=auto", "--gas-adjustment=2", "--gas-prices=0.001azeta", "--node", node}...) + args = append( + args, + []string{ + distributionList[0].TokensDistributed.String(), + "--keyring-backend", + "test", + "--chain-id", + chainID, + "--yes", + "--broadcast-mode", + broadcastMode, + "--gas=auto", + "--gas-adjustment=2", + "--gas-prices=0.001azeta", + "--node", + node, + }...) // #nosec G204 cmd := exec.Command("zetacored", args...) @@ -100,7 +127,19 @@ func main() { for i, address := range addresses { // #nosec G204 - cmd := exec.Command("zetacored", "q", "bank", "balances", address, "--output", "json", "--denom", "azeta", "--node", node) + cmd := exec.Command( + "zetacored", + "q", + "bank", + "balances", + address, + "--output", + "json", + "--denom", + "azeta", + "--node", + node, + ) output, err := cmd.CombinedOutput() if err != nil { fmt.Println(cmd.String()) diff --git a/cmd/zetacored/genaccounts.go b/cmd/zetacored/genaccounts.go index 43a20abe10..7de2cff7e2 100644 --- a/cmd/zetacored/genaccounts.go +++ b/cmd/zetacored/genaccounts.go @@ -174,7 +174,8 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") - cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + cmd.Flags(). + String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") diff --git a/cmd/zetacored/observer_accounts.go b/cmd/zetacored/observer_accounts.go index a4f6dedf84..abde9a6e9a 100644 --- a/cmd/zetacored/observer_accounts.go +++ b/cmd/zetacored/observer_accounts.go @@ -228,7 +228,7 @@ func AddObserverAccountsCmd() *cobra.Command { return cmd } -func removeDuplicate[T string | int](sliceList []T) []T { +func removeDuplicate(sliceList []T) []T { allKeys := make(map[T]bool) list := []T{} for _, item := range sliceList { @@ -332,7 +332,9 @@ func addStakingGrants(grants []authz.GrantAuthorization, info ObserverInfoReader if !ok { panic("Failed to parse staking max tokens") } - alllowList := stakingtypes.StakeAuthorization_AllowList{AllowList: &stakingtypes.StakeAuthorization_Validators{Address: info.StakingValidatorAllowList}} + alllowList := stakingtypes.StakeAuthorization_AllowList{ + AllowList: &stakingtypes.StakeAuthorization_Validators{Address: info.StakingValidatorAllowList}, + } stakingAuth, err := codectypes.NewAnyWithValue(&stakingtypes.StakeAuthorization{ MaxTokens: &sdk.Coin{Denom: config.BaseDenom, Amount: stakingMaxTokens}, @@ -380,7 +382,11 @@ func addStakingGrants(grants []authz.GrantAuthorization, info ObserverInfoReader } -func AddGenesisAccount(clientCtx client.Context, balances []banktypes.Balance, appState map[string]json.RawMessage) (map[string]json.RawMessage, error) { +func AddGenesisAccount( + clientCtx client.Context, + balances []banktypes.Balance, + appState map[string]json.RawMessage, +) (map[string]json.RawMessage, error) { var genAccount authtypes.GenesisAccount totalBalanceAdded := sdk.Coins{} genAccounts := make([]authtypes.GenesisAccount, len(balances)) diff --git a/cmd/zetacored/parse_genesis.go b/cmd/zetacored/parse_genesis.go index 730f35b282..e0ace23030 100644 --- a/cmd/zetacored/parse_genesis.go +++ b/cmd/zetacored/parse_genesis.go @@ -152,7 +152,11 @@ func ImportDataIntoFile(genDoc *types.GenesisDoc, importFile *types.GenesisDoc, // ModifyCrosschainState modifies the crosschain state before importing // It truncates the crosschain transactions, inbound transactions and finalized inbounds to MaxItemsForList -func ModifyCrosschainState(appState map[string]json.RawMessage, importAppState map[string]json.RawMessage, cdc codec.Codec) error { +func ModifyCrosschainState( + appState map[string]json.RawMessage, + importAppState map[string]json.RawMessage, + cdc codec.Codec, +) error { importedCrossChainGenState := crosschaintypes.GetGenesisStateFromAppState(cdc, importAppState) importedCrossChainGenState.CrossChainTxs = importedCrossChainGenState.CrossChainTxs[:math.Min(MaxItemsForList, len(importedCrossChainGenState.CrossChainTxs))] importedCrossChainGenState.InTxHashToCctxList = importedCrossChainGenState.InTxHashToCctxList[:math.Min(MaxItemsForList, len(importedCrossChainGenState.InTxHashToCctxList))] @@ -167,7 +171,11 @@ func ModifyCrosschainState(appState map[string]json.RawMessage, importAppState m // ModifyObserverState modifies the observer state before importing // It truncates the ballots and nonce to cctx list to MaxItemsForList -func ModifyObserverState(appState map[string]json.RawMessage, importAppState map[string]json.RawMessage, cdc codec.Codec) error { +func ModifyObserverState( + appState map[string]json.RawMessage, + importAppState map[string]json.RawMessage, + cdc codec.Codec, +) error { importedObserverGenState := observertypes.GetGenesisStateFromAppState(cdc, importAppState) importedObserverGenState.Ballots = importedObserverGenState.Ballots[:math.Min(MaxItemsForList, len(importedObserverGenState.Ballots))] importedObserverGenState.NonceToCctx = importedObserverGenState.NonceToCctx[:math.Min(MaxItemsForList, len(importedObserverGenState.NonceToCctx))] diff --git a/cmd/zetacored/parsers_test.go b/cmd/zetacored/parsers_test.go index a2c963214c..c5b6c041a4 100644 --- a/cmd/zetacored/parsers_test.go +++ b/cmd/zetacored/parsers_test.go @@ -25,7 +25,11 @@ func TestParsefileToObserverMapper(t *testing.T) { obsListReadFromFile, err := ParsefileToObserverDetails(file) require.NoError(t, err) for _, obs := range obsListReadFromFile { - require.Equal(t, obs.ZetaClientGranteeAddress, sdk.AccAddress(crypto.AddressHash([]byte("ObserverGranteeAddress"))).String()) + require.Equal( + t, + obs.ZetaClientGranteeAddress, + sdk.AccAddress(crypto.AddressHash([]byte("ObserverGranteeAddress"))).String(), + ) } } diff --git a/cmd/zetacored/root.go b/cmd/zetacored/root.go index 1a674e699f..7a5d4ee5d8 100644 --- a/cmd/zetacored/root.go +++ b/cmd/zetacored/root.go @@ -128,8 +128,17 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig appparams.EncodingConfig ethermintclient.ValidateChainID( genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome), ), - genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome, genutiltypes.DefaultMessageValidator), - genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), + genutilcli.CollectGenTxsCmd( + banktypes.GenesisBalancesIterator{}, + app.DefaultNodeHome, + genutiltypes.DefaultMessageValidator, + ), + genutilcli.GenTxCmd( + app.ModuleBasics, + encodingConfig.TxConfig, + banktypes.GenesisBalancesIterator{}, + app.DefaultNodeHome, + ), genutilcli.ValidateGenesisCmd(app.ModuleBasics), AddGenesisAccountCmd(app.DefaultNodeHome), AddObserverAccountsCmd(), @@ -145,7 +154,12 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig appparams.EncodingConfig snapshot.Cmd(ac.newApp), ) - zevmserver.AddCommands(rootCmd, zevmserver.NewDefaultStartOptions(ac.newApp, app.DefaultNodeHome), ac.appExport, addModuleInitFlags) + zevmserver.AddCommands( + rootCmd, + zevmserver.NewDefaultStartOptions(ac.newApp, app.DefaultNodeHome), + ac.appExport, + addModuleInitFlags, + ) // the ethermintserver one supercedes the sdk one //server.AddCommands(rootCmd, app.DefaultNodeHome, ac.newApp, ac.createSimappAndExport, addModuleInitFlags) diff --git a/cmd/zetae2e/config/clients.go b/cmd/zetae2e/config/clients.go index bb8bc85dbb..7b86fc2bb3 100644 --- a/cmd/zetae2e/config/clients.go +++ b/cmd/zetae2e/config/clients.go @@ -41,7 +41,9 @@ func getClientsFromConfig(ctx context.Context, conf config.Config, evmPrivKey st if err != nil { return nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("failed to get evm client: %w", err) } - cctxClient, fungibleClient, authClient, bankClient, observerClient, lightclientClient, err := getZetaClients(conf.RPCs.ZetaCoreGRPC) + cctxClient, fungibleClient, authClient, bankClient, observerClient, lightclientClient, err := getZetaClients( + conf.RPCs.ZetaCoreGRPC, + ) if err != nil { return nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("failed to get zeta clients: %w", err) } diff --git a/cmd/zetae2e/init.go b/cmd/zetae2e/init.go index f3308da4ca..0c24edef2b 100644 --- a/cmd/zetae2e/init.go +++ b/cmd/zetae2e/init.go @@ -20,8 +20,10 @@ func NewInitCmd() *cobra.Command { InitCmd.Flags().StringVar(&initConf.RPCs.EVM, "ethURL", "http://eth:8545", "--ethURL http://eth:8545") InitCmd.Flags().StringVar(&initConf.RPCs.ZetaCoreGRPC, "grpcURL", "zetacore0:9090", "--grpcURL zetacore0:9090") - InitCmd.Flags().StringVar(&initConf.RPCs.ZetaCoreRPC, "rpcURL", "http://zetacore0:26657", "--rpcURL http://zetacore0:26657") - InitCmd.Flags().StringVar(&initConf.RPCs.Zevm, "zevmURL", "http://zetacore0:8545", "--zevmURL http://zetacore0:8545") + InitCmd.Flags(). + StringVar(&initConf.RPCs.ZetaCoreRPC, "rpcURL", "http://zetacore0:26657", "--rpcURL http://zetacore0:26657") + InitCmd.Flags(). + StringVar(&initConf.RPCs.Zevm, "zevmURL", "http://zetacore0:8545", "--zevmURL http://zetacore0:8545") InitCmd.Flags().StringVar(&initConf.RPCs.Bitcoin.Host, "btcURL", "bitcoin:18443", "--grpcURL bitcoin:18443") InitCmd.Flags().StringVar(&initConf.ZetaChainID, "chainID", "athens_101-1", "--chainID athens_101-1") diff --git a/cmd/zetae2e/stress.go b/cmd/zetae2e/stress.go index f8ca5b9f28..0864892ef9 100644 --- a/cmd/zetae2e/stress.go +++ b/cmd/zetae2e/stress.go @@ -52,11 +52,15 @@ func NewStressTestCmd() *cobra.Command { Run: StressTest, } - StressCmd.Flags().StringVar(&stressTestArgs.deployerAddress, "addr", "0xE5C5367B8224807Ac2207d350E60e1b6F27a7ecC", "--addr ") - StressCmd.Flags().StringVar(&stressTestArgs.deployerPrivateKey, "privKey", "d87baf7bf6dc560a252596678c12e41f7d1682837f05b29d411bc3f78ae2c263", "--privKey ") + StressCmd.Flags(). + StringVar(&stressTestArgs.deployerAddress, "addr", "0xE5C5367B8224807Ac2207d350E60e1b6F27a7ecC", "--addr ") + StressCmd.Flags(). + StringVar(&stressTestArgs.deployerPrivateKey, "privKey", "d87baf7bf6dc560a252596678c12e41f7d1682837f05b29d411bc3f78ae2c263", "--privKey ") StressCmd.Flags().StringVar(&stressTestArgs.network, "network", "LOCAL", "--network TESTNET") - StressCmd.Flags().Int64Var(&stressTestArgs.txnInterval, "tx-interval", 500, "--tx-interval [TIME_INTERVAL_MILLISECONDS]") - StressCmd.Flags().BoolVar(&stressTestArgs.contractsDeployed, "contracts-deployed", false, "--contracts-deployed=false") + StressCmd.Flags(). + Int64Var(&stressTestArgs.txnInterval, "tx-interval", 500, "--tx-interval [TIME_INTERVAL_MILLISECONDS]") + StressCmd.Flags(). + BoolVar(&stressTestArgs.contractsDeployed, "contracts-deployed", false, "--contracts-deployed=false") StressCmd.Flags().StringVar(&stressTestArgs.config, local.FlagConfigFile, "", "config file to use for the E2E test") StressCmd.Flags().Bool(flagVerbose, false, "set to true to enable verbose logging") @@ -112,7 +116,10 @@ func StressTest(cmd *cobra.Command, _ []string) { time.Sleep(20 * time.Second) for { time.Sleep(5 * time.Second) - response, err := cctxClient.LastZetaHeight(context.Background(), &crosschaintypes.QueryLastZetaHeightRequest{}) + response, err := cctxClient.LastZetaHeight( + context.Background(), + &crosschaintypes.QueryLastZetaHeightRequest{}, + ) if err != nil { fmt.Printf("cctxClient.LastZetaHeight error: %s", err) continue @@ -252,9 +259,12 @@ func EchoNetworkMetrics(runner *runner.E2ERunner) { case <-ticker.C: numTicks++ // Get all pending outbound transactions - cctxResp, err := runner.CctxClient.ListPendingCctx(context.Background(), &crosschaintypes.QueryListPendingCctxRequest{ - ChainId: chainID.Int64(), - }) + cctxResp, err := runner.CctxClient.ListPendingCctx( + context.Background(), + &crosschaintypes.QueryListPendingCctxRequest{ + ChainId: chainID.Int64(), + }, + ) if err != nil { continue } @@ -263,13 +273,20 @@ func EchoNetworkMetrics(runner *runner.E2ERunner) { return sends[i].GetCurrentOutTxParam().OutboundTxTssNonce < sends[j].GetCurrentOutTxParam().OutboundTxTssNonce }) if len(sends) > 0 { - fmt.Printf("pending nonces %d to %d\n", sends[0].GetCurrentOutTxParam().OutboundTxTssNonce, sends[len(sends)-1].GetCurrentOutTxParam().OutboundTxTssNonce) + fmt.Printf( + "pending nonces %d to %d\n", + sends[0].GetCurrentOutTxParam().OutboundTxTssNonce, + sends[len(sends)-1].GetCurrentOutTxParam().OutboundTxTssNonce, + ) } else { continue } // // Get all trackers - trackerResp, err := runner.CctxClient.OutTxTrackerAll(context.Background(), &crosschaintypes.QueryAllOutTxTrackerRequest{}) + trackerResp, err := runner.CctxClient.OutTxTrackerAll( + context.Background(), + &crosschaintypes.QueryAllOutTxTrackerRequest{}, + ) if err != nil { continue } @@ -293,7 +310,15 @@ func EchoNetworkMetrics(runner *runner.E2ERunner) { numPending := len(cctxResp.CrossChainTx) numTrackers := len(trackerResp.OutTxTracker) - fmt.Println("Network Stat => Num of Pending cctx: ", numPending, "Num active trackers: ", numTrackers, "Tx Rate: ", rate, " tx/min") + fmt.Println( + "Network Stat => Num of Pending cctx: ", + numPending, + "Num active trackers: ", + numTrackers, + "Tx Rate: ", + rate, + " tx/min", + ) } } } diff --git a/cmd/zetatool/filterdeposit/filterdeposit.go b/cmd/zetatool/filterdeposit/filterdeposit.go index 6dfa6d6c11..1361c01c81 100644 --- a/cmd/zetatool/filterdeposit/filterdeposit.go +++ b/cmd/zetatool/filterdeposit/filterdeposit.go @@ -27,7 +27,8 @@ func NewFilterDepositCmd() *cobra.Command { cmd.AddCommand(NewEvmCmd()) // Required for TSS address query - cmd.PersistentFlags().String(BTCChainIDFlag, "8332", "chain id used on zetachain to identify bitcoin - default: 8332") + cmd.PersistentFlags(). + String(BTCChainIDFlag, "8332", "chain id used on zetachain to identify bitcoin - default: 8332") return cmd } diff --git a/contrib/rpctest/main.go b/contrib/rpctest/main.go index 202c4bb236..50d55468ba 100644 --- a/contrib/rpctest/main.go +++ b/contrib/rpctest/main.go @@ -139,7 +139,12 @@ func main() { if err != nil { panic(err) } - zetaContractAddress, tx2, zetaContract, err := zetaeth.DeployZetaEth(zevmAuth, zevmClient, zevmAuth.From, big.NewInt(2_100_000_000)) + zetaContractAddress, tx2, zetaContract, err := zetaeth.DeployZetaEth( + zevmAuth, + zevmClient, + zevmAuth.From, + big.NewInt(2_100_000_000), + ) _, _ = zetaContractAddress, zetaContract if err != nil { panic(err) @@ -194,7 +199,12 @@ func main() { } for approveIter.Next() { event := approveIter.Event - fmt.Printf("Approval event: owner %s, spender %s, amount %s\n", event.Owner.Hex(), event.Spender.Hex(), event.Value.String()) + fmt.Printf( + "Approval event: owner %s, spender %s, amount %s\n", + event.Owner.Hex(), + event.Spender.Hex(), + event.Value.String(), + ) fmt.Printf(" raw log txhash: %s\n", event.Raw.TxHash.Hex()) fmt.Printf(" tx hash: %s\n", tx.Hash().Hex()) if event.Raw.TxHash != tx.Hash() { diff --git a/e2e/e2etests/helper_bitcoin.go b/e2e/e2etests/helper_bitcoin.go index 7810bbb508..915df43d75 100644 --- a/e2e/e2etests/helper_bitcoin.go +++ b/e2e/e2etests/helper_bitcoin.go @@ -45,7 +45,11 @@ func parseBitcoinWithdrawArgs(args []string, defaultReceiver string) (btcutil.Ad } func withdrawBTCZRC20(r *runner.E2ERunner, to btcutil.Address, amount *big.Int) *btcjson.TxRawResult { - tx, err := r.BTCZRC20.Approve(r.ZEVMAuth, r.BTCZRC20Addr, big.NewInt(amount.Int64()*2)) // approve more to cover withdraw fee + tx, err := r.BTCZRC20.Approve( + r.ZEVMAuth, + r.BTCZRC20Addr, + big.NewInt(amount.Int64()*2), + ) // approve more to cover withdraw fee if err != nil { panic(err) } diff --git a/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go b/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go index 7f4c37646f..415fc9a3f4 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go +++ b/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go @@ -34,7 +34,10 @@ func TestBitcoinWithdrawRestricted(r *runner.E2ERunner, args []string) { func withdrawBitcoinRestricted(r *runner.E2ERunner, amount *big.Int) { // use restricted BTC P2WPKH address - addressRestricted, err := chains.DecodeBtcAddress(testutils.RestrictedBtcAddressTest, chains.BtcRegtestChain.ChainId) + addressRestricted, err := chains.DecodeBtcAddress( + testutils.RestrictedBtcAddressTest, + chains.BtcRegtestChain.ChainId, + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_crosschain_swap.go b/e2e/e2etests/test_crosschain_swap.go index 34aa6e3d23..fbb9acd625 100644 --- a/e2e/e2etests/test_crosschain_swap.go +++ b/e2e/e2etests/test_crosschain_swap.go @@ -79,7 +79,11 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { // memobytes is dApp specific; see the contracts/ZEVMSwapApp.sol for details msg := []byte{} msg = append(msg, r.ZEVMSwapAppAddr.Bytes()...) - memobytes, err := r.ZEVMSwapApp.EncodeMemo(&bind.CallOpts{}, r.BTCZRC20Addr, []byte(r.BTCDeployerAddress.EncodeAddress())) + memobytes, err := r.ZEVMSwapApp.EncodeMemo( + &bind.CallOpts{}, + r.BTCZRC20Addr, + []byte(r.BTCDeployerAddress.EncodeAddress()), + ) if err != nil { panic(err) @@ -94,7 +98,13 @@ func TestCrosschainSwap(r *runner.E2ERunner, _ []string) { // check the cctx status if cctx1.CctxStatus.Status != types.CctxStatus_OutboundMined { - panic(fmt.Sprintf("expected outbound mined status; got %s, message: %s", cctx1.CctxStatus.Status.String(), cctx1.CctxStatus.StatusMessage)) + panic( + fmt.Sprintf( + "expected outbound mined status; got %s, message: %s", + cctx1.CctxStatus.Status.String(), + cctx1.CctxStatus.StatusMessage, + ), + ) } // mine 10 blocks to confirm the outbound tx diff --git a/e2e/e2etests/test_erc20_deposit_refund.go b/e2e/e2etests/test_erc20_deposit_refund.go index 4d378f91b5..82dab0ef8a 100644 --- a/e2e/e2etests/test_erc20_deposit_refund.go +++ b/e2e/e2etests/test_erc20_deposit_refund.go @@ -58,7 +58,13 @@ func TestERC20DepositAndCallRefund(r *runner.E2ERunner, _ []string) { } expectedBalance := initialBal.Add(initialBal, amount) if newBalance.Cmp(expectedBalance) != 0 { - panic(fmt.Sprintf("expected balance to be %s after refund; got %s", expectedBalance.String(), newBalance.String())) + panic( + fmt.Sprintf( + "expected balance to be %s after refund; got %s", + expectedBalance.String(), + newBalance.String(), + ), + ) } r.Logger.Info("CCTX has been aborted on ZetaChain") diff --git a/e2e/e2etests/test_erc20_multiple_deposits.go b/e2e/e2etests/test_erc20_multiple_deposits.go index f314716d08..5ab322df1c 100644 --- a/e2e/e2etests/test_erc20_multiple_deposits.go +++ b/e2e/e2etests/test_erc20_multiple_deposits.go @@ -31,7 +31,14 @@ func TestMultipleERC20Deposit(r *runner.E2ERunner, args []string) { panic(err) } txhash := multipleDeposits(r, depositAmount, numberOfDeposits) - cctxs := utils.WaitCctxsMinedByInTxHash(r.Ctx, txhash.Hex(), r.CctxClient, int(numberOfDeposits.Int64()), r.Logger, r.CctxTimeout) + cctxs := utils.WaitCctxsMinedByInTxHash( + r.Ctx, + txhash.Hex(), + r.CctxClient, + int(numberOfDeposits.Int64()), + r.Logger, + r.CctxTimeout, + ) if len(cctxs) != 3 { panic(fmt.Sprintf("cctxs length is not correct: %d", len(cctxs))) } diff --git a/e2e/e2etests/test_erc20_multiple_withdraws.go b/e2e/e2etests/test_erc20_multiple_withdraws.go index 91dff73d9a..1b253e7f93 100644 --- a/e2e/e2etests/test_erc20_multiple_withdraws.go +++ b/e2e/e2etests/test_erc20_multiple_withdraws.go @@ -13,7 +13,9 @@ import ( func TestMultipleERC20Withdraws(r *runner.E2ERunner, args []string) { approvedAmount := big.NewInt(1e18) if len(args) != 2 { - panic("TestMultipleWithdraws requires exactly two arguments: the withdrawal amount and the number of withdrawals.") + panic( + "TestMultipleWithdraws requires exactly two arguments: the withdrawal amount and the number of withdrawals.", + ) } withdrawalAmount, ok := big.NewInt(0).SetString(args[0], 10) @@ -87,7 +89,14 @@ func TestMultipleERC20Withdraws(r *runner.E2ERunner, args []string) { panic("withdraw failed") } - cctxs := utils.WaitCctxsMinedByInTxHash(r.Ctx, tx.Hash().Hex(), r.CctxClient, int(numberOfWithdrawals.Int64()), r.Logger, r.CctxTimeout) + cctxs := utils.WaitCctxsMinedByInTxHash( + r.Ctx, + tx.Hash().Hex(), + r.CctxClient, + int(numberOfWithdrawals.Int64()), + r.Logger, + r.CctxTimeout, + ) if len(cctxs) != 3 { panic(fmt.Sprintf("cctxs length is not correct: %d", len(cctxs))) } diff --git a/e2e/e2etests/test_eth_deposit_call.go b/e2e/e2etests/test_eth_deposit_call.go index 948b8975c2..65fc56bc9f 100644 --- a/e2e/e2etests/test_eth_deposit_call.go +++ b/e2e/e2etests/test_eth_deposit_call.go @@ -79,7 +79,13 @@ func TestEtherDepositAndCall(r *runner.E2ERunner, args []string) { panic(err) } if bar.Cmp(value) != 0 { - panic(fmt.Sprintf("cross-chain call failed bar value %s should be equal to amount %s", bar.String(), value.String())) + panic( + fmt.Sprintf( + "cross-chain call failed bar value %s should be equal to amount %s", + bar.String(), + value.String(), + ), + ) } r.Logger.Info("Cross-chain call succeeded") @@ -127,6 +133,8 @@ func TestEtherDepositAndCall(r *runner.E2ERunner, args []string) { // check the status message contains revert error hash in case of revert // 0xbfb4ebcf is the hash of "Foo()" if !strings.Contains(cctx.CctxStatus.StatusMessage, "0xbfb4ebcf") { - panic(fmt.Sprintf("expected cctx status message to contain revert reason; got %s", cctx.CctxStatus.StatusMessage)) + panic( + fmt.Sprintf("expected cctx status message to contain revert reason; got %s", cctx.CctxStatus.StatusMessage), + ) } } diff --git a/e2e/e2etests/test_eth_deposit_refund.go b/e2e/e2etests/test_eth_deposit_refund.go index 487fd47f9e..b5b9fe8555 100644 --- a/e2e/e2etests/test_eth_deposit_refund.go +++ b/e2e/e2etests/test_eth_deposit_refund.go @@ -103,7 +103,13 @@ func TestEtherDepositAndCallRefund(r *runner.E2ERunner, args []string) { // we check that the value is still greater than 0 if tx.Value().Cmp(value) != -1 || tx.Value().Cmp(big.NewInt(0)) != 1 { printTxInfo() - panic(fmt.Sprintf("expected tx value %s; should be non-null and lower than %s", tx.Value().String(), value.String())) + panic( + fmt.Sprintf( + "expected tx value %s; should be non-null and lower than %s", + tx.Value().String(), + value.String(), + ), + ) } r.Logger.Info("REVERT tx receipt: %d", receipt.Status) diff --git a/e2e/e2etests/test_message_passing_evm_to_zevm.go b/e2e/e2etests/test_message_passing_evm_to_zevm.go index 33e8c0c681..75392d9e8a 100644 --- a/e2e/e2etests/test_message_passing_evm_to_zevm.go +++ b/e2e/e2etests/test_message_passing_evm_to_zevm.go @@ -76,7 +76,10 @@ func TestMessagePassingEVMtoZEVM(r *runner.E2ERunner, args []string) { r.Logger.Info(fmt.Sprintf("🔄 Cctx mined for contract call chain zevm %s", cctx.Index)) // On finalization the Fungible module calls the onReceive function which in turn calls the onZetaMessage function on the destination contract - receipt, err = r.ZEVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.ZEVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go b/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go index 1c6a5ec699..d284b817e6 100644 --- a/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go +++ b/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go @@ -76,7 +76,10 @@ func TestMessagePassingEVMtoZEVMRevert(r *runner.E2ERunner, args []string) { } // On finalization the Tss address calls the onRevert function which in turn calls the onZetaRevert function on the sender contract - receipt, err = r.EVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.EVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } @@ -101,7 +104,9 @@ func TestMessagePassingEVMtoZEVMRevert(r *runner.E2ERunner, args []string) { panic(err) } if newBalanceZEVM.Cmp(previousBalanceZEVM) != 0 { - panic(fmt.Sprintf("expected new balance to be %s, got %s", previousBalanceZEVM.String(), newBalanceZEVM.String())) + panic( + fmt.Sprintf("expected new balance to be %s, got %s", previousBalanceZEVM.String(), newBalanceZEVM.String()), + ) } // Check ZETA balance on EVM TestDApp and check new balance is between previous balance and previous balance + amount diff --git a/e2e/e2etests/test_message_passing_external_chains.go b/e2e/e2etests/test_message_passing_external_chains.go index a589de2430..f9c36982cd 100644 --- a/e2e/e2etests/test_message_passing_external_chains.go +++ b/e2e/e2etests/test_message_passing_external_chains.go @@ -83,7 +83,10 @@ func TestMessagePassingExternalChains(r *runner.E2ERunner, args []string) { cctx.CctxStatus.StatusMessage, )) } - receipt, err = r.EVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.EVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_message_passing_external_chains_revert_fail.go b/e2e/e2etests/test_message_passing_external_chains_revert_fail.go index b4639e891c..4e21d58b77 100644 --- a/e2e/e2etests/test_message_passing_external_chains_revert_fail.go +++ b/e2e/e2etests/test_message_passing_external_chains_revert_fail.go @@ -44,9 +44,11 @@ func TestMessagePassingRevertFailExternalChains(r *runner.E2ERunner, args []stri DestinationChainId: chainID, DestinationAddress: r.DeployerAddress.Bytes(), DestinationGasLimit: big.NewInt(400_000), - Message: []byte("revert"), // non-empty message will cause revert, because the dest address is not a contract - ZetaValueAndGas: amount, - ZetaParams: nil, + Message: []byte( + "revert", + ), // non-empty message will cause revert, because the dest address is not a contract + ZetaValueAndGas: amount, + ZetaParams: nil, }) if err != nil { panic(err) @@ -70,7 +72,10 @@ func TestMessagePassingRevertFailExternalChains(r *runner.E2ERunner, args []stri // expect revert tx to fail cctx := utils.WaitCctxMinedByInTxHash(r.Ctx, receipt.TxHash.String(), r.CctxClient, r.Logger, r.CctxTimeout) - receipt, err = r.EVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.EVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_message_passing_zevm_to_evm.go b/e2e/e2etests/test_message_passing_zevm_to_evm.go index 49cff5c575..9896ff1de4 100644 --- a/e2e/e2etests/test_message_passing_zevm_to_evm.go +++ b/e2e/e2etests/test_message_passing_zevm_to_evm.go @@ -91,7 +91,10 @@ func TestMessagePassingZEVMtoEVM(r *runner.E2ERunner, args []string) { } // On finalization the Tss calls the onReceive function which in turn calls the onZetaMessage function on the destination contract. - receipt, err = r.EVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.EVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go b/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go index edef6977b0..e533d99bb1 100644 --- a/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go +++ b/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go @@ -91,7 +91,10 @@ func TestMessagePassingZEVMtoEVMRevert(r *runner.E2ERunner, args []string) { } // On finalization the Fungible module calls the onRevert function which in turn calls the onZetaRevert function on the sender contract - receipt, err = r.ZEVMClient.TransactionReceipt(r.Ctx, ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash)) + receipt, err = r.ZEVMClient.TransactionReceipt( + r.Ctx, + ethcommon.HexToHash(cctx.GetCurrentOutTxParam().OutboundTxHash), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_message_passing_zevm_to_evm_revert_fail.go b/e2e/e2etests/test_message_passing_zevm_to_evm_revert_fail.go index 0809f39b87..0bb3f1d0c7 100644 --- a/e2e/e2etests/test_message_passing_zevm_to_evm_revert_fail.go +++ b/e2e/e2etests/test_message_passing_zevm_to_evm_revert_fail.go @@ -120,6 +120,8 @@ func TestMessagePassingZEVMtoEVMRevertFail(r *runner.E2ERunner, args []string) { panic(err) } if newBalanceZEVM.Cmp(previousBalanceZEVM) != 0 { - panic(fmt.Sprintf("expected new balance to be %s, got %s", previousBalanceZEVM.String(), newBalanceZEVM.String())) + panic( + fmt.Sprintf("expected new balance to be %s, got %s", previousBalanceZEVM.String(), newBalanceZEVM.String()), + ) } } diff --git a/e2e/e2etests/test_migrate_chain_support.go b/e2e/e2etests/test_migrate_chain_support.go index 32ec65af2f..bdc15b0471 100644 --- a/e2e/e2etests/test_migrate_chain_support.go +++ b/e2e/e2etests/test_migrate_chain_support.go @@ -88,7 +88,10 @@ func TestMigrateChainSupport(r *runner.E2ERunner, _ []string) { } // set the gas token in the runner - ethZRC20Addr, err := newRunner.SystemContract.GasCoinZRC20ByChainId(&bind.CallOpts{}, big.NewInt(chainParams.ChainId)) + ethZRC20Addr, err := newRunner.SystemContract.GasCoinZRC20ByChainId( + &bind.CallOpts{}, + big.NewInt(chainParams.ChainId), + ) if err != nil { panic(err) } diff --git a/e2e/e2etests/test_rate_limiter.go b/e2e/e2etests/test_rate_limiter.go index f40c4d6b9f..3d8a018217 100644 --- a/e2e/e2etests/test_rate_limiter.go +++ b/e2e/e2etests/test_rate_limiter.go @@ -150,7 +150,13 @@ func createAndWaitWithdraws(r *runner.E2ERunner, withdrawType withdrawType, with // waitForWithdrawMined waits for a withdraw to be mined // we first wait to get the receipt // NOTE: this could be a more general function but we define it here for this test because we emit in the function logs specific to this test -func waitForWithdrawMined(ctx context.Context, r *runner.E2ERunner, tx *ethtypes.Transaction, index int, startTime time.Time) error { +func waitForWithdrawMined( + ctx context.Context, + r *runner.E2ERunner, + tx *ethtypes.Transaction, + index int, + startTime time.Time, +) error { // wait for the cctx to be mined cctx := utils.WaitCctxMinedByInTxHash(ctx, tx.Hash().Hex(), r.CctxClient, r.Logger, r.CctxTimeout) r.Logger.CCTX(*cctx, "withdraw") diff --git a/e2e/e2etests/test_stress_btc_withdraw.go b/e2e/e2etests/test_stress_btc_withdraw.go index f6eae14dd6..0399da29fc 100644 --- a/e2e/e2etests/test_stress_btc_withdraw.go +++ b/e2e/e2etests/test_stress_btc_withdraw.go @@ -17,7 +17,9 @@ import ( // TestStressBTCWithdraw tests the stressing withdraw of btc func TestStressBTCWithdraw(r *runner.E2ERunner, args []string) { if len(args) != 2 { - panic("TestStressBTCWithdraw requires exactly two arguments: the withdrawal amount and the number of withdrawals.") + panic( + "TestStressBTCWithdraw requires exactly two arguments: the withdrawal amount and the number of withdrawals.", + ) } withdrawalAmount, err := strconv.ParseFloat(args[0], 64) diff --git a/e2e/e2etests/test_stress_eth_withdraw.go b/e2e/e2etests/test_stress_eth_withdraw.go index a7feec2bd7..f20cf7fead 100644 --- a/e2e/e2etests/test_stress_eth_withdraw.go +++ b/e2e/e2etests/test_stress_eth_withdraw.go @@ -18,7 +18,9 @@ import ( // TestStressEtherWithdraw tests the stressing withdraw of ether func TestStressEtherWithdraw(r *runner.E2ERunner, args []string) { if len(args) != 2 { - panic("TestStressEtherWithdraw requires exactly two arguments: the withdrawal amount and the number of withdrawals.") + panic( + "TestStressEtherWithdraw requires exactly two arguments: the withdrawal amount and the number of withdrawals.", + ) } withdrawalAmount, ok := big.NewInt(0).SetString(args[0], 10) diff --git a/e2e/runner/accounting.go b/e2e/runner/accounting.go index 5edc8abc8a..31a53f9371 100644 --- a/e2e/runner/accounting.go +++ b/e2e/runner/accounting.go @@ -75,7 +75,11 @@ func (runner *E2ERunner) CheckBtcTSSBalance() error { ) } // #nosec G701 test - always in range - runner.Logger.Info("BTC: Balance (%d) >= ZRC20 TotalSupply (%d)", int64(btcBalance*1e8), zrc20Supply.Int64()-10000000) + runner.Logger.Info( + "BTC: Balance (%d) >= ZRC20 TotalSupply (%d)", + int64(btcBalance*1e8), + zrc20Supply.Int64()-10000000, + ) return nil } diff --git a/e2e/runner/bitcoin.go b/e2e/runner/bitcoin.go index 55d36c17b3..675999d071 100644 --- a/e2e/runner/bitcoin.go +++ b/e2e/runner/bitcoin.go @@ -33,7 +33,11 @@ func (runner *E2ERunner) DepositBTCWithAmount(amount float64) (txHash *chainhash runner.Logger.Print("⏳ depositing BTC into ZEVM") // fetch utxos - utxos, err := runner.BtcRPCClient.ListUnspentMinMaxAddresses(1, 9999999, []btcutil.Address{runner.BTCDeployerAddress}) + utxos, err := runner.BtcRPCClient.ListUnspentMinMaxAddresses( + 1, + 9999999, + []btcutil.Address{runner.BTCDeployerAddress}, + ) if err != nil { panic(err) } @@ -57,7 +61,13 @@ func (runner *E2ERunner) DepositBTCWithAmount(amount float64) (txHash *chainhash runner.Logger.Info("Now sending two txs to TSS address...") amount = amount + zetabitcoin.DefaultDepositorFee - txHash, err = runner.SendToTSSFromDeployerToDeposit(runner.BTCTSSAddress, amount, utxos, runner.BtcRPCClient, runner.BTCDeployerAddress) + txHash, err = runner.SendToTSSFromDeployerToDeposit( + runner.BTCTSSAddress, + amount, + utxos, + runner.BtcRPCClient, + runner.BTCDeployerAddress, + ) if err != nil { panic(err) } @@ -103,12 +113,24 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { // send two transactions to the TSS address amount1 := 1.1 + zetabitcoin.DefaultDepositorFee - txHash1, err := runner.SendToTSSFromDeployerToDeposit(runner.BTCTSSAddress, amount1, utxos[:2], btc, runner.BTCDeployerAddress) + txHash1, err := runner.SendToTSSFromDeployerToDeposit( + runner.BTCTSSAddress, + amount1, + utxos[:2], + btc, + runner.BTCDeployerAddress, + ) if err != nil { panic(err) } amount2 := 0.05 + zetabitcoin.DefaultDepositorFee - txHash2, err := runner.SendToTSSFromDeployerToDeposit(runner.BTCTSSAddress, amount2, utxos[2:4], btc, runner.BTCDeployerAddress) + txHash2, err := runner.SendToTSSFromDeployerToDeposit( + runner.BTCTSSAddress, + amount2, + utxos[2:4], + btc, + runner.BTCDeployerAddress, + ) if err != nil { panic(err) } @@ -129,7 +151,13 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { runner.Logger.Info("testing if the deposit into BTC ZRC20 is successful...") - cctx := utils.WaitCctxMinedByInTxHash(runner.Ctx, txHash2.String(), runner.CctxClient, runner.Logger, runner.CctxTimeout) + cctx := utils.WaitCctxMinedByInTxHash( + runner.Ctx, + txHash2.String(), + runner.CctxClient, + runner.Logger, + runner.CctxTimeout, + ) if cctx.CctxStatus.Status != crosschaintypes.CctxStatus_OutboundMined { panic(fmt.Sprintf( "expected mined status; got %s, message: %s", @@ -160,7 +188,14 @@ func (runner *E2ERunner) SendToTSSFromDeployerToDeposit( btc *rpcclient.Client, btcDeployerAddress *btcutil.AddressWitnessPubKeyHash, ) (*chainhash.Hash, error) { - return runner.SendToTSSFromDeployerWithMemo(to, amount, inputUTXOs, btc, runner.DeployerAddress.Bytes(), btcDeployerAddress) + return runner.SendToTSSFromDeployerWithMemo( + to, + amount, + inputUTXOs, + btc, + runner.DeployerAddress.Bytes(), + btcDeployerAddress, + ) } func (runner *E2ERunner) SendToTSSFromDeployerWithMemo( @@ -384,7 +419,11 @@ func (runner *E2ERunner) ProveBTCTransaction(txHash *chainhash.Hash) { BlockHash: hash.CloneBytes(), }) if err != nil { - runner.Logger.Info("waiting for block header to show up in observer... current hash %s; err %s", hash.String(), err.Error()) + runner.Logger.Info( + "waiting for block header to show up in observer... current hash %s; err %s", + hash.String(), + err.Error(), + ) } if err == nil { break diff --git a/e2e/runner/e2etest.go b/e2e/runner/e2etest.go index 499d45144d..c6e49bdc9d 100644 --- a/e2e/runner/e2etest.go +++ b/e2e/runner/e2etest.go @@ -73,7 +73,10 @@ func (runner *E2ERunner) GetE2ETestsToRunByName(availableTests []E2ETest, testNa } // GetE2ETestsToRunByConfig prepares a list of E2ETests to run based on provided test names and their corresponding arguments -func (runner *E2ERunner) GetE2ETestsToRunByConfig(availableTests []E2ETest, testConfigs []E2ETestRunConfig) ([]E2ETest, error) { +func (runner *E2ERunner) GetE2ETestsToRunByConfig( + availableTests []E2ETest, + testConfigs []E2ETestRunConfig, +) ([]E2ETest, error) { tests := []E2ETest{} for _, testSpec := range testConfigs { e2eTest, found := findE2ETestByName(availableTests, testSpec.Name) diff --git a/e2e/runner/evm.go b/e2e/runner/evm.go index 1cb2826b73..18464850d2 100644 --- a/e2e/runner/evm.go +++ b/e2e/runner/evm.go @@ -78,7 +78,11 @@ func (runner *E2ERunner) DepositERC20() ethcommon.Hash { return runner.DepositERC20WithAmountAndMessage(runner.DeployerAddress, big.NewInt(1e18), []byte{}) } -func (runner *E2ERunner) DepositERC20WithAmountAndMessage(to ethcommon.Address, amount *big.Int, msg []byte) ethcommon.Hash { +func (runner *E2ERunner) DepositERC20WithAmountAndMessage( + to ethcommon.Address, + amount *big.Int, + msg []byte, +) ethcommon.Hash { // reset allowance, necessary for USDT tx, err := runner.ERC20.Approve(runner.EVMAuth, runner.ERC20CustodyAddr, big.NewInt(0)) if err != nil { diff --git a/e2e/runner/setup_evm.go b/e2e/runner/setup_evm.go index 01188c759a..b9abf827ef 100644 --- a/e2e/runner/setup_evm.go +++ b/e2e/runner/setup_evm.go @@ -62,7 +62,11 @@ func (runner *E2ERunner) SetupEVM(contractsDeployed bool, whitelistERC20 bool) { // donate to the TSS address to avoid account errors because deploying gas token ZRC20 will automatically mint // gas token on ZetaChain to initialize the pool - txDonation, err := runner.SendEther(runner.TSSAddress, big.NewInt(101000000000000000), []byte(constant.DonationMessage)) + txDonation, err := runner.SendEther( + runner.TSSAddress, + big.NewInt(101000000000000000), + []byte(constant.DonationMessage), + ) if err != nil { panic(err) } @@ -98,7 +102,11 @@ func (runner *E2ERunner) SetupEVM(contractsDeployed bool, whitelistERC20 bool) { runner.ConnectorEthAddr = connectorEthAddr conf.Contracts.EVM.ConnectorEthAddr = connectorEthAddr.String() - runner.Logger.Info("ZetaConnectorEth contract address: %s, tx hash: %s", connectorEthAddr.Hex(), txConnector.Hash().Hex()) + runner.Logger.Info( + "ZetaConnectorEth contract address: %s, tx hash: %s", + connectorEthAddr.Hex(), + txConnector.Hash().Hex(), + ) runner.Logger.Info("Deploying ERC20Custody contract") erc20CustodyAddr, txCustody, ERC20Custody, err := erc20custody.DeployERC20Custody( @@ -127,7 +135,12 @@ func (runner *E2ERunner) SetupEVM(contractsDeployed bool, whitelistERC20 bool) { runner.Logger.Info("ERC20 contract address: %s, tx hash: %s", erc20Addr.Hex(), txERC20.Hash().Hex()) // deploy TestDApp contract - appAddr, txApp, _, err := testdapp.DeployTestDApp(runner.EVMAuth, runner.EVMClient, runner.ConnectorEthAddr, runner.ZetaEthAddr) + appAddr, txApp, _, err := testdapp.DeployTestDApp( + runner.EVMAuth, + runner.EVMClient, + runner.ConnectorEthAddr, + runner.ZetaEthAddr, + ) if err != nil { panic(err) } diff --git a/e2e/runner/setup_zeta.go b/e2e/runner/setup_zeta.go index b78f9b3e02..422595f7b2 100644 --- a/e2e/runner/setup_zeta.go +++ b/e2e/runner/setup_zeta.go @@ -143,7 +143,12 @@ func (runner *E2ERunner) SetZEVMContracts() { runner.SetupBTCZRC20() // deploy TestDApp contract on zEVM - appAddr, txApp, _, err := testdapp.DeployTestDApp(runner.ZEVMAuth, runner.ZEVMClient, runner.ConnectorZEVMAddr, runner.WZetaAddr) + appAddr, txApp, _, err := testdapp.DeployTestDApp( + runner.ZEVMAuth, + runner.ZEVMClient, + runner.ConnectorZEVMAddr, + runner.WZetaAddr, + ) if err != nil { panic(err) } @@ -166,14 +171,26 @@ func (runner *E2ERunner) SetZEVMContracts() { panic(err) } - receipt := e2eutils.MustWaitForTxReceipt(runner.Ctx, runner.ZEVMClient, txZEVMSwapApp, runner.Logger, runner.ReceiptTimeout) + receipt := e2eutils.MustWaitForTxReceipt( + runner.Ctx, + runner.ZEVMClient, + txZEVMSwapApp, + runner.Logger, + runner.ReceiptTimeout, + ) if receipt.Status != 1 { panic("ZEVMSwapApp deployment failed") } runner.ZEVMSwapAppAddr = zevmSwapAppAddr runner.ZEVMSwapApp = zevmSwapApp - receipt = e2eutils.MustWaitForTxReceipt(runner.Ctx, runner.ZEVMClient, txContextApp, runner.Logger, runner.ReceiptTimeout) + receipt = e2eutils.MustWaitForTxReceipt( + runner.Ctx, + runner.ZEVMClient, + txContextApp, + runner.Logger, + runner.ReceiptTimeout, + ) if receipt.Status != 1 { panic("ContextApp deployment failed") } @@ -184,7 +201,10 @@ func (runner *E2ERunner) SetZEVMContracts() { // SetupETHZRC20 sets up the ETH ZRC20 in the runner from the values queried from the chain func (runner *E2ERunner) SetupETHZRC20() { - ethZRC20Addr, err := runner.SystemContract.GasCoinZRC20ByChainId(&bind.CallOpts{}, big.NewInt(chains.GoerliLocalnetChain.ChainId)) + ethZRC20Addr, err := runner.SystemContract.GasCoinZRC20ByChainId( + &bind.CallOpts{}, + big.NewInt(chains.GoerliLocalnetChain.ChainId), + ) if err != nil { panic(err) } @@ -201,7 +221,10 @@ func (runner *E2ERunner) SetupETHZRC20() { // SetupBTCZRC20 sets up the BTC ZRC20 in the runner from the values queried from the chain func (runner *E2ERunner) SetupBTCZRC20() { - BTCZRC20Addr, err := runner.SystemContract.GasCoinZRC20ByChainId(&bind.CallOpts{}, big.NewInt(chains.BtcRegtestChain.ChainId)) + BTCZRC20Addr, err := runner.SystemContract.GasCoinZRC20ByChainId( + &bind.CallOpts{}, + big.NewInt(chains.BtcRegtestChain.ChainId), + ) if err != nil { panic(err) } diff --git a/e2e/runner/zeta.go b/e2e/runner/zeta.go index 20c31ff043..0e2bbb220f 100644 --- a/e2e/runner/zeta.go +++ b/e2e/runner/zeta.go @@ -32,7 +32,13 @@ func (runner *E2ERunner) WaitForMinedCCTX(txHash ethcommon.Hash) { }() runner.Lock() - cctx := utils.WaitCctxMinedByInTxHash(runner.Ctx, txHash.Hex(), runner.CctxClient, runner.Logger, runner.CctxTimeout) + cctx := utils.WaitCctxMinedByInTxHash( + runner.Ctx, + txHash.Hex(), + runner.CctxClient, + runner.Logger, + runner.CctxTimeout, + ) if cctx.CctxStatus.Status != types.CctxStatus_OutboundMined { panic(fmt.Sprintf("expected cctx status to be mined; got %s, message: %s", cctx.CctxStatus.Status.String(), diff --git a/e2e/txserver/zeta_tx_server.go b/e2e/txserver/zeta_tx_server.go index e5bf2d3339..1efb3f6aae 100644 --- a/e2e/txserver/zeta_tx_server.go +++ b/e2e/txserver/zeta_tx_server.go @@ -272,7 +272,9 @@ func (zts ZetaTxServer) EnableHeaderVerification(account string, chainIDList []i // DeploySystemContractsAndZRC20 deploys the system contracts and ZRC20 contracts // returns the addresses of uniswap factory, router and erc20 zrc20 -func (zts ZetaTxServer) DeploySystemContractsAndZRC20(account, erc20Addr string) (string, string, string, string, string, error) { +func (zts ZetaTxServer) DeploySystemContractsAndZRC20( + account, erc20Addr string, +) (string, string, string, string, string, error) { // retrieve account acc, err := zts.clientCtx.Keyring.Key(account) if err != nil { @@ -291,7 +293,11 @@ func (zts ZetaTxServer) DeploySystemContractsAndZRC20(account, erc20Addr string) systemContractAddress, err := FetchAttributeFromTxResponse(res, "system_contract") if err != nil { - return "", "", "", "", "", fmt.Errorf("failed to fetch system contract address: %s; rawlog %s", err.Error(), res.RawLog) + return "", "", "", "", "", fmt.Errorf( + "failed to fetch system contract address: %s; rawlog %s", + err.Error(), + res.RawLog, + ) } // get system contract @@ -313,13 +319,21 @@ func (zts ZetaTxServer) DeploySystemContractsAndZRC20(account, erc20Addr string) // get zevm connector address zevmConnectorAddr, err := FetchAttributeFromTxResponse(res, "connector_zevm") if err != nil { - return "", "", "", "", "", fmt.Errorf("failed to fetch zevm connector address: %s, txResponse: %s", err.Error(), res.String()) + return "", "", "", "", "", fmt.Errorf( + "failed to fetch zevm connector address: %s, txResponse: %s", + err.Error(), + res.String(), + ) } // get wzeta address wzetaAddr, err := FetchAttributeFromTxResponse(res, "wzeta") if err != nil { - return "", "", "", "", "", fmt.Errorf("failed to fetch wzeta address: %s, txResponse: %s", err.Error(), res.String()) + return "", "", "", "", "", fmt.Errorf( + "failed to fetch wzeta address: %s, txResponse: %s", + err.Error(), + res.String(), + ) } // deploy eth zrc20 diff --git a/pkg/chains/address_taproot_test.go b/pkg/chains/address_taproot_test.go index d29e91a67d..08de704937 100644 --- a/pkg/chains/address_taproot_test.go +++ b/pkg/chains/address_taproot_test.go @@ -70,6 +70,10 @@ func TestAddressTaproot(t *testing.T) { addrStr := "bc1p6pls9gpm24g8ntl37pajpjtuhd3y08hs5rnf9a4n0wq595hwdh9suw7m2h" addr, err := DecodeTaprootAddress(addrStr) require.Nil(t, err) - require.Equal(t, "d07f02a03b555079aff1f07b20c97cbb62479ef0a0e692f6b37b8142d2ee6dcb", hex.EncodeToString(addr.ScriptAddress())) + require.Equal( + t, + "d07f02a03b555079aff1f07b20c97cbb62479ef0a0e692f6b37b8142d2ee6dcb", + hex.EncodeToString(addr.ScriptAddress()), + ) } } diff --git a/pkg/chains/address_test.go b/pkg/chains/address_test.go index c4535e07db..cd7bdf53ec 100644 --- a/pkg/chains/address_test.go +++ b/pkg/chains/address_test.go @@ -22,11 +22,21 @@ func TestAddress(t *testing.T) { require.True(t, addr.IsEmpty()) addr = NewAddress("0x90f2b1ae50e6018230e90a33f98c7844a0ab635a") - require.EqualValuesf(t, "0x90f2b1ae50e6018230e90a33f98c7844a0ab635a", addr.String(), "address string should be equal") + require.EqualValuesf( + t, + "0x90f2b1ae50e6018230e90a33f98c7844a0ab635a", + addr.String(), + "address string should be equal", + ) require.False(t, addr.IsEmpty()) addr2 := NewAddress("0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5") - require.EqualValuesf(t, "0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", addr2.String(), "address string should be equal") + require.EqualValuesf( + t, + "0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", + addr2.String(), + "address string should be equal", + ) require.False(t, addr.IsEmpty()) require.False(t, addr.Equals(addr2)) @@ -74,11 +84,17 @@ func TestDecodeBtcAddress(t *testing.T) { }) t.Run("taproot address with correct params", func(t *testing.T) { - _, err := DecodeBtcAddress("bc1p4ur084x8y63mj5hj7eydscuc4awals7ly749x8vhyquc0twcmvhquspa5c", BtcMainnetChain.ChainId) + _, err := DecodeBtcAddress( + "bc1p4ur084x8y63mj5hj7eydscuc4awals7ly749x8vhyquc0twcmvhquspa5c", + BtcMainnetChain.ChainId, + ) require.NoError(t, err) }) t.Run("taproot address with incorrect params", func(t *testing.T) { - _, err := DecodeBtcAddress("bc1p4ur084x8y63mj5hj7eydscuc4awals7ly749x8vhyquc0twcmvhquspa5c", BtcTestNetChain.ChainId) + _, err := DecodeBtcAddress( + "bc1p4ur084x8y63mj5hj7eydscuc4awals7ly749x8vhyquc0twcmvhquspa5c", + BtcTestNetChain.ChainId, + ) require.ErrorContains(t, err, "not for network testnet") }) } diff --git a/pkg/chains/chains_test.go b/pkg/chains/chains_test.go index e5167948b3..ba3452b6be 100644 --- a/pkg/chains/chains_test.go +++ b/pkg/chains/chains_test.go @@ -176,8 +176,24 @@ func TestChainListByNetworkType(t *testing.T) { networkType NetworkType expected []Chain }{ - {"MainnetChainList", NetworkType_mainnet, []Chain{ZetaChainMainnet, BtcMainnetChain, BscMainnetChain, EthChain, PolygonChain}}, - {"TestnetChainList", NetworkType_testnet, []Chain{ZetaTestnetChain, BtcTestNetChain, MumbaiChain, AmoyChain, BscTestnetChain, GoerliChain, SepoliaChain}}, + { + "MainnetChainList", + NetworkType_mainnet, + []Chain{ZetaChainMainnet, BtcMainnetChain, BscMainnetChain, EthChain, PolygonChain}, + }, + { + "TestnetChainList", + NetworkType_testnet, + []Chain{ + ZetaTestnetChain, + BtcTestNetChain, + MumbaiChain, + AmoyChain, + BscTestnetChain, + GoerliChain, + SepoliaChain, + }, + }, {"PrivnetChainList", NetworkType_privnet, []Chain{ZetaPrivnetChain, BtcRegtestChain, GoerliLocalnetChain}}, } @@ -233,8 +249,46 @@ func TestChainListFunctions(t *testing.T) { function func() []*Chain expected []Chain }{ - {"DefaultChainsList", DefaultChainsList, []Chain{BtcMainnetChain, BscMainnetChain, EthChain, BtcTestNetChain, MumbaiChain, AmoyChain, BscTestnetChain, GoerliChain, SepoliaChain, BtcRegtestChain, GoerliLocalnetChain, ZetaChainMainnet, ZetaTestnetChain, ZetaMocknetChain, ZetaPrivnetChain, PolygonChain}}, - {"ExternalChainList", ExternalChainList, []Chain{BtcMainnetChain, BscMainnetChain, EthChain, BtcTestNetChain, MumbaiChain, AmoyChain, BscTestnetChain, GoerliChain, SepoliaChain, BtcRegtestChain, GoerliLocalnetChain, PolygonChain}}, + { + "DefaultChainsList", + DefaultChainsList, + []Chain{ + BtcMainnetChain, + BscMainnetChain, + EthChain, + BtcTestNetChain, + MumbaiChain, + AmoyChain, + BscTestnetChain, + GoerliChain, + SepoliaChain, + BtcRegtestChain, + GoerliLocalnetChain, + ZetaChainMainnet, + ZetaTestnetChain, + ZetaMocknetChain, + ZetaPrivnetChain, + PolygonChain, + }, + }, + { + "ExternalChainList", + ExternalChainList, + []Chain{ + BtcMainnetChain, + BscMainnetChain, + EthChain, + BtcTestNetChain, + MumbaiChain, + AmoyChain, + BscTestnetChain, + GoerliChain, + SepoliaChain, + BtcRegtestChain, + GoerliLocalnetChain, + PolygonChain, + }, + }, } for _, lt := range listTests { diff --git a/pkg/chains/utils_test.go b/pkg/chains/utils_test.go index ca1f4722ef..cb025e025b 100644 --- a/pkg/chains/utils_test.go +++ b/pkg/chains/utils_test.go @@ -77,7 +77,13 @@ func TestStringToHash(t *testing.T) { expect []byte wantErr bool }{ - {"evm chain", evmChainId, "95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", ethcommon.HexToHash("95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5").Bytes(), false}, + { + "evm chain", + evmChainId, + "95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", + ethcommon.HexToHash("95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5").Bytes(), + false, + }, {"btc chain", btcChainId, expectedBtcHash.String(), expectedBtcHash.CloneBytes(), false}, {"btc chain invalid hash", btcChainId, wrontBtcHash, nil, true}, {"unknown chain", unknownChainId, "", nil, true}, @@ -106,7 +112,13 @@ func TestParseAddressAndData(t *testing.T) { expectData []byte wantErr bool }{ - {"valid msg", "95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", ethcommon.HexToAddress("95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5"), []byte{}, false}, + { + "valid msg", + "95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5", + ethcommon.HexToAddress("95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5"), + []byte{}, + false, + }, {"empty msg", "", ethcommon.Address{}, nil, false}, {"invalid hex", "invalidHex", ethcommon.Address{}, nil, true}, {"short msg", "1a2b3c4d5e6f708192a3b4c5d6e7f808", ethcommon.Address{}, expectedShortMsgResult, false}, diff --git a/pkg/crypto/tss.go b/pkg/crypto/tss.go index fc3c36ed8a..8ddffec855 100644 --- a/pkg/crypto/tss.go +++ b/pkg/crypto/tss.go @@ -35,7 +35,10 @@ func GetTssAddrBTC(tssPubkey string, bitcoinParams *chaincfg.Params) (string, er return addrWPKH.EncodeAddress(), nil } -func getKeyAddrBTCWitnessPubkeyHash(tssPubkey string, bitcoinParams *chaincfg.Params) (*btcutil.AddressWitnessPubKeyHash, error) { +func getKeyAddrBTCWitnessPubkeyHash( + tssPubkey string, + bitcoinParams *chaincfg.Params, +) (*btcutil.AddressWitnessPubKeyHash, error) { pubk, err := cosmos.GetPubKeyFromBech32(cosmos.Bech32PubKeyTypeAccPub, tssPubkey) if err != nil { return nil, err diff --git a/pkg/proofs/proof_test.go b/pkg/proofs/proof_test.go index 44f28535cb..6a54f6543d 100644 --- a/pkg/proofs/proof_test.go +++ b/pkg/proofs/proof_test.go @@ -136,11 +136,26 @@ func BitcoinMerkleProofLiveTest(t *testing.T) { // Validate block validateBitcoinBlock(t, header, headerBytes, blockVerbose, "", "", 0) - fmt.Printf("Verification succeeded for block: %d hash: %s root: %s target: %064x transactions: %d\n", height, blockHash, header.MerkleRoot, target, len(blockVerbose.Tx)) + fmt.Printf( + "Verification succeeded for block: %d hash: %s root: %s target: %064x transactions: %d\n", + height, + blockHash, + header.MerkleRoot, + target, + len(blockVerbose.Tx), + ) } } -func validateBitcoinBlock(t *testing.T, _ *wire.BlockHeader, headerBytes []byte, blockVerbose *btcjson.GetBlockVerboseTxResult, outTxid string, tssAddress string, nonce uint64) { +func validateBitcoinBlock( + t *testing.T, + _ *wire.BlockHeader, + headerBytes []byte, + blockVerbose *btcjson.GetBlockVerboseTxResult, + outTxid string, + tssAddress string, + nonce uint64, +) { // Deserialization should work for each transaction in the block txns := []*btcutil.Tx{} txBodies := [][]byte{} diff --git a/rpc/backend/account_info.go b/rpc/backend/account_info.go index b6175b5cd1..e1e2c4882b 100644 --- a/rpc/backend/account_info.go +++ b/rpc/backend/account_info.go @@ -52,7 +52,11 @@ func (b *Backend) GetCode(address common.Address, blockNrOrHash rpctypes.BlockNu } // GetProof returns an account object with proof and any storage proofs -func (b *Backend) GetProof(address common.Address, storageKeys []string, blockNrOrHash rpctypes.BlockNumberOrHash) (*rpctypes.AccountResult, error) { +func (b *Backend) GetProof( + address common.Address, + storageKeys []string, + blockNrOrHash rpctypes.BlockNumberOrHash, +) (*rpctypes.AccountResult, error) { blockNum, err := b.BlockNumberFromTendermint(blockNrOrHash) if err != nil { return nil, err @@ -88,7 +92,11 @@ func (b *Backend) GetProof(address common.Address, storageKeys []string, blockNr for i, key := range storageKeys { hexKey := common.HexToHash(key) - valueBz, proof, err := b.queryClient.GetProof(clientCtx, evmtypes.StoreKey, evmtypes.StateKey(address, hexKey.Bytes())) + valueBz, proof, err := b.queryClient.GetProof( + clientCtx, + evmtypes.StoreKey, + evmtypes.StateKey(address, hexKey.Bytes()), + ) if err != nil { return nil, err } @@ -134,7 +142,11 @@ func (b *Backend) GetProof(address common.Address, storageKeys []string, blockNr } // GetStorageAt returns the contract storage at the given address, block number, and key. -func (b *Backend) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) { +func (b *Backend) GetStorageAt( + address common.Address, + key string, + blockNrOrHash rpctypes.BlockNumberOrHash, +) (hexutil.Bytes, error) { blockNum, err := b.BlockNumberFromTendermint(blockNrOrHash) if err != nil { return nil, err diff --git a/rpc/backend/backend.go b/rpc/backend/backend.go index 1719993abb..5e5c6dd24d 100644 --- a/rpc/backend/backend.go +++ b/rpc/backend/backend.go @@ -64,7 +64,12 @@ type EVMBackend interface { SetGasPrice(gasPrice hexutil.Big) bool ImportRawKey(privkey, password string) (common.Address, error) ListAccounts() ([]common.Address, error) - NewMnemonic(uid string, language keyring.Language, hdPath, bip39Passphrase string, algo keyring.SignatureAlgo) (*keyring.Record, error) + NewMnemonic( + uid string, + language keyring.Language, + hdPath, bip39Passphrase string, + algo keyring.SignatureAlgo, + ) (*keyring.Record, error) UnprotectedAllowed() bool RPCGasCap() uint64 // global gas cap for eth_call over rpc: DoS protection RPCEVMTimeout() time.Duration // global timeout for eth_call over rpc: DoS protection @@ -87,19 +92,33 @@ type EVMBackend interface { TendermintBlockByHash(blockHash common.Hash) (*tmrpctypes.ResultBlock, error) BlockNumberFromTendermint(blockNrOrHash rpctypes.BlockNumberOrHash) (rpctypes.BlockNumber, error) BlockNumberFromTendermintByHash(blockHash common.Hash) (*big.Int, error) - EthMsgsFromTendermintBlock(block *tmrpctypes.ResultBlock, blockRes *tmrpctypes.ResultBlockResults) ([]*evmtypes.MsgEthereumTx, []*rpctypes.TxResultAdditionalFields) + EthMsgsFromTendermintBlock( + block *tmrpctypes.ResultBlock, + blockRes *tmrpctypes.ResultBlockResults, + ) ([]*evmtypes.MsgEthereumTx, []*rpctypes.TxResultAdditionalFields) BlockBloom(blockRes *tmrpctypes.ResultBlockResults) (ethtypes.Bloom, error) HeaderByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Header, error) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) - RPCBlockFromTendermintBlock(resBlock *tmrpctypes.ResultBlock, blockRes *tmrpctypes.ResultBlockResults, fullTx bool) (map[string]interface{}, error) + RPCBlockFromTendermintBlock( + resBlock *tmrpctypes.ResultBlock, + blockRes *tmrpctypes.ResultBlockResults, + fullTx bool, + ) (map[string]interface{}, error) EthBlockByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Block, error) - EthBlockFromTendermintBlock(resBlock *tmrpctypes.ResultBlock, blockRes *tmrpctypes.ResultBlockResults) (*ethtypes.Block, error) + EthBlockFromTendermintBlock( + resBlock *tmrpctypes.ResultBlock, + blockRes *tmrpctypes.ResultBlockResults, + ) (*ethtypes.Block, error) // Account Info GetCode(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) GetBalance(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Big, error) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) - GetProof(address common.Address, storageKeys []string, blockNrOrHash rpctypes.BlockNumberOrHash) (*rpctypes.AccountResult, error) + GetProof( + address common.Address, + storageKeys []string, + blockNrOrHash rpctypes.BlockNumberOrHash, + ) (*rpctypes.AccountResult, error) GetTransactionCount(address common.Address, blockNum rpctypes.BlockNumber) (*hexutil.Uint64, error) // Chain Info @@ -110,7 +129,11 @@ type EVMBackend interface { CurrentHeader() *ethtypes.Header PendingTransactions() ([]*sdk.Tx, error) GetCoinbase() (sdk.AccAddress, error) - FeeHistory(blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*rpctypes.FeeHistoryResult, error) + FeeHistory( + blockCount rpc.DecimalOrHex, + lastBlock rpc.BlockNumber, + rewardPercentiles []float64, + ) (*rpctypes.FeeHistoryResult, error) SuggestGasTipCap(baseFee *big.Int) (*big.Int, error) // Tx Info @@ -120,7 +143,10 @@ type EVMBackend interface { GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) - GetTransactionByBlockNumberAndIndex(blockNum rpctypes.BlockNumber, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) + GetTransactionByBlockNumberAndIndex( + blockNum rpctypes.BlockNumber, + idx hexutil.Uint, + ) (*rpctypes.RPCTransaction, error) // Send Transaction Resend(args evmtypes.TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) @@ -137,7 +163,11 @@ type EVMBackend interface { // Tracing TraceTransaction(hash common.Hash, config *evmtypes.TraceConfig) (interface{}, error) - TraceBlock(height rpctypes.BlockNumber, config *evmtypes.TraceConfig, block *tmrpctypes.ResultBlock) ([]*evmtypes.TxTraceResult, error) + TraceBlock( + height rpctypes.BlockNumber, + config *evmtypes.TraceConfig, + block *tmrpctypes.ResultBlock, + ) ([]*evmtypes.TxTraceResult, error) } var _ BackendI = (*Backend)(nil) diff --git a/rpc/backend/blocks.go b/rpc/backend/blocks.go index b2a5870a16..6904858829 100644 --- a/rpc/backend/blocks.go +++ b/rpc/backend/blocks.go @@ -51,7 +51,12 @@ func (b *Backend) BlockNumber() (hexutil.Uint64, error) { blockHeightHeader := header.Get(grpctypes.GRPCBlockHeightHeader) if headerLen := len(blockHeightHeader); headerLen != 1 { - return 0, fmt.Errorf("unexpected '%s' gRPC header length; got %d, expected: %d", grpctypes.GRPCBlockHeightHeader, headerLen, 1) + return 0, fmt.Errorf( + "unexpected '%s' gRPC header length; got %d, expected: %d", + grpctypes.GRPCBlockHeightHeader, + headerLen, + 1, + ) } height, err := strconv.ParseUint(blockHeightHeader[0], 10, 64) @@ -106,7 +111,13 @@ func (b *Backend) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]inte blockRes, err := b.TendermintBlockResultByNumber(&resBlock.Block.Height) if err != nil { - b.logger.Debug("failed to fetch block result from Tendermint", "block-hash", hash.String(), "error", err.Error()) + b.logger.Debug( + "failed to fetch block result from Tendermint", + "block-hash", + hash.String(), + "error", + err.Error(), + ) return nil, nil } @@ -332,7 +343,13 @@ func (b *Backend) HeaderByNumber(blockNum rpctypes.BlockNumber) (*ethtypes.Heade baseFee, err := b.BaseFee(blockRes) if err != nil { // handle the error for pruned node. - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", resBlock.Block.Height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + resBlock.Block.Height, + "error", + err, + ) } ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header, bloom, baseFee) @@ -362,7 +379,13 @@ func (b *Backend) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) baseFee, err := b.BaseFee(blockRes) if err != nil { // handle the error for pruned node. - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", resBlock.Block.Height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + resBlock.Block.Height, + "error", + err, + ) } ethHeader := rpctypes.EthHeaderFromTendermint(resBlock.Block.Header, bloom, baseFee) @@ -398,7 +421,13 @@ func (b *Backend) RPCBlockFromTendermintBlock( baseFee, err := b.BaseFee(blockRes) if err != nil { // handle the error for pruned node. - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", block.Height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + block.Height, + "error", + err, + ) } msgs, txsAdditional := b.EthMsgsFromTendermintBlock(resBlock, blockRes) @@ -523,7 +552,13 @@ func (b *Backend) EthBlockFromTendermintBlock( baseFee, err := b.BaseFee(blockRes) if err != nil { // handle error for pruned node and log - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + height, + "error", + err, + ) } ethHeader := rpctypes.EthHeaderFromTendermint(block.Header, bloom, baseFee) diff --git a/rpc/backend/call_tx.go b/rpc/backend/call_tx.go index fd757d2f04..8da6e1bb28 100644 --- a/rpc/backend/call_tx.go +++ b/rpc/backend/call_tx.go @@ -39,7 +39,11 @@ import ( // Resend accepts an existing transaction and a new gas price and limit. It will remove // the given transaction from the pool and reinsert it with the new gas price and limit. -func (b *Backend) Resend(args evmtypes.TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { +func (b *Backend) Resend( + args evmtypes.TransactionArgs, + gasPrice *hexutil.Big, + gasLimit *hexutil.Uint64, +) (common.Hash, error) { if args.Nonce == nil { return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") } @@ -210,7 +214,11 @@ func (b *Backend) SetTxDefaults(args evmtypes.TransactionArgs) (evmtypes.Transac } if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 { - return args, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas) + return args, fmt.Errorf( + "maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", + args.MaxFeePerGas, + args.MaxPriorityFeePerGas, + ) } } else { if args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil { @@ -252,7 +260,9 @@ func (b *Backend) SetTxDefaults(args evmtypes.TransactionArgs) (evmtypes.Transac } if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) { - return args, errors.New("both 'data' and 'input' are set and not equal. Please use 'input' to pass transaction call data") + return args, errors.New( + "both 'data' and 'input' are set and not equal. Please use 'input' to pass transaction call data", + ) } if args.To == nil { @@ -308,7 +318,10 @@ func (b *Backend) SetTxDefaults(args evmtypes.TransactionArgs) (evmtypes.Transac } // EstimateGas returns an estimate of gas usage for the given smart contract call. -func (b *Backend) EstimateGas(args evmtypes.TransactionArgs, blockNrOptional *rpctypes.BlockNumber) (hexutil.Uint64, error) { +func (b *Backend) EstimateGas( + args evmtypes.TransactionArgs, + blockNrOptional *rpctypes.BlockNumber, +) (hexutil.Uint64, error) { blockNr := rpctypes.EthPendingBlockNumber if blockNrOptional != nil { blockNr = *blockNrOptional diff --git a/rpc/backend/chain_info.go b/rpc/backend/chain_info.go index f0e2e12b08..744a71088d 100644 --- a/rpc/backend/chain_info.go +++ b/rpc/backend/chain_info.go @@ -297,7 +297,9 @@ func (b *Backend) SuggestGasTipCap(baseFee *big.Int) (*big.Int, error) { // = BaseFee * (ElasticityMultiplier - 1) / Denominator // ``` // #nosec G701 range checked - maxDelta := baseFee.Int64() * (int64(params.Params.ElasticityMultiplier) - 1) / int64(params.Params.BaseFeeChangeDenominator) + maxDelta := baseFee.Int64() * (int64(params.Params.ElasticityMultiplier) - 1) / int64( + params.Params.BaseFeeChangeDenominator, + ) if maxDelta < 0 { // impossible if the parameter validation passed. maxDelta = 0 diff --git a/rpc/backend/sign_tx.go b/rpc/backend/sign_tx.go index 0c16da0c34..df67e1f4a4 100644 --- a/rpc/backend/sign_tx.go +++ b/rpc/backend/sign_tx.go @@ -39,11 +39,19 @@ func (b *Backend) SendTransaction(args evmtypes.TransactionArgs) (common.Hash, e _, err := b.clientCtx.Keyring.KeyByAddress(sdk.AccAddress(args.GetFrom().Bytes())) if err != nil { b.logger.Error("failed to find key in keyring", "address", args.GetFrom(), "error", err.Error()) - return common.Hash{}, fmt.Errorf("failed to find key in the node's keyring; %s; %s", keystore.ErrNoMatch, err.Error()) + return common.Hash{}, fmt.Errorf( + "failed to find key in the node's keyring; %s; %s", + keystore.ErrNoMatch, + err.Error(), + ) } if args.ChainID != nil && (b.chainID).Cmp((*big.Int)(args.ChainID)) != 0 { - return common.Hash{}, fmt.Errorf("chainId does not match node's (have=%v, want=%v)", args.ChainID, (*hexutil.Big)(b.chainID)) + return common.Hash{}, fmt.Errorf( + "chainId does not match node's (have=%v, want=%v)", + args.ChainID, + (*hexutil.Big)(b.chainID), + ) } args, err = b.SetTxDefaults(args) diff --git a/rpc/backend/tracing.go b/rpc/backend/tracing.go index d9cd79af6b..2d19273d45 100644 --- a/rpc/backend/tracing.go +++ b/rpc/backend/tracing.go @@ -52,7 +52,15 @@ func (b *Backend) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfi // check tx index is not out of bound // #nosec G701 txs number in block is always less than MaxUint32 if uint32(len(blk.Block.Txs)) < transaction.TxIndex { - b.logger.Debug("tx index out of bounds", "index", transaction.TxIndex, "hash", hash.String(), "height", blk.Block.Height) + b.logger.Debug( + "tx index out of bounds", + "index", + transaction.TxIndex, + "hash", + hash.String(), + "height", + blk.Block.Height, + ) return nil, fmt.Errorf("transaction not included in block %v", blk.Block.Height) } diff --git a/rpc/backend/tx_info.go b/rpc/backend/tx_info.go index 6195668a15..77ff6109af 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -92,7 +92,13 @@ func (b *Backend) GetTransactionByHash(txHash common.Hash) (*rpctypes.RPCTransac baseFee, err := b.BaseFee(blockRes) if err != nil { // handle the error for pruned node. - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", blockRes.Height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + blockRes.Height, + "error", + err, + ) } return rpctypes.NewTransactionFromMsg( @@ -309,7 +315,10 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{ } // GetTransactionByBlockHashAndIndex returns the transaction identified by hash and index. -func (b *Backend) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { +func (b *Backend) GetTransactionByBlockHashAndIndex( + hash common.Hash, + idx hexutil.Uint, +) (*rpctypes.RPCTransaction, error) { b.logger.Debug("eth_getTransactionByBlockHashAndIndex", "hash", hash.Hex(), "index", idx) sc, ok := b.clientCtx.Client.(tmrpcclient.SignClient) @@ -331,7 +340,10 @@ func (b *Backend) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexuti } // GetTransactionByBlockNumberAndIndex returns the transaction identified by number and index. -func (b *Backend) GetTransactionByBlockNumberAndIndex(blockNum rpctypes.BlockNumber, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { +func (b *Backend) GetTransactionByBlockNumberAndIndex( + blockNum rpctypes.BlockNumber, + idx hexutil.Uint, +) (*rpctypes.RPCTransaction, error) { b.logger.Debug("eth_getTransactionByBlockNumberAndIndex", "number", blockNum, "index", idx) block, err := b.TendermintBlockByNumber(blockNum) @@ -371,7 +383,10 @@ func (b *Backend) GetTxByEthHash(hash common.Hash) (*ethermint.TxResult, *rpctyp } // GetTxByTxIndex uses `/tx_query` to find transaction by tx index of valid ethereum txs -func (b *Backend) GetTxByTxIndex(height int64, index uint) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { +func (b *Backend) GetTxByTxIndex( + height int64, + index uint, +) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { if b.indexer != nil { // #nosec G701 always in range txRes, err := b.indexer.GetByBlockAndIndex(height, int32(index)) @@ -396,7 +411,10 @@ func (b *Backend) GetTxByTxIndex(height int64, index uint) (*ethermint.TxResult, } // queryTendermintTxIndexer query tx in tendermint tx indexer -func (b *Backend) queryTendermintTxIndexer(query string, txGetter func(*rpctypes.ParsedTxs) *rpctypes.ParsedTx) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { +func (b *Backend) queryTendermintTxIndexer( + query string, + txGetter func(*rpctypes.ParsedTxs) *rpctypes.ParsedTx, +) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { resTxs, err := b.clientCtx.Client.TxSearch(b.ctx, query, false, nil, nil, "") if err != nil { return nil, nil, err @@ -422,7 +440,10 @@ func (b *Backend) queryTendermintTxIndexer(query string, txGetter func(*rpctypes } // GetTransactionByBlockAndIndex is the common code shared by `GetTransactionByBlockNumberAndIndex` and `GetTransactionByBlockHashAndIndex`. -func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { +func (b *Backend) GetTransactionByBlockAndIndex( + block *tmrpctypes.ResultBlock, + idx hexutil.Uint, +) (*rpctypes.RPCTransaction, error) { blockRes, err := b.TendermintBlockResultByNumber(&block.Block.Height) if err != nil { return nil, nil @@ -467,7 +488,13 @@ func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, i baseFee, err := b.BaseFee(blockRes) if err != nil { // handle the error for pruned node. - b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", block.Block.Height, "error", err) + b.logger.Error( + "failed to fetch Base Fee from prunned block. Check node prunning configuration", + "height", + block.Block.Height, + "error", + err, + ) } return rpctypes.NewTransactionFromMsg( diff --git a/rpc/backend/utils.go b/rpc/backend/utils.go index 5b55e959f2..204ea2605a 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -61,7 +61,12 @@ func (s sortGasAndReward) Less(i, j int) bool { // If the pending value is true, it will iterate over the mempool (pending) // txs in order to compute and return the pending tx sequence. // Todo: include the ability to specify a blockNumber -func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height int64, logger log.Logger) (uint64, error) { +func (b *Backend) getAccountNonce( + accAddr common.Address, + pending bool, + height int64, + logger log.Logger, +) (uint64, error) { queryClient := authtypes.NewQueryClient(b.clientCtx) adr := sdk.AccAddress(accAddr.Bytes()).String() ctx := types.ContextWithHeight(height) @@ -152,7 +157,11 @@ func (b *Backend) processBlock( gasusedfloat, _ := new(big.Float).SetInt(gasUsedBig.ToInt()).Float64() if gasLimitUint64 <= 0 { - return fmt.Errorf("gasLimit of block height %d should be bigger than 0 , current gaslimit %d", blockHeight, gasLimitUint64) + return fmt.Errorf( + "gasLimit of block height %d should be bigger than 0 , current gaslimit %d", + blockHeight, + gasLimitUint64, + ) } gasUsedRatio := gasusedfloat / float64(gasLimitUint64) diff --git a/rpc/namespaces/ethereum/debug/api.go b/rpc/namespaces/ethereum/debug/api.go index bbc037d423..1875883019 100644 --- a/rpc/namespaces/ethereum/debug/api.go +++ b/rpc/namespaces/ethereum/debug/api.go @@ -79,7 +79,10 @@ func (a *API) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfig) ( // TraceBlockByNumber returns the structured logs created during the execution of // EVM and returns them as a JSON object. -func (a *API) TraceBlockByNumber(height rpctypes.BlockNumber, config *evmtypes.TraceConfig) ([]*evmtypes.TxTraceResult, error) { +func (a *API) TraceBlockByNumber( + height rpctypes.BlockNumber, + config *evmtypes.TraceConfig, +) ([]*evmtypes.TxTraceResult, error) { a.logger.Debug("debug_traceBlockByNumber", "height", height) if height == 0 { return nil, errors.New("genesis is not traceable") diff --git a/rpc/namespaces/ethereum/eth/api.go b/rpc/namespaces/ethereum/eth/api.go index 38b1a6cb26..e4079d0172 100644 --- a/rpc/namespaces/ethereum/eth/api.go +++ b/rpc/namespaces/ethereum/eth/api.go @@ -53,7 +53,10 @@ type EthereumAPI interface { GetTransactionCount(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Uint64, error) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) - GetTransactionByBlockNumberAndIndex(blockNum rpctypes.BlockNumber, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) + GetTransactionByBlockNumberAndIndex( + blockNum rpctypes.BlockNumber, + idx hexutil.Uint, + ) (*rpctypes.RPCTransaction, error) // eth_getBlockReceipts // Writing Transactions @@ -71,13 +74,21 @@ type EthereumAPI interface { GetBalance(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Big, error) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) GetCode(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) - GetProof(address common.Address, storageKeys []string, blockNrOrHash rpctypes.BlockNumberOrHash) (*rpctypes.AccountResult, error) + GetProof( + address common.Address, + storageKeys []string, + blockNrOrHash rpctypes.BlockNumberOrHash, + ) (*rpctypes.AccountResult, error) // EVM/Smart Contract Execution // // Allows developers to read data from the blockchain which includes executing // smart contracts. However, no data is published to the Ethereum network. - Call(args evmtypes.TransactionArgs, blockNrOrHash rpctypes.BlockNumberOrHash, _ *rpctypes.StateOverride) (hexutil.Bytes, error) + Call( + args evmtypes.TransactionArgs, + blockNrOrHash rpctypes.BlockNumberOrHash, + _ *rpctypes.StateOverride, + ) (hexutil.Bytes, error) // Chain Information // @@ -85,7 +96,11 @@ type EthereumAPI interface { ProtocolVersion() hexutil.Uint GasPrice() (*hexutil.Big, error) EstimateGas(args evmtypes.TransactionArgs, blockNrOptional *rpctypes.BlockNumber) (hexutil.Uint64, error) - FeeHistory(blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*rpctypes.FeeHistoryResult, error) + FeeHistory( + blockCount rpc.DecimalOrHex, + lastBlock rpc.BlockNumber, + rewardPercentiles []float64, + ) (*rpctypes.FeeHistoryResult, error) MaxPriorityFeePerGas() (*hexutil.Big, error) ChainId() (*hexutil.Big, error) @@ -106,7 +121,12 @@ type EthereumAPI interface { Coinbase() (string, error) GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, error) FillTransaction(args evmtypes.TransactionArgs) (*rpctypes.SignTransactionResult, error) - Resend(ctx context.Context, args evmtypes.TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) + Resend( + ctx context.Context, + args evmtypes.TransactionArgs, + gasPrice *hexutil.Big, + gasLimit *hexutil.Uint64, + ) (common.Hash, error) GetPendingTransactions() ([]*rpctypes.RPCTransaction, error) // eth_signTransaction (on Ethereum.org) // eth_getCompilers (on Ethereum.org) @@ -176,7 +196,10 @@ func (e *PublicAPI) GetTransactionByHash(hash common.Hash) (*rpctypes.RPCTransac } // GetTransactionCount returns the number of transactions at the given address up to the given block number. -func (e *PublicAPI) GetTransactionCount(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Uint64, error) { +func (e *PublicAPI) GetTransactionCount( + address common.Address, + blockNrOrHash rpctypes.BlockNumberOrHash, +) (*hexutil.Uint64, error) { e.logger.Debug("eth_getTransactionCount", "address", address.Hex(), "block number or hash", blockNrOrHash) blockNum, err := e.backend.BlockNumberFromTendermint(blockNrOrHash) if err != nil { @@ -205,13 +228,19 @@ func (e *PublicAPI) GetBlockTransactionCountByNumber(blockNum rpctypes.BlockNumb } // GetTransactionByBlockHashAndIndex returns the transaction identified by hash and index. -func (e *PublicAPI) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { +func (e *PublicAPI) GetTransactionByBlockHashAndIndex( + hash common.Hash, + idx hexutil.Uint, +) (*rpctypes.RPCTransaction, error) { e.logger.Debug("eth_getTransactionByBlockHashAndIndex", "hash", hash.Hex(), "index", idx) return e.backend.GetTransactionByBlockHashAndIndex(hash, idx) } // GetTransactionByBlockNumberAndIndex returns the transaction identified by number and index. -func (e *PublicAPI) GetTransactionByBlockNumberAndIndex(blockNum rpctypes.BlockNumber, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) { +func (e *PublicAPI) GetTransactionByBlockNumberAndIndex( + blockNum rpctypes.BlockNumber, + idx hexutil.Uint, +) (*rpctypes.RPCTransaction, error) { e.logger.Debug("eth_getTransactionByBlockNumberAndIndex", "number", blockNum, "index", idx) return e.backend.GetTransactionByBlockNumberAndIndex(blockNum, idx) } @@ -243,7 +272,11 @@ func (e *PublicAPI) GetBalance(address common.Address, blockNrOrHash rpctypes.Bl } // GetStorageAt returns the contract storage at the given address, block number, and key. -func (e *PublicAPI) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) { +func (e *PublicAPI) GetStorageAt( + address common.Address, + key string, + blockNrOrHash rpctypes.BlockNumberOrHash, +) (hexutil.Bytes, error) { e.logger.Debug("eth_getStorageAt", "address", address.Hex(), "key", key, "block number or hash", blockNrOrHash) return e.backend.GetStorageAt(address, key, blockNrOrHash) } @@ -308,7 +341,10 @@ func (e *PublicAPI) GasPrice() (*hexutil.Big, error) { } // EstimateGas returns an estimate of gas usage for the given smart contract call. -func (e *PublicAPI) EstimateGas(args evmtypes.TransactionArgs, blockNrOptional *rpctypes.BlockNumber) (hexutil.Uint64, error) { +func (e *PublicAPI) EstimateGas( + args evmtypes.TransactionArgs, + blockNrOptional *rpctypes.BlockNumber, +) (hexutil.Uint64, error) { e.logger.Debug("eth_estimateGas") return e.backend.EstimateGas(args, blockNrOptional) } diff --git a/rpc/namespaces/ethereum/eth/filters/api.go b/rpc/namespaces/ethereum/eth/filters/api.go index f8fecb0d08..eb67682783 100644 --- a/rpc/namespaces/ethereum/eth/filters/api.go +++ b/rpc/namespaces/ethereum/eth/filters/api.go @@ -89,7 +89,12 @@ type PublicFilterAPI struct { } // NewPublicAPI returns a new PublicFilterAPI instance. -func NewPublicAPI(logger log.Logger, clientCtx client.Context, tmWSClient *rpcclient.WSClient, backend Backend) *PublicFilterAPI { +func NewPublicAPI( + logger log.Logger, + clientCtx client.Context, + tmWSClient *rpcclient.WSClient, + backend Backend, +) *PublicFilterAPI { logger = logger.With("api", "filter") api := &PublicFilterAPI{ logger: logger, @@ -285,7 +290,12 @@ func (api *PublicFilterAPI) NewBlockFilter() rpc.ID { return rpc.ID(fmt.Sprintf("error creating block filter: %s", err.Error())) } - api.filters[headerSub.ID()] = &filter{typ: filters.BlocksSubscription, deadline: time.NewTimer(deadline), hashes: []common.Hash{}, s: headerSub} + api.filters[headerSub.ID()] = &filter{ + typ: filters.BlocksSubscription, + deadline: time.NewTimer(deadline), + hashes: []common.Hash{}, + s: headerSub, + } go func(headersCh <-chan coretypes.ResultEvent, errCh <-chan error) { defer cancelSubs() @@ -423,7 +433,13 @@ func (api *PublicFilterAPI) Logs(ctx context.Context, crit filters.FilterCriteri return } - logs := FilterLogs(evmtypes.LogsToEthereum(txResponse.Logs), crit.FromBlock, crit.ToBlock, crit.Addresses, crit.Topics) + logs := FilterLogs( + evmtypes.LogsToEthereum(txResponse.Logs), + crit.FromBlock, + crit.ToBlock, + crit.Addresses, + crit.Topics, + ) for _, log := range logs { err = notifier.Notify(rpcSub.ID, log) @@ -509,7 +525,13 @@ func (api *PublicFilterAPI) NewFilter(criteria filters.FilterCriteria) (rpc.ID, return } - logs := FilterLogs(evmtypes.LogsToEthereum(txResponse.Logs), criteria.FromBlock, criteria.ToBlock, criteria.Addresses, criteria.Topics) + logs := FilterLogs( + evmtypes.LogsToEthereum(txResponse.Logs), + criteria.FromBlock, + criteria.ToBlock, + criteria.Addresses, + criteria.Topics, + ) api.filtersMu.Lock() if f, found := api.filters[filterID]; found { diff --git a/rpc/namespaces/ethereum/eth/filters/filters.go b/rpc/namespaces/ethereum/eth/filters/filters.go index 6ddbcc420e..ebbcc0adfe 100644 --- a/rpc/namespaces/ethereum/eth/filters/filters.go +++ b/rpc/namespaces/ethereum/eth/filters/filters.go @@ -57,7 +57,13 @@ func NewBlockFilter(logger log.Logger, backend Backend, criteria filters.FilterC // NewRangeFilter creates a new filter which uses a bloom filter on blocks to // figure out whether a particular block is interesting or not. -func NewRangeFilter(logger log.Logger, backend Backend, begin, end int64, addresses []common.Address, topics [][]common.Hash) *Filter { +func NewRangeFilter( + logger log.Logger, + backend Backend, + begin, end int64, + addresses []common.Address, + topics [][]common.Hash, +) *Filter { // Flatten the address and topic filter clauses into a single bloombits filter // system. Since the bloombits are not positional, nil topics are permitted, // which get flattened into a nil byte slice. @@ -118,7 +124,13 @@ func (f *Filter) Logs(_ context.Context, logLimit int, blockLimit int64) ([]*eth blockRes, err := f.backend.TendermintBlockResultByNumber(&resBlock.Block.Height) if err != nil { - f.logger.Debug("failed to fetch block result from Tendermint", "height", resBlock.Block.Height, "error", err.Error()) + f.logger.Debug( + "failed to fetch block result from Tendermint", + "height", + resBlock.Block.Height, + "error", + err.Error(), + ) return nil, nil } diff --git a/rpc/namespaces/ethereum/eth/filters/utils.go b/rpc/namespaces/ethereum/eth/filters/utils.go index 0315f4dc01..2d4557f568 100644 --- a/rpc/namespaces/ethereum/eth/filters/utils.go +++ b/rpc/namespaces/ethereum/eth/filters/utils.go @@ -28,7 +28,12 @@ import ( // [null, B] -> anything in first position, B in second position // [A, B] -> A in first position and B in second position // [[A, B], [A, B]] -> A or B in first position, A or B in second position -func FilterLogs(logs []*ethtypes.Log, fromBlock, toBlock *big.Int, addresses []common.Address, topics [][]common.Hash) []*ethtypes.Log { +func FilterLogs( + logs []*ethtypes.Log, + fromBlock, toBlock *big.Int, + addresses []common.Address, + topics [][]common.Hash, +) []*ethtypes.Log { var ret []*ethtypes.Log Logs: for _, log := range logs { diff --git a/rpc/namespaces/ethereum/personal/api.go b/rpc/namespaces/ethereum/personal/api.go index 0123aed713..4f33e802f7 100644 --- a/rpc/namespaces/ethereum/personal/api.go +++ b/rpc/namespaces/ethereum/personal/api.go @@ -106,7 +106,11 @@ func (api *PrivateAccountAPI) NewAccount(password string) (common.Address, error } addr := common.BytesToAddress(pubKey.Address().Bytes()) api.logger.Info("Your new key was generated", "address", addr.String()) - api.logger.Info("Please backup your key file!", "path", os.Getenv("HOME")+"/.ethermint/"+name) // TODO: pass the correct binary + api.logger.Info( + "Please backup your key file!", + "path", + os.Getenv("HOME")+"/.ethermint/"+name, + ) // TODO: pass the correct binary api.logger.Info("Please remember your password!") return addr, nil } @@ -123,7 +127,11 @@ func (api *PrivateAccountAPI) UnlockAccount(_ context.Context, addr common.Addre // SendTransaction will create a transaction from the given arguments and // tries to sign it with the key associated with args.To. If the given password isn't // able to decrypt the key it fails. -func (api *PrivateAccountAPI) SendTransaction(_ context.Context, args evmtypes.TransactionArgs, _ string) (common.Hash, error) { +func (api *PrivateAccountAPI) SendTransaction( + _ context.Context, + args evmtypes.TransactionArgs, + _ string, +) (common.Hash, error) { api.logger.Debug("personal_sendTransaction", "address", args.To.String()) return api.backend.SendTransaction(args) } @@ -137,7 +145,12 @@ func (api *PrivateAccountAPI) SendTransaction(_ context.Context, args evmtypes.T // The key used to calculate the signature is decrypted with the given password. // // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign -func (api *PrivateAccountAPI) Sign(_ context.Context, data hexutil.Bytes, addr common.Address, _ string) (hexutil.Bytes, error) { +func (api *PrivateAccountAPI) Sign( + _ context.Context, + data hexutil.Bytes, + addr common.Address, + _ string, +) (hexutil.Bytes, error) { api.logger.Debug("personal_sign", "data", data, "address", addr.String()) return api.backend.Sign(addr, data) } diff --git a/rpc/namespaces/ethereum/web3/api.go b/rpc/namespaces/ethereum/web3/api.go index de40837ee1..4b3806cae7 100644 --- a/rpc/namespaces/ethereum/web3/api.go +++ b/rpc/namespaces/ethereum/web3/api.go @@ -34,7 +34,13 @@ func NewPublicAPI() *PublicAPI { // ClientVersion returns the client version in the Web3 user agent format. func (a *PublicAPI) ClientVersion() string { - return fmt.Sprintf("%s/%s/%s/%s", constant.Name, constant.Version, runtime.GOOS+"-"+runtime.GOARCH, runtime.Version()) + return fmt.Sprintf( + "%s/%s/%s/%s", + constant.Name, + constant.Version, + runtime.GOOS+"-"+runtime.GOARCH, + runtime.Version(), + ) } // Sha3 returns the keccak-256 hash of the passed-in input. diff --git a/rpc/types/block.go b/rpc/types/block.go index 4079d264de..c99111ad61 100644 --- a/rpc/types/block.go +++ b/rpc/types/block.go @@ -70,7 +70,11 @@ func ContextWithHeight(height int64) context.Context { return context.Background() } - return metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, fmt.Sprintf("%d", height)) + return metadata.AppendToOutgoingContext( + context.Background(), + grpctypes.GRPCBlockHeightHeader, + fmt.Sprintf("%d", height), + ) } // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports: diff --git a/rpc/types/block_test.go b/rpc/types/block_test.go index 1cbb11f61e..4fb145b459 100644 --- a/rpc/types/block_test.go +++ b/rpc/types/block_test.go @@ -21,7 +21,11 @@ func TestUnmarshalBlockNumberOrHash(t *testing.T) { "JSON input with block hash", []byte("{\"blockHash\": \"0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739\"}"), func() { - require.Equal(t, *bnh.BlockHash, common.HexToHash("0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739")) + require.Equal( + t, + *bnh.BlockHash, + common.HexToHash("0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739"), + ) require.Nil(t, bnh.BlockNumber) }, true, @@ -46,7 +50,9 @@ func TestUnmarshalBlockNumberOrHash(t *testing.T) { }, { "JSON input with both block hash and block number", - []byte("{\"blockHash\": \"0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739\", \"blockNumber\": \"0x35\"}"), + []byte( + "{\"blockHash\": \"0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739\", \"blockNumber\": \"0x35\"}", + ), func() { }, false, @@ -55,7 +61,11 @@ func TestUnmarshalBlockNumberOrHash(t *testing.T) { "String input with block hash", []byte("\"0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739\""), func() { - require.Equal(t, *bnh.BlockHash, common.HexToHash("0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739")) + require.Equal( + t, + *bnh.BlockHash, + common.HexToHash("0x579917054e325746fda5c3ee431d73d26255bc4e10b51163862368629ae19739"), + ) require.Nil(t, bnh.BlockNumber) }, true, diff --git a/rpc/types/events.go b/rpc/types/events.go index 3f40668719..e6e9a3c994 100644 --- a/rpc/types/events.go +++ b/rpc/types/events.go @@ -110,7 +110,8 @@ func ParseTxResult(result *abci.ResponseDeliverTx, tx sdk.Tx) (*ParsedTxs, error } prevEventType := "" for _, event := range result.Events { - if event.Type != evmtypes.EventTypeEthereumTx && (prevEventType != evmtypes.EventTypeEthereumTx || event.Type != MessageType) { + if event.Type != evmtypes.EventTypeEthereumTx && + (prevEventType != evmtypes.EventTypeEthereumTx || event.Type != MessageType) { continue } @@ -180,15 +181,28 @@ func ParseTxResult(result *abci.ResponseDeliverTx, tx sdk.Tx) (*ParsedTxs, error } // ParseTxIndexerResult parse tm tx result to a format compatible with the custom tx indexer. -func ParseTxIndexerResult(txResult *tmrpctypes.ResultTx, tx sdk.Tx, getter func(*ParsedTxs) *ParsedTx) (*ethermint.TxResult, *TxResultAdditionalFields, error) { +func ParseTxIndexerResult( + txResult *tmrpctypes.ResultTx, + tx sdk.Tx, + getter func(*ParsedTxs) *ParsedTx, +) (*ethermint.TxResult, *TxResultAdditionalFields, error) { txs, err := ParseTxResult(&txResult.TxResult, tx) if err != nil { - return nil, nil, fmt.Errorf("failed to parse tx events: block %d, index %d, %v", txResult.Height, txResult.Index, err) + return nil, nil, fmt.Errorf( + "failed to parse tx events: block %d, index %d, %v", + txResult.Height, + txResult.Index, + err, + ) } parsedTx := getter(txs) if parsedTx == nil { - return nil, nil, fmt.Errorf("ethereum tx not found in msgs: block %d, index %d", txResult.Height, txResult.Index) + return nil, nil, fmt.Errorf( + "ethereum tx not found in msgs: block %d, index %d", + txResult.Height, + txResult.Index, + ) } if parsedTx.Type == 88 { return ðermint.TxResult{ @@ -222,7 +236,12 @@ func ParseTxIndexerResult(txResult *tmrpctypes.ResultTx, tx sdk.Tx, getter func( } // ParseTxIndexerResult parse tm tx result to a format compatible with the custom tx indexer. -func ParseTxBlockResult(txResult *abci.ResponseDeliverTx, tx sdk.Tx, txIndex int, height int64) (*ethermint.TxResult, *TxResultAdditionalFields, error) { +func ParseTxBlockResult( + txResult *abci.ResponseDeliverTx, + tx sdk.Tx, + txIndex int, + height int64, +) (*ethermint.TxResult, *TxResultAdditionalFields, error) { txs, err := ParseTxResult(txResult, tx) if err != nil { return nil, nil, fmt.Errorf("failed to parse tx events: block %d, index %d, %v", height, txIndex, err) diff --git a/rpc/websockets.go b/rpc/websockets.go index 3cb6af3977..feb9159cef 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -98,7 +98,12 @@ type websocketsServer struct { logger log.Logger } -func NewWebsocketsServer(clientCtx client.Context, logger log.Logger, tmWSClient *rpcclient.WSClient, cfg *config.Config) WebsocketsServer { +func NewWebsocketsServer( + clientCtx client.Context, + logger log.Logger, + tmWSClient *rpcclient.WSClient, + cfg *config.Config, +) WebsocketsServer { logger = logger.With("api", "websocket-server") _, port, err := net.SplitHostPort(cfg.JSONRPC.Address) if err != nil { @@ -465,7 +470,13 @@ func (api *pubSubAPI) subscribeNewHeads(wsConn *wsConn, subID rpc.ID) (pubsub.Un if !ok { return } - api.logger.Debug("dropping NewHeads WebSocket subscription", "subscription-id", subID, "error", err.Error()) + api.logger.Debug( + "dropping NewHeads WebSocket subscription", + "subscription-id", + subID, + "error", + err.Error(), + ) } } }() @@ -618,7 +629,13 @@ func (api *pubSubAPI) subscribeLogs(wsConn *wsConn, subID rpc.ID, extra interfac return } - logs := rpcfilters.FilterLogs(evmtypes.LogsToEthereum(txResponse.Logs), crit.FromBlock, crit.ToBlock, crit.Addresses, crit.Topics) + logs := rpcfilters.FilterLogs( + evmtypes.LogsToEthereum(txResponse.Logs), + crit.FromBlock, + crit.ToBlock, + crit.Addresses, + crit.Topics, + ) if len(logs) == 0 { continue } diff --git a/server/flags/flags.go b/server/flags/flags.go index 5f3d9c7112..abc3d6dc72 100644 --- a/server/flags/flags.go +++ b/server/flags/flags.go @@ -89,10 +89,17 @@ func AddTxFlags(cmd *cobra.Command) (*cobra.Command, error) { cmd.PersistentFlags().String(flags.FlagChainID, "testnet", "Specify Chain ID for sending Tx") cmd.PersistentFlags().String(flags.FlagFrom, "", "Name or address of private key with which to sign") cmd.PersistentFlags().String(flags.FlagFees, "", "Fees to pay along with transaction; eg: 10aphoton") - cmd.PersistentFlags().String(flags.FlagGasPrices, "", "Gas prices to determine the transaction fee (e.g. 10aphoton)") - cmd.PersistentFlags().String(flags.FlagNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") //nolint:lll - cmd.PersistentFlags().Float64(flags.FlagGasAdjustment, flags.DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ") //nolint:lll - cmd.PersistentFlags().StringP(flags.FlagBroadcastMode, "b", flags.BroadcastSync, "Transaction broadcasting mode (sync|async|block)") + cmd.PersistentFlags(). + String(flags.FlagGasPrices, "", "Gas prices to determine the transaction fee (e.g. 10aphoton)") + cmd.PersistentFlags(). + String(flags.FlagNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") + //nolint:lll + cmd.PersistentFlags(). + Float64(flags.FlagGasAdjustment, flags.DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ") + + //nolint:lll + cmd.PersistentFlags(). + StringP(flags.FlagBroadcastMode, "b", flags.BroadcastSync, "Transaction broadcasting mode (sync|async|block)") cmd.PersistentFlags().String(flags.FlagKeyringBackend, keyring.BackendOS, "Select keyring's backend") // --gas can accept integers and "simulate" diff --git a/server/start.go b/server/start.go index b2c5a46a4a..bd82aaf767 100644 --- a/server/start.go +++ b/server/start.go @@ -178,48 +178,90 @@ which accepts a path for the resulting pprof file. cmd.Flags().String(srvflags.Address, "tcp://0.0.0.0:26658", "Listen address") cmd.Flags().String(srvflags.Transport, "socket", "Transport protocol: socket, grpc") cmd.Flags().String(srvflags.TraceStore, "", "Enable KVStore tracing to an output file") - cmd.Flags().String(server.FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; Any fee in a tx must meet this minimum (e.g. 0.01photon;0.0001stake)") //nolint:lll - cmd.Flags().IntSlice(server.FlagUnsafeSkipUpgrades, []int{}, "Skip a set of upgrade heights to continue the old binary") - cmd.Flags().Uint64(server.FlagHaltHeight, 0, "Block height at which to gracefully halt the chain and shutdown the node") - cmd.Flags().Uint64(server.FlagHaltTime, 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node") + cmd.Flags(). + String(server.FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; Any fee in a tx must meet this minimum (e.g. 0.01photon;0.0001stake)") + + //nolint:lll + cmd.Flags(). + IntSlice(server.FlagUnsafeSkipUpgrades, []int{}, "Skip a set of upgrade heights to continue the old binary") + cmd.Flags(). + Uint64(server.FlagHaltHeight, 0, "Block height at which to gracefully halt the chain and shutdown the node") + cmd.Flags(). + Uint64(server.FlagHaltTime, 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node") cmd.Flags().Bool(server.FlagInterBlockCache, true, "Enable inter-block caching") cmd.Flags().String(srvflags.CPUProfile, "", "Enable CPU profiling and write to the provided file") cmd.Flags().Bool(server.FlagTrace, false, "Provide full stack traces for errors in ABCI Log") - cmd.Flags().String(server.FlagPruning, pruningtypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") - cmd.Flags().Uint64(server.FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") - cmd.Flags().Uint64(server.FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')") //nolint:lll + cmd.Flags(). + String(server.FlagPruning, pruningtypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)") + cmd.Flags(). + Uint64(server.FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')") + cmd.Flags(). + Uint64(server.FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')") + + //nolint:lll cmd.Flags().Uint(server.FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks") - cmd.Flags().Uint64(server.FlagMinRetainBlocks, 0, "Minimum block height offset during ABCI commit to prune Tendermint blocks") + cmd.Flags(). + Uint64(server.FlagMinRetainBlocks, 0, "Minimum block height offset during ABCI commit to prune Tendermint blocks") cmd.Flags().String(srvflags.AppDBBackend, "", "The type of database for application and snapshots databases") cmd.Flags().Bool(srvflags.GRPCOnly, false, "Start the node in gRPC query only mode without Tendermint process") cmd.Flags().Bool(srvflags.GRPCEnable, true, "Define if the gRPC server should be enabled") cmd.Flags().String(srvflags.GRPCAddress, serverconfig.DefaultGRPCAddress, "the gRPC server address to listen on") - cmd.Flags().Bool(srvflags.GRPCWebEnable, true, "Define if the gRPC-Web server should be enabled. (Note: gRPC must also be enabled.)") - cmd.Flags().String(srvflags.GRPCWebAddress, serverconfig.DefaultGRPCWebAddress, "The gRPC-Web server address to listen on") + cmd.Flags(). + Bool(srvflags.GRPCWebEnable, true, "Define if the gRPC-Web server should be enabled. (Note: gRPC must also be enabled.)") + cmd.Flags(). + String(srvflags.GRPCWebAddress, serverconfig.DefaultGRPCWebAddress, "The gRPC-Web server address to listen on") cmd.Flags().Bool(srvflags.RPCEnable, false, "Defines if Cosmos-sdk REST server should be enabled") - cmd.Flags().Bool(srvflags.EnabledUnsafeCors, false, "Defines if CORS should be enabled (unsafe - use it at your own risk)") + cmd.Flags(). + Bool(srvflags.EnabledUnsafeCors, false, "Defines if CORS should be enabled (unsafe - use it at your own risk)") cmd.Flags().Bool(srvflags.JSONRPCEnable, true, "Define if the JSON-RPC server should be enabled") - cmd.Flags().StringSlice(srvflags.JSONRPCAPI, config.GetDefaultAPINamespaces(), "Defines a list of JSON-RPC namespaces that should be enabled") - cmd.Flags().String(srvflags.JSONRPCAddress, config.DefaultJSONRPCAddress, "the JSON-RPC server address to listen on") - cmd.Flags().String(srvflags.JSONWsAddress, config.DefaultJSONRPCWsAddress, "the JSON-RPC WS server address to listen on") - cmd.Flags().Uint64(srvflags.JSONRPCGasCap, config.DefaultGasCap, "Sets a cap on gas that can be used in eth_call/estimateGas unit is aphoton (0=infinite)") //nolint:lll - cmd.Flags().Float64(srvflags.JSONRPCTxFeeCap, config.DefaultTxFeeCap, "Sets a cap on transaction fee that can be sent via the RPC APIs (1 = default 1 photon)") //nolint:lll - cmd.Flags().Int32(srvflags.JSONRPCFilterCap, config.DefaultFilterCap, "Sets the global cap for total number of filters that can be created") - cmd.Flags().Duration(srvflags.JSONRPCEVMTimeout, config.DefaultEVMTimeout, "Sets a timeout used for eth_call (0=infinite)") - cmd.Flags().Duration(srvflags.JSONRPCHTTPTimeout, config.DefaultHTTPTimeout, "Sets a read/write timeout for json-rpc http server (0=infinite)") - cmd.Flags().Duration(srvflags.JSONRPCHTTPIdleTimeout, config.DefaultHTTPIdleTimeout, "Sets a idle timeout for json-rpc http server (0=infinite)") - cmd.Flags().Bool(srvflags.JSONRPCAllowUnprotectedTxs, config.DefaultAllowUnprotectedTxs, "Allow for unprotected (non EIP155 signed) transactions to be submitted via the node's RPC when the global parameter is disabled") //nolint:lll - cmd.Flags().Int32(srvflags.JSONRPCLogsCap, config.DefaultLogsCap, "Sets the max number of results can be returned from single `eth_getLogs` query") - cmd.Flags().Int32(srvflags.JSONRPCBlockRangeCap, config.DefaultBlockRangeCap, "Sets the max block range allowed for `eth_getLogs` query") - cmd.Flags().Int(srvflags.JSONRPCMaxOpenConnections, config.DefaultMaxOpenConnections, "Sets the maximum number of simultaneous connections for the server listener") //nolint:lll + cmd.Flags(). + StringSlice(srvflags.JSONRPCAPI, config.GetDefaultAPINamespaces(), "Defines a list of JSON-RPC namespaces that should be enabled") + cmd.Flags(). + String(srvflags.JSONRPCAddress, config.DefaultJSONRPCAddress, "the JSON-RPC server address to listen on") + cmd.Flags(). + String(srvflags.JSONWsAddress, config.DefaultJSONRPCWsAddress, "the JSON-RPC WS server address to listen on") + cmd.Flags(). + Uint64(srvflags.JSONRPCGasCap, config.DefaultGasCap, "Sets a cap on gas that can be used in eth_call/estimateGas unit is aphoton (0=infinite)") + + //nolint:lll + cmd.Flags(). + Float64(srvflags.JSONRPCTxFeeCap, config.DefaultTxFeeCap, "Sets a cap on transaction fee that can be sent via the RPC APIs (1 = default 1 photon)") + + //nolint:lll + cmd.Flags(). + Int32(srvflags.JSONRPCFilterCap, config.DefaultFilterCap, "Sets the global cap for total number of filters that can be created") + cmd.Flags(). + Duration(srvflags.JSONRPCEVMTimeout, config.DefaultEVMTimeout, "Sets a timeout used for eth_call (0=infinite)") + cmd.Flags(). + Duration(srvflags.JSONRPCHTTPTimeout, config.DefaultHTTPTimeout, "Sets a read/write timeout for json-rpc http server (0=infinite)") + cmd.Flags(). + Duration(srvflags.JSONRPCHTTPIdleTimeout, config.DefaultHTTPIdleTimeout, "Sets a idle timeout for json-rpc http server (0=infinite)") + cmd.Flags(). + Bool(srvflags.JSONRPCAllowUnprotectedTxs, config.DefaultAllowUnprotectedTxs, "Allow for unprotected (non EIP155 signed) transactions to be submitted via the node's RPC when the global parameter is disabled") + + //nolint:lll + cmd.Flags(). + Int32(srvflags.JSONRPCLogsCap, config.DefaultLogsCap, "Sets the max number of results can be returned from single `eth_getLogs` query") + cmd.Flags(). + Int32(srvflags.JSONRPCBlockRangeCap, config.DefaultBlockRangeCap, "Sets the max block range allowed for `eth_getLogs` query") + cmd.Flags(). + Int(srvflags.JSONRPCMaxOpenConnections, config.DefaultMaxOpenConnections, "Sets the maximum number of simultaneous connections for the server listener") + + //nolint:lll cmd.Flags().Bool(srvflags.JSONRPCEnableIndexer, false, "Enable the custom tx indexer for json-rpc") cmd.Flags().Bool(srvflags.JSONRPCEnableMetrics, false, "Define if EVM rpc metrics server should be enabled") - cmd.Flags().String(srvflags.EVMTracer, config.DefaultEVMTracer, "the EVM tracer type to collect execution traces from the EVM transaction execution (json|struct|access_list|markdown)") //nolint:lll - cmd.Flags().Uint64(srvflags.EVMMaxTxGasWanted, config.DefaultMaxTxGasWanted, "the gas wanted for each eth tx returned in ante handler in check tx mode") //nolint:lll + cmd.Flags(). + String(srvflags.EVMTracer, config.DefaultEVMTracer, "the EVM tracer type to collect execution traces from the EVM transaction execution (json|struct|access_list|markdown)") + + //nolint:lll + cmd.Flags(). + Uint64(srvflags.EVMMaxTxGasWanted, config.DefaultMaxTxGasWanted, "the gas wanted for each eth tx returned in ante handler in check tx mode") + + //nolint:lll cmd.Flags().String(srvflags.TLSCertPath, "", "the cert.pem file path for the server TLS configuration") cmd.Flags().String(srvflags.TLSKeyPath, "", "the key.pem file path for the server TLS configuration") @@ -408,7 +450,8 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt // Add the tx service to the gRPC router. We only need to register this // service if API or gRPC or JSONRPC is enabled, and avoid doing so in the general // case, because it spawns a new local tendermint RPC client. - if (config.API.Enable || config.GRPC.Enable || config.JSONRPC.Enable || config.JSONRPC.EnableIndexer) && tmNode != nil { + if (config.API.Enable || config.GRPC.Enable || config.JSONRPC.Enable || config.JSONRPC.EnableIndexer) && + tmNode != nil { clientCtx = clientCtx.WithClient(local.New(tmNode)) app.RegisterTxService(clientCtx) diff --git a/testutil/keeper/crosschain.go b/testutil/keeper/crosschain.go index 8dfa0a0bf1..846147bd1b 100644 --- a/testutil/keeper/crosschain.go +++ b/testutil/keeper/crosschain.go @@ -266,7 +266,13 @@ func MockGetSupportedChainFromChainID(m *crosschainmocks.CrosschainObserverKeepe Return(senderChain).Once() } -func MockGetRevertGasLimitForERC20(m *crosschainmocks.CrosschainFungibleKeeper, asset string, senderChain chains.Chain, returnVal int64) { + +func MockGetRevertGasLimitForERC20( + m *crosschainmocks.CrosschainFungibleKeeper, + asset string, + senderChain chains.Chain, + returnVal int64, +) { m.On("GetForeignCoinFromAsset", mock.Anything, asset, senderChain.ChainId). Return(fungibletypes.ForeignCoins{ Zrc20ContractAddress: sample.EthAddress().String(), @@ -275,7 +281,15 @@ func MockGetRevertGasLimitForERC20(m *crosschainmocks.CrosschainFungibleKeeper, Return(big.NewInt(returnVal), nil).Once() } -func MockPayGasAndUpdateCCTX(m *crosschainmocks.CrosschainFungibleKeeper, m2 *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context, k keeper.Keeper, senderChain chains.Chain, asset string) { + +func MockPayGasAndUpdateCCTX( + m *crosschainmocks.CrosschainFungibleKeeper, + m2 *crosschainmocks.CrosschainObserverKeeper, + ctx sdk.Context, + k keeper.Keeper, + senderChain chains.Chain, + asset string, +) { m2.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). Return(&senderChain).Twice() m.On("GetForeignCoinFromAsset", mock.Anything, asset, senderChain.ChainId). @@ -303,7 +317,8 @@ func MockPayGasAndUpdateCCTX(m *crosschainmocks.CrosschainFungibleKeeper, m2 *cr m.On("CallZRC20Approve", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(nil).Once() m.On("CallUniswapV2RouterSwapExactTokensForTokens", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return([]*big.Int{big.NewInt(0), big.NewInt(1), big.NewInt(1000)}, nil).Once() + Return([]*big.Int{big.NewInt(0), big.NewInt(1), big.NewInt(1000)}, nil). + Once() m.On("CallZRC20Burn", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(nil).Once() @@ -325,7 +340,13 @@ func MockUpdateNonce(m *crosschainmocks.CrosschainObserverKeeper, senderChain ch return } -func MockRevertForHandleEVMDeposit(m *crosschainmocks.CrosschainFungibleKeeper, receiver ethcommon.Address, amount *big.Int, senderChainID int64, errDeposit error) { +func MockRevertForHandleEVMDeposit( + m *crosschainmocks.CrosschainFungibleKeeper, + receiver ethcommon.Address, + amount *big.Int, + senderChainID int64, + errDeposit error, +) { m.On( "ZRC20DepositAndCallContract", mock.Anything, @@ -339,28 +360,52 @@ func MockRevertForHandleEVMDeposit(m *crosschainmocks.CrosschainFungibleKeeper, ).Return(&evmtypes.MsgEthereumTxResponse{VmError: "reverted"}, false, errDeposit) } -func MockVoteOnOutboundSuccessBallot(m *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context, cctx *types.CrossChainTx, senderChain chains.Chain, observer string) { +func MockVoteOnOutboundSuccessBallot( + m *crosschainmocks.CrosschainObserverKeeper, + ctx sdk.Context, + cctx *types.CrossChainTx, + senderChain chains.Chain, + observer string, +) { m.On("VoteOnOutboundBallot", ctx, mock.Anything, cctx.GetCurrentOutTxParam().ReceiverChainId, chains.ReceiveStatus_success, observer). - Return(true, true, observertypes.Ballot{BallotStatus: observertypes.BallotStatus_BallotFinalized_SuccessObservation}, senderChain.ChainName.String(), nil).Once() + Return(true, true, observertypes.Ballot{BallotStatus: observertypes.BallotStatus_BallotFinalized_SuccessObservation}, senderChain.ChainName.String(), nil). + Once() } -func MockVoteOnOutboundFailedBallot(m *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context, cctx *types.CrossChainTx, senderChain chains.Chain, observer string) { +func MockVoteOnOutboundFailedBallot( + m *crosschainmocks.CrosschainObserverKeeper, + ctx sdk.Context, + cctx *types.CrossChainTx, + senderChain chains.Chain, + observer string, +) { m.On("VoteOnOutboundBallot", ctx, mock.Anything, cctx.GetCurrentOutTxParam().ReceiverChainId, chains.ReceiveStatus_failed, observer). - Return(true, true, observertypes.Ballot{BallotStatus: observertypes.BallotStatus_BallotFinalized_FailureObservation}, senderChain.ChainName.String(), nil).Once() + Return(true, true, observertypes.Ballot{BallotStatus: observertypes.BallotStatus_BallotFinalized_FailureObservation}, senderChain.ChainName.String(), nil). + Once() } func MockGetOutBound(m *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context) { m.On("GetTSS", ctx).Return(observertypes.TSS{}, true).Once() } -func MockSaveOutBound(m *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context, cctx *types.CrossChainTx, tss observertypes.TSS) { +func MockSaveOutBound( + m *crosschainmocks.CrosschainObserverKeeper, + ctx sdk.Context, + cctx *types.CrossChainTx, + tss observertypes.TSS, +) { m.On("RemoveFromPendingNonces", ctx, tss.TssPubkey, cctx.GetCurrentOutTxParam().ReceiverChainId, mock.Anything). Return().Once() m.On("GetTSS", ctx).Return(observertypes.TSS{}, true) } -func MockSaveOutBoundNewRevertCreated(m *crosschainmocks.CrosschainObserverKeeper, ctx sdk.Context, cctx *types.CrossChainTx, tss observertypes.TSS) { +func MockSaveOutBoundNewRevertCreated( + m *crosschainmocks.CrosschainObserverKeeper, + ctx sdk.Context, + cctx *types.CrossChainTx, + tss observertypes.TSS, +) { m.On("RemoveFromPendingNonces", ctx, tss.TssPubkey, cctx.GetCurrentOutTxParam().ReceiverChainId, mock.Anything). Return().Once() @@ -391,7 +436,9 @@ func MockCctxByNonce( k.SetCrossChainTx(ctx, *cctx) observerKeeper.On("GetTSS", mock.Anything).Return(observertypes.TSS{}, true).Once() - observerKeeper.On("GetNonceToCctx", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(observertypes.NonceToCctx{ - CctxIndex: cctx.Index, - }, true).Once() + observerKeeper.On("GetNonceToCctx", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(observertypes.NonceToCctx{ + CctxIndex: cctx.Index, + }, true). + Once() } diff --git a/testutil/keeper/fungible.go b/testutil/keeper/fungible.go index 1da1550925..dc43653fe9 100644 --- a/testutil/keeper/fungible.go +++ b/testutil/keeper/fungible.go @@ -67,7 +67,10 @@ func initFungibleKeeper( } // FungibleKeeperWithMocks initializes a fungible keeper for testing purposes with option to mock specific keepers -func FungibleKeeperWithMocks(t testing.TB, mockOptions FungibleMockOptions) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { +func FungibleKeeperWithMocks( + t testing.TB, + mockOptions FungibleMockOptions, +) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { storeKey := sdk.NewKVStoreKey(types.StoreKey) memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) diff --git a/testutil/keeper/keeper.go b/testutil/keeper/keeper.go index f6f944bbb0..59e72db97b 100644 --- a/testutil/keeper/keeper.go +++ b/testutil/keeper/keeper.go @@ -243,10 +243,21 @@ func StakingKeeper( } // SlashingKeeper instantiates a slashing keeper for testing purposes -func SlashingKeeper(cdc codec.Codec, db *tmdb.MemDB, ss store.CommitMultiStore, stakingKeeper stakingkeeper.Keeper) slashingkeeper.Keeper { +func SlashingKeeper( + cdc codec.Codec, + db *tmdb.MemDB, + ss store.CommitMultiStore, + stakingKeeper stakingkeeper.Keeper, +) slashingkeeper.Keeper { storeKey := sdk.NewKVStoreKey(slashingtypes.StoreKey) ss.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) - return slashingkeeper.NewKeeper(cdc, codec.NewLegacyAmino(), storeKey, stakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + return slashingkeeper.NewKeeper( + cdc, + codec.NewLegacyAmino(), + storeKey, + stakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) } // DistributionKeeper instantiates a distribution keeper for testing purposes @@ -454,11 +465,31 @@ func NewSDKKeepers( stakingKeeper := StakingKeeper(cdc, db, ss, authKeeper, bankKeeper) consensusKeeper := ConsensusKeeper(cdc, db, ss) feeMarketKeeper := FeeMarketKeeper(cdc, db, ss, paramsKeeper, consensusKeeper) - evmKeeper := EVMKeeper(cdc, db, ss, authKeeper, bankKeeper, stakingKeeper, feeMarketKeeper, paramsKeeper, consensusKeeper) + evmKeeper := EVMKeeper( + cdc, + db, + ss, + authKeeper, + bankKeeper, + stakingKeeper, + feeMarketKeeper, + paramsKeeper, + consensusKeeper, + ) slashingKeeper := SlashingKeeper(cdc, db, ss, stakingKeeper) ibcKeeper := IBCKeeper(cdc, db, ss, paramsKeeper, stakingKeeper, UpgradeKeeper(cdc, db, ss), *capabilityKeeper) - transferKeeper := TransferKeeper(cdc, db, ss, paramsKeeper, ibcKeeper, authKeeper, bankKeeper, *capabilityKeeper, ibcRouter) + transferKeeper := TransferKeeper( + cdc, + db, + ss, + paramsKeeper, + ibcKeeper, + authKeeper, + bankKeeper, + *capabilityKeeper, + ibcRouter, + ) return SDKKeepers{ CapabilityKeeper: capabilityKeeper, diff --git a/testutil/keeper/lightclient.go b/testutil/keeper/lightclient.go index c8aa3c56de..12580ed2d7 100644 --- a/testutil/keeper/lightclient.go +++ b/testutil/keeper/lightclient.go @@ -41,7 +41,10 @@ func initLightclientKeeper( } // LightclientKeeperWithMocks instantiates a lightclient keeper for testing purposes with the option to mock specific keepers -func LightclientKeeperWithMocks(t testing.TB, mockOptions LightclientMockOptions) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { +func LightclientKeeperWithMocks( + t testing.TB, + mockOptions LightclientMockOptions, +) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { storeKey := sdk.NewKVStoreKey(types.StoreKey) memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) diff --git a/testutil/keeper/observer.go b/testutil/keeper/observer.go index e7048a414a..c1620ee722 100644 --- a/testutil/keeper/observer.go +++ b/testutil/keeper/observer.go @@ -65,7 +65,10 @@ func initObserverKeeper( } // ObserverKeeperWithMocks instantiates an observer keeper for testing purposes with the option to mock specific keepers -func ObserverKeeperWithMocks(t testing.TB, mockOptions ObserverMockOptions) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { +func ObserverKeeperWithMocks( + t testing.TB, + mockOptions ObserverMockOptions, +) (*keeper.Keeper, sdk.Context, SDKKeepers, ZetaKeepers) { storeKey := sdk.NewKVStoreKey(types.StoreKey) memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) diff --git a/testutil/network/genesis_state.go b/testutil/network/genesis_state.go index d999e9b9f8..fda107a42b 100644 --- a/testutil/network/genesis_state.go +++ b/testutil/network/genesis_state.go @@ -21,7 +21,13 @@ import ( observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) -func SetupZetaGenesisState(t *testing.T, genesisState map[string]json.RawMessage, codec codec.Codec, observerList []string, setupChainNonces bool) { +func SetupZetaGenesisState( + t *testing.T, + genesisState map[string]json.RawMessage, + codec codec.Codec, + observerList []string, + setupChainNonces bool, +) { // Cross-chain genesis state var crossChainGenesis types.GenesisState @@ -119,7 +125,13 @@ func SetupZetaGenesisState(t *testing.T, genesisState map[string]json.RawMessage genesisState[authoritytypes.ModuleName] = authorityGenesisBz } -func AddObserverData(t *testing.T, n int, genesisState map[string]json.RawMessage, codec codec.Codec, ballots []*observertypes.Ballot) *observertypes.GenesisState { +func AddObserverData( + t *testing.T, + n int, + genesisState map[string]json.RawMessage, + codec codec.Codec, + ballots []*observertypes.Ballot, +) *observertypes.GenesisState { state := observertypes.GenesisState{} require.NoError(t, codec.UnmarshalJSON(genesisState[observertypes.ModuleName], &state)) @@ -166,7 +178,10 @@ func AddObserverData(t *testing.T, n int, genesisState map[string]json.RawMessag state.CrosschainFlags = crosschainFlags for i := 0; i < n; i++ { - state.ChainNonces = append(state.ChainNonces, observertypes.ChainNonces{Creator: "ANY", Index: strconv.Itoa(i), Signers: []string{}}) + state.ChainNonces = append( + state.ChainNonces, + observertypes.ChainNonces{Creator: "ANY", Index: strconv.Itoa(i), Signers: []string{}}, + ) } // check genesis state validity @@ -178,7 +193,13 @@ func AddObserverData(t *testing.T, n int, genesisState map[string]json.RawMessag genesisState[observertypes.ModuleName] = buf return &state } -func AddCrosschainData(t *testing.T, n int, genesisState map[string]json.RawMessage, codec codec.Codec) *types.GenesisState { + +func AddCrosschainData( + t *testing.T, + n int, + genesisState map[string]json.RawMessage, + codec codec.Codec, +) *types.GenesisState { state := types.GenesisState{} require.NoError(t, codec.UnmarshalJSON(genesisState[types.ModuleName], &state)) // TODO : Fix add EVM balance to deploy contracts @@ -191,17 +212,33 @@ func AddCrosschainData(t *testing.T, n int, genesisState map[string]json.RawMess StatusMessage: "", LastUpdateTimestamp: 0, }, - InboundTxParams: &types.InboundTxParams{InboundTxObservedHash: fmt.Sprintf("Hash-%d", i), Amount: math.OneUint()}, + InboundTxParams: &types.InboundTxParams{ + InboundTxObservedHash: fmt.Sprintf("Hash-%d", i), + Amount: math.OneUint(), + }, OutboundTxParams: []*types.OutboundTxParams{}, ZetaFees: math.OneUint()}, ) } for i := 0; i < n; i++ { - state.GasPriceList = append(state.GasPriceList, &types.GasPrice{Creator: "ANY", ChainId: int64(i), Index: strconv.Itoa(i), Prices: []uint64{}, BlockNums: []uint64{}, Signers: []string{}}) + state.GasPriceList = append( + state.GasPriceList, + &types.GasPrice{ + Creator: "ANY", + ChainId: int64(i), + Index: strconv.Itoa(i), + Prices: []uint64{}, + BlockNums: []uint64{}, + Signers: []string{}, + }, + ) } for i := 0; i < n; i++ { - state.LastBlockHeightList = append(state.LastBlockHeightList, &types.LastBlockHeight{Creator: "ANY", Index: strconv.Itoa(i)}) + state.LastBlockHeightList = append( + state.LastBlockHeightList, + &types.LastBlockHeight{Creator: "ANY", Index: strconv.Itoa(i)}, + ) } for i := 0; i < n; i++ { diff --git a/testutil/network/network_setup.go b/testutil/network/network_setup.go index ea8d5b2596..dadcc16320 100644 --- a/testutil/network/network_setup.go +++ b/testutil/network/network_setup.go @@ -362,7 +362,13 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { nodeIDs[i] = nodeID valPubKeys[i] = pubKey - kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, cfg.Codec, cfg.KeyringOptions...) + kb, err := keyring.New( + sdk.KeyringServiceName(), + keyring.BackendTest, + clientDir, + buf, + cfg.Codec, + cfg.KeyringOptions...) if err != nil { return nil, err } diff --git a/testutil/network/util.go b/testutil/network/util.go index 746ad331cc..9692adbac3 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -169,7 +169,12 @@ func ExportGenesisFileWithTimeAndConsensusParams( return genDoc.SaveAs(genFile) } -func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string) error { +func initGenFiles( + cfg Config, + genAccounts []authtypes.GenesisAccount, + genBalances []banktypes.Balance, + genFiles []string, +) error { // set the accounts in the genesis state var authGenState authtypes.GenesisState cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[authtypes.ModuleName], &authGenState) diff --git a/testutil/sample/crosschain.go b/testutil/sample/crosschain.go index 9142d6f532..24b3f3566e 100644 --- a/testutil/sample/crosschain.go +++ b/testutil/sample/crosschain.go @@ -52,7 +52,12 @@ func RateLimiterFlags() types.RateLimiterFlags { } // CustomRateLimiterFlags creates a custom rate limiter flags with the given parameters -func CustomRateLimiterFlags(enabled bool, window int64, rate math.Uint, conversions []types.Conversion) types.RateLimiterFlags { +func CustomRateLimiterFlags( + enabled bool, + window int64, + rate math.Uint, + conversions []types.Conversion, +) types.RateLimiterFlags { return types.RateLimiterFlags{ Enabled: enabled, Window: window, @@ -74,7 +79,13 @@ func AssetRate() types.AssetRate { } // CustomAssetRate creates a custom asset rate with the given parameters -func CustomAssetRate(chainID int64, asset string, decimals uint32, coinType coin.CoinType, rate sdk.Dec) types.AssetRate { +func CustomAssetRate( + chainID int64, + asset string, + decimals uint32, + coinType coin.CoinType, + rate sdk.Dec, +) types.AssetRate { return types.AssetRate{ ChainId: chainID, Asset: strings.ToLower(asset), diff --git a/testutil/sample/sample.go b/testutil/sample/sample.go index c3011b1cb6..4a40c04312 100644 --- a/testutil/sample/sample.go +++ b/testutil/sample/sample.go @@ -111,7 +111,9 @@ func AppState(t *testing.T) map[string]json.RawMessage { } func GenDoc(t *testing.T) *types.GenesisDoc { - jsonBlob := []byte("{\n \"genesis_time\": \"2024-04-12T05:07:56.004517Z\",\n \"chain_id\": \"localnet_101-1\",\n \"initial_height\": \"1\",\n \"consensus_params\": {\n \"block\": {\n \"max_bytes\": \"22020096\",\n \"max_gas\": \"10000000\",\n \"time_iota_ms\": \"1000\"\n },\n \"evidence\": {\n \"max_age_num_blocks\": \"100000\",\n \"max_age_duration\": \"172800000000000\",\n \"max_bytes\": \"1048576\"\n },\n \"validator\": {\n \"pub_key_types\": [\n \"ed25519\"\n ]\n },\n \"version\": {}\n },\n \"app_hash\": \"\",\n \"app_state\": {\n \"auth\": {\n \"params\": {\n \"max_memo_characters\": \"256\",\n \"tx_sig_limit\": \"7\",\n \"tx_size_cost_per_byte\": \"10\",\n \"sig_verify_cost_ed25519\": \"590\",\n \"sig_verify_cost_secp256k1\": \"1000\"\n },\n \"accounts\": [\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n }\n ]\n },\n \"authority\": {\n \"policies\": {\n \"items\": [\n {\n \"policy_type\": \"groupEmergency\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n },\n {\n \"policy_type\": \"groupOperational\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n },\n {\n \"policy_type\": \"groupAdmin\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n }\n ]\n }\n },\n \"authz\": {\n \"authorization\": [\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgGasPriceVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedInboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedOutboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgCreateTSSVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgAddToOutTxTracker\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlameVote\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlockHeader\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgGasPriceVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedInboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedOutboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgCreateTSSVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgAddToOutTxTracker\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlameVote\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlockHeader\"\n },\n \"expiration\": null\n }\n ]\n },\n \"bank\": {\n \"params\": {\n \"send_enabled\": [],\n \"default_send_enabled\": true\n },\n \"balances\": [\n {\n \"address\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"4200000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"4200000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n ]\n }\n ],\n \"supply\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"8402000000000000000000000\"\n }\n ],\n \"denom_metadata\": []\n },\n \"crisis\": {\n \"constant_fee\": {\n \"denom\": \"azeta\",\n \"amount\": \"1000\"\n }\n },\n \"crosschain\": {\n \"outTxTrackerList\": [],\n \"inTxHashToCctxList\": [],\n \"in_tx_tracker_list\": [],\n \"zeta_accounting\": {\n \"aborted_zeta_amount\": \"0\"\n }\n },\n \"distribution\": {\n \"params\": {\n \"community_tax\": \"0.020000000000000000\",\n \"base_proposer_reward\": \"0.010000000000000000\",\n \"bonus_proposer_reward\": \"0.040000000000000000\",\n \"withdraw_addr_enabled\": true\n },\n \"fee_pool\": {\n \"community_pool\": []\n },\n \"delegator_withdraw_infos\": [],\n \"previous_proposer\": \"\",\n \"outstanding_rewards\": [],\n \"validator_accumulated_commissions\": [],\n \"validator_historical_rewards\": [],\n \"validator_current_rewards\": [],\n \"delegator_starting_infos\": [],\n \"validator_slash_events\": []\n },\n \"emissions\": {\n \"params\": {\n \"max_bond_factor\": \"1.25\",\n \"min_bond_factor\": \"0.75\",\n \"avg_block_time\": \"6.00\",\n \"target_bond_ratio\": \"00.67\",\n \"validator_emission_percentage\": \"00.50\",\n \"observer_emission_percentage\": \"00.25\",\n \"tss_signer_emission_percentage\": \"00.25\",\n \"duration_factor_constant\": \"0.001877876953694702\",\n \"observer_slash_amount\": \"0\"\n },\n \"withdrawableEmissions\": []\n },\n \"evidence\": {\n \"evidence\": []\n },\n \"evm\": {\n \"accounts\": [],\n \"params\": {\n \"evm_denom\": \"azeta\",\n \"enable_create\": true,\n \"enable_call\": true,\n \"extra_eips\": [],\n \"chain_config\": {\n \"homestead_block\": \"0\",\n \"dao_fork_block\": \"0\",\n \"dao_fork_support\": true,\n \"eip150_block\": \"0\",\n \"eip150_hash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"eip155_block\": \"0\",\n \"eip158_block\": \"0\",\n \"byzantium_block\": \"0\",\n \"constantinople_block\": \"0\",\n \"petersburg_block\": \"0\",\n \"istanbul_block\": \"0\",\n \"muir_glacier_block\": \"0\",\n \"berlin_block\": \"0\",\n \"london_block\": \"0\",\n \"arrow_glacier_block\": \"0\",\n \"gray_glacier_block\": \"0\",\n \"merge_netsplit_block\": \"0\",\n \"shanghai_block\": \"0\",\n \"cancun_block\": \"0\"\n },\n \"allow_unprotected_txs\": false\n }\n },\n \"feemarket\": {\n \"params\": {\n \"no_base_fee\": false,\n \"base_fee_change_denominator\": 8,\n \"elasticity_multiplier\": 2,\n \"enable_height\": \"0\",\n \"base_fee\": \"1000000000\",\n \"min_gas_price\": \"0.000000000000000000\",\n \"min_gas_multiplier\": \"0.500000000000000000\"\n },\n \"block_gas\": \"0\"\n },\n \"fungible\": {\n \"params\": {},\n \"foreignCoinsList\": [],\n \"systemContract\": null\n },\n \"genutil\": {\n \"gen_txs\": [\n {\n \"body\": {\n \"messages\": [\n {\n \"@type\": \"/cosmos.staking.v1beta1.MsgCreateValidator\",\n \"description\": {\n \"moniker\": \"Zetanode-Localnet\",\n \"identity\": \"\",\n \"website\": \"\",\n \"security_contact\": \"\",\n \"details\": \"\"\n },\n \"commission\": {\n \"rate\": \"0.100000000000000000\",\n \"max_rate\": \"0.200000000000000000\",\n \"max_change_rate\": \"0.010000000000000000\"\n },\n \"min_self_delegation\": \"1\",\n \"delegator_address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"validator_address\": \"zetavaloper13c7p3xrhd6q2rx3h235jpt8pjdwvacyw7tkass\",\n \"pubkey\": {\n \"@type\": \"/cosmos.crypto.ed25519.PubKey\",\n \"key\": \"sBSs5r1vQn1idTp4uRTbdUK0jjmEscI3pn88LUXI4CQ=\"\n },\n \"value\": {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n }\n ],\n \"memo\": \"1db4f4185e68c1c17d508294de2592616dad37a5@192.168.2.12:26656\",\n \"timeout_height\": \"0\",\n \"extension_options\": [],\n \"non_critical_extension_options\": []\n },\n \"auth_info\": {\n \"signer_infos\": [\n {\n \"public_key\": {\n \"@type\": \"/cosmos.crypto.secp256k1.PubKey\",\n \"key\": \"A05F6QuFVpb/5KrIPvlHr209ZsD22gW0omhLSXWAtQrh\"\n },\n \"mode_info\": {\n \"single\": {\n \"mode\": \"SIGN_MODE_DIRECT\"\n }\n },\n \"sequence\": \"0\"\n }\n ],\n \"fee\": {\n \"amount\": [],\n \"gas_limit\": \"200000\",\n \"payer\": \"\",\n \"granter\": \"\"\n },\n \"tip\": null\n },\n \"signatures\": [\n \"y5YROwZmV0jcgv5BgRJCDE+Kq5OsX8+88or1ogekPLBw3ecPt8GsCeEbPQ24JONLzNwQEIUDNYTeSQnXnCfzyg==\"\n ]\n }\n ]\n },\n \"gov\": {\n \"starting_proposal_id\": \"1\",\n \"deposits\": [],\n \"votes\": [],\n \"proposals\": [],\n \"deposit_params\": {\n \"min_deposit\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"10000000\"\n }\n ],\n \"max_deposit_period\": \"172800s\"\n },\n \"voting_params\": {\n \"voting_period\": \"10s\"\n },\n \"tally_params\": {\n \"quorum\": \"0.334000000000000000\",\n \"threshold\": \"0.500000000000000000\",\n \"veto_threshold\": \"0.334000000000000000\"\n }\n },\n \"group\": {\n \"group_seq\": \"0\",\n \"groups\": [],\n \"group_members\": [],\n \"group_policy_seq\": \"0\",\n \"group_policies\": [],\n \"proposal_seq\": \"0\",\n \"proposals\": [],\n \"votes\": []\n },\n \"mint\": {\n \"params\": {\n \"mint_denom\": \"azeta\"\n }\n },\n \"observer\": {\n \"observers\": {\n \"observer_list\": [\n \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\"\n ]\n },\n \"nodeAccountList\": [\n {\n \"operator\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"granteeAddress\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"granteePubkey\": {\n \"secp256k1\": \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\"\n },\n \"nodeStatus\": 4\n },\n {\n \"operator\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"granteeAddress\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"granteePubkey\": {\n \"secp256k1\": \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n },\n \"nodeStatus\": 4\n }\n ],\n \"crosschain_flags\": {\n \"isInboundEnabled\": true,\n \"isOutboundEnabled\": true\n },\n \"keygen\": {\n \"status\": 1,\n \"granteePubkeys\": [\n \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\",\n \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n ]\n },\n \"chain_params_list\": {},\n \"tss\": {\n \"tss_pubkey\": \"zetapub1addwnpepq28c57cvcs0a2htsem5zxr6qnlvq9mzhmm76z3jncsnzz32rclangr2g35p\",\n \"tss_participant_list\": [\n \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\",\n \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n ],\n \"operator_address_list\": [\n \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\"\n ]\n },\n \"tss_history\": [],\n \"tss_fund_migrators\": [],\n \"blame_list\": [],\n \"pending_nonces\": [],\n \"chain_nonces\": [],\n \"nonce_to_cctx\": []\n },\n \"params\": null,\n \"slashing\": {\n \"params\": {\n \"signed_blocks_window\": \"100\",\n \"min_signed_per_window\": \"0.500000000000000000\",\n \"downtime_jail_duration\": \"600s\",\n \"slash_fraction_double_sign\": \"0.050000000000000000\",\n \"slash_fraction_downtime\": \"0.010000000000000000\"\n },\n \"signing_infos\": [],\n \"missed_blocks\": []\n },\n \"staking\": {\n \"params\": {\n \"unbonding_time\": \"1814400s\",\n \"max_validators\": 100,\n \"max_entries\": 7,\n \"historical_entries\": 10000,\n \"bond_denom\": \"azeta\",\n \"min_commission_rate\": \"0.000000000000000000\"\n },\n \"last_total_power\": \"0\",\n \"last_validator_powers\": [],\n \"validators\": [],\n \"delegations\": [],\n \"unbonding_delegations\": [],\n \"redelegations\": [],\n \"exported\": false\n },\n \"upgrade\": {},\n \"vesting\": {}\n }\n }") + jsonBlob := []byte( + "{\n \"genesis_time\": \"2024-04-12T05:07:56.004517Z\",\n \"chain_id\": \"localnet_101-1\",\n \"initial_height\": \"1\",\n \"consensus_params\": {\n \"block\": {\n \"max_bytes\": \"22020096\",\n \"max_gas\": \"10000000\",\n \"time_iota_ms\": \"1000\"\n },\n \"evidence\": {\n \"max_age_num_blocks\": \"100000\",\n \"max_age_duration\": \"172800000000000\",\n \"max_bytes\": \"1048576\"\n },\n \"validator\": {\n \"pub_key_types\": [\n \"ed25519\"\n ]\n },\n \"version\": {}\n },\n \"app_hash\": \"\",\n \"app_state\": {\n \"auth\": {\n \"params\": {\n \"max_memo_characters\": \"256\",\n \"tx_sig_limit\": \"7\",\n \"tx_size_cost_per_byte\": \"10\",\n \"sig_verify_cost_ed25519\": \"590\",\n \"sig_verify_cost_secp256k1\": \"1000\"\n },\n \"accounts\": [\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n },\n {\n \"@type\": \"/ethermint.types.v1.EthAccount\",\n \"base_account\": {\n \"address\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"pub_key\": null,\n \"account_number\": \"0\",\n \"sequence\": \"0\"\n },\n \"code_hash\": \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"\n }\n ]\n },\n \"authority\": {\n \"policies\": {\n \"items\": [\n {\n \"policy_type\": \"groupEmergency\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n },\n {\n \"policy_type\": \"groupOperational\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n },\n {\n \"policy_type\": \"groupAdmin\",\n \"address\": \"zeta1afk9zr2hn2jsac63h4hm60vl9z3e5u69gndzf7c99cqge3vzwjzsxn0x73\"\n }\n ]\n }\n },\n \"authz\": {\n \"authorization\": [\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgGasPriceVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedInboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedOutboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgCreateTSSVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgAddToOutTxTracker\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlameVote\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"grantee\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlockHeader\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgGasPriceVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedInboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgVoteOnObservedOutboundTx\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgCreateTSSVoter\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.crosschain.MsgAddToOutTxTracker\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlameVote\"\n },\n \"expiration\": null\n },\n {\n \"granter\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"grantee\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"authorization\": {\n \"@type\": \"/cosmos.authz.v1beta1.GenericAuthorization\",\n \"msg\": \"/zetachain.zetacore.observer.MsgAddBlockHeader\"\n },\n \"expiration\": null\n }\n ]\n },\n \"bank\": {\n \"params\": {\n \"send_enabled\": [],\n \"default_send_enabled\": true\n },\n \"balances\": [\n {\n \"address\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"4200000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"4200000000000000000000000\"\n }\n ]\n },\n {\n \"address\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"coins\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n ]\n }\n ],\n \"supply\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"8402000000000000000000000\"\n }\n ],\n \"denom_metadata\": []\n },\n \"crisis\": {\n \"constant_fee\": {\n \"denom\": \"azeta\",\n \"amount\": \"1000\"\n }\n },\n \"crosschain\": {\n \"outTxTrackerList\": [],\n \"inTxHashToCctxList\": [],\n \"in_tx_tracker_list\": [],\n \"zeta_accounting\": {\n \"aborted_zeta_amount\": \"0\"\n }\n },\n \"distribution\": {\n \"params\": {\n \"community_tax\": \"0.020000000000000000\",\n \"base_proposer_reward\": \"0.010000000000000000\",\n \"bonus_proposer_reward\": \"0.040000000000000000\",\n \"withdraw_addr_enabled\": true\n },\n \"fee_pool\": {\n \"community_pool\": []\n },\n \"delegator_withdraw_infos\": [],\n \"previous_proposer\": \"\",\n \"outstanding_rewards\": [],\n \"validator_accumulated_commissions\": [],\n \"validator_historical_rewards\": [],\n \"validator_current_rewards\": [],\n \"delegator_starting_infos\": [],\n \"validator_slash_events\": []\n },\n \"emissions\": {\n \"params\": {\n \"max_bond_factor\": \"1.25\",\n \"min_bond_factor\": \"0.75\",\n \"avg_block_time\": \"6.00\",\n \"target_bond_ratio\": \"00.67\",\n \"validator_emission_percentage\": \"00.50\",\n \"observer_emission_percentage\": \"00.25\",\n \"tss_signer_emission_percentage\": \"00.25\",\n \"duration_factor_constant\": \"0.001877876953694702\",\n \"observer_slash_amount\": \"0\"\n },\n \"withdrawableEmissions\": []\n },\n \"evidence\": {\n \"evidence\": []\n },\n \"evm\": {\n \"accounts\": [],\n \"params\": {\n \"evm_denom\": \"azeta\",\n \"enable_create\": true,\n \"enable_call\": true,\n \"extra_eips\": [],\n \"chain_config\": {\n \"homestead_block\": \"0\",\n \"dao_fork_block\": \"0\",\n \"dao_fork_support\": true,\n \"eip150_block\": \"0\",\n \"eip150_hash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"eip155_block\": \"0\",\n \"eip158_block\": \"0\",\n \"byzantium_block\": \"0\",\n \"constantinople_block\": \"0\",\n \"petersburg_block\": \"0\",\n \"istanbul_block\": \"0\",\n \"muir_glacier_block\": \"0\",\n \"berlin_block\": \"0\",\n \"london_block\": \"0\",\n \"arrow_glacier_block\": \"0\",\n \"gray_glacier_block\": \"0\",\n \"merge_netsplit_block\": \"0\",\n \"shanghai_block\": \"0\",\n \"cancun_block\": \"0\"\n },\n \"allow_unprotected_txs\": false\n }\n },\n \"feemarket\": {\n \"params\": {\n \"no_base_fee\": false,\n \"base_fee_change_denominator\": 8,\n \"elasticity_multiplier\": 2,\n \"enable_height\": \"0\",\n \"base_fee\": \"1000000000\",\n \"min_gas_price\": \"0.000000000000000000\",\n \"min_gas_multiplier\": \"0.500000000000000000\"\n },\n \"block_gas\": \"0\"\n },\n \"fungible\": {\n \"params\": {},\n \"foreignCoinsList\": [],\n \"systemContract\": null\n },\n \"genutil\": {\n \"gen_txs\": [\n {\n \"body\": {\n \"messages\": [\n {\n \"@type\": \"/cosmos.staking.v1beta1.MsgCreateValidator\",\n \"description\": {\n \"moniker\": \"Zetanode-Localnet\",\n \"identity\": \"\",\n \"website\": \"\",\n \"security_contact\": \"\",\n \"details\": \"\"\n },\n \"commission\": {\n \"rate\": \"0.100000000000000000\",\n \"max_rate\": \"0.200000000000000000\",\n \"max_change_rate\": \"0.010000000000000000\"\n },\n \"min_self_delegation\": \"1\",\n \"delegator_address\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"validator_address\": \"zetavaloper13c7p3xrhd6q2rx3h235jpt8pjdwvacyw7tkass\",\n \"pubkey\": {\n \"@type\": \"/cosmos.crypto.ed25519.PubKey\",\n \"key\": \"sBSs5r1vQn1idTp4uRTbdUK0jjmEscI3pn88LUXI4CQ=\"\n },\n \"value\": {\n \"denom\": \"azeta\",\n \"amount\": \"1000000000000000000000\"\n }\n }\n ],\n \"memo\": \"1db4f4185e68c1c17d508294de2592616dad37a5@192.168.2.12:26656\",\n \"timeout_height\": \"0\",\n \"extension_options\": [],\n \"non_critical_extension_options\": []\n },\n \"auth_info\": {\n \"signer_infos\": [\n {\n \"public_key\": {\n \"@type\": \"/cosmos.crypto.secp256k1.PubKey\",\n \"key\": \"A05F6QuFVpb/5KrIPvlHr209ZsD22gW0omhLSXWAtQrh\"\n },\n \"mode_info\": {\n \"single\": {\n \"mode\": \"SIGN_MODE_DIRECT\"\n }\n },\n \"sequence\": \"0\"\n }\n ],\n \"fee\": {\n \"amount\": [],\n \"gas_limit\": \"200000\",\n \"payer\": \"\",\n \"granter\": \"\"\n },\n \"tip\": null\n },\n \"signatures\": [\n \"y5YROwZmV0jcgv5BgRJCDE+Kq5OsX8+88or1ogekPLBw3ecPt8GsCeEbPQ24JONLzNwQEIUDNYTeSQnXnCfzyg==\"\n ]\n }\n ]\n },\n \"gov\": {\n \"starting_proposal_id\": \"1\",\n \"deposits\": [],\n \"votes\": [],\n \"proposals\": [],\n \"deposit_params\": {\n \"min_deposit\": [\n {\n \"denom\": \"azeta\",\n \"amount\": \"10000000\"\n }\n ],\n \"max_deposit_period\": \"172800s\"\n },\n \"voting_params\": {\n \"voting_period\": \"10s\"\n },\n \"tally_params\": {\n \"quorum\": \"0.334000000000000000\",\n \"threshold\": \"0.500000000000000000\",\n \"veto_threshold\": \"0.334000000000000000\"\n }\n },\n \"group\": {\n \"group_seq\": \"0\",\n \"groups\": [],\n \"group_members\": [],\n \"group_policy_seq\": \"0\",\n \"group_policies\": [],\n \"proposal_seq\": \"0\",\n \"proposals\": [],\n \"votes\": []\n },\n \"mint\": {\n \"params\": {\n \"mint_denom\": \"azeta\"\n }\n },\n \"observer\": {\n \"observers\": {\n \"observer_list\": [\n \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\"\n ]\n },\n \"nodeAccountList\": [\n {\n \"operator\": \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"granteeAddress\": \"zeta10up34mvwjhjd9xkq56fwsf0k75vtg287uav69n\",\n \"granteePubkey\": {\n \"secp256k1\": \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\"\n },\n \"nodeStatus\": 4\n },\n {\n \"operator\": \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\",\n \"granteeAddress\": \"zeta1unzpyll3tmutf0r8sqpxpnj46vtdr59mw8qepx\",\n \"granteePubkey\": {\n \"secp256k1\": \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n },\n \"nodeStatus\": 4\n }\n ],\n \"crosschain_flags\": {\n \"isInboundEnabled\": true,\n \"isOutboundEnabled\": true\n },\n \"keygen\": {\n \"status\": 1,\n \"granteePubkeys\": [\n \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\",\n \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n ]\n },\n \"chain_params_list\": {},\n \"tss\": {\n \"tss_pubkey\": \"zetapub1addwnpepq28c57cvcs0a2htsem5zxr6qnlvq9mzhmm76z3jncsnzz32rclangr2g35p\",\n \"tss_participant_list\": [\n \"zetapub1addwnpepqtlu7fykuh875xjckz4mn4x0mzc25rrqk5qne7mrwxqmatgllv3nx6lrkdp\",\n \"zetapub1addwnpepqwy5pmg39regpq0gkggxehmfm8hwmxxw94sch7qzh4smava0szs07kk5045\"\n ],\n \"operator_address_list\": [\n \"zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax\",\n \"zeta1f203dypqg5jh9hqfx0gfkmmnkdfuat3jr45ep2\"\n ]\n },\n \"tss_history\": [],\n \"tss_fund_migrators\": [],\n \"blame_list\": [],\n \"pending_nonces\": [],\n \"chain_nonces\": [],\n \"nonce_to_cctx\": []\n },\n \"params\": null,\n \"slashing\": {\n \"params\": {\n \"signed_blocks_window\": \"100\",\n \"min_signed_per_window\": \"0.500000000000000000\",\n \"downtime_jail_duration\": \"600s\",\n \"slash_fraction_double_sign\": \"0.050000000000000000\",\n \"slash_fraction_downtime\": \"0.010000000000000000\"\n },\n \"signing_infos\": [],\n \"missed_blocks\": []\n },\n \"staking\": {\n \"params\": {\n \"unbonding_time\": \"1814400s\",\n \"max_validators\": 100,\n \"max_entries\": 7,\n \"historical_entries\": 10000,\n \"bond_denom\": \"azeta\",\n \"min_commission_rate\": \"0.000000000000000000\"\n },\n \"last_total_power\": \"0\",\n \"last_validator_powers\": [],\n \"validators\": [],\n \"delegations\": [],\n \"unbonding_delegations\": [],\n \"redelegations\": [],\n \"exported\": false\n },\n \"upgrade\": {},\n \"vesting\": {}\n }\n }", + ) genDoc, err := types.GenesisDocFromJSON(jsonBlob) require.NoError(t, err) return genDoc diff --git a/testutil/simapp/simapp.go b/testutil/simapp/simapp.go index 73857ace40..10e941acb5 100644 --- a/testutil/simapp/simapp.go +++ b/testutil/simapp/simapp.go @@ -52,14 +52,32 @@ func Setup(isCheckTx bool) *app.App { func setup(withGenesis bool, invCheckPeriod uint) (*app.App, app.GenesisState) { db := tmdb.NewMemDB() encCdc := app.MakeEncodingConfig() - a := app.New(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, invCheckPeriod, encCdc, simtestutil.EmptyAppOptions{}) + a := app.New( + log.NewNopLogger(), + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + invCheckPeriod, + encCdc, + simtestutil.EmptyAppOptions{}, + ) if withGenesis { return a, app.NewDefaultGenesisState(encCdc.Codec) } return a, app.GenesisState{} } -func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genDelAccs []authtypes.GenesisAccount, bondAmt sdk.Int, emissionParams types2.Params, genDelBalances []banktypes.Balance, genBalances []banktypes.Balance) *app.App { +func SetupWithGenesisValSet( + t *testing.T, + valSet *tmtypes.ValidatorSet, + genDelAccs []authtypes.GenesisAccount, + bondAmt sdk.Int, + emissionParams types2.Params, + genDelBalances []banktypes.Balance, + genBalances []banktypes.Balance, +) *app.App { app, genesisState := setup(true, 5) // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genDelAccs) @@ -88,7 +106,10 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genDelAc MinSelfDelegation: sdk.ZeroInt(), } validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genDelAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + delegations = append( + delegations, + stakingtypes.NewDelegation(genDelAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec()), + ) } emissionsGenesis := types2.DefaultGenesis() @@ -124,7 +145,13 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genDelAc // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, totalBalances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) + bankGenesis := banktypes.NewGenesisState( + banktypes.DefaultGenesisState().Params, + totalBalances, + totalSupply, + []banktypes.Metadata{}, + []banktypes.SendEnabled{}, + ) genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) stateBytes, err := json.MarshalIndent(genesisState, "", " ") @@ -164,7 +191,13 @@ func SetupWithGenesisAccounts(genAccs []authtypes.GenesisAccount, balances ...ba totalSupply = totalSupply.Add(b.Coins...) } - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) + bankGenesis := banktypes.NewGenesisState( + banktypes.DefaultGenesisState().Params, + balances, + totalSupply, + []banktypes.Metadata{}, + []banktypes.SendEnabled{}, + ) genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) stateBytes, err := json.MarshalIndent(genesisState, "", " ") diff --git a/x/authority/keeper/grpc_query_policies.go b/x/authority/keeper/grpc_query_policies.go index e799ce97ec..057a21ed93 100644 --- a/x/authority/keeper/grpc_query_policies.go +++ b/x/authority/keeper/grpc_query_policies.go @@ -10,7 +10,10 @@ import ( ) // Policies queries policies -func (k Keeper) Policies(c context.Context, req *types.QueryGetPoliciesRequest) (*types.QueryGetPoliciesResponse, error) { +func (k Keeper) Policies( + c context.Context, + req *types.QueryGetPoliciesRequest, +) (*types.QueryGetPoliciesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/authority/keeper/msg_server_update_policies.go b/x/authority/keeper/msg_server_update_policies.go index e228c8cdce..1a7cb2465f 100644 --- a/x/authority/keeper/msg_server_update_policies.go +++ b/x/authority/keeper/msg_server_update_policies.go @@ -10,7 +10,10 @@ import ( ) // UpdatePolicies updates policies -func (k msgServer) UpdatePolicies(goCtx context.Context, msg *types.MsgUpdatePolicies) (*types.MsgUpdatePoliciesResponse, error) { +func (k msgServer) UpdatePolicies( + goCtx context.Context, + msg *types.MsgUpdatePolicies, +) (*types.MsgUpdatePoliciesResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check called by governance diff --git a/x/authority/types/policies.go b/x/authority/types/policies.go index 30bb5d6823..28a97594ce 100644 --- a/x/authority/types/policies.go +++ b/x/authority/types/policies.go @@ -42,7 +42,8 @@ func (p Policies) Validate() error { return fmt.Errorf("invalid address: %s", err) } - if policy.PolicyType != PolicyType_groupEmergency && policy.PolicyType != PolicyType_groupAdmin && policy.PolicyType != PolicyType_groupOperational { + if policy.PolicyType != PolicyType_groupEmergency && policy.PolicyType != PolicyType_groupAdmin && + policy.PolicyType != PolicyType_groupOperational { return fmt.Errorf("invalid policy type: %s", policy.PolicyType) } diff --git a/x/crosschain/client/cli/cli_gas_price.go b/x/crosschain/client/cli/cli_gas_price.go index 9de219aefb..b136dc5278 100644 --- a/x/crosschain/client/cli/cli_gas_price.go +++ b/x/crosschain/client/cli/cli_gas_price.go @@ -99,7 +99,13 @@ func CmdVoteGasPrice() *cobra.Command { return err } - msg := types.NewMsgVoteGasPrice(clientCtx.GetFromAddress().String(), argsChain, argsPrice, argsSupply, argsBlockNumber) + msg := types.NewMsgVoteGasPrice( + clientCtx.GetFromAddress().String(), + argsChain, + argsPrice, + argsSupply, + argsBlockNumber, + ) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, diff --git a/x/crosschain/keeper/abci_test.go b/x/crosschain/keeper/abci_test.go index 7f89e36c08..b0609c4563 100644 --- a/x/crosschain/keeper/abci_test.go +++ b/x/crosschain/keeper/abci_test.go @@ -106,7 +106,9 @@ func TestKeeper_IterateAndUpdateCctxGasPrice(t *testing.T) { func TestCheckAndUpdateCctxGasPrice(t *testing.T) { sampleTimestamp := time.Now() retryIntervalReached := sampleTimestamp.Add(observertypes.DefaultGasPriceIncreaseFlags.RetryInterval + time.Second) - retryIntervalNotReached := sampleTimestamp.Add(observertypes.DefaultGasPriceIncreaseFlags.RetryInterval - time.Second) + retryIntervalNotReached := sampleTimestamp.Add( + observertypes.DefaultGasPriceIncreaseFlags.RetryInterval - time.Second, + ) tt := []struct { name string @@ -382,8 +384,20 @@ func TestCheckAndUpdateCctxGasPrice(t *testing.T) { require.NoError(t, err) // check values - require.True(t, gasPriceIncrease.Equal(tc.expectedGasPriceIncrease), "expected %s, got %s", tc.expectedGasPriceIncrease.String(), gasPriceIncrease.String()) - require.True(t, feesPaid.Equal(tc.expectedAdditionalFees), "expected %s, got %s", tc.expectedAdditionalFees.String(), feesPaid.String()) + require.True( + t, + gasPriceIncrease.Equal(tc.expectedGasPriceIncrease), + "expected %s, got %s", + tc.expectedGasPriceIncrease.String(), + gasPriceIncrease.String(), + ) + require.True( + t, + feesPaid.Equal(tc.expectedAdditionalFees), + "expected %s, got %s", + tc.expectedAdditionalFees.String(), + feesPaid.String(), + ) // check cctx if !tc.expectedGasPriceIncrease.IsZero() { @@ -391,7 +405,14 @@ func TestCheckAndUpdateCctxGasPrice(t *testing.T) { require.True(t, found) newGasPrice, err := cctx.GetCurrentOutTxParam().GetGasPrice() require.NoError(t, err) - require.EqualValues(t, tc.expectedGasPriceIncrease.AddUint64(previousGasPrice).Uint64(), newGasPrice, "%d - %d", tc.expectedGasPriceIncrease.Uint64(), previousGasPrice) + require.EqualValues( + t, + tc.expectedGasPriceIncrease.AddUint64(previousGasPrice).Uint64(), + newGasPrice, + "%d - %d", + tc.expectedGasPriceIncrease.Uint64(), + previousGasPrice, + ) require.EqualValues(t, tc.blockTimestamp.Unix(), cctx.CctxStatus.LastUpdateTimestamp) } }) diff --git a/x/crosschain/keeper/cctx.go b/x/crosschain/keeper/cctx.go index 42604c9098..64f0296fd2 100644 --- a/x/crosschain/keeper/cctx.go +++ b/x/crosschain/keeper/cctx.go @@ -21,7 +21,8 @@ func (k Keeper) SetCctxAndNonceToCctxAndInTxHashToCctx(ctx sdk.Context, cctx typ return } // set mapping nonce => cctxIndex - if cctx.CctxStatus.Status == types.CctxStatus_PendingOutbound || cctx.CctxStatus.Status == types.CctxStatus_PendingRevert { + if cctx.CctxStatus.Status == types.CctxStatus_PendingOutbound || + cctx.CctxStatus.Status == types.CctxStatus_PendingRevert { k.GetObserverKeeper().SetNonceToCctx(ctx, observerTypes.NonceToCctx{ ChainId: cctx.GetCurrentOutTxParam().ReceiverChainId, // #nosec G701 always in range diff --git a/x/crosschain/keeper/cctx_test.go b/x/crosschain/keeper/cctx_test.go index 3a7fb7fe5b..26b64c0aea 100644 --- a/x/crosschain/keeper/cctx_test.go +++ b/x/crosschain/keeper/cctx_test.go @@ -19,7 +19,12 @@ import ( "github.com/zeta-chain/zetacore/x/crosschain/types" ) -func createNCctxWithStatus(keeper *keeper.Keeper, ctx sdk.Context, n int, status types.CctxStatus) []types.CrossChainTx { +func createNCctxWithStatus( + keeper *keeper.Keeper, + ctx sdk.Context, + n int, + status types.CctxStatus, +) []types.CrossChainTx { items := make([]types.CrossChainTx, n) for i := range items { items[i].Creator = "any" @@ -30,7 +35,10 @@ func createNCctxWithStatus(keeper *keeper.Keeper, ctx sdk.Context, n int, status LastUpdateTimestamp: 0, } items[i].ZetaFees = math.OneUint() - items[i].InboundTxParams = &types.InboundTxParams{InboundTxObservedHash: fmt.Sprintf("%d", i), Amount: math.OneUint()} + items[i].InboundTxParams = &types.InboundTxParams{ + InboundTxObservedHash: fmt.Sprintf("%d", i), + Amount: math.OneUint(), + } items[i].OutboundTxParams = []*types.OutboundTxParams{{Amount: math.ZeroUint()}} keeper.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, items[i]) @@ -118,11 +126,19 @@ func TestSends(t *testing.T) { keeper.SetZetaAccounting(ctx, types.ZetaAccounting{AbortedZetaAmount: math.ZeroUint()}) var sends []types.CrossChainTx zk.ObserverKeeper.SetTSS(ctx, sample.Tss()) - sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.PendingInbound, types.CctxStatus_PendingInbound)...) - sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.PendingOutbound, types.CctxStatus_PendingOutbound)...) - sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.PendingRevert, types.CctxStatus_PendingRevert)...) + sends = append( + sends, + createNCctxWithStatus(keeper, ctx, tt.PendingInbound, types.CctxStatus_PendingInbound)...) + sends = append( + sends, + createNCctxWithStatus(keeper, ctx, tt.PendingOutbound, types.CctxStatus_PendingOutbound)...) + sends = append( + sends, + createNCctxWithStatus(keeper, ctx, tt.PendingRevert, types.CctxStatus_PendingRevert)...) sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.Aborted, types.CctxStatus_Aborted)...) - sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.OutboundMined, types.CctxStatus_OutboundMined)...) + sends = append( + sends, + createNCctxWithStatus(keeper, ctx, tt.OutboundMined, types.CctxStatus_OutboundMined)...) sends = append(sends, createNCctxWithStatus(keeper, ctx, tt.Reverted, types.CctxStatus_Reverted)...) //require.Equal(t, tt.PendingOutbound, len(keeper.GetAllCctxByStatuses(ctx, []types.CctxStatus{types.CctxStatus_PendingOutbound}))) //require.Equal(t, tt.PendingInbound, len(keeper.GetAllCctxByStatuses(ctx, []types.CctxStatus{types.CctxStatus_PendingInbound}))) diff --git a/x/crosschain/keeper/cctx_utils.go b/x/crosschain/keeper/cctx_utils.go index 591f131c16..1100fc6173 100644 --- a/x/crosschain/keeper/cctx_utils.go +++ b/x/crosschain/keeper/cctx_utils.go @@ -26,24 +26,36 @@ func (k Keeper) UpdateNonce(ctx sdk.Context, receiveChainID int64, cctx *types.C nonce, found := k.GetObserverKeeper().GetChainNonces(ctx, chain.ChainName.String()) if !found { - return cosmoserrors.Wrap(types.ErrCannotFindReceiverNonce, fmt.Sprintf("Chain(%s) | Identifiers : %s ", chain.ChainName.String(), cctx.LogIdentifierForCCTX())) + return cosmoserrors.Wrap( + types.ErrCannotFindReceiverNonce, + fmt.Sprintf("Chain(%s) | Identifiers : %s ", chain.ChainName.String(), cctx.LogIdentifierForCCTX()), + ) } // SET nonce cctx.GetCurrentOutTxParam().OutboundTxTssNonce = nonce.Nonce tss, found := k.GetObserverKeeper().GetTSS(ctx) if !found { - return cosmoserrors.Wrap(types.ErrCannotFindTSSKeys, fmt.Sprintf("Chain(%s) | Identifiers : %s ", chain.ChainName.String(), cctx.LogIdentifierForCCTX())) + return cosmoserrors.Wrap( + types.ErrCannotFindTSSKeys, + fmt.Sprintf("Chain(%s) | Identifiers : %s ", chain.ChainName.String(), cctx.LogIdentifierForCCTX()), + ) } p, found := k.GetObserverKeeper().GetPendingNonces(ctx, tss.TssPubkey, receiveChainID) if !found { - return cosmoserrors.Wrap(types.ErrCannotFindPendingNonces, fmt.Sprintf("chain_id %d, nonce %d", receiveChainID, nonce.Nonce)) + return cosmoserrors.Wrap( + types.ErrCannotFindPendingNonces, + fmt.Sprintf("chain_id %d, nonce %d", receiveChainID, nonce.Nonce), + ) } // #nosec G701 always in range if p.NonceHigh != int64(nonce.Nonce) { - return cosmoserrors.Wrap(types.ErrNonceMismatch, fmt.Sprintf("chain_id %d, high nonce %d, current nonce %d", receiveChainID, p.NonceHigh, nonce.Nonce)) + return cosmoserrors.Wrap( + types.ErrNonceMismatch, + fmt.Sprintf("chain_id %d, high nonce %d, current nonce %d", receiveChainID, p.NonceHigh, nonce.Nonce), + ) } nonce.Nonce++ @@ -89,7 +101,8 @@ func (k Keeper) GetRevertGasLimit(ctx sdk.Context, cctx types.CrossChainTx) (uin func IsPending(cctx *types.CrossChainTx) bool { // pending inbound is not considered a "pending" state because it has not reached consensus yet - return cctx.CctxStatus.Status == types.CctxStatus_PendingOutbound || cctx.CctxStatus.Status == types.CctxStatus_PendingRevert + return cctx.CctxStatus.Status == types.CctxStatus_PendingOutbound || + cctx.CctxStatus.Status == types.CctxStatus_PendingRevert } // GetAbortedAmount returns the amount to refund for a given CCTX . diff --git a/x/crosschain/keeper/cctx_utils_test.go b/x/crosschain/keeper/cctx_utils_test.go index a268c20b78..9d12a103e9 100644 --- a/x/crosschain/keeper/cctx_utils_test.go +++ b/x/crosschain/keeper/cctx_utils_test.go @@ -216,7 +216,11 @@ func Test_IsPending(t *testing.T) { } for _, tc := range tt { t.Run(fmt.Sprintf("status %s", tc.status), func(t *testing.T) { - require.Equal(t, tc.expected, crosschainkeeper.IsPending(&types.CrossChainTx{CctxStatus: &types.Status{Status: tc.status}})) + require.Equal( + t, + tc.expected, + crosschainkeeper.IsPending(&types.CrossChainTx{CctxStatus: &types.Status{Status: tc.status}}), + ) }) } } @@ -298,7 +302,8 @@ func TestKeeper_UpdateNonce(t *testing.T) { Nonce: 100, }, true) observerMock.On("GetTSS", mock.Anything).Return(observertypes.TSS{}, true) - observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything).Return(observertypes.PendingNonces{}, false) + observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything). + Return(observertypes.PendingNonces{}, false) cctx := types.CrossChainTx{ InboundTxParams: &types.InboundTxParams{ @@ -326,9 +331,10 @@ func TestKeeper_UpdateNonce(t *testing.T) { Nonce: 100, }, true) observerMock.On("GetTSS", mock.Anything).Return(observertypes.TSS{}, true) - observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything).Return(observertypes.PendingNonces{ - NonceHigh: 99, - }, true) + observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything). + Return(observertypes.PendingNonces{ + NonceHigh: 99, + }, true) cctx := types.CrossChainTx{ InboundTxParams: &types.InboundTxParams{ @@ -356,9 +362,10 @@ func TestKeeper_UpdateNonce(t *testing.T) { Nonce: 100, }, true) observerMock.On("GetTSS", mock.Anything).Return(observertypes.TSS{}, true) - observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything).Return(observertypes.PendingNonces{ - NonceHigh: 100, - }, true) + observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything). + Return(observertypes.PendingNonces{ + NonceHigh: 100, + }, true) observerMock.On("SetChainNonces", mock.Anything, mock.Anything).Once() observerMock.On("SetPendingNonces", mock.Anything, mock.Anything).Once() diff --git a/x/crosschain/keeper/evm_deposit.go b/x/crosschain/keeper/evm_deposit.go index 3a25353e06..43dbfcf281 100644 --- a/x/crosschain/keeper/evm_deposit.go +++ b/x/crosschain/keeper/evm_deposit.go @@ -51,7 +51,15 @@ func (k Keeper) HandleEVMDeposit(ctx sdk.Context, cctx *types.CrossChainTx) (boo return true, errors.Wrap(types.ErrUnableToDecodeMessageString, err.Error()) } // if coin type is Zeta, this is a deposit ZETA to zEVM cctx. - evmTxResponse, err := k.fungibleKeeper.ZETADepositAndCallContract(ctx, sender, to, inboundSenderChainID, inboundAmount, data, indexBytes) + evmTxResponse, err := k.fungibleKeeper.ZETADepositAndCallContract( + ctx, + sender, + to, + inboundSenderChainID, + inboundAmount, + data, + indexBytes, + ) if fungibletypes.IsContractReverted(evmTxResponse, err) || errShouldRevertCctx(err) { return true, err } else if err != nil { diff --git a/x/crosschain/keeper/evm_deposit_test.go b/x/crosschain/keeper/evm_deposit_test.go index d30424697c..9b9ab13a1e 100644 --- a/x/crosschain/keeper/evm_deposit_test.go +++ b/x/crosschain/keeper/evm_deposit_test.go @@ -31,7 +31,8 @@ func TestMsgServer_HandleEVMDeposit(t *testing.T) { senderChainId := int64(0) // expect DepositCoinZeta to be called - fungibleMock.On("ZETADepositAndCallContract", ctx, ethcommon.HexToAddress(sender.String()), receiver, senderChainId, amount, mock.Anything, mock.Anything).Return(nil, nil) + fungibleMock.On("ZETADepositAndCallContract", ctx, ethcommon.HexToAddress(sender.String()), receiver, senderChainId, amount, mock.Anything, mock.Anything). + Return(nil, nil) // call HandleEVMDeposit cctx := sample.CrossChainTx(t, "foo") @@ -62,8 +63,10 @@ func TestMsgServer_HandleEVMDeposit(t *testing.T) { cctx := sample.CrossChainTx(t, "foo") // expect DepositCoinZeta to be called errDeposit := errors.New("deposit failed") - fungibleMock.On("ZETADepositAndCallContract", ctx, ethcommon.HexToAddress(sender.String()), receiver, senderChainId, amount, mock.Anything, mock.Anything).Return(nil, errDeposit) - // call HandleEVMDeposit + fungibleMock.On("ZETADepositAndCallContract", ctx, ethcommon.HexToAddress(sender.String()), receiver, senderChainId, amount, mock.Anything, mock.Anything). + Return(nil, errDeposit) + + // call HandleEVMDeposit cctx.InboundTxParams.Sender = sender.String() cctx.GetCurrentOutTxParam().Receiver = receiver.String() @@ -122,125 +125,131 @@ func TestMsgServer_HandleEVMDeposit(t *testing.T) { fungibleMock.AssertExpectations(t) }) - t.Run("should error on processing ERC20 deposit calling fungible method for contract call if process logs fails", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - }) - - senderChain := getValidEthChainID() - - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - - // expect DepositCoinZeta to be called - // ZRC20DepositAndCallContract(ctx, from, to, msg.Amount.BigInt(), senderChain, msg.Message, contract, data, msg.CoinType, msg.Asset) - fungibleMock.On( - "ZRC20DepositAndCallContract", - ctx, - mock.Anything, - receiver, - amount, - senderChain, - mock.Anything, - coin.CoinType_ERC20, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{ - Logs: []*evmtypes.Log{ - { - Address: receiver.Hex(), - Topics: []string{}, - Data: []byte{}, - BlockNumber: uint64(ctx.BlockHeight()), - TxHash: sample.Hash().Hex(), - TxIndex: 1, - BlockHash: sample.Hash().Hex(), - Index: 1, + t.Run( + "should error on processing ERC20 deposit calling fungible method for contract call if process logs fails", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + }) + + senderChain := getValidEthChainID() + + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + + // expect DepositCoinZeta to be called + // ZRC20DepositAndCallContract(ctx, from, to, msg.Amount.BigInt(), senderChain, msg.Message, contract, data, msg.CoinType, msg.Asset) + fungibleMock.On( + "ZRC20DepositAndCallContract", + ctx, + mock.Anything, + receiver, + amount, + senderChain, + mock.Anything, + coin.CoinType_ERC20, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{ + Logs: []*evmtypes.Log{ + { + Address: receiver.Hex(), + Topics: []string{}, + Data: []byte{}, + BlockNumber: uint64(ctx.BlockHeight()), + TxHash: sample.Hash().Hex(), + TxIndex: 1, + BlockHash: sample.Hash().Hex(), + Index: 1, + }, }, - }, - }, true, nil) - - fungibleMock.On("GetSystemContract", mock.Anything).Return(fungibletypes.SystemContract{}, false) - - // call HandleEVMDeposit - cctx := sample.CrossChainTx(t, "foo") - cctx.InboundTxParams.TxOrigin = "" - cctx.GetCurrentOutTxParam().Receiver = receiver.String() - cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundTxParams().Sender = sample.EthAddress().String() - cctx.GetInboundTxParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundTxParams().Asset = "" - reverted, err := k.HandleEVMDeposit( - ctx, - cctx, - ) - require.Error(t, err) - require.False(t, reverted) - fungibleMock.AssertExpectations(t) - }) - - t.Run("can process ERC20 deposit calling fungible method for contract call if process logs doesnt fail", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - }) - - senderChain := getValidEthChainID() - - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - - // expect DepositCoinZeta to be called - // ZRC20DepositAndCallContract(ctx, from, to, msg.Amount.BigInt(), senderChain, msg.Message, contract, data, msg.CoinType, msg.Asset) - fungibleMock.On( - "ZRC20DepositAndCallContract", - ctx, - mock.Anything, - receiver, - amount, - senderChain, - mock.Anything, - coin.CoinType_ERC20, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{ - Logs: []*evmtypes.Log{ - { - Address: receiver.Hex(), - Topics: []string{}, - Data: []byte{}, - BlockNumber: uint64(ctx.BlockHeight()), - TxHash: sample.Hash().Hex(), - TxIndex: 1, - BlockHash: sample.Hash().Hex(), - Index: 1, + }, true, nil) + + fungibleMock.On("GetSystemContract", mock.Anything).Return(fungibletypes.SystemContract{}, false) + + // call HandleEVMDeposit + cctx := sample.CrossChainTx(t, "foo") + cctx.InboundTxParams.TxOrigin = "" + cctx.GetCurrentOutTxParam().Receiver = receiver.String() + cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundTxParams().Sender = sample.EthAddress().String() + cctx.GetInboundTxParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundTxParams().Asset = "" + reverted, err := k.HandleEVMDeposit( + ctx, + cctx, + ) + require.Error(t, err) + require.False(t, reverted) + fungibleMock.AssertExpectations(t) + }, + ) + + t.Run( + "can process ERC20 deposit calling fungible method for contract call if process logs doesnt fail", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + }) + + senderChain := getValidEthChainID() + + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + + // expect DepositCoinZeta to be called + // ZRC20DepositAndCallContract(ctx, from, to, msg.Amount.BigInt(), senderChain, msg.Message, contract, data, msg.CoinType, msg.Asset) + fungibleMock.On( + "ZRC20DepositAndCallContract", + ctx, + mock.Anything, + receiver, + amount, + senderChain, + mock.Anything, + coin.CoinType_ERC20, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{ + Logs: []*evmtypes.Log{ + { + Address: receiver.Hex(), + Topics: []string{}, + Data: []byte{}, + BlockNumber: uint64(ctx.BlockHeight()), + TxHash: sample.Hash().Hex(), + TxIndex: 1, + BlockHash: sample.Hash().Hex(), + Index: 1, + }, }, - }, - }, true, nil) - - fungibleMock.On("GetSystemContract", mock.Anything).Return(fungibletypes.SystemContract{ - ConnectorZevm: sample.EthAddress().Hex(), - }, true) - - // call HandleEVMDeposit - cctx := sample.CrossChainTx(t, "foo") - cctx.InboundTxParams.TxOrigin = "" - cctx.GetCurrentOutTxParam().Receiver = receiver.String() - cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundTxParams().Sender = sample.EthAddress().String() - cctx.GetInboundTxParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundTxParams().Asset = "" - reverted, err := k.HandleEVMDeposit( - ctx, - cctx, - ) - require.NoError(t, err) - require.False(t, reverted) - fungibleMock.AssertExpectations(t) - }) + }, true, nil) + + fungibleMock.On("GetSystemContract", mock.Anything).Return(fungibletypes.SystemContract{ + ConnectorZevm: sample.EthAddress().Hex(), + }, true) + + // call HandleEVMDeposit + cctx := sample.CrossChainTx(t, "foo") + cctx.InboundTxParams.TxOrigin = "" + cctx.GetCurrentOutTxParam().Receiver = receiver.String() + cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundTxParams().Sender = sample.EthAddress().String() + cctx.GetInboundTxParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundTxParams().Asset = "" + reverted, err := k.HandleEVMDeposit( + ctx, + cctx, + ) + require.NoError(t, err) + require.False(t, reverted) + fungibleMock.AssertExpectations(t) + }, + ) t.Run("should error if invalid sender", func(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ @@ -442,46 +451,49 @@ func TestMsgServer_HandleEVMDeposit(t *testing.T) { fungibleMock.AssertExpectations(t) }) - t.Run("should return error with reverted if deposit ERC20 fails with calling a non-contract address", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - }) - - senderChain := getValidEthChainID() - - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - - fungibleMock.On( - "ZRC20DepositAndCallContract", - ctx, - mock.Anything, - receiver, - amount, - senderChain, - mock.Anything, - coin.CoinType_ERC20, - mock.Anything, - ).Return(&evmtypes.MsgEthereumTxResponse{}, false, fungibletypes.ErrCallNonContract) - - // call HandleEVMDeposit - cctx := sample.CrossChainTx(t, "foo") - cctx.GetCurrentOutTxParam().Receiver = receiver.String() - cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundTxParams().Sender = sample.EthAddress().String() - cctx.GetInboundTxParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundTxParams().Asset = "" - reverted, err := k.HandleEVMDeposit( - ctx, - cctx, - ) - require.ErrorIs(t, err, fungibletypes.ErrCallNonContract) - require.True(t, reverted) - fungibleMock.AssertExpectations(t) - }) + t.Run( + "should return error with reverted if deposit ERC20 fails with calling a non-contract address", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + }) + + senderChain := getValidEthChainID() + + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + + fungibleMock.On( + "ZRC20DepositAndCallContract", + ctx, + mock.Anything, + receiver, + amount, + senderChain, + mock.Anything, + coin.CoinType_ERC20, + mock.Anything, + ).Return(&evmtypes.MsgEthereumTxResponse{}, false, fungibletypes.ErrCallNonContract) + + // call HandleEVMDeposit + cctx := sample.CrossChainTx(t, "foo") + cctx.GetCurrentOutTxParam().Receiver = receiver.String() + cctx.GetInboundTxParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundTxParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundTxParams().Sender = sample.EthAddress().String() + cctx.GetInboundTxParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundTxParams().Asset = "" + reverted, err := k.HandleEVMDeposit( + ctx, + cctx, + ) + require.ErrorIs(t, err, fungibletypes.ErrCallNonContract) + require.True(t, reverted) + fungibleMock.AssertExpectations(t) + }, + ) t.Run("should fail if can't parse address and data", func(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ diff --git a/x/crosschain/keeper/evm_hooks.go b/x/crosschain/keeper/evm_hooks.go index 0bdda7a6ae..a4a0ec57fe 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -61,7 +61,12 @@ func (k Keeper) PostTxProcessing( // - clear the logs // TODO: implement unit tests // https://github.com/zeta-chain/node/issues/1759 -func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContract ethcommon.Address, txOrigin string) error { +func (k Keeper) ProcessLogs( + ctx sdk.Context, + logs []*ethtypes.Log, + emittingContract ethcommon.Address, + txOrigin string, +) error { system, found := k.fungibleKeeper.GetSystemContract(ctx) if !found { return fmt.Errorf("cannot find system contract") @@ -79,7 +84,8 @@ func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContr } if eventZrc20Withdrawal != nil && eventZetaSent != nil { // This log contains both events, this is not possible - ctx.Logger().Error(fmt.Sprintf("ProcessLogs: log contains both ZRC20Withdrawal and ZetaSent events, %s , %s", log.Topics, log.Data)) + ctx.Logger(). + Error(fmt.Sprintf("ProcessLogs: log contains both ZRC20Withdrawal and ZetaSent events, %s , %s", log.Topics, log.Data)) continue } @@ -100,7 +106,8 @@ func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContr // Check if the contract is a registered ZRC20 contract. If its not a registered ZRC20 contract, we can discard this event as it is not relevant coin, foundCoin := k.fungibleKeeper.GetForeignCoins(ctx, eventZrc20Withdrawal.Raw.Address.Hex()) if !foundCoin { - ctx.Logger().Info(fmt.Sprintf("cannot find foreign coin with contract address %s", eventZrc20Withdrawal.Raw.Address.Hex())) + ctx.Logger(). + Info(fmt.Sprintf("cannot find foreign coin with contract address %s", eventZrc20Withdrawal.Raw.Address.Hex())) continue } @@ -127,7 +134,13 @@ func (k Keeper) ProcessLogs(ctx sdk.Context, logs []*ethtypes.Log, emittingContr // ProcessZRC20WithdrawalEvent creates a new CCTX to process the withdrawal event // error indicates system error and non-recoverable; should abort -func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20Withdrawal, emittingContract ethcommon.Address, txOrigin string, tss observertypes.TSS) error { +func (k Keeper) ProcessZRC20WithdrawalEvent( + ctx sdk.Context, + event *zrc20.ZRC20Withdrawal, + emittingContract ethcommon.Address, + txOrigin string, + tss observertypes.TSS, +) error { ctx.Logger().Info(fmt.Sprintf("ZRC20 withdrawal to %s amount %d", hex.EncodeToString(event.To), event.Value)) foreignCoin, found := k.fungibleKeeper.GetForeignCoins(ctx, event.Raw.Address.Hex()) @@ -136,7 +149,11 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W } receiverChain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, foreignCoin.ForeignChainId) if receiverChain == nil { - return errorsmod.Wrapf(observertypes.ErrSupportedChains, "chain with chainID %d not supported", foreignCoin.ForeignChainId) + return errorsmod.Wrapf( + observertypes.ErrSupportedChains, + "chain with chainID %d not supported", + foreignCoin.ForeignChainId, + ) } senderChain, err := chains.ZetaChainFromChainID(ctx.ChainID()) if err != nil { @@ -188,7 +205,13 @@ func (k Keeper) ProcessZRC20WithdrawalEvent(ctx sdk.Context, event *zrc20.ZRC20W return k.ProcessCCTX(ctx, cctx, receiverChain) } -func (k Keeper) ProcessZetaSentEvent(ctx sdk.Context, event *connectorzevm.ZetaConnectorZEVMZetaSent, emittingContract ethcommon.Address, txOrigin string, tss observertypes.TSS) error { +func (k Keeper) ProcessZetaSentEvent( + ctx sdk.Context, + event *connectorzevm.ZetaConnectorZEVMZetaSent, + emittingContract ethcommon.Address, + txOrigin string, + tss observertypes.TSS, +) error { ctx.Logger().Info(fmt.Sprintf( "Zeta withdrawal to %s amount %d to chain with chainId %d", hex.EncodeToString(event.DestinationAddress), @@ -320,7 +343,10 @@ func ValidateZrc20WithdrawEvent(event *zrc20.ZRC20Withdrawal, chainID int64) err // ParseZetaSentEvent tries extracting ZetaSent event from connectorZEVM contract; // returns error if the log entry is not a ZetaSent event, or is not emitted from connectorZEVM // It only returns a not-nil event if all the error checks pass -func ParseZetaSentEvent(log ethtypes.Log, connectorZEVM ethcommon.Address) (*connectorzevm.ZetaConnectorZEVMZetaSent, error) { +func ParseZetaSentEvent( + log ethtypes.Log, + connectorZEVM ethcommon.Address, +) (*connectorzevm.ZetaConnectorZEVMZetaSent, error) { zetaConnectorZEVM, err := connectorzevm.NewZetaConnectorZEVMFilterer(log.Address, bind.ContractFilterer(nil)) if err != nil { return nil, err @@ -334,7 +360,11 @@ func ParseZetaSentEvent(log ethtypes.Log, connectorZEVM ethcommon.Address) (*con } if event.Raw.Address != connectorZEVM { - return nil, fmt.Errorf("ParseZetaSentEvent: event address %s does not match connectorZEVM %s", event.Raw.Address.Hex(), connectorZEVM.Hex()) + return nil, fmt.Errorf( + "ParseZetaSentEvent: event address %s does not match connectorZEVM %s", + event.Raw.Address.Hex(), + connectorZEVM.Hex(), + ) } return event, nil } diff --git a/x/crosschain/keeper/evm_hooks_test.go b/x/crosschain/keeper/evm_hooks_test.go index 21352d9dc0..4719d4558c 100644 --- a/x/crosschain/keeper/evm_hooks_test.go +++ b/x/crosschain/keeper/evm_hooks_test.go @@ -25,7 +25,15 @@ import ( // SetupStateForProcessLogsZetaSent sets up additional state required for processing logs for ZetaSent events // This sets up the gas coin, zrc20 contract, gas price, zrc20 pool. // This should be used in conjunction with SetupStateForProcessLogs for processing ZetaSent events -func SetupStateForProcessLogsZetaSent(t *testing.T, ctx sdk.Context, k *crosschainkeeper.Keeper, zk keepertest.ZetaKeepers, sdkk keepertest.SDKKeepers, chain chains.Chain, admin string) { +func SetupStateForProcessLogsZetaSent( + t *testing.T, + ctx sdk.Context, + k *crosschainkeeper.Keeper, + zk keepertest.ZetaKeepers, + sdkk keepertest.SDKKeepers, + chain chains.Chain, + admin string, +) { assetAddress := sample.EthAddress().String() gasZRC20 := setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, chain.ChainId, "ethereum", "ETH") @@ -61,7 +69,14 @@ func SetupStateForProcessLogsZetaSent(t *testing.T, ctx sdk.Context, k *crosscha // SetupStateForProcessLogs sets up observer state for required for processing logs // It deploys system contracts, sets up TSS, gas price, chain nonce's, pending nonce's.These are all required to create a cctx from a log -func SetupStateForProcessLogs(t *testing.T, ctx sdk.Context, k *crosschainkeeper.Keeper, zk keepertest.ZetaKeepers, sdkk keepertest.SDKKeepers, chain chains.Chain) { +func SetupStateForProcessLogs( + t *testing.T, + ctx sdk.Context, + k *crosschainkeeper.Keeper, + zk keepertest.ZetaKeepers, + sdkk keepertest.SDKKeepers, + chain chains.Chain, +) { deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) tss := sample.Tss() @@ -140,14 +155,18 @@ func TestParseZRC20WithdrawalEvent(t *testing.T) { } func TestValidateZrc20WithdrawEvent(t *testing.T) { t.Run("successfully validate a valid event", func(t *testing.T) { - btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent(*sample.GetValidZRC20WithdrawToBTC(t).Logs[3]) + btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent( + *sample.GetValidZRC20WithdrawToBTC(t).Logs[3], + ) require.NoError(t, err) err = crosschainkeeper.ValidateZrc20WithdrawEvent(btcMainNetWithdrawalEvent, chains.BtcMainnetChain.ChainId) require.NoError(t, err) }) t.Run("unable to validate a event with an invalid amount", func(t *testing.T) { - btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent(*sample.GetValidZRC20WithdrawToBTC(t).Logs[3]) + btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent( + *sample.GetValidZRC20WithdrawToBTC(t).Logs[3], + ) require.NoError(t, err) btcMainNetWithdrawalEvent.Value = big.NewInt(0) err = crosschainkeeper.ValidateZrc20WithdrawEvent(btcMainNetWithdrawalEvent, chains.BtcMainnetChain.ChainId) @@ -155,14 +174,18 @@ func TestValidateZrc20WithdrawEvent(t *testing.T) { }) t.Run("unable to validate a event with an invalid chain ID", func(t *testing.T) { - btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent(*sample.GetValidZRC20WithdrawToBTC(t).Logs[3]) + btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent( + *sample.GetValidZRC20WithdrawToBTC(t).Logs[3], + ) require.NoError(t, err) err = crosschainkeeper.ValidateZrc20WithdrawEvent(btcMainNetWithdrawalEvent, chains.BtcTestNetChain.ChainId) require.ErrorContains(t, err, "invalid address") }) t.Run("unable to validate an unsupported address type", func(t *testing.T) { - btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent(*sample.GetValidZRC20WithdrawToBTC(t).Logs[3]) + btcMainNetWithdrawalEvent, err := crosschainkeeper.ParseZRC20WithdrawalEvent( + *sample.GetValidZRC20WithdrawToBTC(t).Logs[3], + ) require.NoError(t, err) btcMainNetWithdrawalEvent.To = []byte("04b2891ba8cb491828db3ebc8a780d43b169e7b3974114e6e50f9bab6ec" + "63c2f20f6d31b2025377d05c2a704d3bd799d0d56f3a8543d79a01ab6084a1cb204f260") @@ -334,7 +357,8 @@ func TestKeeper_ProcessZRC20WithdrawalEvent(t *testing.T) { fc, _ := zk.FungibleKeeper.GetForeignCoins(ctx, zrc20.Hex()) fungibleMock.On("GetForeignCoins", mock.Anything, mock.Anything).Return(fc, true) - fungibleMock.On("QueryGasLimit", mock.Anything, mock.Anything).Return(big.NewInt(0), fmt.Errorf("error querying gas limit")) + fungibleMock.On("QueryGasLimit", mock.Anything, mock.Anything). + Return(big.NewInt(0), fmt.Errorf("error querying gas limit")) err = k.ProcessZRC20WithdrawalEvent(ctx, event, emittingContract, txOrigin.Hex(), tss) require.ErrorContains(t, err, "error querying gas limit") require.Empty(t, k.GetAllCrossChainTx(ctx)) @@ -450,10 +474,17 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -463,7 +494,11 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { require.NoError(t, err) cctxList := k.GetAllCrossChainTx(ctx) require.Len(t, cctxList, 1) - require.Equal(t, strings.Compare("0x60983881bdf302dcfa96603a58274d15d5966209", cctxList[0].GetCurrentOutTxParam().Receiver), 0) + require.Equal( + t, + strings.Compare("0x60983881bdf302dcfa96603a58274d15d5966209", cctxList[0].GetCurrentOutTxParam().Receiver), + 0, + ) require.Equal(t, chains.EthChain.ChainId, cctxList[0].GetCurrentOutTxParam().ReceiverChainId) require.Equal(t, emittingContract.Hex(), cctxList[0].InboundTxParams.Sender) require.Equal(t, txOrigin.Hex(), cctxList[0].InboundTxParams.TxOrigin) @@ -480,7 +515,10 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { admin := keepertest.SetAdminPolices(ctx, zk.AuthorityKeeper) SetupStateForProcessLogsZetaSent(t, ctx, k, zk, sdkk, chain, admin) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -501,10 +539,17 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -526,10 +571,17 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -550,9 +602,16 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -581,10 +640,17 @@ func TestKeeper_ProcessZetaSentEvent(t *testing.T) { }) amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) - event, err := crosschainkeeper.ParseZetaSentEvent(*sample.GetValidZetaSentDestinationExternal(t).Logs[4], sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address) + event, err := crosschainkeeper.ParseZetaSentEvent( + *sample.GetValidZetaSentDestinationExternal(t).Logs[4], + sample.GetValidZetaSentDestinationExternal(t).Logs[4].Address, + ) require.NoError(t, err) emittingContract := sample.EthAddress() txOrigin := sample.EthAddress() @@ -634,7 +700,11 @@ func TestKeeper_ProcessLogs(t *testing.T) { amount, ok := sdkmath.NewIntFromString("20000000000000000000000") require.True(t, ok) - err := sdkk.BankKeeper.MintCoins(ctx, fungibletypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := sdkk.BankKeeper.MintCoins( + ctx, + fungibletypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)), + ) require.NoError(t, err) block := sample.GetValidZetaSentDestinationExternal(t) system, found := zk.FungibleKeeper.GetSystemContract(ctx) @@ -649,7 +719,11 @@ func TestKeeper_ProcessLogs(t *testing.T) { require.NoError(t, err) cctxList := k.GetAllCrossChainTx(ctx) require.Len(t, cctxList, 1) - require.Equal(t, strings.Compare("0x60983881bdf302dcfa96603a58274d15d5966209", cctxList[0].GetCurrentOutTxParam().Receiver), 0) + require.Equal( + t, + strings.Compare("0x60983881bdf302dcfa96603a58274d15d5966209", cctxList[0].GetCurrentOutTxParam().Receiver), + 0, + ) require.Equal(t, chains.EthChain.ChainId, cctxList[0].GetCurrentOutTxParam().ReceiverChainId) require.Equal(t, emittingContract.Hex(), cctxList[0].InboundTxParams.Sender) require.Equal(t, txOrigin.Hex(), cctxList[0].InboundTxParams.TxOrigin) @@ -687,25 +761,28 @@ func TestKeeper_ProcessLogs(t *testing.T) { require.Len(t, cctxList, 0) }) - t.Run("no cctx created for logs containing proper event but not emitted from a known ZRC20 contract", func(t *testing.T) { - k, ctx, sdkk, zk := keepertest.CrosschainKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, fungibletypes.ModuleName) - chain := chains.BtcMainnetChain - chainID := chain.ChainId - setSupportedChain(ctx, zk, chainID) - SetupStateForProcessLogs(t, ctx, k, zk, sdkk, chain) - - block := sample.GetValidZRC20WithdrawToBTC(t) - setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, chainID, "bitcoin", "BTC") - for _, log := range block.Logs { - log.Address = sample.EthAddress() - } + t.Run( + "no cctx created for logs containing proper event but not emitted from a known ZRC20 contract", + func(t *testing.T) { + k, ctx, sdkk, zk := keepertest.CrosschainKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, fungibletypes.ModuleName) + chain := chains.BtcMainnetChain + chainID := chain.ChainId + setSupportedChain(ctx, zk, chainID) + SetupStateForProcessLogs(t, ctx, k, zk, sdkk, chain) + + block := sample.GetValidZRC20WithdrawToBTC(t) + setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, chainID, "bitcoin", "BTC") + for _, log := range block.Logs { + log.Address = sample.EthAddress() + } - err := k.ProcessLogs(ctx, block.Logs, sample.EthAddress(), "") - require.NoError(t, err) - cctxList := k.GetAllCrossChainTx(ctx) - require.Len(t, cctxList, 0) - }) + err := k.ProcessLogs(ctx, block.Logs, sample.EthAddress(), "") + require.NoError(t, err) + cctxList := k.GetAllCrossChainTx(ctx) + require.Len(t, cctxList, 0) + }, + ) t.Run("no cctx created for valid logs if Inbound is disabled", func(t *testing.T) { k, ctx, sdkk, zk := keepertest.CrosschainKeeper(t) diff --git a/x/crosschain/keeper/finalized_inbounds_test.go b/x/crosschain/keeper/finalized_inbounds_test.go index 9946024aa8..aa5e788465 100644 --- a/x/crosschain/keeper/finalized_inbounds_test.go +++ b/x/crosschain/keeper/finalized_inbounds_test.go @@ -77,6 +77,10 @@ func TestKeeper_GetAllFinalizedInbound(t *testing.T) { for i := 0; i < listSize; i++ { require.Contains(t, list, types.FinalizedInboundKey(txHashList[i], chainIdList[i], eventIndexList[i])) } - require.NotContains(t, list, types.FinalizedInboundKey(sample.Hash().String(), sample.Chain(5).ChainId, sample.EventIndex())) + require.NotContains( + t, + list, + types.FinalizedInboundKey(sample.Hash().String(), sample.Chain(5).ChainId, sample.EventIndex()), + ) }) } diff --git a/x/crosschain/keeper/gas_payment.go b/x/crosschain/keeper/gas_payment.go index a26658534c..488f28bb91 100644 --- a/x/crosschain/keeper/gas_payment.go +++ b/x/crosschain/keeper/gas_payment.go @@ -91,7 +91,11 @@ func (k Keeper) PayGasNativeAndUpdateCctx( ) error { // preliminary checks if cctx.InboundTxParams.CoinType != coin.CoinType_Gas { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in native gas with %s", cctx.InboundTxParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in native gas with %s", + cctx.InboundTxParams.CoinType.String(), + ) } if chain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, chainID); chain == nil { return observertypes.ErrSupportedChains @@ -108,10 +112,12 @@ func (k Keeper) PayGasNativeAndUpdateCctx( // subtract the withdraw fee from the input amount if outTxGasFee.GT(inputAmount) { - return cosmoserrors.Wrap(types.ErrNotEnoughGas, fmt.Sprintf("outTxGasFee(%s) more than available gas for tx (%s) | Identifiers : %s ", - outTxGasFee, - inputAmount, - cctx.LogIdentifierForCCTX()), + return cosmoserrors.Wrap( + types.ErrNotEnoughGas, + fmt.Sprintf("outTxGasFee(%s) more than available gas for tx (%s) | Identifiers : %s ", + outTxGasFee, + inputAmount, + cctx.LogIdentifierForCCTX()), ) } ctx.Logger().Info("Subtracting amount from inbound tx", "amount", inputAmount.String(), "fee", outTxGasFee.String()) @@ -138,7 +144,11 @@ func (k Keeper) PayGasInERC20AndUpdateCctx( ) error { // preliminary checks if cctx.InboundTxParams.CoinType != coin.CoinType_ERC20 { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in erc20 with %s", cctx.InboundTxParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in erc20 with %s", + cctx.InboundTxParams.CoinType.String(), + ) } if chain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, chainID); chain == nil { @@ -153,15 +163,28 @@ func (k Keeper) PayGasInERC20AndUpdateCctx( // get address of the zrc20 fc, found := k.fungibleKeeper.GetForeignCoinFromAsset(ctx, cctx.InboundTxParams.Asset, chainID) if !found { - return cosmoserrors.Wrapf(types.ErrForeignCoinNotFound, "zrc20 from asset %s not found", cctx.InboundTxParams.Asset) + return cosmoserrors.Wrapf( + types.ErrForeignCoinNotFound, + "zrc20 from asset %s not found", + cctx.InboundTxParams.Asset, + ) } zrc20 := ethcommon.HexToAddress(fc.Zrc20ContractAddress) if zrc20 == (ethcommon.Address{}) { - return cosmoserrors.Wrapf(types.ErrForeignCoinNotFound, "zrc20 from asset %s invalid address", cctx.InboundTxParams.Asset) + return cosmoserrors.Wrapf( + types.ErrForeignCoinNotFound, + "zrc20 from asset %s invalid address", + cctx.InboundTxParams.Asset, + ) } // get the necessary ERC20 amount for gas - feeInZRC20, err := k.fungibleKeeper.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, outTxGasFee.BigInt(), zrc20, gasZRC20) + feeInZRC20, err := k.fungibleKeeper.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx, + outTxGasFee.BigInt(), + zrc20, + gasZRC20, + ) if err != nil { // NOTE: this is the first method that fails when a liquidity pool is not set for the gas ZRC20, so we return a specific error return cosmoserrors.Wrap(types.ErrNoLiquidityPool, err.Error()) @@ -169,10 +192,12 @@ func (k Keeper) PayGasInERC20AndUpdateCctx( // subtract the withdraw fee from the input amount if math.NewUintFromBigInt(feeInZRC20).GT(inputAmount) { - return cosmoserrors.Wrap(types.ErrNotEnoughGas, fmt.Sprintf("feeInZRC20(%s) more than available gas for tx (%s) | Identifiers : %s ", - feeInZRC20, - inputAmount, - cctx.LogIdentifierForCCTX()), + return cosmoserrors.Wrap( + types.ErrNotEnoughGas, + fmt.Sprintf("feeInZRC20(%s) more than available gas for tx (%s) | Identifiers : %s ", + feeInZRC20, + inputAmount, + cctx.LogIdentifierForCCTX()), ) } newAmount := inputAmount.Sub(math.NewUintFromBigInt(feeInZRC20)) @@ -228,7 +253,12 @@ func (k Keeper) PayGasInERC20AndUpdateCctx( // check if the final gas received after swap matches the gas fee defined // if not there might be issues with the pool liquidity and it is safer from an accounting perspective to return an error if gasObtained.Cmp(outTxGasFee.BigInt()) == -1 { - return cosmoserrors.Wrapf(types.ErrInvalidGasAmount, "gas obtained for burn (%s) is lower than gas fee(%s)", gasObtained, outTxGasFee) + return cosmoserrors.Wrapf( + types.ErrInvalidGasAmount, + "gas obtained for burn (%s) is lower than gas fee(%s)", + gasObtained, + outTxGasFee, + ) } // burn the gas ZRC20 @@ -263,7 +293,11 @@ func (k Keeper) PayGasInZetaAndUpdateCctx( ) error { // preliminary checks if cctx.InboundTxParams.CoinType != coin.CoinType_Zeta { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundTxParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in zeta with %s", + cctx.InboundTxParams.CoinType.String(), + ) } if chain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, chainID); chain == nil { @@ -272,7 +306,11 @@ func (k Keeper) PayGasInZetaAndUpdateCctx( gasZRC20, err := k.fungibleKeeper.QuerySystemContractGasCoinZRC20(ctx, big.NewInt(chainID)) if err != nil { - return cosmoserrors.Wrapf(err, "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin, chaind ID %d", chainID) + return cosmoserrors.Wrapf( + err, + "PayGasInZetaAndUpdateCctx: unable to get system contract gas coin, chaind ID %d", + chainID, + ) } // get the gas price @@ -297,10 +335,12 @@ func (k Keeper) PayGasInZetaAndUpdateCctx( feeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(outTxGasFeeInZeta)) // reduce the amount of the outbound tx if feeInZeta.GT(zetaBurnt) { - return cosmoserrors.Wrap(types.ErrNotEnoughZetaBurnt, fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", - feeInZeta, - zetaBurnt, - cctx.LogIdentifierForCCTX()), + return cosmoserrors.Wrap( + types.ErrNotEnoughZetaBurnt, + fmt.Sprintf("feeInZeta(%s) more than zetaBurnt (%s) | Identifiers : %s ", + feeInZeta, + zetaBurnt, + cctx.LogIdentifierForCCTX()), ) } ctx.Logger().Info("Subtracting amount from inbound tx", @@ -327,7 +367,10 @@ func (k Keeper) PayGasInZetaAndUpdateCctx( noEthereumTxEvent, ) if err != nil { - return cosmoserrors.Wrap(err, "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken") + return cosmoserrors.Wrap( + err, + "PayGasInZetaAndUpdateCctx: unable to CallUniswapv2RouterSwapExactETHForToken", + ) } ctx.Logger().Info("gas fee", "outTxGasFee", outTxGasFee, "outTxGasFeeInZeta", outTxGasFeeInZeta) diff --git a/x/crosschain/keeper/gas_payment_test.go b/x/crosschain/keeper/gas_payment_test.go index e315c1221a..d84ffeed60 100644 --- a/x/crosschain/keeper/gas_payment_test.go +++ b/x/crosschain/keeper/gas_payment_test.go @@ -442,7 +442,13 @@ func TestKeeper_PayGasInERC20AndUpdateCctx(t *testing.T) { require.NoError(t, err) // Provide expected value minus 1 - err = k.PayGasInERC20AndUpdateCctx(ctx, chainID, &cctx, math.NewUintFromBigInt(expectedInZRC20).SubUint64(1), false) + err = k.PayGasInERC20AndUpdateCctx( + ctx, + chainID, + &cctx, + math.NewUintFromBigInt(expectedInZRC20).SubUint64(1), + false, + ) require.ErrorIs(t, err, types.ErrNotEnoughGas) }) } @@ -477,7 +483,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { ZetaFees: math.NewUint(100), } // gasLimit * gasPrice * 2 = 1000 * 2 * 2 = 4000 - expectedOutTxGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutTxGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn( + ctx, + big.NewInt(4000), + zrc20, + ) require.NoError(t, err) // the output amount must be input amount - (out tx fee in zeta + protocol flat fee) @@ -487,7 +497,13 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { require.NoError(t, err) require.Equal(t, "100000", cctx.GetCurrentOutTxParam().Amount.String()) require.Equal(t, "4", cctx.GetCurrentOutTxParam().OutboundTxGasPrice) // gas price is doubled - require.True(t, cctx.ZetaFees.Equal(expectedFeeInZeta.Add(math.NewUint(100))), "expected %s, got %s", expectedFeeInZeta.String(), cctx.ZetaFees.String()) + require.True( + t, + cctx.ZetaFees.Equal(expectedFeeInZeta.Add(math.NewUint(100))), + "expected %s, got %s", + expectedFeeInZeta.String(), + cctx.ZetaFees.String(), + ) // can call with undefined zeta fees cctx = types.CrossChainTx{ @@ -501,7 +517,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { }, }, } - expectedOutTxGasFeeInZeta, err = zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutTxGasFeeInZeta, err = zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn( + ctx, + big.NewInt(4000), + zrc20, + ) require.NoError(t, err) expectedFeeInZeta = types.GetProtocolFee().Add(math.NewUintFromBigInt(expectedOutTxGasFeeInZeta)) inputAmount = expectedFeeInZeta.Add(math.NewUint(100000)) @@ -509,7 +529,13 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { require.NoError(t, err) require.Equal(t, "100000", cctx.GetCurrentOutTxParam().Amount.String()) require.Equal(t, "4", cctx.GetCurrentOutTxParam().OutboundTxGasPrice) // gas price is doubled - require.True(t, cctx.ZetaFees.Equal(expectedFeeInZeta), "expected %s, got %s", expectedFeeInZeta.String(), cctx.ZetaFees.String()) + require.True( + t, + cctx.ZetaFees.Equal(expectedFeeInZeta), + "expected %s, got %s", + expectedFeeInZeta.String(), + cctx.ZetaFees.String(), + ) }) t.Run("should fail if pay gas in zeta with coin type other than zeta", func(t *testing.T) { @@ -596,7 +622,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { }, ZetaFees: math.NewUint(100), } - expectedOutTxGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutTxGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn( + ctx, + big.NewInt(4000), + zrc20, + ) require.NoError(t, err) expectedFeeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(expectedOutTxGasFeeInZeta)) diff --git a/x/crosschain/keeper/grpc_query_cctx.go b/x/crosschain/keeper/grpc_query_cctx.go index 688c9cb205..9aa6fc30e3 100644 --- a/x/crosschain/keeper/grpc_query_cctx.go +++ b/x/crosschain/keeper/grpc_query_cctx.go @@ -21,7 +21,10 @@ const ( MaxLookbackNonce = 1000 ) -func (k Keeper) ZetaAccounting(c context.Context, _ *types.QueryZetaAccountingRequest) (*types.QueryZetaAccountingResponse, error) { +func (k Keeper) ZetaAccounting( + c context.Context, + _ *types.QueryZetaAccountingRequest, +) (*types.QueryZetaAccountingResponse, error) { ctx := sdk.UnwrapSDKContext(c) amount, found := k.GetZetaAccounting(ctx) if !found { @@ -72,7 +75,10 @@ func (k Keeper) Cctx(c context.Context, req *types.QueryGetCctxRequest) (*types. return &types.QueryGetCctxResponse{CrossChainTx: &val}, nil } -func (k Keeper) CctxByNonce(c context.Context, req *types.QueryGetCctxByNonceRequest) (*types.QueryGetCctxResponse, error) { +func (k Keeper) CctxByNonce( + c context.Context, + req *types.QueryGetCctxByNonceRequest, +) (*types.QueryGetCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -92,7 +98,10 @@ func (k Keeper) CctxByNonce(c context.Context, req *types.QueryGetCctxByNonceReq // ListPendingCctx returns a list of pending cctxs and the total number of pending cctxs // a limit for the number of cctxs to return can be specified or the default is MaxPendingCctxs -func (k Keeper) ListPendingCctx(c context.Context, req *types.QueryListPendingCctxRequest) (*types.QueryListPendingCctxResponse, error) { +func (k Keeper) ListPendingCctx( + c context.Context, + req *types.QueryListPendingCctxRequest, +) (*types.QueryListPendingCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -164,10 +173,19 @@ func (k Keeper) ListPendingCctx(c context.Context, req *types.QueryListPendingCc } // getCctxByChainIDAndNonce returns the cctx by chainID and nonce -func getCctxByChainIDAndNonce(k Keeper, ctx sdk.Context, tssPubkey string, chainID int64, nonce int64) (*types.CrossChainTx, error) { +func getCctxByChainIDAndNonce( + k Keeper, + ctx sdk.Context, + tssPubkey string, + chainID int64, + nonce int64, +) (*types.CrossChainTx, error) { nonceToCctx, found := k.GetObserverKeeper().GetNonceToCctx(ctx, tssPubkey, chainID, nonce) if !found { - return nil, status.Error(codes.Internal, fmt.Sprintf("nonceToCctx not found: chainid %d, nonce %d", chainID, nonce)) + return nil, status.Error( + codes.Internal, + fmt.Sprintf("nonceToCctx not found: chainid %d, nonce %d", chainID, nonce), + ) } cctx, found := k.GetCrossChainTx(ctx, nonceToCctx.CctxIndex) if !found { diff --git a/x/crosschain/keeper/grpc_query_cctx_rate_limit.go b/x/crosschain/keeper/grpc_query_cctx_rate_limit.go index 1bb3c552a7..9e3939d56f 100644 --- a/x/crosschain/keeper/grpc_query_cctx_rate_limit.go +++ b/x/crosschain/keeper/grpc_query_cctx_rate_limit.go @@ -13,7 +13,10 @@ import ( ) // RateLimiterInput collects the input data for the rate limiter -func (k Keeper) RateLimiterInput(c context.Context, req *types.QueryRateLimiterInputRequest) (res *types.QueryRateLimiterInputResponse, err error) { +func (k Keeper) RateLimiterInput( + c context.Context, + req *types.QueryRateLimiterInputRequest, +) (res *types.QueryRateLimiterInputResponse, err error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -130,7 +133,9 @@ func (k Keeper) RateLimiterInput(c context.Context, req *types.QueryRateLimiterI // sum up past cctxs' value within window if inWindow && isPast { - pastCctxsValue = pastCctxsValue.Add(types.ConvertCctxValueToAzeta(chain.ChainId, cctx, gasAssetRateMap, erc20AssetRateMap)) + pastCctxsValue = pastCctxsValue.Add( + types.ConvertCctxValueToAzeta(chain.ChainId, cctx, gasAssetRateMap, erc20AssetRateMap), + ) } // add cctx to corresponding list @@ -171,7 +176,10 @@ func (k Keeper) RateLimiterInput(c context.Context, req *types.QueryRateLimiterI // ListPendingCctxWithinRateLimit returns a list of pending cctxs that do not exceed the outbound rate limit // a limit for the number of cctxs to return can be specified or the default is MaxPendingCctxs -func (k Keeper) ListPendingCctxWithinRateLimit(c context.Context, req *types.QueryListPendingCctxWithinRateLimitRequest) (res *types.QueryListPendingCctxWithinRateLimitResponse, err error) { +func (k Keeper) ListPendingCctxWithinRateLimit( + c context.Context, + req *types.QueryListPendingCctxWithinRateLimitRequest, +) (res *types.QueryListPendingCctxWithinRateLimitResponse, err error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -203,7 +211,10 @@ func (k Keeper) ListPendingCctxWithinRateLimit(c context.Context, req *types.Que // fallback to non-rate-limited query if rate limiter is disabled if !applyLimit { for _, chain := range chains { - resp, err := k.ListPendingCctx(ctx, &types.QueryListPendingCctxRequest{ChainId: chain.ChainId, Limit: limit}) + resp, err := k.ListPendingCctx( + ctx, + &types.QueryListPendingCctxRequest{ChainId: chain.ChainId, Limit: limit}, + ) if err == nil { cctxs = append(cctxs, resp.CrossChainTx...) totalPending += resp.TotalPending @@ -314,7 +325,15 @@ func (k Keeper) ListPendingCctxWithinRateLimit(c context.Context, req *types.Que break } // skip the cctx if rate limit is exceeded but still accumulate the total withdraw value - if inWindow && types.RateLimitExceeded(chain.ChainId, cctx, gasAssetRateMap, erc20AssetRateMap, &totalWithdrawInAzeta, withdrawLimitInAzeta) { + if inWindow && + types.RateLimitExceeded( + chain.ChainId, + cctx, + gasAssetRateMap, + erc20AssetRateMap, + &totalWithdrawInAzeta, + withdrawLimitInAzeta, + ) { limitExceeded = true continue } @@ -347,7 +366,14 @@ func (k Keeper) ListPendingCctxWithinRateLimit(c context.Context, req *types.Que } // skip the cctx if rate limit is exceeded but still accumulate the total withdraw value - if types.RateLimitExceeded(chain.ChainId, cctx, gasAssetRateMap, erc20AssetRateMap, &totalWithdrawInAzeta, withdrawLimitInAzeta) { + if types.RateLimitExceeded( + chain.ChainId, + cctx, + gasAssetRateMap, + erc20AssetRateMap, + &totalWithdrawInAzeta, + withdrawLimitInAzeta, + ) { limitExceeded = true continue } diff --git a/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go b/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go index fc5c96cf09..a2e8074497 100644 --- a/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go +++ b/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go @@ -102,13 +102,49 @@ func TestKeeper_RateLimiterInput(t *testing.T) { // create Eth chain 999 mined and 200 pending cctxs for rate limiter test // the number 999 is to make it less than `MaxLookbackNonce` so the LoopBackwards gets the chance to hit nonce 0 - ethMinedCctxs := sample.CustomCctxsInBlockRange(t, 1, 999, ethChainID, coin.CoinType_Gas, "", uint64(1e15), types.CctxStatus_OutboundMined) - ethPendingCctxs := sample.CustomCctxsInBlockRange(t, 1000, 1199, ethChainID, coin.CoinType_Gas, "", uint64(1e15), types.CctxStatus_PendingOutbound) + ethMinedCctxs := sample.CustomCctxsInBlockRange( + t, + 1, + 999, + ethChainID, + coin.CoinType_Gas, + "", + uint64(1e15), + types.CctxStatus_OutboundMined, + ) + ethPendingCctxs := sample.CustomCctxsInBlockRange( + t, + 1000, + 1199, + ethChainID, + coin.CoinType_Gas, + "", + uint64(1e15), + types.CctxStatus_PendingOutbound, + ) // create Btc chain 999 mined and 200 pending cctxs for rate limiter test // the number 999 is to make it less than `MaxLookbackNonce` so the LoopBackwards gets the chance to hit nonce 0 - btcMinedCctxs := sample.CustomCctxsInBlockRange(t, 1, 999, btcChainID, coin.CoinType_Gas, "", 1000, types.CctxStatus_OutboundMined) - btcPendingCctxs := sample.CustomCctxsInBlockRange(t, 1000, 1199, btcChainID, coin.CoinType_Gas, "", 1000, types.CctxStatus_PendingOutbound) + btcMinedCctxs := sample.CustomCctxsInBlockRange( + t, + 1, + 999, + btcChainID, + coin.CoinType_Gas, + "", + 1000, + types.CctxStatus_OutboundMined, + ) + btcPendingCctxs := sample.CustomCctxsInBlockRange( + t, + 1000, + 1199, + btcChainID, + coin.CoinType_Gas, + "", + 1000, + types.CctxStatus_PendingOutbound, + ) // define test cases tests := []struct { @@ -139,8 +175,17 @@ func TestKeeper_RateLimiterInput(t *testing.T) { expectedLowestPendingCctxHeight int64 }{ { - name: "can retrieve all pending cctxs", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "can retrieve all pending cctxs", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -161,17 +206,30 @@ func TestKeeper_RateLimiterInput(t *testing.T) { queryLimit: 0, // use default MaxPendingCctxs // expected results - expectedHeight: 1199, - expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...)), - expectedCctxsPending: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:200]...), btcPendingCctxs[100:200]...)), + expectedHeight: 1199, + expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + ), + expectedCctxsPending: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:200]...), btcPendingCctxs[100:200]...), + ), expectedTotalPending: 400, expectedPastCctxsValue: sdk.NewInt(1200).Mul(sdk.NewInt(1e18)).String(), // 400 * (2.5 + 0.5) ZETA expectedPendingCctxsValue: sdk.NewInt(300).Mul(sdk.NewInt(1e18)).String(), // 100 * 1e15 ZETA expectedLowestPendingCctxHeight: 1100, }, { - name: "should use left window boundary 1 if window > currentHeight", - rateLimitFlags: createTestRateLimiterFlags(1200, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "should use left window boundary 1 if window > currentHeight", + rateLimitFlags: createTestRateLimiterFlags( + 1200, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -192,17 +250,30 @@ func TestKeeper_RateLimiterInput(t *testing.T) { queryLimit: keeper.MaxPendingCctxs + 1, // should use default MaxPendingCctxs // expected results - expectedHeight: 1199, - expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...)), - expectedCctxsPending: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:200]...), btcPendingCctxs[100:200]...)), + expectedHeight: 1199, + expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + ), + expectedCctxsPending: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:200]...), btcPendingCctxs[100:200]...), + ), expectedTotalPending: 400, expectedPastCctxsValue: sdk.NewInt(3297).Mul(sdk.NewInt(1e18)).String(), // 1099 * (2.5 + 0.5) ZETA expectedPendingCctxsValue: sdk.NewInt(300).Mul(sdk.NewInt(1e18)).String(), // 100 * 1e15 ZETA expectedLowestPendingCctxHeight: 1100, }, { - name: "should loop from nonce 0", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "should loop from nonce 0", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -223,17 +294,28 @@ func TestKeeper_RateLimiterInput(t *testing.T) { queryLimit: keeper.MaxPendingCctxs, // expected results - expectedHeight: 1199, - expectedCctxsMissed: []*types.CrossChainTx{}, // no missed cctxs - expectedCctxsPending: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs...), btcPendingCctxs...)), + expectedHeight: 1199, + expectedCctxsMissed: []*types.CrossChainTx{}, // no missed cctxs + expectedCctxsPending: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs...), btcPendingCctxs...), + ), expectedTotalPending: 400, expectedPastCctxsValue: sdk.NewInt(900).Mul(sdk.NewInt(1e18)).String(), // 300 * (2.5 + 0.5) ZETA expectedPendingCctxsValue: sdk.NewInt(600).Mul(sdk.NewInt(1e18)).String(), // 200 * (2.5 + 0.5) ZETA expectedLowestPendingCctxHeight: 1000, }, { - name: "set a lower gRPC request limit < len(pending_cctxs)", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "set a lower gRPC request limit < len(pending_cctxs)", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -256,8 +338,12 @@ func TestKeeper_RateLimiterInput(t *testing.T) { // expected results expectedHeight: 1199, // should include all missed and 50 pending cctxs for each chain - expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...)), - expectedCctxsPending: keeper.SortCctxsByHeightAndChainID(append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:150]...), btcPendingCctxs[100:150]...)), + expectedCctxsMissed: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + ), + expectedCctxsPending: keeper.SortCctxsByHeightAndChainID( + append(append([]*types.CrossChainTx{}, ethPendingCctxs[100:150]...), btcPendingCctxs[100:150]...), + ), expectedTotalPending: 400, expectedPastCctxsValue: sdk.NewInt(1200).Mul(sdk.NewInt(1e18)).String(), // 400 * (2.5 + 0.5) ZETA expectedPendingCctxsValue: sdk.NewInt(300).Mul(sdk.NewInt(1e18)).String(), // 100 * (2.5 + 0.5) ZETA @@ -388,13 +474,49 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { // create Eth chain 999 mined and 200 pending cctxs for rate limiter test // the number 999 is to make it less than `MaxLookbackNonce` so the LoopBackwards gets the chance to hit nonce 0 - ethMinedCctxs := sample.CustomCctxsInBlockRange(t, 1, 999, ethChainID, coin.CoinType_Gas, "", uint64(1e15), types.CctxStatus_OutboundMined) - ethPendingCctxs := sample.CustomCctxsInBlockRange(t, 1000, 1199, ethChainID, coin.CoinType_Gas, "", uint64(1e15), types.CctxStatus_PendingOutbound) + ethMinedCctxs := sample.CustomCctxsInBlockRange( + t, + 1, + 999, + ethChainID, + coin.CoinType_Gas, + "", + uint64(1e15), + types.CctxStatus_OutboundMined, + ) + ethPendingCctxs := sample.CustomCctxsInBlockRange( + t, + 1000, + 1199, + ethChainID, + coin.CoinType_Gas, + "", + uint64(1e15), + types.CctxStatus_PendingOutbound, + ) // create Btc chain 999 mined and 200 pending cctxs for rate limiter test // the number 999 is to make it less than `MaxLookbackNonce` so the LoopBackwards gets the chance to hit nonce 0 - btcMinedCctxs := sample.CustomCctxsInBlockRange(t, 1, 999, btcChainID, coin.CoinType_Gas, "", 1000, types.CctxStatus_OutboundMined) - btcPendingCctxs := sample.CustomCctxsInBlockRange(t, 1000, 1199, btcChainID, coin.CoinType_Gas, "", 1000, types.CctxStatus_PendingOutbound) + btcMinedCctxs := sample.CustomCctxsInBlockRange( + t, + 1, + 999, + btcChainID, + coin.CoinType_Gas, + "", + 1000, + types.CctxStatus_OutboundMined, + ) + btcPendingCctxs := sample.CustomCctxsInBlockRange( + t, + 1000, + 1199, + btcChainID, + coin.CoinType_Gas, + "", + 1000, + types.CctxStatus_PendingOutbound, + ) // define test cases tests := []struct { @@ -449,9 +571,18 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { expectedTotalPending: 400, }, { - name: "should use fallback query if rate is 0", - fallback: true, - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(0), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "should use fallback query if rate is 0", + fallback: true, + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(0), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -474,8 +605,17 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { expectedTotalPending: 400, }, { - name: "can retrieve all pending cctx without exceeding rate limit", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "can retrieve all pending cctx without exceeding rate limit", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -501,8 +641,17 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { rateLimitExceeded: false, }, { - name: "can loop backwards all the way to endNonce 0", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "can loop backwards all the way to endNonce 0", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -528,8 +677,17 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { rateLimitExceeded: false, }, { - name: "set a low rate (rate < 2.4 ZETA) to exceed rate limit in backward loop", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(2*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "set a low rate (rate < 2.4 ZETA) to exceed rate limit in backward loop", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(2*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -549,15 +707,26 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { currentHeight: 1199, queryLimit: keeper.MaxPendingCctxs, // return missed cctxs only if rate limit is exceeded - expectedCctxs: append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + expectedCctxs: append( + append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), + btcPendingCctxs[0:100]...), expectedTotalPending: 400, expectedWithdrawWindow: 500, // the sliding window expectedWithdrawRate: sdk.NewInt(3e18).String(), // 3 ZETA, (2.5 + 0.5) per block rateLimitExceeded: true, }, { - name: "set a lower gRPC request limit and reach the limit of the query in forward loop", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(10*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "set a lower gRPC request limit and reach the limit of the query in forward loop", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(10*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -574,17 +743,28 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { NonceHigh: 1199, Tss: tss.TssPubkey, }, - currentHeight: 1199, - queryLimit: 300, // 300 < keeper.MaxPendingCctxs - expectedCctxs: append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs...), + currentHeight: 1199, + queryLimit: 300, // 300 < keeper.MaxPendingCctxs + expectedCctxs: append( + append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), + btcPendingCctxs...), expectedTotalPending: 400, expectedWithdrawWindow: 500, // the sliding window expectedWithdrawRate: sdk.NewInt(3e18).String(), // 3 ZETA, (2.5 + 0.5) per block rateLimitExceeded: false, }, { - name: "set a median rate (2.4 ZETA < rate < 3 ZETA) to exceed rate limit in forward loop", - rateLimitFlags: createTestRateLimiterFlags(500, math.NewUint(26*1e17), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + name: "set a median rate (2.4 ZETA < rate < 3 ZETA) to exceed rate limit in forward loop", + rateLimitFlags: createTestRateLimiterFlags( + 500, + math.NewUint(26*1e17), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -604,7 +784,9 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { currentHeight: 1199, queryLimit: keeper.MaxPendingCctxs, // return missed cctxs only if rate limit is exceeded - expectedCctxs: append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + expectedCctxs: append( + append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), + btcPendingCctxs[0:100]...), expectedTotalPending: 400, expectedWithdrawWindow: 500, // the sliding window expectedWithdrawRate: sdk.NewInt(3e18).String(), // 3 ZETA, (2.5 + 0.5) per block @@ -616,7 +798,16 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { // the left boundary will be 1149 (currentHeight-50), the pending nonces [1099, 1148] fall beyond the left boundary. // `pendingCctxWindow` is 100 which is wider than rate limiter window 50. // give a block rate of 2 ZETA/block, the max value allowed should be 100 * 2 = 200 ZETA - rateLimitFlags: createTestRateLimiterFlags(50, math.NewUint(2*1e18), zrc20ETH, zrc20BTC, zrc20USDT, "2500", "50000", "0.8"), + rateLimitFlags: createTestRateLimiterFlags( + 50, + math.NewUint(2*1e18), + zrc20ETH, + zrc20BTC, + zrc20USDT, + "2500", + "50000", + "0.8", + ), ethMinedCctxs: ethMinedCctxs, ethPendingCctxs: ethPendingCctxs, ethPendingNonces: observertypes.PendingNonces{ @@ -636,7 +827,9 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { currentHeight: 1199, queryLimit: keeper.MaxPendingCctxs, // return missed cctxs only if rate limit is exceeded - expectedCctxs: append(append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), btcPendingCctxs[0:100]...), + expectedCctxs: append( + append([]*types.CrossChainTx{}, ethPendingCctxs[0:100]...), + btcPendingCctxs[0:100]...), expectedTotalPending: 400, expectedWithdrawWindow: 100, // 100 > sliding window 50 expectedWithdrawRate: sdk.NewInt(3e18).String(), // 3 ZETA, (2.5 + 0.5) per block @@ -675,7 +868,10 @@ func TestKeeper_ListPendingCctxWithinRateLimit(t *testing.T) { ctx = ctx.WithBlockHeight(tt.currentHeight) // Query pending cctxs - res, err := k.ListPendingCctxWithinRateLimit(ctx, &types.QueryListPendingCctxWithinRateLimitRequest{Limit: tt.queryLimit}) + res, err := k.ListPendingCctxWithinRateLimit( + ctx, + &types.QueryListPendingCctxWithinRateLimitRequest{Limit: tt.queryLimit}, + ) require.NoError(t, err) require.EqualValues(t, tt.expectedCctxs, res.CrossChainTx) require.Equal(t, tt.expectedTotalPending, res.TotalPending) diff --git a/x/crosschain/keeper/grpc_query_gas_price.go b/x/crosschain/keeper/grpc_query_gas_price.go index 311bdc1d6b..668607da0a 100644 --- a/x/crosschain/keeper/grpc_query_gas_price.go +++ b/x/crosschain/keeper/grpc_query_gas_price.go @@ -12,7 +12,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) GasPriceAll(c context.Context, req *types.QueryAllGasPriceRequest) (*types.QueryAllGasPriceResponse, error) { +func (k Keeper) GasPriceAll( + c context.Context, + req *types.QueryAllGasPriceRequest, +) (*types.QueryAllGasPriceResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -40,7 +43,10 @@ func (k Keeper) GasPriceAll(c context.Context, req *types.QueryAllGasPriceReques return &types.QueryAllGasPriceResponse{GasPrice: gasPrices, Pagination: pageRes}, nil } -func (k Keeper) GasPrice(c context.Context, req *types.QueryGetGasPriceRequest) (*types.QueryGetGasPriceResponse, error) { +func (k Keeper) GasPrice( + c context.Context, + req *types.QueryGetGasPriceRequest, +) (*types.QueryGetGasPriceResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx.go b/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx.go index a30c33edf8..2dd86717fd 100644 --- a/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx.go +++ b/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx.go @@ -11,7 +11,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) InTxHashToCctxAll(c context.Context, req *types.QueryAllInTxHashToCctxRequest) (*types.QueryAllInTxHashToCctxResponse, error) { +func (k Keeper) InTxHashToCctxAll( + c context.Context, + req *types.QueryAllInTxHashToCctxRequest, +) (*types.QueryAllInTxHashToCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -39,7 +42,10 @@ func (k Keeper) InTxHashToCctxAll(c context.Context, req *types.QueryAllInTxHash return &types.QueryAllInTxHashToCctxResponse{InTxHashToCctx: inTxHashToCctxs, Pagination: pageRes}, nil } -func (k Keeper) InTxHashToCctx(c context.Context, req *types.QueryGetInTxHashToCctxRequest) (*types.QueryGetInTxHashToCctxResponse, error) { +func (k Keeper) InTxHashToCctx( + c context.Context, + req *types.QueryGetInTxHashToCctxRequest, +) (*types.QueryGetInTxHashToCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx_test.go b/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx_test.go index 306b977ed9..661031f146 100644 --- a/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx_test.go +++ b/x/crosschain/keeper/grpc_query_in_tx_hash_to_cctx_test.go @@ -134,7 +134,10 @@ func createInTxHashToCctxWithCctxs(keeper *crosschainkeeper.Keeper, ctx sdk.Cont cctxs[i].Creator = "any" cctxs[i].Index = fmt.Sprintf("0x123%d", i) cctxs[i].ZetaFees = math.OneUint() - cctxs[i].InboundTxParams = &types.InboundTxParams{InboundTxObservedHash: fmt.Sprintf("%d", i), Amount: math.OneUint()} + cctxs[i].InboundTxParams = &types.InboundTxParams{ + InboundTxObservedHash: fmt.Sprintf("%d", i), + Amount: math.OneUint(), + } cctxs[i].CctxStatus = &types.Status{Status: types.CctxStatus_PendingInbound} keeper.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctxs[i]) } diff --git a/x/crosschain/keeper/grpc_query_in_tx_tracker.go b/x/crosschain/keeper/grpc_query_in_tx_tracker.go index 59fdd21155..2b1519a29d 100644 --- a/x/crosschain/keeper/grpc_query_in_tx_tracker.go +++ b/x/crosschain/keeper/grpc_query_in_tx_tracker.go @@ -10,7 +10,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) InTxTrackerAllByChain(goCtx context.Context, request *types.QueryAllInTxTrackerByChainRequest) (*types.QueryAllInTxTrackerByChainResponse, error) { +func (k Keeper) InTxTrackerAllByChain( + goCtx context.Context, + request *types.QueryAllInTxTrackerByChainRequest, +) (*types.QueryAllInTxTrackerByChainResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) var inTxTrackers []types.InTxTracker inTxTrackers, pageRes, err := k.GetAllInTxTrackerForChainPaginated(ctx, request.ChainId, request.Pagination) @@ -20,7 +23,10 @@ func (k Keeper) InTxTrackerAllByChain(goCtx context.Context, request *types.Quer return &types.QueryAllInTxTrackerByChainResponse{InTxTracker: inTxTrackers, Pagination: pageRes}, nil } -func (k Keeper) InTxTrackerAll(goCtx context.Context, req *types.QueryAllInTxTrackersRequest) (*types.QueryAllInTxTrackersResponse, error) { +func (k Keeper) InTxTrackerAll( + goCtx context.Context, + req *types.QueryAllInTxTrackersRequest, +) (*types.QueryAllInTxTrackersResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) var inTxTrackers []types.InTxTracker inTxTrackers, pageRes, err := k.GetAllInTxTrackerPaginated(ctx, req.Pagination) diff --git a/x/crosschain/keeper/grpc_query_last_block_height.go b/x/crosschain/keeper/grpc_query_last_block_height.go index 875a5facf2..c6ee331f7f 100644 --- a/x/crosschain/keeper/grpc_query_last_block_height.go +++ b/x/crosschain/keeper/grpc_query_last_block_height.go @@ -12,7 +12,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) LastBlockHeightAll(c context.Context, req *types.QueryAllLastBlockHeightRequest) (*types.QueryAllLastBlockHeightResponse, error) { +func (k Keeper) LastBlockHeightAll( + c context.Context, + req *types.QueryAllLastBlockHeightRequest, +) (*types.QueryAllLastBlockHeightResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -40,7 +43,10 @@ func (k Keeper) LastBlockHeightAll(c context.Context, req *types.QueryAllLastBlo return &types.QueryAllLastBlockHeightResponse{LastBlockHeight: lastBlockHeights, Pagination: pageRes}, nil } -func (k Keeper) LastBlockHeight(c context.Context, req *types.QueryGetLastBlockHeightRequest) (*types.QueryGetLastBlockHeightResponse, error) { +func (k Keeper) LastBlockHeight( + c context.Context, + req *types.QueryGetLastBlockHeightRequest, +) (*types.QueryGetLastBlockHeightResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_last_zeta_height.go b/x/crosschain/keeper/grpc_query_last_zeta_height.go index ff1639d8dd..ce8f5c372d 100644 --- a/x/crosschain/keeper/grpc_query_last_zeta_height.go +++ b/x/crosschain/keeper/grpc_query_last_zeta_height.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) LastZetaHeight(goCtx context.Context, req *types.QueryLastZetaHeightRequest) (*types.QueryLastZetaHeightResponse, error) { +func (k Keeper) LastZetaHeight( + goCtx context.Context, + req *types.QueryLastZetaHeightRequest, +) (*types.QueryLastZetaHeightResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_out_tx_tracker.go b/x/crosschain/keeper/grpc_query_out_tx_tracker.go index 0170953eb2..1cfe747b83 100644 --- a/x/crosschain/keeper/grpc_query_out_tx_tracker.go +++ b/x/crosschain/keeper/grpc_query_out_tx_tracker.go @@ -12,7 +12,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) OutTxTrackerAll(c context.Context, req *types.QueryAllOutTxTrackerRequest) (*types.QueryAllOutTxTrackerResponse, error) { +func (k Keeper) OutTxTrackerAll( + c context.Context, + req *types.QueryAllOutTxTrackerRequest, +) (*types.QueryAllOutTxTrackerResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -38,7 +41,10 @@ func (k Keeper) OutTxTrackerAll(c context.Context, req *types.QueryAllOutTxTrack return &types.QueryAllOutTxTrackerResponse{OutTxTracker: outTxTrackers, Pagination: pageRes}, nil } -func (k Keeper) OutTxTrackerAllByChain(c context.Context, req *types.QueryAllOutTxTrackerByChainRequest) (*types.QueryAllOutTxTrackerByChainResponse, error) { +func (k Keeper) OutTxTrackerAllByChain( + c context.Context, + req *types.QueryAllOutTxTrackerByChainRequest, +) (*types.QueryAllOutTxTrackerByChainResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -65,7 +71,10 @@ func (k Keeper) OutTxTrackerAllByChain(c context.Context, req *types.QueryAllOut return &types.QueryAllOutTxTrackerByChainResponse{OutTxTracker: outTxTrackers, Pagination: pageRes}, nil } -func (k Keeper) OutTxTracker(c context.Context, req *types.QueryGetOutTxTrackerRequest) (*types.QueryGetOutTxTrackerResponse, error) { +func (k Keeper) OutTxTracker( + c context.Context, + req *types.QueryGetOutTxTrackerRequest, +) (*types.QueryGetOutTxTrackerResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_rate_limiter_flags.go b/x/crosschain/keeper/grpc_query_rate_limiter_flags.go index 998b9cf0a2..855c288336 100644 --- a/x/crosschain/keeper/grpc_query_rate_limiter_flags.go +++ b/x/crosschain/keeper/grpc_query_rate_limiter_flags.go @@ -10,7 +10,10 @@ import ( ) // RateLimiterFlags queries the rate limiter flags -func (k Keeper) RateLimiterFlags(c context.Context, req *types.QueryRateLimiterFlagsRequest) (*types.QueryRateLimiterFlagsResponse, error) { +func (k Keeper) RateLimiterFlags( + c context.Context, + req *types.QueryRateLimiterFlagsRequest, +) (*types.QueryRateLimiterFlagsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go b/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go index 5cb26ef831..68d27f2ff7 100644 --- a/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go +++ b/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go @@ -13,7 +13,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) ConvertGasToZeta(context context.Context, request *types.QueryConvertGasToZetaRequest) (*types.QueryConvertGasToZetaResponse, error) { +func (k Keeper) ConvertGasToZeta( + context context.Context, + request *types.QueryConvertGasToZetaRequest, +) (*types.QueryConvertGasToZetaResponse, error) { ctx := sdk.UnwrapSDKContext(context) chain := chains.GetChainFromChainID(request.ChainId) @@ -42,7 +45,10 @@ func (k Keeper) ConvertGasToZeta(context context.Context, request *types.QueryCo }, nil } -func (k Keeper) ProtocolFee(_ context.Context, _ *types.QueryMessagePassingProtocolFeeRequest) (*types.QueryMessagePassingProtocolFeeResponse, error) { +func (k Keeper) ProtocolFee( + _ context.Context, + _ *types.QueryMessagePassingProtocolFeeRequest, +) (*types.QueryMessagePassingProtocolFeeResponse, error) { return &types.QueryMessagePassingProtocolFeeResponse{ FeeInZeta: types.GetProtocolFee().String(), }, nil diff --git a/x/crosschain/keeper/in_tx_tracker.go b/x/crosschain/keeper/in_tx_tracker.go index 2d7849ee49..cbd37122d0 100644 --- a/x/crosschain/keeper/in_tx_tracker.go +++ b/x/crosschain/keeper/in_tx_tracker.go @@ -40,7 +40,11 @@ func (k Keeper) RemoveInTxTrackerIfExists(ctx sdk.Context, chainID int64, txHash store.Delete(types.KeyPrefix(key)) } } -func (k Keeper) GetAllInTxTrackerPaginated(ctx sdk.Context, pagination *query.PageRequest) (inTxTrackers []types.InTxTracker, pageRes *query.PageResponse, err error) { + +func (k Keeper) GetAllInTxTrackerPaginated( + ctx sdk.Context, + pagination *query.PageRequest, +) (inTxTrackers []types.InTxTracker, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.InTxTrackerKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer iterator.Close() @@ -79,7 +83,11 @@ func (k Keeper) GetAllInTxTrackerForChain(ctx sdk.Context, chainID int64) (list return list } -func (k Keeper) GetAllInTxTrackerForChainPaginated(ctx sdk.Context, chainID int64, pagination *query.PageRequest) (inTxTrackers []types.InTxTracker, pageRes *query.PageResponse, err error) { +func (k Keeper) GetAllInTxTrackerForChainPaginated( + ctx sdk.Context, + chainID int64, + pagination *query.PageRequest, +) (inTxTrackers []types.InTxTracker, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(fmt.Sprintf("%s", types.InTxTrackerKeyPrefix))) chainStore := prefix.NewStore(store, types.KeyPrefix(fmt.Sprintf("%d-", chainID))) pageRes, err = query.Paginate(chainStore, pagination, func(_ []byte, value []byte) error { diff --git a/x/crosschain/keeper/in_tx_tracker_test.go b/x/crosschain/keeper/in_tx_tracker_test.go index 317f305a82..a07b5b83f8 100644 --- a/x/crosschain/keeper/in_tx_tracker_test.go +++ b/x/crosschain/keeper/in_tx_tracker_test.go @@ -56,7 +56,11 @@ func TestKeeper_GetAllInTxTrackerForChain(t *testing.T) { t.Run("Get all InTx trackers for chain paginated by limit", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) intxTrackers := createNInTxTracker(keeper, ctx, 100, 6) - rst, pageRes, err := keeper.GetAllInTxTrackerForChainPaginated(ctx, 6, &query.PageRequest{Limit: 10, CountTotal: true}) + rst, pageRes, err := keeper.GetAllInTxTrackerForChainPaginated( + ctx, + 6, + &query.PageRequest{Limit: 10, CountTotal: true}, + ) require.NoError(t, err) require.Subset(t, nullify.Fill(intxTrackers), nullify.Fill(rst)) require.Equal(t, len(intxTrackers), int(pageRes.Total)) @@ -64,7 +68,11 @@ func TestKeeper_GetAllInTxTrackerForChain(t *testing.T) { t.Run("Get all InTx trackers for chain paginated by offset", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) intxTrackers := createNInTxTracker(keeper, ctx, 100, 6) - rst, pageRes, err := keeper.GetAllInTxTrackerForChainPaginated(ctx, 6, &query.PageRequest{Offset: 10, CountTotal: true}) + rst, pageRes, err := keeper.GetAllInTxTrackerForChainPaginated( + ctx, + 6, + &query.PageRequest{Offset: 10, CountTotal: true}, + ) require.NoError(t, err) require.Subset(t, nullify.Fill(intxTrackers), nullify.Fill(rst)) require.Equal(t, len(intxTrackers), int(pageRes.Total)) diff --git a/x/crosschain/keeper/migrator.go b/x/crosschain/keeper/migrator.go index 4de64140c8..20f7c25ac4 100644 --- a/x/crosschain/keeper/migrator.go +++ b/x/crosschain/keeper/migrator.go @@ -22,7 +22,12 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates the store from consensus version 1 to 2 func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.crossChainKeeper.zetaObserverKeeper, m.crossChainKeeper.storeKey, m.crossChainKeeper.cdc) + return v2.MigrateStore( + ctx, + m.crossChainKeeper.zetaObserverKeeper, + m.crossChainKeeper.storeKey, + m.crossChainKeeper.cdc, + ) } // Migrate2to3 migrates the store from consensus version 2 to 3 diff --git a/x/crosschain/keeper/msg_server_add_to_intx_tracker.go b/x/crosschain/keeper/msg_server_add_to_intx_tracker.go index 51e3a7763e..38e8374614 100644 --- a/x/crosschain/keeper/msg_server_add_to_intx_tracker.go +++ b/x/crosschain/keeper/msg_server_add_to_intx_tracker.go @@ -12,7 +12,10 @@ import ( ) // AddToInTxTracker adds a new record to the inbound transaction tracker. -func (k msgServer) AddToInTxTracker(goCtx context.Context, msg *types.MsgAddToInTxTracker) (*types.MsgAddToInTxTrackerResponse, error) { +func (k msgServer) AddToInTxTracker( + goCtx context.Context, + msg *types.MsgAddToInTxTracker, +) (*types.MsgAddToInTxTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) chain := k.GetObserverKeeper().GetSupportedChainFromChainID(ctx, msg.ChainId) if chain == nil { diff --git a/x/crosschain/keeper/msg_server_add_to_intx_tracker_test.go b/x/crosschain/keeper/msg_server_add_to_intx_tracker_test.go index 281692318e..8d77635a66 100644 --- a/x/crosschain/keeper/msg_server_add_to_intx_tracker_test.go +++ b/x/crosschain/keeper/msg_server_add_to_intx_tracker_test.go @@ -160,7 +160,8 @@ func TestMsgServer_AddToInTxTracker(t *testing.T) { keepertest.MockIsAuthorized(&authorityMock.Mock, mock.Anything, authoritytypes.PolicyType_groupEmergency, false) observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("error")) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(nil, errors.New("error")) txHash := "string" chainID := getValidEthChainID() @@ -193,7 +194,8 @@ func TestMsgServer_AddToInTxTracker(t *testing.T) { keepertest.MockIsAuthorized(&authorityMock.Mock, mock.Anything, authoritytypes.PolicyType_groupEmergency, false) observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(sample.Bytes(), nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(sample.Bytes(), nil) observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything).Return(nil, false) txHash := "string" @@ -227,8 +229,10 @@ func TestMsgServer_AddToInTxTracker(t *testing.T) { keepertest.MockIsAuthorized(&authorityMock.Mock, mock.Anything, authoritytypes.PolicyType_groupEmergency, false) observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(sample.Bytes(), nil) - observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything).Return(sample.ChainParams(chains.EthChain.ChainId), true) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(sample.Bytes(), nil) + observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything). + Return(sample.ChainParams(chains.EthChain.ChainId), true) observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(nil, errors.New("error")) txHash := "string" @@ -263,13 +267,15 @@ func TestMsgServer_AddToInTxTracker(t *testing.T) { keepertest.MockIsAuthorized(&authorityMock.Mock, mock.Anything, authoritytypes.PolicyType_groupEmergency, false) observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) - observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything).Return(sample.ChainParams(chains.EthChain.ChainId), true) + observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything). + Return(sample.ChainParams(chains.EthChain.ChainId), true) observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(&observertypes.QueryGetTssAddressResponse{ Eth: sample.EthAddress().Hex(), }, nil) // verifying the body will fail because the bytes are tried to be unmarshaled but they are not valid - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]byte("invalid"), nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return([]byte("invalid"), nil) txHash := "string" chainID := getValidEthChainID() @@ -309,11 +315,13 @@ func TestMsgServer_AddToInTxTracker(t *testing.T) { keepertest.MockIsAuthorized(&authorityMock.Mock, mock.Anything, authoritytypes.PolicyType_groupEmergency, false) observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) - observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything).Return(sample.ChainParams(chains.EthChain.ChainId), true) + observerMock.On("GetChainParamsByChainID", mock.Anything, mock.Anything). + Return(sample.ChainParams(chains.EthChain.ChainId), true) observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(&observertypes.QueryGetTssAddressResponse{ Eth: tssAddress.Hex(), }, nil) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ethTxBytes, nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(ethTxBytes, nil) _, err := msgServer.AddToInTxTracker(ctx, &types.MsgAddToInTxTracker{ Creator: admin, diff --git a/x/crosschain/keeper/msg_server_add_to_outtx_tracker.go b/x/crosschain/keeper/msg_server_add_to_outtx_tracker.go index 4f149a901f..55b439669f 100644 --- a/x/crosschain/keeper/msg_server_add_to_outtx_tracker.go +++ b/x/crosschain/keeper/msg_server_add_to_outtx_tracker.go @@ -19,7 +19,10 @@ const MaxOutTxTrackerHashes = 2 // AddToOutTxTracker adds a new record to the outbound transaction tracker. // only the admin policy account and the observer validators are authorized to broadcast this message without proof. // If no pending cctx is found, the tracker is removed, if there is an existed tracker with the nonce & chainID. -func (k msgServer) AddToOutTxTracker(goCtx context.Context, msg *types.MsgAddToOutTxTracker) (*types.MsgAddToOutTxTrackerResponse, error) { +func (k msgServer) AddToOutTxTracker( + goCtx context.Context, + msg *types.MsgAddToOutTxTracker, +) (*types.MsgAddToOutTxTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check the chain is supported @@ -37,7 +40,12 @@ func (k msgServer) AddToOutTxTracker(goCtx context.Context, msg *types.MsgAddToO return nil, cosmoserrors.Wrap(types.ErrCannotFindCctx, err.Error()) } if cctx == nil || cctx.CrossChainTx == nil { - return nil, cosmoserrors.Wrapf(types.ErrCannotFindCctx, "no corresponding cctx found for chain %d, nonce %d", msg.ChainId, msg.Nonce) + return nil, cosmoserrors.Wrapf( + types.ErrCannotFindCctx, + "no corresponding cctx found for chain %d, nonce %d", + msg.ChainId, + msg.Nonce, + ) } // tracker submission is only allowed when the cctx is pending diff --git a/x/crosschain/keeper/msg_server_add_to_outtx_tracker_test.go b/x/crosschain/keeper/msg_server_add_to_outtx_tracker_test.go index 2de8a61606..55fe6d2d13 100644 --- a/x/crosschain/keeper/msg_server_add_to_outtx_tracker_test.go +++ b/x/crosschain/keeper/msg_server_add_to_outtx_tracker_test.go @@ -345,7 +345,8 @@ func TestMsgServer_AddToOutTxTracker(t *testing.T) { observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(&observertypes.QueryGetTssAddressResponse{ Eth: tssAddress.Hex(), }, nil) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ethTxBytes, nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(ethTxBytes, nil) _, err := msgServer.AddToOutTxTracker(ctx, &types.MsgAddToOutTxTracker{ Creator: admin, @@ -387,7 +388,8 @@ func TestMsgServer_AddToOutTxTracker(t *testing.T) { observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(&observertypes.QueryGetTssAddressResponse{ Eth: tssAddress.Hex(), }, nil) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ethTxBytes, nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(ethTxBytes, nil) k.SetOutTxTracker(ctx, types.OutTxTracker{ ChainId: chainID, @@ -442,7 +444,8 @@ func TestMsgServer_AddToOutTxTracker(t *testing.T) { observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) keepertest.MockCctxByNonce(t, ctx, *k, observerMock, types.CctxStatus_PendingOutbound, false) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ethTxBytes, errors.New("error")) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(ethTxBytes, errors.New("error")) _, err := msgServer.AddToOutTxTracker(ctx, &types.MsgAddToOutTxTracker{ Creator: admin, @@ -477,7 +480,8 @@ func TestMsgServer_AddToOutTxTracker(t *testing.T) { observerMock.On("GetSupportedChainFromChainID", mock.Anything, mock.Anything).Return(&chains.Chain{}) observerMock.On("IsNonTombstonedObserver", mock.Anything, mock.Anything).Return(false) keepertest.MockCctxByNonce(t, ctx, *k, observerMock, types.CctxStatus_PendingOutbound, false) - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ethTxBytes, nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(ethTxBytes, nil) observerMock.On("GetTssAddress", mock.Anything, mock.Anything).Return(&observertypes.QueryGetTssAddressResponse{ Eth: tssAddress.Hex(), }, errors.New("error")) @@ -520,7 +524,8 @@ func TestMsgServer_AddToOutTxTracker(t *testing.T) { }, nil) // makes VerifyProof returning an invalid hash - lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(sample.Bytes(), nil) + lightclientMock.On("VerifyProof", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(sample.Bytes(), nil) _, err := msgServer.AddToOutTxTracker(ctx, &types.MsgAddToOutTxTracker{ Creator: admin, diff --git a/x/crosschain/keeper/msg_server_migrate_tss_funds.go b/x/crosschain/keeper/msg_server_migrate_tss_funds.go index dc748a097d..68664b7fc1 100644 --- a/x/crosschain/keeper/msg_server_migrate_tss_funds.go +++ b/x/crosschain/keeper/msg_server_migrate_tss_funds.go @@ -23,12 +23,18 @@ import ( ) // MigrateTssFunds migrates the funds from the current TSS to the new TSS -func (k msgServer) MigrateTssFunds(goCtx context.Context, msg *types.MsgMigrateTssFunds) (*types.MsgMigrateTssFundsResponse, error) { +func (k msgServer) MigrateTssFunds( + goCtx context.Context, + msg *types.MsgMigrateTssFunds, +) (*types.MsgMigrateTssFundsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check if authorized if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupAdmin) { - return nil, errorsmod.Wrap(authoritytypes.ErrUnauthorized, "Update can only be executed by the correct policy account") + return nil, errorsmod.Wrap( + authoritytypes.ErrUnauthorized, + "Update can only be executed by the correct policy account", + ) } if k.zetaObserverKeeper.IsInboundEnabled(ctx) { @@ -75,14 +81,26 @@ func (k msgServer) MigrateTssFunds(goCtx context.Context, msg *types.MsgMigrateT return &types.MsgMigrateTssFundsResponse{}, nil } -func (k Keeper) MigrateTSSFundsForChain(ctx sdk.Context, chainID int64, amount sdkmath.Uint, currentTss observertypes.TSS, tssList []observertypes.TSS) error { +func (k Keeper) MigrateTSSFundsForChain( + ctx sdk.Context, + chainID int64, + amount sdkmath.Uint, + currentTss observertypes.TSS, + tssList []observertypes.TSS, +) error { // Always migrate to the latest TSS if multiple TSS addresses have been generated newTss := tssList[len(tssList)-1] medianGasPrice, isFound := k.GetMedianGasPriceInUint(ctx, chainID) if !isFound { return types.ErrUnableToGetGasPrice } - indexString := GetIndexStringForTssMigration(currentTss.TssPubkey, newTss.TssPubkey, chainID, amount, ctx.BlockHeight()) + indexString := GetIndexStringForTssMigration( + currentTss.TssPubkey, + newTss.TssPubkey, + chainID, + amount, + ctx.BlockHeight(), + ) hash := crypto.Keccak256Hash([]byte(indexString)) index := hash.Hex() @@ -149,7 +167,15 @@ func (k Keeper) MigrateTSSFundsForChain(ctx sdk.Context, chainID int64, amount s cctx.GetCurrentOutTxParam().OutboundTxGasPrice = multipliedGasPrice.String() evmFee := sdkmath.NewUint(cctx.GetCurrentOutTxParam().OutboundTxGasLimit).Mul(multipliedGasPrice) if evmFee.GT(amount) { - return errorsmod.Wrap(types.ErrInsufficientFundsTssMigration, fmt.Sprintf("insufficient funds to pay for gas fee, amount: %s, gas fee: %s, chainid: %d", amount.String(), evmFee.String(), chainID)) + return errorsmod.Wrap( + types.ErrInsufficientFundsTssMigration, + fmt.Sprintf( + "insufficient funds to pay for gas fee, amount: %s, gas fee: %s, chainid: %d", + amount.String(), + evmFee.String(), + chainID, + ), + ) } cctx.GetCurrentOutTxParam().Amount = amount.Sub(evmFee) } @@ -185,10 +211,19 @@ func (k Keeper) MigrateTSSFundsForChain(ctx sdk.Context, chainID int64, amount s if found { olderMigrationCctx, found := k.GetCrossChainTx(ctx, existingMigrationInfo.MigrationCctxIndex) if !found { - return errorsmod.Wrapf(types.ErrCannotFindCctx, "cannot find existing migration cctx but migration info is present for chainID %d , migrator info : %s", chainID, existingMigrationInfo.String()) + return errorsmod.Wrapf( + types.ErrCannotFindCctx, + "cannot find existing migration cctx but migration info is present for chainID %d , migrator info : %s", + chainID, + existingMigrationInfo.String(), + ) } if olderMigrationCctx.CctxStatus.Status == types.CctxStatus_PendingOutbound { - return errorsmod.Wrapf(types.ErrUnsupportedStatus, "cannot migrate funds while there are pending migrations , migrator info : %s", existingMigrationInfo.String()) + return errorsmod.Wrapf( + types.ErrUnsupportedStatus, + "cannot migrate funds while there are pending migrations , migrator info : %s", + existingMigrationInfo.String(), + ) } } @@ -202,6 +237,11 @@ func (k Keeper) MigrateTSSFundsForChain(ctx sdk.Context, chainID int64, amount s return nil } -func GetIndexStringForTssMigration(currentTssPubkey, newTssPubkey string, chainID int64, amount sdkmath.Uint, height int64) string { +func GetIndexStringForTssMigration( + currentTssPubkey, newTssPubkey string, + chainID int64, + amount sdkmath.Uint, + height int64, +) string { return fmt.Sprintf("%s-%s-%d-%s-%d", currentTssPubkey, newTssPubkey, chainID, amount.String(), height) } diff --git a/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go b/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go index 5865c6ccca..30c04451e2 100644 --- a/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go +++ b/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go @@ -74,7 +74,13 @@ func setupTssMigrationParams( ChainId: chain.ChainId, Nonce: 1, }) - indexString := keeper.GetIndexStringForTssMigration(currentTss.TssPubkey, newTss.TssPubkey, chain.ChainId, amount, ctx.BlockHeight()) + indexString := keeper.GetIndexStringForTssMigration( + currentTss.TssPubkey, + newTss.TssPubkey, + chain.ChainId, + amount, + ctx.BlockHeight(), + ) return indexString, currentTss.TssPubkey } @@ -308,7 +314,8 @@ func TestMsgServer_MigrateTssFunds(t *testing.T) { tss2.FinalizedZetaHeight = 3 observerMock.On("GetTSS", mock.Anything).Return(tss1, true) observerMock.On("GetAllTSS", mock.Anything).Return([]observertypes.TSS{tss2}) - observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything).Return(observertypes.PendingNonces{}, false) + observerMock.On("GetPendingNonces", mock.Anything, mock.Anything, mock.Anything). + Return(observertypes.PendingNonces{}, false) msgServer := keeper.NewMsgServerImpl(*k) chain := getValidEthChain() @@ -472,35 +479,38 @@ func TestMsgServer_MigrateTssFunds(t *testing.T) { require.True(t, found) }) - t.Run("unable to migrate funds if current TSS is not present in TSSHistory and no new TSS has been generated", func(t *testing.T) { - k, ctx, _, zk := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseAuthorityMock: true, - }) - - admin := sample.AccAddress() - authorityMock := keepertest.GetCrosschainAuthorityMock(t, k) - keepertest.MockIsAuthorized(&authorityMock.Mock, admin, authoritytypes.PolicyType_groupAdmin, true) - - msgServer := keeper.NewMsgServerImpl(*k) - chain := getValidEthChain() - amount := sdkmath.NewUintFromString("10000000000000000000") - indexString, _ := setupTssMigrationParams(zk, k, ctx, *chain, amount, false, false) - currentTss, found := k.GetObserverKeeper().GetTSS(ctx) - require.True(t, found) - newTss := sample.Tss() - newTss.FinalizedZetaHeight = currentTss.FinalizedZetaHeight - 10 - newTss.KeyGenZetaHeight = currentTss.KeyGenZetaHeight - 10 - k.GetObserverKeeper().SetTSSHistory(ctx, newTss) - _, err := msgServer.MigrateTssFunds(ctx, &crosschaintypes.MsgMigrateTssFunds{ - Creator: admin, - ChainId: chain.ChainId, - Amount: amount, - }) - require.ErrorIs(t, err, crosschaintypes.ErrCannotMigrateTssFunds) - require.ErrorContains(t, err, "current tss is the latest") - hash := crypto.Keccak256Hash([]byte(indexString)) - index := hash.Hex() - _, found = k.GetCrossChainTx(ctx, index) - require.False(t, found) - }) + t.Run( + "unable to migrate funds if current TSS is not present in TSSHistory and no new TSS has been generated", + func(t *testing.T) { + k, ctx, _, zk := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseAuthorityMock: true, + }) + + admin := sample.AccAddress() + authorityMock := keepertest.GetCrosschainAuthorityMock(t, k) + keepertest.MockIsAuthorized(&authorityMock.Mock, admin, authoritytypes.PolicyType_groupAdmin, true) + + msgServer := keeper.NewMsgServerImpl(*k) + chain := getValidEthChain() + amount := sdkmath.NewUintFromString("10000000000000000000") + indexString, _ := setupTssMigrationParams(zk, k, ctx, *chain, amount, false, false) + currentTss, found := k.GetObserverKeeper().GetTSS(ctx) + require.True(t, found) + newTss := sample.Tss() + newTss.FinalizedZetaHeight = currentTss.FinalizedZetaHeight - 10 + newTss.KeyGenZetaHeight = currentTss.KeyGenZetaHeight - 10 + k.GetObserverKeeper().SetTSSHistory(ctx, newTss) + _, err := msgServer.MigrateTssFunds(ctx, &crosschaintypes.MsgMigrateTssFunds{ + Creator: admin, + ChainId: chain.ChainId, + Amount: amount, + }) + require.ErrorIs(t, err, crosschaintypes.ErrCannotMigrateTssFunds) + require.ErrorContains(t, err, "current tss is the latest") + hash := crypto.Keccak256Hash([]byte(indexString)) + index := hash.Hex() + _, found = k.GetCrossChainTx(ctx, index) + require.False(t, found) + }, + ) } diff --git a/x/crosschain/keeper/msg_server_refund_aborted_tx.go b/x/crosschain/keeper/msg_server_refund_aborted_tx.go index 954cb2c4a9..70fc8bd6a4 100644 --- a/x/crosschain/keeper/msg_server_refund_aborted_tx.go +++ b/x/crosschain/keeper/msg_server_refund_aborted_tx.go @@ -17,7 +17,10 @@ import ( // It refunds the amount to the refund address and sets the CCTX as refunded. // Refer to documentation for GetRefundAddress for the refund address logic. // Refer to documentation for GetAbortedAmount for the aborted amount logic. -func (k msgServer) RefundAbortedCCTX(goCtx context.Context, msg *types.MsgRefundAbortedCCTX) (*types.MsgRefundAbortedCCTXResponse, error) { +func (k msgServer) RefundAbortedCCTX( + goCtx context.Context, + msg *types.MsgRefundAbortedCCTX, +) (*types.MsgRefundAbortedCCTXResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) diff --git a/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go b/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go index 0b54a93c69..a95c9d319d 100644 --- a/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go +++ b/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go @@ -57,7 +57,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundTxParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundTxParams.SenderChainId, "foobar", "foobar") + zrc20 := setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundTxParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -328,7 +336,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundTxParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundTxParams.SenderChainId, "foobar", "foobar") + zrc20 := setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundTxParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -491,7 +507,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundTxParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - _ = setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundTxParams.SenderChainId, "foobar", "foobar") + _ = setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundTxParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -552,7 +576,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundTxParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - _ = setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundTxParams.SenderChainId, "foobar", "foobar") + _ = setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundTxParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, diff --git a/x/crosschain/keeper/msg_server_remove_out_tx_tracker.go b/x/crosschain/keeper/msg_server_remove_out_tx_tracker.go index 0eba210cbd..a0bceb816b 100644 --- a/x/crosschain/keeper/msg_server_remove_out_tx_tracker.go +++ b/x/crosschain/keeper/msg_server_remove_out_tx_tracker.go @@ -11,7 +11,10 @@ import ( // RemoveFromOutTxTracker removes a record from the outbound transaction tracker by chain ID and nonce. // // Authorized: admin policy group 1. -func (k msgServer) RemoveFromOutTxTracker(goCtx context.Context, msg *types.MsgRemoveFromOutTxTracker) (*types.MsgRemoveFromOutTxTrackerResponse, error) { +func (k msgServer) RemoveFromOutTxTracker( + goCtx context.Context, + msg *types.MsgRemoveFromOutTxTracker, +) (*types.MsgRemoveFromOutTxTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupEmergency) { return &types.MsgRemoveFromOutTxTrackerResponse{}, authoritytypes.ErrUnauthorized diff --git a/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go b/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go index 357bbfa7fc..588bae45f1 100644 --- a/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go +++ b/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go @@ -12,7 +12,10 @@ import ( // UpdateRateLimiterFlags updates the rate limiter flags. // Authorized: admin policy operational. -func (k msgServer) UpdateRateLimiterFlags(goCtx context.Context, msg *types.MsgUpdateRateLimiterFlags) (*types.MsgUpdateRateLimiterFlagsResponse, error) { +func (k msgServer) UpdateRateLimiterFlags( + goCtx context.Context, + msg *types.MsgUpdateRateLimiterFlags, +) (*types.MsgUpdateRateLimiterFlagsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { diff --git a/x/crosschain/keeper/msg_server_update_tss.go b/x/crosschain/keeper/msg_server_update_tss.go index 29e8fe25db..172fcc95c2 100644 --- a/x/crosschain/keeper/msg_server_update_tss.go +++ b/x/crosschain/keeper/msg_server_update_tss.go @@ -11,14 +11,20 @@ import ( ) // UpdateTssAddress updates the TSS address. -func (k msgServer) UpdateTssAddress(goCtx context.Context, msg *types.MsgUpdateTssAddress) (*types.MsgUpdateTssAddressResponse, error) { +func (k msgServer) UpdateTssAddress( + goCtx context.Context, + msg *types.MsgUpdateTssAddress, +) (*types.MsgUpdateTssAddressResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check if authorized // TODO : Add a new policy type for updating the TSS address // https://github.com/zeta-chain/node/issues/1715 if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupAdmin) { - return nil, errorsmod.Wrap(authoritytypes.ErrUnauthorized, "Update can only be executed by the correct policy account") + return nil, errorsmod.Wrap( + authoritytypes.ErrUnauthorized, + "Update can only be executed by the correct policy account", + ) } currentTss, found := k.zetaObserverKeeper.GetTSS(ctx) @@ -37,7 +43,10 @@ func (k msgServer) UpdateTssAddress(goCtx context.Context, msg *types.MsgUpdateT tssMigrators := k.zetaObserverKeeper.GetAllTssFundMigrators(ctx) // Each connected chain should have its own tss migrator if len(k.zetaObserverKeeper.GetSupportedChains(ctx)) != len(tssMigrators) { - return nil, errorsmod.Wrap(types.ErrUnableToUpdateTss, "cannot update tss address not enough migrations have been created and completed") + return nil, errorsmod.Wrap( + types.ErrUnableToUpdateTss, + "cannot update tss address not enough migrations have been created and completed", + ) } // GetAllTssFundMigrators would return the migrators created for the current migration @@ -49,8 +58,11 @@ func (k msgServer) UpdateTssAddress(goCtx context.Context, msg *types.MsgUpdateT return nil, errorsmod.Wrap(types.ErrUnableToUpdateTss, "migration cross chain tx not found") } if migratorTx.CctxStatus.Status != types.CctxStatus_OutboundMined { - return nil, errorsmod.Wrapf(types.ErrUnableToUpdateTss, - "cannot update tss address while there are pending migrations , current status of migration cctx : %s ", migratorTx.CctxStatus.Status.String()) + return nil, errorsmod.Wrapf( + types.ErrUnableToUpdateTss, + "cannot update tss address while there are pending migrations , current status of migration cctx : %s ", + migratorTx.CctxStatus.Status.String(), + ) } } diff --git a/x/crosschain/keeper/msg_server_update_tss_test.go b/x/crosschain/keeper/msg_server_update_tss_test.go index 56bfdc205f..75d8897bd6 100644 --- a/x/crosschain/keeper/msg_server_update_tss_test.go +++ b/x/crosschain/keeper/msg_server_update_tss_test.go @@ -74,7 +74,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { cctx.CctxStatus.Status = crosschaintypes.CctxStatus_OutboundMined k.SetCrossChainTx(ctx, *cctx) } - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) _, err := msgServer.UpdateTssAddress(ctx, &crosschaintypes.MsgUpdateTssAddress{ Creator: admin, TssPubkey: tssNew.TssPubkey, @@ -111,7 +115,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { cctx.CctxStatus.Status = crosschaintypes.CctxStatus_OutboundMined k.SetCrossChainTx(ctx, *cctx) } - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) _, err := msgServer.UpdateTssAddress(ctx, &crosschaintypes.MsgUpdateTssAddress{ Creator: admin, TssPubkey: tssNew.TssPubkey, @@ -121,7 +129,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { tss, found := k.GetObserverKeeper().GetTSS(ctx) require.True(t, found) require.Equal(t, tssOld, tss) - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) }) t.Run("old tss pubkey provided", func(t *testing.T) { @@ -147,7 +159,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { cctx.CctxStatus.Status = crosschaintypes.CctxStatus_OutboundMined k.SetCrossChainTx(ctx, *cctx) } - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) _, err := msgServer.UpdateTssAddress(ctx, &crosschaintypes.MsgUpdateTssAddress{ Creator: admin, TssPubkey: tssOld.TssPubkey, @@ -157,7 +173,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { tss, found := k.GetObserverKeeper().GetTSS(ctx) require.True(t, found) require.Equal(t, tssOld, tss) - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) }) t.Run("unable to update tss when not enough migrators are present", func(t *testing.T) { @@ -231,7 +251,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { cctx.CctxStatus.Status = crosschaintypes.CctxStatus_PendingOutbound k.SetCrossChainTx(ctx, *cctx) } - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) _, err := msgServer.UpdateTssAddress(ctx, &crosschaintypes.MsgUpdateTssAddress{ Creator: admin, TssPubkey: tssNew.TssPubkey, @@ -270,7 +294,11 @@ func TestMsgServer_UpdateTssAddress(t *testing.T) { MigrationCctxIndex: sample.GetCctxIndexFromString(index), }) } - require.Equal(t, len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), len(k.GetObserverKeeper().GetSupportedChains(ctx))) + require.Equal( + t, + len(k.GetObserverKeeper().GetAllTssFundMigrators(ctx)), + len(k.GetObserverKeeper().GetSupportedChains(ctx)), + ) _, err := msgServer.UpdateTssAddress(ctx, &crosschaintypes.MsgUpdateTssAddress{ Creator: admin, TssPubkey: tssNew.TssPubkey, diff --git a/x/crosschain/keeper/msg_server_vote_gas_price.go b/x/crosschain/keeper/msg_server_vote_gas_price.go index 77df7eaf48..4300de3695 100644 --- a/x/crosschain/keeper/msg_server_vote_gas_price.go +++ b/x/crosschain/keeper/msg_server_vote_gas_price.go @@ -20,7 +20,10 @@ import ( // median index is updated. // // Only observer validators are authorized to broadcast this message. -func (k msgServer) VoteGasPrice(goCtx context.Context, msg *types.MsgVoteGasPrice) (*types.MsgVoteGasPriceResponse, error) { +func (k msgServer) VoteGasPrice( + goCtx context.Context, + msg *types.MsgVoteGasPrice, +) (*types.MsgVoteGasPriceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) chain := k.zetaObserverKeeper.GetSupportedChainFromChainID(ctx, msg.ChainId) diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx.go b/x/crosschain/keeper/msg_server_vote_inbound_tx.go index 5d36965647..6e1eff743d 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx.go @@ -52,7 +52,10 @@ import ( // ``` // // Only observer validators are authorized to broadcast this message. -func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.MsgVoteOnObservedInboundTx) (*types.MsgVoteOnObservedInboundTxResponse, error) { +func (k msgServer) VoteOnObservedInboundTx( + goCtx context.Context, + msg *types.MsgVoteOnObservedInboundTx, +) (*types.MsgVoteOnObservedInboundTxResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) index := msg.Digest() @@ -79,7 +82,12 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg if k.IsFinalizedInbound(tmpCtx, msg.InTxHash, msg.SenderChainId, msg.EventIndex) { return nil, cosmoserrors.Wrap( types.ErrObservedTxAlreadyFinalized, - fmt.Sprintf("InTxHash:%s, SenderChainID:%d, EventIndex:%d", msg.InTxHash, msg.SenderChainId, msg.EventIndex), + fmt.Sprintf( + "InTxHash:%s, SenderChainID:%d, EventIndex:%d", + msg.InTxHash, + msg.SenderChainId, + msg.EventIndex, + ), ) } } diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go b/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go index 681ce8f780..0fc362442e 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go @@ -311,7 +311,15 @@ func TestKeeper_SaveInbound(t *testing.T) { eventIndex := sample.Uint64InRange(1, 100) k.SaveInbound(ctx, cctx, eventIndex) require.Equal(t, types.TxFinalizationStatus_Executed, cctx.InboundTxParams.TxFinalizationStatus) - require.True(t, k.IsFinalizedInbound(ctx, cctx.GetInboundTxParams().InboundTxObservedHash, cctx.GetInboundTxParams().SenderChainId, eventIndex)) + require.True( + t, + k.IsFinalizedInbound( + ctx, + cctx.GetInboundTxParams().InboundTxObservedHash, + cctx.GetInboundTxParams().SenderChainId, + eventIndex, + ), + ) _, found := k.GetCrossChainTx(ctx, cctx.Index) require.True(t, found) }) @@ -334,7 +342,15 @@ func TestKeeper_SaveInbound(t *testing.T) { k.SaveInbound(ctx, cctx, eventIndex) require.Equal(t, types.TxFinalizationStatus_Executed, cctx.InboundTxParams.TxFinalizationStatus) - require.True(t, k.IsFinalizedInbound(ctx, cctx.GetInboundTxParams().InboundTxObservedHash, cctx.GetInboundTxParams().SenderChainId, eventIndex)) + require.True( + t, + k.IsFinalizedInbound( + ctx, + cctx.GetInboundTxParams().InboundTxObservedHash, + cctx.GetInboundTxParams().SenderChainId, + eventIndex, + ), + ) _, found := k.GetCrossChainTx(ctx, cctx.Index) require.True(t, found) _, found = k.GetInTxTracker(ctx, senderChain.ChainId, hash.String()) @@ -343,7 +359,13 @@ func TestKeeper_SaveInbound(t *testing.T) { } // GetERC20Cctx returns a sample CrossChainTx with ERC20 params. This is used for testing Inbound and Outbound voting transactions -func GetERC20Cctx(t *testing.T, receiver ethcommon.Address, senderChain chains.Chain, asset string, amount *big.Int) *types.CrossChainTx { +func GetERC20Cctx( + t *testing.T, + receiver ethcommon.Address, + senderChain chains.Chain, + asset string, + amount *big.Int, +) *types.CrossChainTx { r := sample.Rand() cctx := &types.CrossChainTx{ Creator: sample.AccAddress(), diff --git a/x/crosschain/keeper/msg_server_vote_outbound_tx.go b/x/crosschain/keeper/msg_server_vote_outbound_tx.go index fd0c462e4e..3627e9798c 100644 --- a/x/crosschain/keeper/msg_server_vote_outbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_outbound_tx.go @@ -54,7 +54,10 @@ import ( // ``` // // Only observer validators are authorized to broadcast this message. -func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.MsgVoteOnObservedOutboundTx) (*types.MsgVoteOnObservedOutboundTxResponse, error) { +func (k msgServer) VoteOnObservedOutboundTx( + goCtx context.Context, + msg *types.MsgVoteOnObservedOutboundTx, +) (*types.MsgVoteOnObservedOutboundTxResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Validate the message params to verify it against an existing cctx @@ -107,12 +110,17 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms func (k Keeper) FundStabilityPool(ctx sdk.Context, cctx *types.CrossChainTx) { // Fund the gas stability pool with the remaining funds if err := k.FundGasStabilityPoolFromRemainingFees(ctx, *cctx.GetCurrentOutTxParam(), cctx.GetCurrentOutTxParam().ReceiverChainId); err != nil { - ctx.Logger().Error(fmt.Sprintf("VoteOnObservedOutboundTx: CCTX: %s Can't fund the gas stability pool with remaining fees %s", cctx.Index, err.Error())) + ctx.Logger(). + Error(fmt.Sprintf("VoteOnObservedOutboundTx: CCTX: %s Can't fund the gas stability pool with remaining fees %s", cctx.Index, err.Error())) } } // FundGasStabilityPoolFromRemainingFees funds the gas stability pool with the remaining fees of an outbound tx -func (k Keeper) FundGasStabilityPoolFromRemainingFees(ctx sdk.Context, outboundTxParams types.OutboundTxParams, chainID int64) error { +func (k Keeper) FundGasStabilityPoolFromRemainingFees( + ctx sdk.Context, + outboundTxParams types.OutboundTxParams, + chainID int64, +) error { gasUsed := outboundTxParams.OutboundTxGasUsed gasLimit := outboundTxParams.OutboundTxEffectiveGasLimit gasPrice := math.NewUintFromBigInt(outboundTxParams.OutboundTxEffectiveGasPrice.BigInt()) @@ -189,19 +197,33 @@ func (k Keeper) SaveOutbound(ctx sdk.Context, cctx *types.CrossChainTx, ballotIn // #nosec G701 always in range k.GetObserverKeeper().RemoveFromPendingNonces(ctx, tssPubkey, receiverChain, int64(outTxTssNonce)) k.RemoveOutTxTracker(ctx, receiverChain, outTxTssNonce) - ctx.Logger().Info(fmt.Sprintf("Remove tracker %s: , Block Height : %d ", getOutTrackerIndex(receiverChain, outTxTssNonce), ctx.BlockHeight())) + ctx.Logger(). + Info(fmt.Sprintf("Remove tracker %s: , Block Height : %d ", getOutTrackerIndex(receiverChain, outTxTssNonce), ctx.BlockHeight())) // This should set nonce to cctx only if a new revert is created. k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, *cctx) } -func (k Keeper) ValidateOutboundMessage(ctx sdk.Context, msg types.MsgVoteOnObservedOutboundTx) (types.CrossChainTx, error) { +func (k Keeper) ValidateOutboundMessage( + ctx sdk.Context, + msg types.MsgVoteOnObservedOutboundTx, +) (types.CrossChainTx, error) { // check if CCTX exists and if the nonce matches cctx, found := k.GetCrossChainTx(ctx, msg.CctxHash) if !found { - return types.CrossChainTx{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("CCTX %s does not exist", msg.CctxHash)) + return types.CrossChainTx{}, cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf("CCTX %s does not exist", msg.CctxHash), + ) } if cctx.GetCurrentOutTxParam().OutboundTxTssNonce != msg.OutTxTssNonce { - return types.CrossChainTx{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", msg.OutTxTssNonce, cctx.GetCurrentOutTxParam().OutboundTxTssNonce)) + return types.CrossChainTx{}, cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", + msg.OutTxTssNonce, + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + ), + ) } // do not process an outbound vote if TSS is not found _, found = k.zetaObserverKeeper.GetTSS(ctx) @@ -209,7 +231,14 @@ func (k Keeper) ValidateOutboundMessage(ctx sdk.Context, msg types.MsgVoteOnObse return types.CrossChainTx{}, types.ErrCannotFindTSSKeys } if cctx.GetCurrentOutTxParam().ReceiverChainId != msg.OutTxChain { - return types.CrossChainTx{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutTxChain %d does not match CCTX OutTxChain %d", msg.OutTxChain, cctx.GetCurrentOutTxParam().ReceiverChainId)) + return types.CrossChainTx{}, cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "OutTxChain %d does not match CCTX OutTxChain %d", + msg.OutTxChain, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ), + ) } return cctx, nil } diff --git a/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go b/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go index 606f450afc..cca10e7d65 100644 --- a/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go +++ b/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go @@ -69,13 +69,15 @@ func TestKeeper_FundGasStabilityPoolFromRemainingFees(t *testing.T) { isError: true, }, { - name: "should call fund stability pool with correct remaining fees", - effectiveGasLimit: 100, - gasUsed: 90, - effectiveGasPrice: math.NewInt(100), - fundStabilityPoolReturn: nil, - expectFundStabilityPoolCall: true, - fundStabilityPoolExpectedRemainingFee: big.NewInt(10 * keeper.RemainingFeesToStabilityPoolPercent), // (100-90)*100 = 1000 => statbilityPool% of 1000 = 10 * statbilityPool + name: "should call fund stability pool with correct remaining fees", + effectiveGasLimit: 100, + gasUsed: 90, + effectiveGasPrice: math.NewInt(100), + fundStabilityPoolReturn: nil, + expectFundStabilityPoolCall: true, + fundStabilityPoolExpectedRemainingFee: big.NewInt( + 10 * keeper.RemainingFeesToStabilityPoolPercent, + ), // (100-90)*100 = 1000 => statbilityPool% of 1000 = 10 * statbilityPool }, { name: "should return error if fund stability pool returns error", @@ -322,7 +324,8 @@ func TestKeeper_VoteOnObservedOutboundTx(t *testing.T) { keepertest.MockGetOutBound(observerMock, ctx) // Fail ProcessOutbound so that changes are not committed to the state - fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything).Return(fungibletypes.ForeignCoins{}, false) + fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything). + Return(fungibletypes.ForeignCoins{}, false) //Successfully mock SaveFailedOutbound keepertest.MockSaveOutBound(observerMock, ctx, cctx, tss) @@ -363,7 +366,12 @@ func TestKeeper_VoteOnObservedOutboundTx(t *testing.T) { // set state to successfully vote on outbound tx accAddress, err := observertypes.GetAccAddressFromOperatorAddress(validator.OperatorAddress) require.NoError(t, err) - zk.ObserverKeeper.SetObserverSet(ctx, observertypes.ObserverSet{ObserverList: []string{accAddress.String(), sample.AccAddress(), sample.AccAddress()}}) + zk.ObserverKeeper.SetObserverSet( + ctx, + observertypes.ObserverSet{ + ObserverList: []string{accAddress.String(), sample.AccAddress(), sample.AccAddress()}, + }, + ) sk.StakingKeeper.SetValidator(ctx, validator) cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) cctx.GetCurrentOutTxParam().TssPubkey = tss.TssPubkey @@ -454,7 +462,11 @@ func TestKeeper_SaveFailedOutBound(t *testing.T) { cctx.CctxStatus.Status = types.CctxStatus_PendingOutbound k.SaveFailedOutbound(ctx, cctx, sample.String(), sample.ZetaIndex(t)) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_Aborted) - _, found := k.GetOutTxTracker(ctx, cctx.GetCurrentOutTxParam().ReceiverChainId, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) + _, found := k.GetOutTxTracker( + ctx, + cctx.GetCurrentOutTxParam().ReceiverChainId, + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + ) require.False(t, found) }) } @@ -472,7 +484,11 @@ func TestKeeper_SaveSuccessfulOutBound(t *testing.T) { cctx.CctxStatus.Status = types.CctxStatus_PendingOutbound k.SaveSuccessfulOutbound(ctx, cctx, sample.String()) require.Equal(t, cctx.GetCurrentOutTxParam().OutboundTxBallotIndex, sample.String()) - _, found := k.GetOutTxTracker(ctx, cctx.GetCurrentOutTxParam().ReceiverChainId, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) + _, found := k.GetOutTxTracker( + ctx, + cctx.GetCurrentOutTxParam().ReceiverChainId, + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + ) require.False(t, found) }) } @@ -505,15 +521,28 @@ func TestKeeper_SaveOutbound(t *testing.T) { // Save outbound and assert all values are successfully saved k.SaveOutbound(ctx, cctx, ballotIndex) require.Equal(t, cctx.GetCurrentOutTxParam().OutboundTxBallotIndex, ballotIndex) - _, found := k.GetOutTxTracker(ctx, cctx.GetCurrentOutTxParam().ReceiverChainId, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) + _, found := k.GetOutTxTracker( + ctx, + cctx.GetCurrentOutTxParam().ReceiverChainId, + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + ) require.False(t, found) - pn, found := zk.ObserverKeeper.GetPendingNonces(ctx, cctx.GetCurrentOutTxParam().TssPubkey, cctx.GetCurrentOutTxParam().ReceiverChainId) + pn, found := zk.ObserverKeeper.GetPendingNonces( + ctx, + cctx.GetCurrentOutTxParam().TssPubkey, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ) require.True(t, found) require.Equal(t, pn.NonceLow, int64(cctx.GetCurrentOutTxParam().OutboundTxTssNonce)+1) require.Equal(t, pn.NonceHigh, int64(cctx.GetCurrentOutTxParam().OutboundTxTssNonce)+1) _, found = k.GetInTxHashToCctx(ctx, cctx.InboundTxParams.InboundTxObservedHash) require.True(t, found) - _, found = zk.ObserverKeeper.GetNonceToCctx(ctx, cctx.GetCurrentOutTxParam().TssPubkey, cctx.GetCurrentOutTxParam().ReceiverChainId, int64(cctx.GetCurrentOutTxParam().OutboundTxTssNonce)) + _, found = zk.ObserverKeeper.GetNonceToCctx( + ctx, + cctx.GetCurrentOutTxParam().TssPubkey, + cctx.GetCurrentOutTxParam().ReceiverChainId, + int64(cctx.GetCurrentOutTxParam().OutboundTxTssNonce), + ) require.True(t, found) }) } @@ -553,7 +582,15 @@ func TestKeeper_ValidateOutboundMessage(t *testing.T) { } _, err := k.ValidateOutboundMessage(ctx, msg) require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", msg.OutTxTssNonce, cctx.GetCurrentOutTxParam().OutboundTxTssNonce)) + require.ErrorContains( + t, + err, + fmt.Sprintf( + "OutTxTssNonce %d does not match CCTX OutTxTssNonce %d", + msg.OutTxTssNonce, + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + ), + ) }) t.Run("failed to validate outbound message if tss not found", func(t *testing.T) { @@ -578,6 +615,14 @@ func TestKeeper_ValidateOutboundMessage(t *testing.T) { OutTxChain: 2, }) require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("OutTxChain %d does not match CCTX OutTxChain %d", 2, cctx.GetCurrentOutTxParam().ReceiverChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf( + "OutTxChain %d does not match CCTX OutTxChain %d", + 2, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ), + ) }) } diff --git a/x/crosschain/keeper/msg_server_whitelist_erc20.go b/x/crosschain/keeper/msg_server_whitelist_erc20.go index fb2de5e45e..10767f628c 100644 --- a/x/crosschain/keeper/msg_server_whitelist_erc20.go +++ b/x/crosschain/keeper/msg_server_whitelist_erc20.go @@ -22,17 +22,27 @@ import ( // and emit a crosschain tx to whitelist the ERC20 on the external chain // // Authorized: admin policy group 1. -func (k msgServer) WhitelistERC20(goCtx context.Context, msg *types.MsgWhitelistERC20) (*types.MsgWhitelistERC20Response, error) { +func (k msgServer) WhitelistERC20( + goCtx context.Context, + msg *types.MsgWhitelistERC20, +) (*types.MsgWhitelistERC20Response, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check if authorized if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, errorsmod.Wrap(authoritytypes.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, errorsmod.Wrap( + authoritytypes.ErrUnauthorized, + "Deploy can only be executed by the correct policy account", + ) } erc20Addr := ethcommon.HexToAddress(msg.Erc20Address) if erc20Addr == (ethcommon.Address{}) { - return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid ERC20 contract address (%s)", msg.Erc20Address) + return nil, errorsmod.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid ERC20 contract address (%s)", + msg.Erc20Address, + ) } // check if the erc20 is already whitelisted @@ -98,7 +108,11 @@ func (k msgServer) WhitelistERC20(goCtx context.Context, msg *types.MsgWhitelist } medianGasPrice, isFound := k.GetMedianGasPriceInUint(ctx, msg.ChainId) if !isFound { - return nil, errorsmod.Wrapf(types.ErrUnableToGetGasPrice, "median gas price not found for chain id (%d)", msg.ChainId) + return nil, errorsmod.Wrapf( + types.ErrUnableToGetGasPrice, + "median gas price not found for chain id (%d)", + msg.ChainId, + ) } medianGasPrice = medianGasPrice.MulUint64(2) // overpays gas price by 2x diff --git a/x/crosschain/keeper/process_inbound.go b/x/crosschain/keeper/process_inbound.go index 9b2eddbffd..ca895d5f6b 100644 --- a/x/crosschain/keeper/process_inbound.go +++ b/x/crosschain/keeper/process_inbound.go @@ -21,9 +21,13 @@ func (k Keeper) ProcessInbound(ctx sdk.Context, cctx *types.CrossChainTx) { /* processZEVMDeposit processes the EVM deposit CCTX. A deposit is a cctx which has Zetachain as the receiver chain.It trasnsitions state according to the following rules: + - If the deposit is successful, the CCTX status is changed to OutboundMined. + - If the deposit returns an internal error i.e if HandleEVMDeposit() returns an error, but isContractReverted is false, the CCTX status is changed to Aborted. + - If the deposit is reverted, the function tries to create a revert cctx with status PendingRevert. + - If the creation of revert tx also fails it changes the status to Aborted. Note : Aborted CCTXs are not refunded in this function. The refund is done using a separate refunding mechanism. @@ -91,9 +95,12 @@ func (k Keeper) processZEVMDeposit(ctx sdk.Context, cctx *types.CrossChainTx) { /* processCrosschainMsgPassing processes the CCTX for crosschain message passing. A crosschain message passing is a cctx which has a non-Zetachain as the receiver chain.It trasnsitions state according to the following rules: + - If the crosschain message passing is successful, the CCTX status is changed to PendingOutbound. + - If the crosschain message passing returns an error, the CCTX status is changed to Aborted. We do not return an error from this function, as all changes need to be persisted to the state. + Instead, we use a temporary context to make changes and then commit the context on for the happy path ,i.e cctx is set to PendingOutbound. */ func (k Keeper) processCrosschainMsgPassing(ctx sdk.Context, cctx *types.CrossChainTx) { diff --git a/x/crosschain/keeper/process_inbound_test.go b/x/crosschain/keeper/process_inbound_test.go index 28577e797f..01fba85194 100644 --- a/x/crosschain/keeper/process_inbound_test.go +++ b/x/crosschain/keeper/process_inbound_test.go @@ -57,7 +57,8 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { // mock unsuccessful HandleEVMDeposit which does not revert - fungibleMock.On("ZETADepositAndCallContract", mock.Anything, mock.Anything, receiver, int64(0), amount, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("deposit error")) + fungibleMock.On("ZETADepositAndCallContract", mock.Anything, mock.Anything, receiver, int64(0), amount, mock.Anything, mock.Anything). + Return(nil, fmt.Errorf("deposit error")) // call ProcessInbound cctx := sample.CrossChainTx(t, "test") @@ -72,35 +73,42 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { require.Equal(t, "deposit error", cctx.CctxStatus.StatusMessage) }) - t.Run("unable to process zevm deposit HandleEVMDeposit reverts fails at GetSupportedChainFromChainID", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - UseObserverMock: true, - }) - - // Setup mock data - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - observerMock := keepertest.GetCrosschainObserverMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - senderChain := getValidEthChain() - errDeposit := fmt.Errorf("deposit failed") - - // Setup expected calls - // mock unsuccessful HandleEVMDeposit which reverts , i.e returns err and isContractReverted = true - keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) - - // mock unsuccessful GetSupportedChainFromChainID - observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). - Return(nil) - - // call ProcessInbound - cctx := GetERC20Cctx(t, receiver, *senderChain, "", amount) - cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId - k.ProcessInbound(ctx, cctx) - require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) - require.Equal(t, fmt.Sprintf("invalid sender chain id %d", cctx.InboundTxParams.SenderChainId), cctx.CctxStatus.StatusMessage) - }) + t.Run( + "unable to process zevm deposit HandleEVMDeposit reverts fails at GetSupportedChainFromChainID", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + UseObserverMock: true, + }) + + // Setup mock data + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + observerMock := keepertest.GetCrosschainObserverMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + senderChain := getValidEthChain() + errDeposit := fmt.Errorf("deposit failed") + + // Setup expected calls + // mock unsuccessful HandleEVMDeposit which reverts , i.e returns err and isContractReverted = true + keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) + + // mock unsuccessful GetSupportedChainFromChainID + observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). + Return(nil) + + // call ProcessInbound + cctx := GetERC20Cctx(t, receiver, *senderChain, "", amount) + cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId + k.ProcessInbound(ctx, cctx) + require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) + require.Equal( + t, + fmt.Sprintf("invalid sender chain id %d", cctx.InboundTxParams.SenderChainId), + cctx.CctxStatus.StatusMessage, + ) + }, + ) t.Run("unable to process zevm deposit HandleEVMDeposit revert fails at and GetRevertGasLimit", func(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ @@ -132,82 +140,100 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId k.ProcessInbound(ctx, cctx) require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) - require.Equal(t, fmt.Sprintf("revert gas limit error: %s", types.ErrForeignCoinNotFound), cctx.CctxStatus.StatusMessage) + require.Equal( + t, + fmt.Sprintf("revert gas limit error: %s", types.ErrForeignCoinNotFound), + cctx.CctxStatus.StatusMessage, + ) }) - t.Run("unable to process zevm deposit HandleEVMDeposit revert fails at PayGasInERC20AndUpdateCctx", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - UseObserverMock: true, - }) - - // Setup mock data - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - senderChain := getValidEthChain() - asset := "" - - // Setup expected calls - errDeposit := fmt.Errorf("deposit failed") - keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) - - observerMock := keepertest.GetCrosschainObserverMock(t, k) - - // Mock successful GetSupportedChainFromChainID - keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) - - // mock successful GetRevertGasLimit for ERC20 - keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 100) - - // mock unsuccessful PayGasInERC20AndUpdateCctx - observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). - Return(nil).Once() - - // call ProcessInbound - cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) - cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId - k.ProcessInbound(ctx, cctx) - require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) - require.Equal(t, fmt.Sprintf("deposit revert message: %s err : %s", errDeposit, observertypes.ErrSupportedChains), cctx.CctxStatus.StatusMessage) - }) - - t.Run("uunable to process zevm deposit HandleEVMDeposit revert fails at PayGasInERC20AndUpdateCctx with gas limit is 0", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - UseObserverMock: true, - }) - - // Setup mock data - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - senderChain := getValidEthChain() - asset := "" - - // Setup expected calls - errDeposit := fmt.Errorf("deposit failed") - keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) - - observerMock := keepertest.GetCrosschainObserverMock(t, k) - - // Mock successful GetSupportedChainFromChainID - keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) - - // mock successful GetRevertGasLimit for ERC20 - keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 0) - - // mock unsuccessful PayGasInERC20AndUpdateCctx - observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). - Return(nil).Once() - - // call ProcessInbound - cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) - cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId - k.ProcessInbound(ctx, cctx) - require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) - require.Equal(t, fmt.Sprintf("deposit revert message: %s err : %s", errDeposit, observertypes.ErrSupportedChains), cctx.CctxStatus.StatusMessage) - }) + t.Run( + "unable to process zevm deposit HandleEVMDeposit revert fails at PayGasInERC20AndUpdateCctx", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + UseObserverMock: true, + }) + + // Setup mock data + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + senderChain := getValidEthChain() + asset := "" + + // Setup expected calls + errDeposit := fmt.Errorf("deposit failed") + keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) + + observerMock := keepertest.GetCrosschainObserverMock(t, k) + + // Mock successful GetSupportedChainFromChainID + keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) + + // mock successful GetRevertGasLimit for ERC20 + keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 100) + + // mock unsuccessful PayGasInERC20AndUpdateCctx + observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). + Return(nil).Once() + + // call ProcessInbound + cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) + cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId + k.ProcessInbound(ctx, cctx) + require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) + require.Equal( + t, + fmt.Sprintf("deposit revert message: %s err : %s", errDeposit, observertypes.ErrSupportedChains), + cctx.CctxStatus.StatusMessage, + ) + }, + ) + + t.Run( + "uunable to process zevm deposit HandleEVMDeposit revert fails at PayGasInERC20AndUpdateCctx with gas limit is 0", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + UseObserverMock: true, + }) + + // Setup mock data + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + senderChain := getValidEthChain() + asset := "" + + // Setup expected calls + errDeposit := fmt.Errorf("deposit failed") + keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) + + observerMock := keepertest.GetCrosschainObserverMock(t, k) + + // Mock successful GetSupportedChainFromChainID + keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) + + // mock successful GetRevertGasLimit for ERC20 + keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 0) + + // mock unsuccessful PayGasInERC20AndUpdateCctx + observerMock.On("GetSupportedChainFromChainID", mock.Anything, senderChain.ChainId). + Return(nil).Once() + + // call ProcessInbound + cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) + cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId + k.ProcessInbound(ctx, cctx) + require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) + require.Equal( + t, + fmt.Sprintf("deposit revert message: %s err : %s", errDeposit, observertypes.ErrSupportedChains), + cctx.CctxStatus.StatusMessage, + ) + }, + ) t.Run("unable to process zevm deposit HandleEVMDeposit reverts fails at UpdateNonce", func(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ @@ -288,39 +314,46 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { require.Equal(t, updatedNonce, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) }) - t.Run("unable to process zevm deposit HandleEVMDeposit revert fails as the cctx has already been reverted", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ - UseFungibleMock: true, - UseObserverMock: true, - }) - - // Setup mock data - fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - observerMock := keepertest.GetCrosschainObserverMock(t, k) - receiver := sample.EthAddress() - amount := big.NewInt(42) - senderChain := getValidEthChain() - asset := "" - errDeposit := fmt.Errorf("deposit failed") - - // Setup expected calls - // mock unsuccessful HandleEVMDeposit which reverts , i.e returns err and isContractReverted = true - keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) - - // Mock successful GetSupportedChainFromChainID - keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) - - // mock successful GetRevertGasLimit for ERC20 - keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 100) - - // call ProcessInbound - cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) - cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId - cctx.OutboundTxParams = append(cctx.OutboundTxParams, cctx.GetCurrentOutTxParam()) - k.ProcessInbound(ctx, cctx) - require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) - require.Contains(t, cctx.CctxStatus.StatusMessage, fmt.Sprintf("revert outbound error: %s", "cannot revert a revert tx")) - }) + t.Run( + "unable to process zevm deposit HandleEVMDeposit revert fails as the cctx has already been reverted", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeperWithMocks(t, keepertest.CrosschainMockOptions{ + UseFungibleMock: true, + UseObserverMock: true, + }) + + // Setup mock data + fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) + observerMock := keepertest.GetCrosschainObserverMock(t, k) + receiver := sample.EthAddress() + amount := big.NewInt(42) + senderChain := getValidEthChain() + asset := "" + errDeposit := fmt.Errorf("deposit failed") + + // Setup expected calls + // mock unsuccessful HandleEVMDeposit which reverts , i.e returns err and isContractReverted = true + keepertest.MockRevertForHandleEVMDeposit(fungibleMock, receiver, amount, senderChain.ChainId, errDeposit) + + // Mock successful GetSupportedChainFromChainID + keepertest.MockGetSupportedChainFromChainID(observerMock, senderChain) + + // mock successful GetRevertGasLimit for ERC20 + keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 100) + + // call ProcessInbound + cctx := GetERC20Cctx(t, receiver, *senderChain, asset, amount) + cctx.GetCurrentOutTxParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId + cctx.OutboundTxParams = append(cctx.OutboundTxParams, cctx.GetCurrentOutTxParam()) + k.ProcessInbound(ctx, cctx) + require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status) + require.Contains( + t, + cctx.CctxStatus.StatusMessage, + fmt.Sprintf("revert outbound error: %s", "cannot revert a revert tx"), + ) + }, + ) } func TestKeeper_ProcessInboundProcessCrosschainMsgPassing(t *testing.T) { diff --git a/x/crosschain/keeper/process_outbound.go b/x/crosschain/keeper/process_outbound.go index c22dfe0b39..58b5dc4e9d 100644 --- a/x/crosschain/keeper/process_outbound.go +++ b/x/crosschain/keeper/process_outbound.go @@ -18,7 +18,12 @@ import ( // ProcessOutbound processes the finalization of an outbound transaction based on the ballot status // The state is committed only if the individual steps are successful -func (k Keeper) ProcessOutbound(ctx sdk.Context, cctx *types.CrossChainTx, ballotStatus observertypes.BallotStatus, valueReceived string) error { +func (k Keeper) ProcessOutbound( + ctx sdk.Context, + cctx *types.CrossChainTx, + ballotStatus observertypes.BallotStatus, + valueReceived string, +) error { tmpCtx, commit := ctx.CacheContext() err := func() error { switch ballotStatus { @@ -126,7 +131,11 @@ func (k Keeper) ProcessFailedOutbound(ctx sdk.Context, cctx *types.CrossChainTx, } // processFailedOutboundForExternalChainTx processes the failed outbound transaction for external chain tx -func (k Keeper) processFailedOutboundForExternalChainTx(ctx sdk.Context, cctx *types.CrossChainTx, oldStatus types.CctxStatus) error { +func (k Keeper) processFailedOutboundForExternalChainTx( + ctx sdk.Context, + cctx *types.CrossChainTx, + oldStatus types.CctxStatus, +) error { switch oldStatus { case types.CctxStatus_PendingOutbound: diff --git a/x/crosschain/keeper/process_outbound_test.go b/x/crosschain/keeper/process_outbound_test.go index a67a3f412b..1a5cc21b73 100644 --- a/x/crosschain/keeper/process_outbound_test.go +++ b/x/crosschain/keeper/process_outbound_test.go @@ -74,7 +74,11 @@ func TestKeeper_ProcessFailedOutbound(t *testing.T) { receiver := sample.EthAddress() cctx := GetERC20Cctx(t, receiver, chains.GoerliChain, "", big.NewInt(42)) cctx.InboundTxParams.CoinType = coin.CoinType_Zeta - err := sdkk.EvmKeeper.SetAccount(ctx, ethcommon.HexToAddress(cctx.InboundTxParams.Sender), *statedb.NewEmptyAccount()) + err := sdkk.EvmKeeper.SetAccount( + ctx, + ethcommon.HexToAddress(cctx.InboundTxParams.Sender), + *statedb.NewEmptyAccount(), + ) require.NoError(t, err) cctx.InboundTxParams.SenderChainId = chains.ZetaChainMainnet.ChainId err = k.ProcessFailedOutbound(ctx, cctx, sample.String()) @@ -320,27 +324,45 @@ func TestKeeper_ProcessOutbound(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeper(t) cctx := GetERC20Cctx(t, sample.EthAddress(), chains.GoerliChain, "", big.NewInt(42)) cctx.CctxStatus.Status = types.CctxStatus_PendingOutbound - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_SuccessObservation, sample.String()) + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_SuccessObservation, + sample.String(), + ) require.NoError(t, err) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_OutboundMined) }) - t.Run("successfully process outbound with ballot finalized to failed and old status is Pending Revert", func(t *testing.T) { - k, ctx, _, _ := keepertest.CrosschainKeeper(t) - cctx := GetERC20Cctx(t, sample.EthAddress(), chains.GoerliChain, "", big.NewInt(42)) - cctx.CctxStatus.Status = types.CctxStatus_PendingRevert - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_FailureObservation, sample.String()) - require.NoError(t, err) - require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_Aborted) - require.Equal(t, cctx.GetCurrentOutTxParam().TxFinalizationStatus, types.TxFinalizationStatus_Executed) - }) + t.Run( + "successfully process outbound with ballot finalized to failed and old status is Pending Revert", + func(t *testing.T) { + k, ctx, _, _ := keepertest.CrosschainKeeper(t) + cctx := GetERC20Cctx(t, sample.EthAddress(), chains.GoerliChain, "", big.NewInt(42)) + cctx.CctxStatus.Status = types.CctxStatus_PendingRevert + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_FailureObservation, + sample.String(), + ) + require.NoError(t, err) + require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_Aborted) + require.Equal(t, cctx.GetCurrentOutTxParam().TxFinalizationStatus, types.TxFinalizationStatus_Executed) + }, + ) t.Run("successfully process outbound with ballot finalized to failed and coin-type is CMD", func(t *testing.T) { k, ctx, _, _ := keepertest.CrosschainKeeper(t) cctx := GetERC20Cctx(t, sample.EthAddress(), chains.GoerliChain, "", big.NewInt(42)) cctx.CctxStatus.Status = types.CctxStatus_PendingOutbound cctx.InboundTxParams.CoinType = coin.CoinType_Cmd - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_FailureObservation, sample.String()) + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_FailureObservation, + sample.String(), + ) require.NoError(t, err) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_Aborted) require.Equal(t, cctx.GetCurrentOutTxParam().TxFinalizationStatus, types.TxFinalizationStatus_Executed) @@ -376,7 +398,12 @@ func TestKeeper_ProcessOutbound(t *testing.T) { Zrc20ContractAddress: sample.EthAddress().String(), }, false).Once() - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_FailureObservation, sample.String()) + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_FailureObservation, + sample.String(), + ) require.ErrorIs(t, err, types.ErrForeignCoinNotFound) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_PendingOutbound) // New outbound not added and the old outbound is not finalized @@ -406,7 +433,12 @@ func TestKeeper_ProcessOutbound(t *testing.T) { // mock successful GetRevertGasLimit for ERC20 keepertest.MockGetRevertGasLimitForERC20(fungibleMock, asset, *senderChain, 100) - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_FailureObservation, sample.String()) + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_FailureObservation, + sample.String(), + ) require.Error(t, err) }) @@ -436,12 +468,21 @@ func TestKeeper_ProcessOutbound(t *testing.T) { // mock successful UpdateNonce _ = keepertest.MockUpdateNonce(observerMock, *senderChain) - err := k.ProcessOutbound(ctx, cctx, observertypes.BallotStatus_BallotFinalized_FailureObservation, sample.String()) + err := k.ProcessOutbound( + ctx, + cctx, + observertypes.BallotStatus_BallotFinalized_FailureObservation, + sample.String(), + ) require.NoError(t, err) require.Equal(t, cctx.CctxStatus.Status, types.CctxStatus_PendingRevert) // New outbound added for revert and the old outbound is finalized require.Len(t, cctx.OutboundTxParams, oldOutTxParamsLen+1) require.Equal(t, cctx.GetCurrentOutTxParam().TxFinalizationStatus, types.TxFinalizationStatus_NotFinalized) - require.Equal(t, cctx.OutboundTxParams[oldOutTxParamsLen-1].TxFinalizationStatus, types.TxFinalizationStatus_Executed) + require.Equal( + t, + cctx.OutboundTxParams[oldOutTxParamsLen-1].TxFinalizationStatus, + types.TxFinalizationStatus_Executed, + ) }) } diff --git a/x/crosschain/keeper/rate_limiter_flags.go b/x/crosschain/keeper/rate_limiter_flags.go index 973a6a2554..fa63ef898e 100644 --- a/x/crosschain/keeper/rate_limiter_flags.go +++ b/x/crosschain/keeper/rate_limiter_flags.go @@ -29,7 +29,9 @@ func (k Keeper) GetRateLimiterFlags(ctx sdk.Context) (val types.RateLimiterFlags } // GetRateLimiterAssetRateList returns a list of all foreign asset rate -func (k Keeper) GetRateLimiterAssetRateList(ctx sdk.Context) (flags types.RateLimiterFlags, assetRates []types.AssetRate, found bool) { +func (k Keeper) GetRateLimiterAssetRateList( + ctx sdk.Context, +) (flags types.RateLimiterFlags, assetRates []types.AssetRate, found bool) { flags, found = k.GetRateLimiterFlags(ctx) if !found { return flags, nil, false diff --git a/x/crosschain/keeper/rate_limiter_flags_test.go b/x/crosschain/keeper/rate_limiter_flags_test.go index 6e0180bc88..8559b49312 100644 --- a/x/crosschain/keeper/rate_limiter_flags_test.go +++ b/x/crosschain/keeper/rate_limiter_flags_test.go @@ -93,15 +93,39 @@ func TestKeeper_GetRateLimiterAssetRateList(t *testing.T) { k.SetRateLimiterFlags(ctx, testflags) // add gas coin - gasCoin, gasAssetRate := createForeignCoinAndAssetRate(t, zrc20GasAddr, "", chainID, 18, coin.CoinType_Gas, sdk.NewDec(1)) + gasCoin, gasAssetRate := createForeignCoinAndAssetRate( + t, + zrc20GasAddr, + "", + chainID, + 18, + coin.CoinType_Gas, + sdk.NewDec(1), + ) zk.FungibleKeeper.SetForeignCoins(ctx, gasCoin) // add 1st erc20 coin - erc20Coin1, erc20AssetRate1 := createForeignCoinAndAssetRate(t, zrc20ERC20Addr1, sample.EthAddress().Hex(), chainID, 8, coin.CoinType_ERC20, sdk.NewDec(2)) + erc20Coin1, erc20AssetRate1 := createForeignCoinAndAssetRate( + t, + zrc20ERC20Addr1, + sample.EthAddress().Hex(), + chainID, + 8, + coin.CoinType_ERC20, + sdk.NewDec(2), + ) zk.FungibleKeeper.SetForeignCoins(ctx, erc20Coin1) // add 2nd erc20 coin - erc20Coin2, erc20AssetRate2 := createForeignCoinAndAssetRate(t, zrc20ERC20Addr2, sample.EthAddress().Hex(), chainID, 6, coin.CoinType_ERC20, sdk.NewDec(3)) + erc20Coin2, erc20AssetRate2 := createForeignCoinAndAssetRate( + t, + zrc20ERC20Addr2, + sample.EthAddress().Hex(), + chainID, + 6, + coin.CoinType_ERC20, + sdk.NewDec(3), + ) zk.FungibleKeeper.SetForeignCoins(ctx, erc20Coin2) // get rates diff --git a/x/crosschain/keeper/refund.go b/x/crosschain/keeper/refund.go index 1781264c1c..2ee15e6bd2 100644 --- a/x/crosschain/keeper/refund.go +++ b/x/crosschain/keeper/refund.go @@ -12,7 +12,11 @@ import ( "github.com/zeta-chain/zetacore/x/crosschain/types" ) -func (k Keeper) RefundAbortedAmountOnZetaChain(ctx sdk.Context, cctx types.CrossChainTx, refundAddress ethcommon.Address) error { +func (k Keeper) RefundAbortedAmountOnZetaChain( + ctx sdk.Context, + cctx types.CrossChainTx, + refundAddress ethcommon.Address, +) error { coinType := cctx.InboundTxParams.CoinType switch coinType { case coin.CoinType_Gas: @@ -27,7 +31,11 @@ func (k Keeper) RefundAbortedAmountOnZetaChain(ctx sdk.Context, cctx types.Cross } // RefundAmountOnZetaChainGas refunds the amount of the cctx on ZetaChain in case of aborted cctx with cointype gas -func (k Keeper) RefundAmountOnZetaChainGas(ctx sdk.Context, cctx types.CrossChainTx, refundAddress ethcommon.Address) error { +func (k Keeper) RefundAmountOnZetaChainGas( + ctx sdk.Context, + cctx types.CrossChainTx, + refundAddress ethcommon.Address, +) error { // refund in gas token to refund address // Refund the the amount was previously refundAmount := GetAbortedAmount(cctx) @@ -52,7 +60,11 @@ func (k Keeper) RefundAmountOnZetaChainGas(ctx sdk.Context, cctx types.CrossChai } // RefundAmountOnZetaChainGas refunds the amount of the cctx on ZetaChain in case of aborted cctx with cointype zeta -func (k Keeper) RefundAmountOnZetaChainZeta(ctx sdk.Context, cctx types.CrossChainTx, refundAddress ethcommon.Address) error { +func (k Keeper) RefundAmountOnZetaChainZeta( + ctx sdk.Context, + cctx types.CrossChainTx, + refundAddress ethcommon.Address, +) error { // if coin type is Zeta, handle this as a deposit ZETA to zEVM. refundAmount := GetAbortedAmount(cctx) chainID := cctx.InboundTxParams.SenderChainId @@ -73,7 +85,11 @@ func (k Keeper) RefundAmountOnZetaChainZeta(ctx sdk.Context, cctx types.CrossCha // RefundAmountOnZetaChainERC20 refunds the amount of the cctx on ZetaChain in case of aborted cctx // NOTE: GetCurrentOutTxParam should contain the last up to date cctx amount // Refund address should already be validated before calling this function -func (k Keeper) RefundAmountOnZetaChainERC20(ctx sdk.Context, cctx types.CrossChainTx, refundAddress ethcommon.Address) error { +func (k Keeper) RefundAmountOnZetaChainERC20( + ctx sdk.Context, + cctx types.CrossChainTx, + refundAddress ethcommon.Address, +) error { refundAmount := GetAbortedAmount(cctx) // preliminary checks if cctx.InboundTxParams.CoinType != coin.CoinType_ERC20 { @@ -88,7 +104,11 @@ func (k Keeper) RefundAmountOnZetaChainERC20(ctx sdk.Context, cctx types.CrossCh } // get address of the zrc20 - fc, found := k.fungibleKeeper.GetForeignCoinFromAsset(ctx, cctx.InboundTxParams.Asset, cctx.InboundTxParams.SenderChainId) + fc, found := k.fungibleKeeper.GetForeignCoinFromAsset( + ctx, + cctx.InboundTxParams.Asset, + cctx.InboundTxParams.SenderChainId, + ) if !found { return fmt.Errorf("asset %s zrc not found", cctx.InboundTxParams.Asset) } diff --git a/x/crosschain/keeper/refund_test.go b/x/crosschain/keeper/refund_test.go index 5f00310be3..656142c482 100644 --- a/x/crosschain/keeper/refund_test.go +++ b/x/crosschain/keeper/refund_test.go @@ -90,7 +90,8 @@ func TestKeeper_RefundAmountOnZetaChainGas(t *testing.T) { Zrc20ContractAddress: sample.EthAddress().Hex(), }, true) - fungibleMock.On("DepositZRC20", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("")) + fungibleMock.On("DepositZRC20", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(nil, errors.New("")) err := k.RefundAmountOnZetaChainGas(ctx, types.CrossChainTx{ InboundTxParams: &types.InboundTxParams{ @@ -370,9 +371,10 @@ func TestKeeper_RefundAmountOnZetaChainERC20(t *testing.T) { UseFungibleMock: true, }) fungibleMock := keepertest.GetCrosschainFungibleMock(t, k) - fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything).Return(fungibletypes.ForeignCoins{ - Zrc20ContractAddress: "0x", - }, true) + fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything). + Return(fungibletypes.ForeignCoins{ + Zrc20ContractAddress: "0x", + }, true) k.GetAuthKeeper().GetModuleAccount(ctx, fungibletypes.ModuleName) asset := sample.EthAddress().String() sender := sample.EthAddress() @@ -405,11 +407,13 @@ func TestKeeper_RefundAmountOnZetaChainERC20(t *testing.T) { sender := sample.EthAddress() chainID := getValidEthChainID() - fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything).Return(fungibletypes.ForeignCoins{ - Zrc20ContractAddress: sample.EthAddress().Hex(), - }, true) + fungibleMock.On("GetForeignCoinFromAsset", mock.Anything, mock.Anything, mock.Anything). + Return(fungibletypes.ForeignCoins{ + Zrc20ContractAddress: sample.EthAddress().Hex(), + }, true) - fungibleMock.On("DepositZRC20", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("")) + fungibleMock.On("DepositZRC20", mock.Anything, mock.Anything, mock.Anything, mock.Anything). + Return(nil, errors.New("")) err := k.RefundAmountOnZetaChainERC20(ctx, types.CrossChainTx{ InboundTxParams: &types.InboundTxParams{ diff --git a/x/crosschain/migrations/v4/migrate_test.go b/x/crosschain/migrations/v4/migrate_test.go index 8d4cb30833..480d973094 100644 --- a/x/crosschain/migrations/v4/migrate_test.go +++ b/x/crosschain/migrations/v4/migrate_test.go @@ -71,7 +71,10 @@ func TestMigrateStore(t *testing.T) { } store = prefix.NewStore(ctx.KVStore(k.GetStoreKey()), types.KeyPrefix(observertypes.NonceToCctxKeyPrefix)) for _, nonce := range nonceToCctxList { - store.Set(types.KeyPrefix(fmt.Sprintf("%s-%d-%d", nonce.Tss, nonce.ChainId, nonce.Nonce)), k.GetCodec().MustMarshal(&nonce)) + store.Set( + types.KeyPrefix(fmt.Sprintf("%s-%d-%d", nonce.Tss, nonce.ChainId, nonce.Nonce)), + k.GetCodec().MustMarshal(&nonce), + ) } err := v4.MigrateStore(ctx, k.GetObserverKeeper(), k) require.NoError(t, err) diff --git a/x/crosschain/migrations/v5/migrate.go b/x/crosschain/migrations/v5/migrate.go index 194ddfe96b..8706c14e44 100644 --- a/x/crosschain/migrations/v5/migrate.go +++ b/x/crosschain/migrations/v5/migrate.go @@ -97,9 +97,13 @@ func SetZetaAccounting( switch cctx.InboundTxParams.CoinType { case coin.CoinType_ERC20: { - receiverChain := observerKeeper.GetSupportedChainFromChainID(ctx, cctx.GetCurrentOutTxParam().ReceiverChainId) + receiverChain := observerKeeper.GetSupportedChainFromChainID( + ctx, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ) if receiverChain == nil { - ctx.Logger().Error(fmt.Sprintf("Error getting chain from chain id: %d , cctx index", cctx.GetCurrentOutTxParam().ReceiverChainId), cctx.Index) + ctx.Logger(). + Error(fmt.Sprintf("Error getting chain from chain id: %d , cctx index", cctx.GetCurrentOutTxParam().ReceiverChainId), cctx.Index) continue } // There is a chance that this cctx has already been refunded, so we set the isRefunded flag to true. diff --git a/x/crosschain/migrations/v5/migrate_test.go b/x/crosschain/migrations/v5/migrate_test.go index 912fb0c483..7923fb0a35 100644 --- a/x/crosschain/migrations/v5/migrate_test.go +++ b/x/crosschain/migrations/v5/migrate_test.go @@ -25,7 +25,8 @@ func TestMigrateStore(t *testing.T) { v4ZetaAccountingAmount := math.ZeroUint() for _, cctx := range cctxList { k.SetCrossChainTx(ctx, cctx) - if cctx.CctxStatus.Status != crosschaintypes.CctxStatus_Aborted || cctx.InboundTxParams.CoinType != coin.CoinType_Zeta { + if cctx.CctxStatus.Status != crosschaintypes.CctxStatus_Aborted || + cctx.InboundTxParams.CoinType != coin.CoinType_Zeta { continue } v5ZetaAccountingAmount = v5ZetaAccountingAmount.Add(crosschainkeeper.GetAbortedAmount(cctx)) @@ -47,7 +48,10 @@ func TestMigrateStore(t *testing.T) { for _, cctx := range cctxListUpdated { switch cctx.InboundTxParams.CoinType { case coin.CoinType_ERC20: - receiverChain := zk.ObserverKeeper.GetSupportedChainFromChainID(ctx, cctx.GetCurrentOutTxParam().ReceiverChainId) + receiverChain := zk.ObserverKeeper.GetSupportedChainFromChainID( + ctx, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ) require.NotNil(t, receiverChain) if receiverChain.IsZetaChain() { require.True(t, cctx.CctxStatus.IsAbortRefunded) @@ -67,7 +71,12 @@ func TestMigrateStore(t *testing.T) { func TestResetTestnetNonce(t *testing.T) { t.Run("reset only testnet nonce without changing mainnet chains", func(t *testing.T) { k, ctx, _, zk := keepertest.CrosschainKeeper(t) - testnetChains := []chains.Chain{chains.GoerliChain, chains.MumbaiChain, chains.BscTestnetChain, chains.BtcTestNetChain} + testnetChains := []chains.Chain{ + chains.GoerliChain, + chains.MumbaiChain, + chains.BscTestnetChain, + chains.BtcTestNetChain, + } mainnetChains := []chains.Chain{chains.EthChain, chains.BscMainnetChain, chains.BtcMainnetChain} nonceLow := int64(1) nonceHigh := int64(10) diff --git a/x/crosschain/types/cctx.go b/x/crosschain/types/cctx.go index 98fedf0d5d..d6ddb6cb5d 100644 --- a/x/crosschain/types/cctx.go +++ b/x/crosschain/types/cctx.go @@ -101,13 +101,25 @@ func (m *CrossChainTx) AddRevertOutbound(gasLimit uint64) error { } // AddOutbound adds a new outbound tx to the CCTX. -func (m *CrossChainTx) AddOutbound(ctx sdk.Context, msg MsgVoteOnObservedOutboundTx, ballotStatus observertypes.BallotStatus) error { +func (m *CrossChainTx) AddOutbound( + ctx sdk.Context, + msg MsgVoteOnObservedOutboundTx, + ballotStatus observertypes.BallotStatus, +) error { if ballotStatus != observertypes.BallotStatus_BallotFinalized_FailureObservation { if !msg.ValueReceived.Equal(m.GetCurrentOutTxParam().Amount) { - ctx.Logger().Error(fmt.Sprintf("VoteOnObservedOutboundTx: Mint mismatch: %s value received vs %s cctx amount", - msg.ValueReceived, - m.GetCurrentOutTxParam().Amount)) - return cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ValueReceived %s does not match sent value %s", msg.ValueReceived, m.GetCurrentOutTxParam().Amount)) + ctx.Logger(). + Error(fmt.Sprintf("VoteOnObservedOutboundTx: Mint mismatch: %s value received vs %s cctx amount", + msg.ValueReceived, + m.GetCurrentOutTxParam().Amount)) + return cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "ValueReceived %s does not match sent value %s", + msg.ValueReceived, + m.GetCurrentOutTxParam().Amount, + ), + ) } } // Update CCTX values diff --git a/x/crosschain/types/errors.go b/x/crosschain/types/errors.go index edde41849d..ffeda3077c 100644 --- a/x/crosschain/types/errors.go +++ b/x/crosschain/types/errors.go @@ -5,19 +5,23 @@ import ( ) var ( - ErrUnsupportedChain = errorsmod.Register(ModuleName, 1102, "chain parse error") - ErrInvalidChainID = errorsmod.Register(ModuleName, 1101, "chain id cannot be negative") - ErrUnableToGetGasPrice = errorsmod.Register(ModuleName, 1107, "unable to get gas price") - ErrNotEnoughZetaBurnt = errorsmod.Register(ModuleName, 1109, "not enough zeta burnt") - ErrCannotFindReceiverNonce = errorsmod.Register(ModuleName, 1110, "cannot find receiver chain nonce") - ErrGasCoinNotFound = errorsmod.Register(ModuleName, 1113, "gas coin not found for sender chain") - ErrUnableToParseAddress = errorsmod.Register(ModuleName, 1115, "cannot parse address and data") - ErrCannotProcessWithdrawal = errorsmod.Register(ModuleName, 1116, "cannot process withdrawal event") - ErrForeignCoinNotFound = errorsmod.Register(ModuleName, 1118, "foreign coin not found for sender chain") - ErrCannotFindPendingNonces = errorsmod.Register(ModuleName, 1121, "cannot find pending nonces") - ErrCannotFindTSSKeys = errorsmod.Register(ModuleName, 1122, "cannot find TSS keys") - ErrNonceMismatch = errorsmod.Register(ModuleName, 1123, "nonce mismatch") - ErrUnableToSendCoinType = errorsmod.Register(ModuleName, 1127, "unable to send this coin type to a receiver chain") + ErrUnsupportedChain = errorsmod.Register(ModuleName, 1102, "chain parse error") + ErrInvalidChainID = errorsmod.Register(ModuleName, 1101, "chain id cannot be negative") + ErrUnableToGetGasPrice = errorsmod.Register(ModuleName, 1107, "unable to get gas price") + ErrNotEnoughZetaBurnt = errorsmod.Register(ModuleName, 1109, "not enough zeta burnt") + ErrCannotFindReceiverNonce = errorsmod.Register(ModuleName, 1110, "cannot find receiver chain nonce") + ErrGasCoinNotFound = errorsmod.Register(ModuleName, 1113, "gas coin not found for sender chain") + ErrUnableToParseAddress = errorsmod.Register(ModuleName, 1115, "cannot parse address and data") + ErrCannotProcessWithdrawal = errorsmod.Register(ModuleName, 1116, "cannot process withdrawal event") + ErrForeignCoinNotFound = errorsmod.Register(ModuleName, 1118, "foreign coin not found for sender chain") + ErrCannotFindPendingNonces = errorsmod.Register(ModuleName, 1121, "cannot find pending nonces") + ErrCannotFindTSSKeys = errorsmod.Register(ModuleName, 1122, "cannot find TSS keys") + ErrNonceMismatch = errorsmod.Register(ModuleName, 1123, "nonce mismatch") + ErrUnableToSendCoinType = errorsmod.Register( + ModuleName, + 1127, + "unable to send this coin type to a receiver chain", + ) ErrInvalidAddress = errorsmod.Register(ModuleName, 1128, "invalid address") ErrDeployContract = errorsmod.Register(ModuleName, 1129, "unable to deploy contract") ErrUnableToUpdateTss = errorsmod.Register(ModuleName, 1130, "unable to update TSS address") diff --git a/x/crosschain/types/expected_keepers.go b/x/crosschain/types/expected_keepers.go index a7115ad1e5..acd7980ee2 100644 --- a/x/crosschain/types/expected_keepers.go +++ b/x/crosschain/types/expected_keepers.go @@ -45,17 +45,30 @@ type ObserverKeeper interface { SetKeygen(ctx sdk.Context, keygen observertypes.Keygen) SetCrosschainFlags(ctx sdk.Context, crosschainFlags observertypes.CrosschainFlags) SetLastObserverCount(ctx sdk.Context, lbc *observertypes.LastObserverCount) - AddVoteToBallot(ctx sdk.Context, ballot observertypes.Ballot, address string, observationType observertypes.VoteType) (observertypes.Ballot, error) + AddVoteToBallot( + ctx sdk.Context, + ballot observertypes.Ballot, + address string, + observationType observertypes.VoteType, + ) (observertypes.Ballot, error) CheckIfFinalizingVote(ctx sdk.Context, ballot observertypes.Ballot) (observertypes.Ballot, bool) IsNonTombstonedObserver(ctx sdk.Context, address string) bool - FindBallot(ctx sdk.Context, index string, chain *chains.Chain, observationType observertypes.ObservationType) (ballot observertypes.Ballot, isNew bool, err error) + FindBallot( + ctx sdk.Context, + index string, + chain *chains.Chain, + observationType observertypes.ObservationType, + ) (ballot observertypes.Ballot, isNew bool, err error) AddBallotToList(ctx sdk.Context, ballot observertypes.Ballot) CheckIfTssPubkeyHasBeenGenerated(ctx sdk.Context, tssPubkey string) (observertypes.TSS, bool) GetAllTSS(ctx sdk.Context) (list []observertypes.TSS) GetTSS(ctx sdk.Context) (val observertypes.TSS, found bool) SetTSS(ctx sdk.Context, tss observertypes.TSS) SetTSSHistory(ctx sdk.Context, tss observertypes.TSS) - GetTssAddress(goCtx context.Context, req *observertypes.QueryGetTssAddressRequest) (*observertypes.QueryGetTssAddressResponse, error) + GetTssAddress( + goCtx context.Context, + req *observertypes.QueryGetTssAddressRequest, + ) (*observertypes.QueryGetTssAddressResponse, error) SetFundMigrator(ctx sdk.Context, fm observertypes.TssFundMigratorInfo) GetFundMigrator(ctx sdk.Context, chainID int64) (val observertypes.TssFundMigratorInfo, found bool) @@ -104,8 +117,16 @@ type FungibleKeeper interface { GetSystemContract(ctx sdk.Context) (val fungibletypes.SystemContract, found bool) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainID *big.Int) (ethcommon.Address, error) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address, error) - QueryUniswapV2RouterGetZetaAmountsIn(ctx sdk.Context, amountOut *big.Int, outZRC4 ethcommon.Address) (*big.Int, error) - QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx sdk.Context, amountOut *big.Int, inZRC4, outZRC4 ethcommon.Address) (*big.Int, error) + QueryUniswapV2RouterGetZetaAmountsIn( + ctx sdk.Context, + amountOut *big.Int, + outZRC4 ethcommon.Address, + ) (*big.Int, error) + QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx sdk.Context, + amountOut *big.Int, + inZRC4, outZRC4 ethcommon.Address, + ) (*big.Int, error) QueryGasLimit(ctx sdk.Context, contract ethcommon.Address) (*big.Int, error) QueryProtocolFlatFee(ctx sdk.Context, contract ethcommon.Address) (*big.Int, error) SetGasPrice(ctx sdk.Context, chainID *big.Int, gasPrice *big.Int) (uint64, error) @@ -143,7 +164,13 @@ type FungibleKeeper interface { outZRC4 ethcommon.Address, noEthereumTxEvent bool, ) ([]*big.Int, error) - CallZRC20Burn(ctx sdk.Context, sender ethcommon.Address, zrc20address ethcommon.Address, amount *big.Int, noEthereumTxEvent bool) error + CallZRC20Burn( + ctx sdk.Context, + sender ethcommon.Address, + zrc20address ethcommon.Address, + amount *big.Int, + noEthereumTxEvent bool, + ) error CallZRC20Approve( ctx sdk.Context, owner ethcommon.Address, diff --git a/x/crosschain/types/keys.go b/x/crosschain/types/keys.go index af888d0324..e78aaa0ffe 100644 --- a/x/crosschain/types/keys.go +++ b/x/crosschain/types/keys.go @@ -77,7 +77,13 @@ func (m CrossChainTx) LogIdentifierForCCTX() string { } i := len(m.OutboundTxParams) - 1 outTx := m.OutboundTxParams[i] - return fmt.Sprintf("%s-%d-%d-%d", m.InboundTxParams.Sender, m.InboundTxParams.SenderChainId, outTx.ReceiverChainId, outTx.OutboundTxTssNonce) + return fmt.Sprintf( + "%s-%d-%d-%d", + m.InboundTxParams.Sender, + m.InboundTxParams.SenderChainId, + outTx.ReceiverChainId, + outTx.OutboundTxTssNonce, + ) } func FinalizedInboundKey(intxHash string, chainID int64, eventIndex uint64) string { diff --git a/x/crosschain/types/message_add_to_in_tx_tracker.go b/x/crosschain/types/message_add_to_in_tx_tracker.go index 66498192a7..1c1dcf28cf 100644 --- a/x/crosschain/types/message_add_to_in_tx_tracker.go +++ b/x/crosschain/types/message_add_to_in_tx_tracker.go @@ -52,7 +52,11 @@ func (msg *MsgAddToInTxTracker) ValidateBasic() error { return errorsmod.Wrapf(ErrInvalidChainID, "chain id (%d)", msg.ChainId) } if msg.Proof != nil && !chain.SupportMerkleProof() { - return errorsmod.Wrapf(ErrProofVerificationFail, "chain id %d does not support proof-based trackers", msg.ChainId) + return errorsmod.Wrapf( + ErrProofVerificationFail, + "chain id %d does not support proof-based trackers", + msg.ChainId, + ) } _, ok := coin.CoinType_value[msg.CoinType.String()] if !ok { diff --git a/x/crosschain/types/message_add_to_in_tx_tracker_test.go b/x/crosschain/types/message_add_to_in_tx_tracker_test.go index 20d9545d42..67a5cf2995 100644 --- a/x/crosschain/types/message_add_to_in_tx_tracker_test.go +++ b/x/crosschain/types/message_add_to_in_tx_tracker_test.go @@ -48,7 +48,11 @@ func TestMsgAddToInTxTracker_ValidateBasic(t *testing.T) { CoinType: coin.CoinType_Gas, Proof: &proofs.Proof{}, }, - err: errorsmod.Wrapf(types.ErrProofVerificationFail, "chain id %d does not support proof-based trackers", chains.ZetaTestnetChain.ChainId), + err: errorsmod.Wrapf( + types.ErrProofVerificationFail, + "chain id %d does not support proof-based trackers", + chains.ZetaTestnetChain.ChainId, + ), }, { name: "invalid coin type", diff --git a/x/crosschain/types/message_refund_aborted_test.go b/x/crosschain/types/message_refund_aborted_test.go index 2884b8b7c1..a35343c729 100644 --- a/x/crosschain/types/message_refund_aborted_test.go +++ b/x/crosschain/types/message_refund_aborted_test.go @@ -31,7 +31,11 @@ func TestMsgRefundAbortedCCTX_ValidateBasic(t *testing.T) { }) t.Run("invalid refund address 2", func(t *testing.T) { cctx := sample.CrossChainTx(t, "test") - msg := types.NewMsgRefundAbortedCCTX(sample.AccAddress(), cctx.Index, "0x91da5bf3F8Eb72724E6f50Ec6C3D199C6355c59") + msg := types.NewMsgRefundAbortedCCTX( + sample.AccAddress(), + cctx.Index, + "0x91da5bf3F8Eb72724E6f50Ec6C3D199C6355c59", + ) require.ErrorContains(t, msg.ValidateBasic(), "invalid address") }) } diff --git a/x/crosschain/types/status.go b/x/crosschain/types/status.go index b1c6fcdffb..8c6bcb6fc3 100644 --- a/x/crosschain/types/status.go +++ b/x/crosschain/types/status.go @@ -20,7 +20,12 @@ func (m *Status) ChangeStatus(newStatus CctxStatus, msg string) { } } if !m.ValidateTransition(newStatus) { - m.StatusMessage = fmt.Sprintf("Failed to transition : OldStatus %s , NewStatus %s , MSG : %s :", m.Status.String(), newStatus.String(), msg) + m.StatusMessage = fmt.Sprintf( + "Failed to transition : OldStatus %s , NewStatus %s , MSG : %s :", + m.Status.String(), + newStatus.String(), + msg, + ) m.Status = CctxStatus_Aborted return } diff --git a/x/crosschain/types/status_test.go b/x/crosschain/types/status_test.go index ad5298d383..3f62de5601 100644 --- a/x/crosschain/types/status_test.go +++ b/x/crosschain/types/status_test.go @@ -33,33 +33,98 @@ func TestStatus_ValidateTransition(t *testing.T) { newStatus types.CctxStatus expectedValid bool }{ - {"Valid - PendingInbound to PendingOutbound", types.CctxStatus_PendingInbound, types.CctxStatus_PendingOutbound, true}, + { + "Valid - PendingInbound to PendingOutbound", + types.CctxStatus_PendingInbound, + types.CctxStatus_PendingOutbound, + true, + }, {"Valid - PendingInbound to Aborted", types.CctxStatus_PendingInbound, types.CctxStatus_Aborted, true}, - {"Valid - PendingInbound to OutboundMined", types.CctxStatus_PendingInbound, types.CctxStatus_OutboundMined, true}, - {"Valid - PendingInbound to PendingRevert", types.CctxStatus_PendingInbound, types.CctxStatus_PendingRevert, true}, + { + "Valid - PendingInbound to OutboundMined", + types.CctxStatus_PendingInbound, + types.CctxStatus_OutboundMined, + true, + }, + { + "Valid - PendingInbound to PendingRevert", + types.CctxStatus_PendingInbound, + types.CctxStatus_PendingRevert, + true, + }, {"Valid - PendingOutbound to Aborted", types.CctxStatus_PendingOutbound, types.CctxStatus_Aborted, true}, - {"Valid - PendingOutbound to PendingRevert", types.CctxStatus_PendingOutbound, types.CctxStatus_PendingRevert, true}, - {"Valid - PendingOutbound to OutboundMined", types.CctxStatus_PendingOutbound, types.CctxStatus_OutboundMined, true}, + { + "Valid - PendingOutbound to PendingRevert", + types.CctxStatus_PendingOutbound, + types.CctxStatus_PendingRevert, + true, + }, + { + "Valid - PendingOutbound to OutboundMined", + types.CctxStatus_PendingOutbound, + types.CctxStatus_OutboundMined, + true, + }, {"Valid - PendingOutbound to Reverted", types.CctxStatus_PendingOutbound, types.CctxStatus_Reverted, true}, {"Valid - PendingRevert to Aborted", types.CctxStatus_PendingRevert, types.CctxStatus_Aborted, true}, - {"Valid - PendingRevert to OutboundMined", types.CctxStatus_PendingRevert, types.CctxStatus_OutboundMined, true}, + { + "Valid - PendingRevert to OutboundMined", + types.CctxStatus_PendingRevert, + types.CctxStatus_OutboundMined, + true, + }, {"Valid - PendingRevert to Reverted", types.CctxStatus_PendingRevert, types.CctxStatus_Reverted, true}, {"Invalid - PendingInbound to Reverted", types.CctxStatus_PendingInbound, types.CctxStatus_Reverted, false}, - {"Invalid - PendingInbound to PendingInbound", types.CctxStatus_PendingInbound, types.CctxStatus_PendingInbound, false}, - - {"Invalid - PendingOutbound to PendingInbound", types.CctxStatus_PendingOutbound, types.CctxStatus_PendingInbound, false}, - {"Invalid - PendingOutbound to PendingOutbound", types.CctxStatus_PendingOutbound, types.CctxStatus_PendingOutbound, false}, - - {"Invalid - PendingRevert to PendingInbound", types.CctxStatus_PendingRevert, types.CctxStatus_PendingInbound, false}, - {"Invalid - PendingRevert to PendingOutbound", types.CctxStatus_PendingRevert, types.CctxStatus_PendingOutbound, false}, - {"Invalid - PendingRevert to PendingRevert", types.CctxStatus_PendingRevert, types.CctxStatus_PendingRevert, false}, + { + "Invalid - PendingInbound to PendingInbound", + types.CctxStatus_PendingInbound, + types.CctxStatus_PendingInbound, + false, + }, + + { + "Invalid - PendingOutbound to PendingInbound", + types.CctxStatus_PendingOutbound, + types.CctxStatus_PendingInbound, + false, + }, + { + "Invalid - PendingOutbound to PendingOutbound", + types.CctxStatus_PendingOutbound, + types.CctxStatus_PendingOutbound, + false, + }, + + { + "Invalid - PendingRevert to PendingInbound", + types.CctxStatus_PendingRevert, + types.CctxStatus_PendingInbound, + false, + }, + { + "Invalid - PendingRevert to PendingOutbound", + types.CctxStatus_PendingRevert, + types.CctxStatus_PendingOutbound, + false, + }, + { + "Invalid - PendingRevert to PendingRevert", + types.CctxStatus_PendingRevert, + types.CctxStatus_PendingRevert, + false, + }, {"Invalid old status - CctxStatus_Aborted", types.CctxStatus_Aborted, types.CctxStatus_PendingRevert, false}, {"Invalid old status - CctxStatus_Reverted", types.CctxStatus_Reverted, types.CctxStatus_PendingRevert, false}, - {"Invalid old status - CctxStatus_OutboundMined", types.CctxStatus_OutboundMined, types.CctxStatus_PendingRevert, false}, + { + "Invalid old status - CctxStatus_OutboundMined", + types.CctxStatus_OutboundMined, + types.CctxStatus_PendingRevert, + false, + }, } for _, tc := range tests { @@ -95,6 +160,15 @@ func TestStatus_ChangeStatus(t *testing.T) { s.ChangeStatus(types.CctxStatus_PendingInbound, "msg") assert.Equal(t, s.Status, types.CctxStatus_Aborted) - assert.Equal(t, fmt.Sprintf("Failed to transition : OldStatus %s , NewStatus %s , MSG : %s :", types.CctxStatus_PendingOutbound.String(), types.CctxStatus_PendingInbound.String(), "msg"), s.StatusMessage) + assert.Equal( + t, + fmt.Sprintf( + "Failed to transition : OldStatus %s , NewStatus %s , MSG : %s :", + types.CctxStatus_PendingOutbound.String(), + types.CctxStatus_PendingInbound.String(), + "msg", + ), + s.StatusMessage, + ) }) } diff --git a/x/crosschain/types/validate_test.go b/x/crosschain/types/validate_test.go index 3daf789442..5b898ce7e8 100644 --- a/x/crosschain/types/validate_test.go +++ b/x/crosschain/types/validate_test.go @@ -14,20 +14,50 @@ func TestValidateAddressForChain(t *testing.T) { require.Error(t, types.ValidateAddressForChain("0x123", chains.GoerliChain.ChainId)) require.Error(t, types.ValidateAddressForChain("", chains.GoerliChain.ChainId)) require.Error(t, types.ValidateAddressForChain("%%%%", chains.GoerliChain.ChainId)) - require.NoError(t, types.ValidateAddressForChain("0x792c127Fa3AC1D52F904056Baf1D9257391e7D78", chains.GoerliChain.ChainId)) + require.NoError( + t, + types.ValidateAddressForChain("0x792c127Fa3AC1D52F904056Baf1D9257391e7D78", chains.GoerliChain.ChainId), + ) // test for btc chain - require.NoError(t, types.ValidateAddressForChain("bc1p4scddlkkuw9486579autxumxmkvuphm5pz4jvf7f6pdh50p2uzqstawjt9", chains.BtcMainnetChain.ChainId)) - require.NoError(t, types.ValidateAddressForChain("327z4GyFM8Y8DiYfasGKQWhRK4MvyMSEgE", chains.BtcMainnetChain.ChainId)) - require.NoError(t, types.ValidateAddressForChain("1EYVvXLusCxtVuEwoYvWRyN5EZTXwPVvo3", chains.BtcMainnetChain.ChainId)) - require.Error(t, types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.BtcMainnetChain.ChainId)) + require.NoError( + t, + types.ValidateAddressForChain( + "bc1p4scddlkkuw9486579autxumxmkvuphm5pz4jvf7f6pdh50p2uzqstawjt9", + chains.BtcMainnetChain.ChainId, + ), + ) + require.NoError( + t, + types.ValidateAddressForChain("327z4GyFM8Y8DiYfasGKQWhRK4MvyMSEgE", chains.BtcMainnetChain.ChainId), + ) + require.NoError( + t, + types.ValidateAddressForChain("1EYVvXLusCxtVuEwoYvWRyN5EZTXwPVvo3", chains.BtcMainnetChain.ChainId), + ) + require.Error( + t, + types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.BtcMainnetChain.ChainId), + ) require.Error(t, types.ValidateAddressForChain("", chains.BtcRegtestChain.ChainId)) - require.NoError(t, types.ValidateAddressForChain("bc1qysd4sp9q8my59ul9wsf5rvs9p387hf8vfwatzu", chains.BtcMainnetChain.ChainId)) - require.NoError(t, types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.BtcRegtestChain.ChainId)) + require.NoError( + t, + types.ValidateAddressForChain("bc1qysd4sp9q8my59ul9wsf5rvs9p387hf8vfwatzu", chains.BtcMainnetChain.ChainId), + ) + require.NoError( + t, + types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.BtcRegtestChain.ChainId), + ) // test for zeta chain - require.NoError(t, types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.ZetaChainMainnet.ChainId)) - require.NoError(t, types.ValidateAddressForChain("0x792c127Fa3AC1D52F904056Baf1D9257391e7D78", chains.ZetaChainMainnet.ChainId)) + require.NoError( + t, + types.ValidateAddressForChain("bcrt1qs758ursh4q9z627kt3pp5yysm78ddny6txaqgw", chains.ZetaChainMainnet.ChainId), + ) + require.NoError( + t, + types.ValidateAddressForChain("0x792c127Fa3AC1D52F904056Baf1D9257391e7D78", chains.ZetaChainMainnet.ChainId), + ) } func TestValidateZetaIndex(t *testing.T) { @@ -38,10 +68,40 @@ func TestValidateZetaIndex(t *testing.T) { } func TestValidateHashForChain(t *testing.T) { - require.NoError(t, types.ValidateHashForChain("0x84bd5c9922b63c52d8a9ca686e0a57ff978150b71be0583514d01c27aa341910", chains.GoerliChain.ChainId)) + require.NoError( + t, + types.ValidateHashForChain( + "0x84bd5c9922b63c52d8a9ca686e0a57ff978150b71be0583514d01c27aa341910", + chains.GoerliChain.ChainId, + ), + ) require.Error(t, types.ValidateHashForChain("", chains.GoerliChain.ChainId)) - require.Error(t, types.ValidateHashForChain("a0fa5a82f106fb192e4c503bfa8d54b2de20a821e09338094ab825cc9b275059", chains.GoerliChain.ChainId)) - require.NoError(t, types.ValidateHashForChain("15b7880f5d236e857a5e8f043ce9d56f5ef01e1c3f2a786baf740fc0bb7a22a3", chains.BtcMainnetChain.ChainId)) - require.NoError(t, types.ValidateHashForChain("a0fa5a82f106fb192e4c503bfa8d54b2de20a821e09338094ab825cc9b275059", chains.BtcTestNetChain.ChainId)) - require.Error(t, types.ValidateHashForChain("0x84bd5c9922b63c52d8a9ca686e0a57ff978150b71be0583514d01c27aa341910", chains.BtcMainnetChain.ChainId)) + require.Error( + t, + types.ValidateHashForChain( + "a0fa5a82f106fb192e4c503bfa8d54b2de20a821e09338094ab825cc9b275059", + chains.GoerliChain.ChainId, + ), + ) + require.NoError( + t, + types.ValidateHashForChain( + "15b7880f5d236e857a5e8f043ce9d56f5ef01e1c3f2a786baf740fc0bb7a22a3", + chains.BtcMainnetChain.ChainId, + ), + ) + require.NoError( + t, + types.ValidateHashForChain( + "a0fa5a82f106fb192e4c503bfa8d54b2de20a821e09338094ab825cc9b275059", + chains.BtcTestNetChain.ChainId, + ), + ) + require.Error( + t, + types.ValidateHashForChain( + "0x84bd5c9922b63c52d8a9ca686e0a57ff978150b71be0583514d01c27aa341910", + chains.BtcMainnetChain.ChainId, + ), + ) } diff --git a/x/emissions/abci.go b/x/emissions/abci.go index bd1831aa48..c640c1dd0b 100644 --- a/x/emissions/abci.go +++ b/x/emissions/abci.go @@ -15,7 +15,8 @@ func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { emissionPoolBalance := keeper.GetReservesFactor(ctx) blockRewards := types.BlockReward if blockRewards.GT(emissionPoolBalance) { - ctx.Logger().Info(fmt.Sprintf("Block rewards %s are greater than emission pool balance %s", blockRewards.String(), emissionPoolBalance.String())) + ctx.Logger(). + Info(fmt.Sprintf("Block rewards %s are greater than emission pool balance %s", blockRewards.String(), emissionPoolBalance.String())) return } @@ -57,9 +58,15 @@ func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { // DistributeValidatorRewards distributes the rewards to validators who signed the block . // The block proposer gets a bonus reward // This function uses the distribution module of cosmos-sdk , by directly sending funds to the feecollector. -func DistributeValidatorRewards(ctx sdk.Context, amount sdkmath.Int, bankKeeper types.BankKeeper, feeCollector string) error { +func DistributeValidatorRewards( + ctx sdk.Context, + amount sdkmath.Int, + bankKeeper types.BankKeeper, + feeCollector string, +) error { coin := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount)) - ctx.Logger().Info(fmt.Sprintf("Distributing Validator Rewards Total:%s To FeeCollector : %s", amount.String(), feeCollector)) + ctx.Logger(). + Info(fmt.Sprintf("Distributing Validator Rewards Total:%s To FeeCollector : %s", amount.String(), feeCollector)) return bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, feeCollector, coin) } @@ -76,7 +83,8 @@ func DistributeObserverRewards( slashAmount := params.ObserverSlashAmount rewardsDistributer := map[string]int64{} totalRewardsUnits := int64(0) - err := keeper.GetBankKeeper().SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) + err := keeper.GetBankKeeper(). + SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))) if err != nil { return err } @@ -102,7 +110,8 @@ func DistributeObserverRewards( if totalRewardsUnits > 0 && amount.IsPositive() { rewardPerUnit = amount.Quo(sdk.NewInt(totalRewardsUnits)) } - ctx.Logger().Debug(fmt.Sprintf("Total Rewards Units : %d , rewards per Unit %s ,number of ballots :%d", totalRewardsUnits, rewardPerUnit.String(), len(ballotIdentifiers))) + ctx.Logger(). + Debug(fmt.Sprintf("Total Rewards Units : %d , rewards per Unit %s ,number of ballots :%d", totalRewardsUnits, rewardPerUnit.String(), len(ballotIdentifiers))) sortedKeys := make([]string, 0, len(rewardsDistributer)) for k := range rewardsDistributer { sortedKeys = append(sortedKeys, k) diff --git a/x/emissions/abci_test.go b/x/emissions/abci_test.go index 9b7362f4d8..55bfdc85f8 100644 --- a/x/emissions/abci_test.go +++ b/x/emissions/abci_test.go @@ -55,7 +55,11 @@ func TestBeginBlocker(t *testing.T) { t.Run("tmp ctx is not committed if any of the distribution fails", func(t *testing.T) { k, ctx, sk, _ := keepertest.EmissionsKeeper(t) // Fund the emission pool to start the emission process - err := sk.BankKeeper.MintCoins(ctx, emissionstypes.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewInt(1000000000000)))) + err := sk.BankKeeper.MintCoins( + ctx, + emissionstypes.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewInt(1000000000000))), + ) require.NoError(t, err) // Setup module accounts for emission pools except for observer pool , so that the observer distribution fails _ = sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.UndistributedTssRewardsPool).GetAddress() @@ -68,7 +72,16 @@ func TestBeginBlocker(t *testing.T) { ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) } require.True(t, sk.BankKeeper.GetBalance(ctx, feeCollectorAddress, config.BaseDenom).Amount.IsZero()) - require.True(t, sk.BankKeeper.GetBalance(ctx, emissionstypes.EmissionsModuleAddress, config.BaseDenom).Amount.Equal(sdk.NewInt(1000000000000))) + require.True( + t, + sk.BankKeeper.GetBalance( + ctx, + emissionstypes.EmissionsModuleAddress, + config.BaseDenom, + ).Amount.Equal( + sdk.NewInt(1000000000000), + ), + ) }) t.Run("begin blocker returns early if validator distribution fails", func(t *testing.T) { k, ctx, _, _ := keepertest.EmissionKeeperWithMockOptions(t, keepertest.EmissionMockOptions{ @@ -181,17 +194,22 @@ func TestBeginBlocker(t *testing.T) { require.NoError(t, err) // Setup module accounts for emission pools - undistributedObserverPoolAddress := sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.UndistributedObserverRewardsPool).GetAddress() - undistributedTssPoolAddress := sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.UndistributedTssRewardsPool).GetAddress() + undistributedObserverPoolAddress := sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.UndistributedObserverRewardsPool). + GetAddress() + undistributedTssPoolAddress := sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.UndistributedTssRewardsPool). + GetAddress() feeCollecterAddress := sk.AuthKeeper.GetModuleAccount(ctx, types.FeeCollectorName).GetAddress() emissionPool := sk.AuthKeeper.GetModuleAccount(ctx, emissionstypes.ModuleName).GetAddress() params, found := k.GetParams(ctx) require.True(t, found) blockRewards := emissionstypes.BlockReward - observerRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.ObserverEmissionPercentage)).TruncateInt() - validatorRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.ValidatorEmissionPercentage)).TruncateInt() - tssSignerRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.TssSignerEmissionPercentage)).TruncateInt() + observerRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.ObserverEmissionPercentage)). + TruncateInt() + validatorRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.ValidatorEmissionPercentage)). + TruncateInt() + tssSignerRewardsForABlock := blockRewards.Mul(sdk.MustNewDecFromStr(params.TssSignerEmissionPercentage)). + TruncateInt() distributedRewards := observerRewardsForABlock.Add(validatorRewardsForABlock).Add(tssSignerRewardsForABlock) require.True(t, blockRewards.TruncateInt().GT(distributedRewards)) @@ -202,11 +220,20 @@ func TestBeginBlocker(t *testing.T) { emissionsModule.BeginBlocker(ctx, *k) // require distribution amount - emissionPoolBalanceAfterBlockDistribution := sk.BankKeeper.GetBalance(ctx, emissionPool, config.BaseDenom).Amount - require.True(t, emissionPoolBeforeBlockDistribution.Sub(emissionPoolBalanceAfterBlockDistribution).Equal(distributedRewards)) + emissionPoolBalanceAfterBlockDistribution := sk.BankKeeper.GetBalance( + ctx, + emissionPool, + config.BaseDenom, + ).Amount + require.True( + t, + emissionPoolBeforeBlockDistribution.Sub(emissionPoolBalanceAfterBlockDistribution). + Equal(distributedRewards), + ) // totalDistributedTillCurrentBlock is the net amount of rewards distributed till the current block, this works in a unit test as the fees are not being collected by validators - totalDistributedTillCurrentBlock := sk.BankKeeper.GetBalance(ctx, feeCollecterAddress, config.BaseDenom).Amount. + totalDistributedTillCurrentBlock := sk.BankKeeper.GetBalance(ctx, feeCollecterAddress, config.BaseDenom). + Amount. Add(sk.BankKeeper.GetBalance(ctx, undistributedObserverPoolAddress, config.BaseDenom).Amount). Add(sk.BankKeeper.GetBalance(ctx, undistributedTssPoolAddress, config.BaseDenom).Amount) // require we are always under the max limit of block rewards @@ -217,7 +244,9 @@ func TestBeginBlocker(t *testing.T) { } // We can simplify the calculation as the rewards are distributed equally among all the observers - rewardPerUnit := observerRewardsForABlock.Quo(sdk.NewInt(int64(len(ballotList) * len(observerSet.ObserverList)))) + rewardPerUnit := observerRewardsForABlock.Quo( + sdk.NewInt(int64(len(ballotList) * len(observerSet.ObserverList))), + ) emissionAmount := rewardPerUnit.Mul(sdk.NewInt(int64(len(ballotList)))) // Check if the rewards are distributed equally among all the observers @@ -232,10 +261,18 @@ func TestBeginBlocker(t *testing.T) { require.Equal(t, feeCollectorBalance, validatorRewardsForABlock.Mul(sdk.NewInt(int64(numberOfTestBlocks)))) tssPoolBalances := sk.BankKeeper.GetBalance(ctx, undistributedTssPoolAddress, config.BaseDenom).Amount - require.Equal(t, tssSignerRewardsForABlock.Mul(sdk.NewInt(int64(numberOfTestBlocks))).String(), tssPoolBalances.String()) + require.Equal( + t, + tssSignerRewardsForABlock.Mul(sdk.NewInt(int64(numberOfTestBlocks))).String(), + tssPoolBalances.String(), + ) observerPoolBalances := sk.BankKeeper.GetBalance(ctx, undistributedObserverPoolAddress, config.BaseDenom).Amount - require.Equal(t, observerRewardsForABlock.Mul(sdk.NewInt(int64(numberOfTestBlocks))).String(), observerPoolBalances.String()) + require.Equal( + t, + observerRewardsForABlock.Mul(sdk.NewInt(int64(numberOfTestBlocks))).String(), + observerPoolBalances.String(), + ) }) } @@ -253,8 +290,15 @@ func TestDistributeObserverRewards(t *testing.T) { slashAmount sdkmath.Int }{ { - name: "all observers rewarded correctly", - votes: [][]observerTypes.VoteType{{observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}}, + name: "all observers rewarded correctly", + votes: [][]observerTypes.VoteType{ + { + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, + }, // total reward units would be 4 as all votes match the ballot status totalRewardsForBlock: sdkmath.NewInt(100), expectedRewards: map[string]int64{ @@ -267,8 +311,15 @@ func TestDistributeObserverRewards(t *testing.T) { slashAmount: sdkmath.NewInt(25), }, { - name: "one observer slashed", - votes: [][]observerTypes.VoteType{{observerTypes.VoteType_FailureObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}}, + name: "one observer slashed", + votes: [][]observerTypes.VoteType{ + { + observerTypes.VoteType_FailureObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, + }, // total reward units would be 3 as 3 votes match the ballot status totalRewardsForBlock: sdkmath.NewInt(75), expectedRewards: map[string]int64{ @@ -281,8 +332,15 @@ func TestDistributeObserverRewards(t *testing.T) { slashAmount: sdkmath.NewInt(25), }, { - name: "all observer slashed", - votes: [][]observerTypes.VoteType{{observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}}, + name: "all observer slashed", + votes: [][]observerTypes.VoteType{ + { + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, + }, // total reward units would be 0 as no votes match the ballot status totalRewardsForBlock: sdkmath.NewInt(100), expectedRewards: map[string]int64{ @@ -295,8 +353,15 @@ func TestDistributeObserverRewards(t *testing.T) { slashAmount: sdkmath.NewInt(25), }, { - name: "slashed to zero if slash amount is greater than available emissions", - votes: [][]observerTypes.VoteType{{observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}}, + name: "slashed to zero if slash amount is greater than available emissions", + votes: [][]observerTypes.VoteType{ + { + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, + }, // total reward units would be 0 as no votes match the ballot status totalRewardsForBlock: sdkmath.NewInt(100), expectedRewards: map[string]int64{ @@ -311,8 +376,18 @@ func TestDistributeObserverRewards(t *testing.T) { { name: "withdraw able emissions unchanged if rewards and slashes are equal", votes: [][]observerTypes.VoteType{ - {observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}, - {observerTypes.VoteType_FailureObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation, observerTypes.VoteType_SuccessObservation}, + { + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, + { + observerTypes.VoteType_FailureObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + observerTypes.VoteType_SuccessObservation, + }, }, // total reward units would be 7 as 7 votes match the ballot status, including both ballots totalRewardsForBlock: sdkmath.NewInt(70), @@ -387,7 +462,13 @@ func TestDistributeObserverRewards(t *testing.T) { for i, observer := range observerSet.ObserverList { observerEmission, found := k.GetWithdrawableEmission(ctx, observer) require.True(t, found, "withdrawable emission not found for observer %d", i) - require.Equal(t, tc.expectedRewards[observer], observerEmission.Amount.Int64(), "invalid withdrawable emission for observer %d", i) + require.Equal( + t, + tc.expectedRewards[observer], + observerEmission.Amount.Int64(), + "invalid withdrawable emission for observer %d", + i, + ) } }) } diff --git a/x/emissions/keeper/grpc_query_get_emmisons_factors.go b/x/emissions/keeper/grpc_query_get_emmisons_factors.go index 5b265de52a..f57bf8f2de 100644 --- a/x/emissions/keeper/grpc_query_get_emmisons_factors.go +++ b/x/emissions/keeper/grpc_query_get_emmisons_factors.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) GetEmissionsFactors(goCtx context.Context, _ *types.QueryGetEmissionsFactorsRequest) (*types.QueryGetEmissionsFactorsResponse, error) { +func (k Keeper) GetEmissionsFactors( + goCtx context.Context, + _ *types.QueryGetEmissionsFactorsRequest, +) (*types.QueryGetEmissionsFactorsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) params, found := k.GetParams(ctx) if !found { diff --git a/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go b/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go index a2b44ebc6c..1a1719fb6d 100644 --- a/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go +++ b/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go @@ -27,7 +27,10 @@ func TestKeeper_GetEmissionsFactors(t *testing.T) { }) t.Run("should fail if params not found", func(t *testing.T) { - k, ctx, _, _ := keepertest.EmissionKeeperWithMockOptions(t, keepertest.EmissionMockOptions{SkipSettingParams: true}) + k, ctx, _, _ := keepertest.EmissionKeeperWithMockOptions( + t, + keepertest.EmissionMockOptions{SkipSettingParams: true}, + ) wctx := sdk.WrapSDKContext(ctx) res, err := k.GetEmissionsFactors(wctx, nil) diff --git a/x/emissions/keeper/grpc_query_list_balances.go b/x/emissions/keeper/grpc_query_list_balances.go index 589de64573..1d30f5368a 100644 --- a/x/emissions/keeper/grpc_query_list_balances.go +++ b/x/emissions/keeper/grpc_query_list_balances.go @@ -8,12 +8,17 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) ListPoolAddresses(_ context.Context, req *types.QueryListPoolAddressesRequest) (*types.QueryListPoolAddressesResponse, error) { +func (k Keeper) ListPoolAddresses( + _ context.Context, + req *types.QueryListPoolAddressesRequest, +) (*types.QueryListPoolAddressesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } - return &types.QueryListPoolAddressesResponse{UndistributedObserverBalancesAddress: types.UndistributedObserverRewardsPoolAddress.String(), - EmissionModuleAddress: types.EmissionsModuleAddress.String(), - UndistributedTssBalancesAddress: types.UndistributedTssRewardsPoolAddress.String()}, nil + return &types.QueryListPoolAddressesResponse{ + UndistributedObserverBalancesAddress: types.UndistributedObserverRewardsPoolAddress.String(), + EmissionModuleAddress: types.EmissionsModuleAddress.String(), + UndistributedTssBalancesAddress: types.UndistributedTssRewardsPoolAddress.String(), + }, nil } diff --git a/x/emissions/keeper/grpc_query_show_available_emissions.go b/x/emissions/keeper/grpc_query_show_available_emissions.go index 50b9d14dae..861e341713 100644 --- a/x/emissions/keeper/grpc_query_show_available_emissions.go +++ b/x/emissions/keeper/grpc_query_show_available_emissions.go @@ -11,7 +11,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (k Keeper) ShowAvailableEmissions(goCtx context.Context, req *types.QueryShowAvailableEmissionsRequest) (*types.QueryShowAvailableEmissionsResponse, error) { +func (k Keeper) ShowAvailableEmissions( + goCtx context.Context, + req *types.QueryShowAvailableEmissionsRequest, +) (*types.QueryShowAvailableEmissionsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/emissions/keeper/msg_server_update_params.go b/x/emissions/keeper/msg_server_update_params.go index 9581a1b19f..cb83c4c551 100644 --- a/x/emissions/keeper/msg_server_update_params.go +++ b/x/emissions/keeper/msg_server_update_params.go @@ -11,9 +11,17 @@ import ( // UpdateParams defines a governance operation for updating the x/emissions module parameters. // The authority is hard-coded to the x/gov module account. -func (k msgServer) UpdateParams(goCtx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { +func (k msgServer) UpdateParams( + goCtx context.Context, + msg *types.MsgUpdateParams, +) (*types.MsgUpdateParamsResponse, error) { if msg.Authority != k.authority { - return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, msg.Authority) + return nil, errors.Wrapf( + govtypes.ErrInvalidSigner, + "invalid authority; expected %s, got %s", + k.authority, + msg.Authority, + ) } ctx := sdk.UnwrapSDKContext(goCtx) diff --git a/x/emissions/keeper/msg_server_withdraw_emissions.go b/x/emissions/keeper/msg_server_withdraw_emissions.go index 3bf40e1428..0ecd002d8b 100644 --- a/x/emissions/keeper/msg_server_withdraw_emissions.go +++ b/x/emissions/keeper/msg_server_withdraw_emissions.go @@ -14,7 +14,10 @@ import ( // on a successful withdrawal, the amount is transferred from the undistributed rewards pool to the user's account. // if the amount to be withdrawn is greater than the available withdrawable emission, the max available amount is withdrawn. // if the pool does not have enough balance to process this request, an error is returned. -func (k msgServer) WithdrawEmission(goCtx context.Context, msg *types.MsgWithdrawEmission) (*types.MsgWithdrawEmissionResponse, error) { +func (k msgServer) WithdrawEmission( + goCtx context.Context, + msg *types.MsgWithdrawEmission, +) (*types.MsgWithdrawEmissionResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check if the creator address is valid @@ -25,19 +28,28 @@ func (k msgServer) WithdrawEmission(goCtx context.Context, msg *types.MsgWithdra // check if the undistributed rewards pool has enough balance to process this request. // This is just a preliminary check, the actual processing at endblock might still fail if the pool balance gets affected. - undistributedRewardsBalance := k.GetBankKeeper().GetBalance(ctx, types.UndistributedObserverRewardsPoolAddress, config.BaseDenom) + undistributedRewardsBalance := k.GetBankKeeper(). + GetBalance(ctx, types.UndistributedObserverRewardsPoolAddress, config.BaseDenom) if undistributedRewardsBalance.Amount.LT(msg.Amount) { - return nil, errorsmod.Wrap(types.ErrRewardsPoolDoesNotHaveEnoughBalance, " rewards pool does not have enough balance to process this request") + return nil, errorsmod.Wrap( + types.ErrRewardsPoolDoesNotHaveEnoughBalance, + " rewards pool does not have enough balance to process this request", + ) } err = k.RemoveWithdrawableEmission(ctx, msg.Creator, msg.Amount) if err != nil { - return nil, errorsmod.Wrap(types.ErrUnableToWithdrawEmissions, fmt.Sprintf("error while removing withdrawable emission for address %s : %s", msg.Creator, err)) + return nil, errorsmod.Wrap( + types.ErrUnableToWithdrawEmissions, + fmt.Sprintf("error while removing withdrawable emission for address %s : %s", msg.Creator, err), + ) } - err = k.GetBankKeeper().SendCoinsFromModuleToAccount(ctx, types.UndistributedObserverRewardsPool, address, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, msg.Amount))) + err = k.GetBankKeeper(). + SendCoinsFromModuleToAccount(ctx, types.UndistributedObserverRewardsPool, address, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, msg.Amount))) if err != nil { - ctx.Logger().Error(fmt.Sprintf("Error while processing withdraw of emission to adresss %s for amount %s : err %s", address, msg.Amount, err)) + ctx.Logger(). + Error(fmt.Sprintf("Error while processing withdraw of emission to adresss %s for amount %s : err %s", address, msg.Amount, err)) return nil, errorsmod.Wrap(types.ErrUnableToWithdrawEmissions, err.Error()) } diff --git a/x/emissions/keeper/msg_server_withdraw_emissions_test.go b/x/emissions/keeper/msg_server_withdraw_emissions_test.go index d42ede0088..10a95e999f 100644 --- a/x/emissions/keeper/msg_server_withdraw_emissions_test.go +++ b/x/emissions/keeper/msg_server_withdraw_emissions_test.go @@ -21,9 +21,18 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { msgServer := keeper.NewMsgServerImpl(*k) withdrawableEmission := sample.WithdrawableEmissions(t) k.SetWithdrawableEmission(ctx, withdrawableEmission) - err := sk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err := sk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) - err = sk.BankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err = sk.BankKeeper.SendCoinsFromModuleToModule( + ctx, + types.ModuleName, + types.UndistributedObserverRewardsPool, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) _, err = msgServer.WithdrawEmission(ctx, &types.MsgWithdrawEmission{ @@ -32,9 +41,13 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { }) require.NoError(t, err) - balance := k.GetBankKeeper().GetBalance(ctx, sdk.MustAccAddressFromBech32(withdrawableEmission.Address), config.BaseDenom).Amount.String() + balance := k.GetBankKeeper(). + GetBalance(ctx, sdk.MustAccAddressFromBech32(withdrawableEmission.Address), config.BaseDenom). + Amount.String() require.Equal(t, withdrawableEmission.Amount.String(), balance) - balance = k.GetBankKeeper().GetBalance(ctx, types.UndistributedObserverRewardsPoolAddress, config.BaseDenom).Amount.String() + balance = k.GetBankKeeper(). + GetBalance(ctx, types.UndistributedObserverRewardsPoolAddress, config.BaseDenom). + Amount.String() require.Equal(t, sdk.ZeroInt().String(), balance) }) @@ -44,9 +57,18 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { msgServer := keeper.NewMsgServerImpl(*k) withdrawableEmission := sample.WithdrawableEmissions(t) k.SetWithdrawableEmission(ctx, withdrawableEmission) - err := sk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err := sk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) - err = sk.BankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err = sk.BankKeeper.SendCoinsFromModuleToModule( + ctx, + types.ModuleName, + types.UndistributedObserverRewardsPool, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) _, err = msgServer.WithdrawEmission(ctx, &types.MsgWithdrawEmission{ @@ -56,19 +78,22 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { require.ErrorIs(t, err, types.ErrInvalidAddress) }) - t.Run("unable to withdraw emissions if undistributed rewards pool does not have enough balance", func(t *testing.T) { - k, ctx, _, _ := keepertest.EmissionsKeeper(t) + t.Run( + "unable to withdraw emissions if undistributed rewards pool does not have enough balance", + func(t *testing.T) { + k, ctx, _, _ := keepertest.EmissionsKeeper(t) - msgServer := keeper.NewMsgServerImpl(*k) - withdrawableEmission := sample.WithdrawableEmissions(t) - k.SetWithdrawableEmission(ctx, withdrawableEmission) + msgServer := keeper.NewMsgServerImpl(*k) + withdrawableEmission := sample.WithdrawableEmissions(t) + k.SetWithdrawableEmission(ctx, withdrawableEmission) - _, err := msgServer.WithdrawEmission(ctx, &types.MsgWithdrawEmission{ - Creator: withdrawableEmission.Address, - Amount: withdrawableEmission.Amount, - }) - require.ErrorIs(t, err, types.ErrRewardsPoolDoesNotHaveEnoughBalance) - }) + _, err := msgServer.WithdrawEmission(ctx, &types.MsgWithdrawEmission{ + Creator: withdrawableEmission.Address, + Amount: withdrawableEmission.Amount, + }) + require.ErrorIs(t, err, types.ErrRewardsPoolDoesNotHaveEnoughBalance) + }, + ) t.Run("unable to withdraw emissions with invalid amount", func(t *testing.T) { k, ctx, _, _ := keepertest.EmissionsKeeper(t) @@ -91,15 +116,29 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { withdrawableEmission := sample.WithdrawableEmissions(t) k.SetWithdrawableEmission(ctx, withdrawableEmission) - err := sk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err := sk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) - err = sk.BankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))) + err = sk.BankKeeper.SendCoinsFromModuleToModule( + ctx, + types.ModuleName, + types.UndistributedObserverRewardsPool, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ) require.NoError(t, err) address, err := sdk.AccAddressFromBech32(withdrawableEmission.Address) require.NoError(t, err) - bankMock.On("SendCoinsFromModuleToAccount", - ctx, types.UndistributedObserverRewardsPool, address, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount))). + bankMock.On( + "SendCoinsFromModuleToAccount", + ctx, + types.UndistributedObserverRewardsPool, + address, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawableEmission.Amount)), + ). Return(types.ErrUnableToWithdrawEmissions).Once() bankMock.On("GetBalance", ctx, mock.Anything, config.BaseDenom). @@ -110,7 +149,11 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { }) require.ErrorIs(t, err, types.ErrUnableToWithdrawEmissions) - balance := sk.BankKeeper.GetBalance(ctx, sdk.MustAccAddressFromBech32(withdrawableEmission.Address), config.BaseDenom).Amount.String() + balance := sk.BankKeeper.GetBalance( + ctx, + sdk.MustAccAddressFromBech32(withdrawableEmission.Address), + config.BaseDenom, + ).Amount.String() require.Equal(t, sdk.ZeroInt().String(), balance) }) @@ -121,9 +164,18 @@ func TestMsgServer_WithdrawEmission(t *testing.T) { withdrawableEmission := sample.WithdrawableEmissions(t) k.SetWithdrawableEmission(ctx, withdrawableEmission) withdrawAmount := withdrawableEmission.Amount.Add(sdkmath.OneInt()) - err := sk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawAmount))) + err := sk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawAmount)), + ) require.NoError(t, err) - err = sk.BankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedObserverRewardsPool, sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawAmount))) + err = sk.BankKeeper.SendCoinsFromModuleToModule( + ctx, + types.ModuleName, + types.UndistributedObserverRewardsPool, + sdk.NewCoins(sdk.NewCoin(config.BaseDenom, withdrawAmount)), + ) require.NoError(t, err) _, err = msgServer.WithdrawEmission(ctx, &types.MsgWithdrawEmission{ diff --git a/x/emissions/types/errors.go b/x/emissions/types/errors.go index 1ba687f3cd..2c7174b94a 100644 --- a/x/emissions/types/errors.go +++ b/x/emissions/types/errors.go @@ -6,7 +6,11 @@ var ( ErrEmissionsNotFound = errorsmod.Register(ModuleName, 1000, "emissions not found") ErrUnableToWithdrawEmissions = errorsmod.Register(ModuleName, 1002, "unable to withdraw emissions") ErrInvalidAddress = errorsmod.Register(ModuleName, 1003, "invalid address") - ErrRewardsPoolDoesNotHaveEnoughBalance = errorsmod.Register(ModuleName, 1004, "rewards pool does not have enough balance") - ErrInvalidAmount = errorsmod.Register(ModuleName, 1005, "invalid amount") - ErrUnableToSetParams = errorsmod.Register(ModuleName, 1006, "unable to set params") + ErrRewardsPoolDoesNotHaveEnoughBalance = errorsmod.Register( + ModuleName, + 1004, + "rewards pool does not have enough balance", + ) + ErrInvalidAmount = errorsmod.Register(ModuleName, 1005, "invalid amount") + ErrUnableToSetParams = errorsmod.Register(ModuleName, 1006, "unable to set params") ) diff --git a/x/emissions/types/events.go b/x/emissions/types/events.go index 7e15700c93..224212fc5a 100644 --- a/x/emissions/types/events.go +++ b/x/emissions/types/events.go @@ -4,7 +4,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func EmitValidatorEmissions(ctx sdk.Context, bondFactor, reservesFactor, durationsFactor, validatorRewards, observerRewards, tssRewards string) { +func EmitValidatorEmissions( + ctx sdk.Context, + bondFactor, reservesFactor, durationsFactor, validatorRewards, observerRewards, tssRewards string, +) { err := ctx.EventManager().EmitTypedEvents(&EventBlockEmissions{ MsgTypeUrl: "/zetachain.zetacore.emissions.internal.BlockEmissions", BondFactor: bondFactor, diff --git a/x/emissions/types/expected_keepers.go b/x/emissions/types/expected_keepers.go index fc9c6c022d..50d9576230 100644 --- a/x/emissions/types/expected_keepers.go +++ b/x/emissions/types/expected_keepers.go @@ -20,7 +20,12 @@ type ObserverKeeper interface { // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToAccount( + ctx sdk.Context, + senderModule string, + recipientAddr sdk.AccAddress, + amt sdk.Coins, + ) error GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin // Methods imported from bank should be defined here } diff --git a/x/emissions/types/params_legacy.go b/x/emissions/types/params_legacy.go index a98cab6047..8fce4a7be2 100644 --- a/x/emissions/types/params_legacy.go +++ b/x/emissions/types/params_legacy.go @@ -2,8 +2,7 @@ NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov controlled execution of MsgUpdateParams messages. These types remains solely for migration purposes and will be removed in a future release. -*/ -package types +*/package types import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -21,9 +20,25 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeyPrefix(ParamMinBondFactor), &p.MinBondFactor, validateMinBondFactor), paramtypes.NewParamSetPair(KeyPrefix(ParamAvgBlockTime), &p.AvgBlockTime, validateAvgBlockTime), paramtypes.NewParamSetPair(KeyPrefix(ParamTargetBondRatio), &p.TargetBondRatio, validateTargetBondRatio), - paramtypes.NewParamSetPair(KeyPrefix(ParamValidatorEmissionPercentage), &p.ValidatorEmissionPercentage, validateValidatorEmissionPercentage), - paramtypes.NewParamSetPair(KeyPrefix(ParamObserverEmissionPercentage), &p.ObserverEmissionPercentage, validateObserverEmissionPercentage), - paramtypes.NewParamSetPair(KeyPrefix(ParamTssSignerEmissionPercentage), &p.TssSignerEmissionPercentage, validateTssEmissionPercentage), - paramtypes.NewParamSetPair(KeyPrefix(ParamDurationFactorConstant), &p.DurationFactorConstant, validateDurationFactorConstant), + paramtypes.NewParamSetPair( + KeyPrefix(ParamValidatorEmissionPercentage), + &p.ValidatorEmissionPercentage, + validateValidatorEmissionPercentage, + ), + paramtypes.NewParamSetPair( + KeyPrefix(ParamObserverEmissionPercentage), + &p.ObserverEmissionPercentage, + validateObserverEmissionPercentage, + ), + paramtypes.NewParamSetPair( + KeyPrefix(ParamTssSignerEmissionPercentage), + &p.TssSignerEmissionPercentage, + validateTssEmissionPercentage, + ), + paramtypes.NewParamSetPair( + KeyPrefix(ParamDurationFactorConstant), + &p.DurationFactorConstant, + validateDurationFactorConstant, + ), } } diff --git a/x/emissions/types/params_test.go b/x/emissions/types/params_test.go index 6c1afcc575..a132744031 100644 --- a/x/emissions/types/params_test.go +++ b/x/emissions/types/params_test.go @@ -20,9 +20,19 @@ func TestNewParams(t *testing.T) { require.Equal(t, "00.50", params.ValidatorEmissionPercentage, "ValidatorEmissionPercentage should be set to 00.50") require.Equal(t, "00.25", params.ObserverEmissionPercentage, "ObserverEmissionPercentage should be set to 00.25") require.Equal(t, "00.25", params.TssSignerEmissionPercentage, "TssSignerEmissionPercentage should be set to 00.25") - require.Equal(t, "0.001877876953694702", params.DurationFactorConstant, "DurationFactorConstant should be set to 0.001877876953694702") - - require.Equal(t, sdkmath.NewInt(100000000000000000), params.ObserverSlashAmount, "ObserverSlashAmount should be set to 100000000000000000") + require.Equal( + t, + "0.001877876953694702", + params.DurationFactorConstant, + "DurationFactorConstant should be set to 0.001877876953694702", + ) + + require.Equal( + t, + sdkmath.NewInt(100000000000000000), + params.ObserverSlashAmount, + "ObserverSlashAmount should be set to 100000000000000000", + ) } func TestDefaultParams(t *testing.T) { diff --git a/x/fungible/client/cli/query_gas_stability_pool.go b/x/fungible/client/cli/query_gas_stability_pool.go index 516353daae..9dbd0d4e85 100644 --- a/x/fungible/client/cli/query_gas_stability_pool.go +++ b/x/fungible/client/cli/query_gas_stability_pool.go @@ -20,7 +20,10 @@ func CmdGasStabilityPoolAddress() *cobra.Command { queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.GasStabilityPoolAddress(context.Background(), &types.QueryGetGasStabilityPoolAddress{}) + res, err := queryClient.GasStabilityPoolAddress( + context.Background(), + &types.QueryGetGasStabilityPoolAddress{}, + ) if err != nil { return err } @@ -79,7 +82,10 @@ func CmdGasStabilityPoolBalances() *cobra.Command { queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.GasStabilityPoolBalanceAll(context.Background(), &types.QueryAllGasStabilityPoolBalance{}) + res, err := queryClient.GasStabilityPoolBalanceAll( + context.Background(), + &types.QueryAllGasStabilityPoolBalance{}, + ) if err != nil { return err } diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index c4ab0d81de..3daab6d4f5 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -42,7 +42,11 @@ var ( ) // DeployContract deploys a new contract in the ZEVM -func (k Keeper) DeployContract(ctx sdk.Context, metadata *bind.MetaData, ctorArguments ...interface{}) (common.Address, error) { +func (k Keeper) DeployContract( + ctx sdk.Context, + metadata *bind.MetaData, + ctorArguments ...interface{}, +) (common.Address, error) { contractABI, err := metadata.GetAbi() if err != nil { return common.Address{}, cosmoserrors.Wrapf(types.ErrABIGet, "failed to get ABI: %s", err.Error()) @@ -52,7 +56,11 @@ func (k Keeper) DeployContract(ctx sdk.Context, metadata *bind.MetaData, ctorArg ctorArguments..., // feeToSetter ) if err != nil { - return common.Address{}, cosmoserrors.Wrapf(types.ErrABIGet, "failed to abi.Pack ctor arguments: %s", err.Error()) + return common.Address{}, cosmoserrors.Wrapf( + types.ErrABIGet, + "failed to abi.Pack ctor arguments: %s", + err.Error(), + ) } if len(metadata.Bin) <= 2 { @@ -61,7 +69,12 @@ func (k Keeper) DeployContract(ctx sdk.Context, metadata *bind.MetaData, ctorArg bin, err := hex.DecodeString(metadata.Bin[2:]) if err != nil { - return common.Address{}, cosmoserrors.Wrapf(types.ErrABIPack, "error decoding %s hex bytecode string: %s", metadata.Bin[2:], err.Error()) + return common.Address{}, cosmoserrors.Wrapf( + types.ErrABIPack, + "error decoding %s hex bytecode string: %s", + metadata.Bin[2:], + err.Error(), + ) } data := make([]byte, len(bin)+len(ctorArgs)) @@ -121,7 +134,12 @@ func (k Keeper) DeployZRC20Contract( common.HexToAddress(system.SystemContract), ) if err != nil { - return common.Address{}, cosmoserrors.Wrapf(types.ErrABIPack, "failed to deploy ZRC20 contract: %s, %s", name, err.Error()) + return common.Address{}, cosmoserrors.Wrapf( + types.ErrABIPack, + "failed to deploy ZRC20 contract: %s, %s", + name, + err.Error(), + ) } coin, _ := k.GetForeignCoins(ctx, contractAddr.Hex()) coin.CoinType = coinType @@ -137,7 +155,12 @@ func (k Keeper) DeployZRC20Contract( return contractAddr, nil } -func (k Keeper) DeploySystemContract(ctx sdk.Context, wzeta common.Address, v2factory common.Address, router02 common.Address) (common.Address, error) { +func (k Keeper) DeploySystemContract( + ctx sdk.Context, + wzeta common.Address, + v2factory common.Address, + router02 common.Address, +) (common.Address, error) { system, _ := k.GetSystemContract(ctx) contractAddr, err := k.DeployContract(ctx, systemcontract.SystemContractMetaData, wzeta, v2factory, router02) @@ -164,7 +187,11 @@ func (k Keeper) DeployUniswapV2Factory(ctx sdk.Context) (common.Address, error) return contractAddr, nil } -func (k Keeper) DeployUniswapV2Router02(ctx sdk.Context, factory common.Address, wzeta common.Address) (common.Address, error) { +func (k Keeper) DeployUniswapV2Router02( + ctx sdk.Context, + factory common.Address, + wzeta common.Address, +) (common.Address, error) { contractAddr, err := k.DeployContract(ctx, uniswapv2router02.UniswapV2Router02MetaData, factory, wzeta) if err != nil { return common.Address{}, cosmoserrors.Wrapf(err, "UniswapV2Router02") @@ -631,7 +658,12 @@ func (k Keeper) CallEVM( k.Logger(ctx).Debug("calling EVM", "from", from, "contract", contract, "value", value, "method", method) resp, err := k.CallEVMWithData(ctx, from, &contract, data, commit, noEthereumTxEvent, value, gasLimit) if err != nil { - errMes := fmt.Sprintf("contract call failed: method '%s', contract '%s', args: %v", method, contract.Hex(), args) + errMes := fmt.Sprintf( + "contract call failed: method '%s', contract '%s', args: %v", + method, + contract.Hex(), + args, + ) // if it is a revert error then add the revert reason to the error message revertErr, ok := err.(*evmtypes.RevertError) diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index 8e2bc2f005..c603b1332b 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -301,7 +301,12 @@ func TestKeeper_DeploySystemContracts(t *testing.T) { _ = k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) mockEVMKeeper := keepertest.GetFungibleEVMMock(t, k) - wzeta, uniswapV2Factory, uniswapV2Router, _, _ := deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) + wzeta, uniswapV2Factory, uniswapV2Router, _, _ := deploySystemContractsWithMockEvmKeeper( + t, + ctx, + k, + mockEVMKeeper, + ) mockFailedContractDeployment(ctx, t, k) res, err := k.DeploySystemContract(ctx, wzeta, uniswapV2Factory, uniswapV2Router) @@ -388,7 +393,11 @@ func TestKeeper_DeploySystemContracts(t *testing.T) { require.Equal(t, int64(0), balance.Int64()) amount := big.NewInt(100) - err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amount)))) + err = sdkk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amount))), + ) require.NoError(t, err) err = k.CallWZetaDeposit(ctx, types.ModuleAddressEVM, amount) @@ -1343,7 +1352,15 @@ func TestKeeper_CallOnReceiveZevmConnector(t *testing.T) { data := []byte("message") internalSendHash := [32]byte{} - _, err = k.CallOnReceiveZevmConnector(ctx, senderAddress, sourceChainID, destinationAddress, zetaValue, data, internalSendHash) + _, err = k.CallOnReceiveZevmConnector( + ctx, + senderAddress, + sourceChainID, + destinationAddress, + zetaValue, + data, + internalSendHash, + ) require.NoError(t, err) require.NoError(t, err) @@ -1420,7 +1437,16 @@ func TestKeeper_CallOnRevertZevmConnector(t *testing.T) { zetaValue := big.NewInt(45) data := []byte("message") internalSendHash := [32]byte{} - _, err = k.CallOnRevertZevmConnector(ctx, senderAddress, sourceChainID, destinationAddress, destinationChainID, zetaValue, data, internalSendHash) + _, err = k.CallOnRevertZevmConnector( + ctx, + senderAddress, + sourceChainID, + destinationAddress, + destinationChainID, + zetaValue, + data, + internalSendHash, + ) require.NoError(t, err) dappAbi, err := contracts.DappMetaData.GetAbi() diff --git a/x/fungible/keeper/gas_coin_and_pool.go b/x/fungible/keeper/gas_coin_and_pool.go index 60cc436965..e8b7c83dca 100644 --- a/x/fungible/keeper/gas_coin_and_pool.go +++ b/x/fungible/keeper/gas_coin_and_pool.go @@ -49,7 +49,16 @@ func (k Keeper) SetupChainGasCoinAndPool( } } - zrc20Addr, err := k.DeployZRC20Contract(ctx, name, symbol, decimals, chain.ChainId, coin.CoinType_Gas, "", transferGasLimit) + zrc20Addr, err := k.DeployZRC20Contract( + ctx, + name, + symbol, + decimals, + chain.ChainId, + coin.CoinType_Gas, + "", + transferGasLimit, + ) if err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to DeployZRC20Contract") } @@ -71,21 +80,46 @@ func (k Keeper) SetupChainGasCoinAndPool( if err != nil { return ethcommon.Address{}, err } - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountAZeta)))) + err = k.bankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountAZeta))), + ) if err != nil { return ethcommon.Address{}, err } systemContractAddress, err := k.GetSystemContractAddress(ctx) if err != nil || systemContractAddress == (ethcommon.Address{}) { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "system contract address invalid: %s", systemContractAddress) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractNotFound, + "system contract address invalid: %s", + systemContractAddress, + ) } systemABI, err := systemcontract.SystemContractMetaData.GetAbi() if err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get system contract abi") } - _, err = k.CallEVM(ctx, *systemABI, types.ModuleAddressEVM, systemContractAddress, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(chain.ChainId), zrc20Addr) + _, err = k.CallEVM( + ctx, + *systemABI, + types.ModuleAddressEVM, + systemContractAddress, + BigIntZero, + nil, + true, + false, + "setGasZetaPool", + big.NewInt(chain.ChainId), + zrc20Addr, + ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method setGasZetaPool(%d, %s)", chain.ChainId, zrc20Addr.String()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + err, + "failed to CallEVM method setGasZetaPool(%d, %s)", + chain.ChainId, + zrc20Addr.String(), + ) } // setup uniswap v2 pools gas/zeta @@ -101,9 +135,26 @@ func (k Keeper) SetupChainGasCoinAndPool( if err != nil { return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to GetAbi zrc20") } - _, err = k.CallEVM(ctx, *ZRC20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "approve", routerAddress, amount) + _, err = k.CallEVM( + ctx, + *ZRC20ABI, + types.ModuleAddressEVM, + zrc20Addr, + BigIntZero, + nil, + true, + false, + "approve", + routerAddress, + amount, + ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method approve(%s, %d)", routerAddress.String(), amount) + return ethcommon.Address{}, cosmoserrors.Wrapf( + err, + "failed to CallEVM method approve(%s, %d)", + routerAddress.String(), + amount, + ) } //function addLiquidityETH( @@ -114,10 +165,30 @@ func (k Keeper) SetupChainGasCoinAndPool( // address to, // uint deadline //) external payable returns (uint amountToken, uint amountETH, uint liquidity); - res, err := k.CallEVM(ctx, *routerABI, types.ModuleAddressEVM, routerAddress, amountAZeta, big.NewInt(5_000_000), true, false, - "addLiquidityETH", zrc20Addr, amount, BigIntZero, BigIntZero, types.ModuleAddressEVM, amountAZeta) + res, err := k.CallEVM( + ctx, + *routerABI, + types.ModuleAddressEVM, + routerAddress, + amountAZeta, + big.NewInt(5_000_000), + true, + false, + "addLiquidityETH", + zrc20Addr, + amount, + BigIntZero, + BigIntZero, + types.ModuleAddressEVM, + amountAZeta, + ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to CallEVM method addLiquidityETH(%s, %s)", zrc20Addr.String(), amountAZeta.String()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + err, + "failed to CallEVM method addLiquidityETH(%s, %s)", + zrc20Addr.String(), + amountAZeta.String(), + ) } AmountToken := new(*big.Int) AmountETH := new(*big.Int) diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 636cffeec9..cfbbcb1c68 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -27,7 +27,19 @@ func (k Keeper) SetGasPrice(ctx sdk.Context, chainid *big.Int, gasPrice *big.Int if err != nil { return 0, cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, big.NewInt(50_000), true, false, "setGasPrice", chainid, gasPrice) + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + oracle, + BigIntZero, + big.NewInt(50_000), + true, + false, + "setGasPrice", + chainid, + gasPrice, + ) if err != nil { return 0, cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } @@ -51,7 +63,19 @@ func (k Keeper) SetGasCoin(ctx sdk.Context, chainid *big.Int, address ethcommon. if err != nil { return cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasCoinZRC20", chainid, address) + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + oracle, + BigIntZero, + nil, + true, + false, + "setGasCoinZRC20", + chainid, + address, + ) if err != nil { return cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } @@ -75,7 +99,19 @@ func (k Keeper) SetGasZetaPool(ctx sdk.Context, chainid *big.Int, pool ethcommon if err != nil { return cosmoserrors.Wrapf(types.ErrABIGet, "SystemContractMetaData") } - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, oracle, BigIntZero, nil, true, false, "setGasZetaPool", chainid, pool) + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + oracle, + BigIntZero, + nil, + true, + false, + "setGasZetaPool", + chainid, + pool, + ) if err != nil { return cosmoserrors.Wrapf(types.ErrContractCall, err.Error()) } diff --git a/x/fungible/keeper/gas_price_test.go b/x/fungible/keeper/gas_price_test.go index acd03d359b..a8d82f0fb5 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -22,7 +22,18 @@ func TestKeeper_SetGasPrice(t *testing.T) { queryGasPrice := func(chainID *big.Int) *big.Int { abi, err := systemcontract.SystemContractMetaData.GetAbi() require.NoError(t, err) - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, system, keeper.BigIntZero, nil, false, false, "gasPriceByChainId", chainID) + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + system, + keeper.BigIntZero, + nil, + false, + false, + "gasPriceByChainId", + chainID, + ) require.NoError(t, err) unpacked, err := abi.Unpack("gasPriceByChainId", res.Ret) require.NoError(t, err) @@ -136,7 +147,18 @@ func TestKeeper_SetGasZetaPool(t *testing.T) { queryZetaPool := func(chainID *big.Int) ethcommon.Address { abi, err := systemcontract.SystemContractMetaData.GetAbi() require.NoError(t, err) - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, system, keeper.BigIntZero, nil, false, false, "gasZetaPoolByChainId", chainID) + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + system, + keeper.BigIntZero, + nil, + false, + false, + "gasZetaPoolByChainId", + chainID, + ) require.NoError(t, err) unpacked, err := abi.Unpack("gasZetaPoolByChainId", res.Ret) require.NoError(t, err) diff --git a/x/fungible/keeper/grpc_query_foreign_coins.go b/x/fungible/keeper/grpc_query_foreign_coins.go index 20c661d7d1..d60cf9591f 100644 --- a/x/fungible/keeper/grpc_query_foreign_coins.go +++ b/x/fungible/keeper/grpc_query_foreign_coins.go @@ -11,7 +11,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) ForeignCoinsAll(c context.Context, req *types.QueryAllForeignCoinsRequest) (*types.QueryAllForeignCoinsResponse, error) { +func (k Keeper) ForeignCoinsAll( + c context.Context, + req *types.QueryAllForeignCoinsRequest, +) (*types.QueryAllForeignCoinsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -39,7 +42,10 @@ func (k Keeper) ForeignCoinsAll(c context.Context, req *types.QueryAllForeignCoi return &types.QueryAllForeignCoinsResponse{ForeignCoins: foreignCoinss, Pagination: pageRes}, nil } -func (k Keeper) ForeignCoins(c context.Context, req *types.QueryGetForeignCoinsRequest) (*types.QueryGetForeignCoinsResponse, error) { +func (k Keeper) ForeignCoins( + c context.Context, + req *types.QueryGetForeignCoinsRequest, +) (*types.QueryGetForeignCoinsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/fungible/keeper/grpc_query_system_contract.go b/x/fungible/keeper/grpc_query_system_contract.go index f753a57ed4..c21632f7a3 100644 --- a/x/fungible/keeper/grpc_query_system_contract.go +++ b/x/fungible/keeper/grpc_query_system_contract.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) SystemContract(c context.Context, req *types.QueryGetSystemContractRequest) (*types.QueryGetSystemContractResponse, error) { +func (k Keeper) SystemContract( + c context.Context, + req *types.QueryGetSystemContractRequest, +) (*types.QueryGetSystemContractResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go index da8e135b94..a4b7719214 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go @@ -30,7 +30,10 @@ import ( // * The coin is added to the list of foreign coins in the module's state // // Authorized: admin policy group 2. -func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.MsgDeployFungibleCoinZRC20) (*types.MsgDeployFungibleCoinZRC20Response, error) { +func (k msgServer) DeployFungibleCoinZRC20( + goCtx context.Context, + msg *types.MsgDeployFungibleCoinZRC20, +) (*types.MsgDeployFungibleCoinZRC20Response, error) { ctx := sdk.UnwrapSDKContext(goCtx) var address common.Address @@ -41,12 +44,22 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg } if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "Deploy can only be executed by the correct policy account", + ) } if msg.CoinType == coin.CoinType_Gas { // #nosec G701 always in range - address, err = k.SetupChainGasCoinAndPool(ctx, msg.ForeignChainId, msg.Name, msg.Symbol, uint8(msg.Decimals), big.NewInt(msg.GasLimit)) + address, err = k.SetupChainGasCoinAndPool( + ctx, + msg.ForeignChainId, + msg.Name, + msg.Symbol, + uint8(msg.Decimals), + big.NewInt(msg.GasLimit), + ) if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to setupChainGasCoinAndPool") } diff --git a/x/fungible/keeper/msg_server_deploy_system_contract.go b/x/fungible/keeper/msg_server_deploy_system_contract.go index 2b504ee524..aac1b85093 100644 --- a/x/fungible/keeper/msg_server_deploy_system_contract.go +++ b/x/fungible/keeper/msg_server_deploy_system_contract.go @@ -12,11 +12,17 @@ import ( // DeploySystemContracts deploy new instances of the system contracts // // Authorized: admin policy group 2. -func (k msgServer) DeploySystemContracts(goCtx context.Context, msg *types.MsgDeploySystemContracts) (*types.MsgDeploySystemContractsResponse, error) { +func (k msgServer) DeploySystemContracts( + goCtx context.Context, + msg *types.MsgDeploySystemContracts, +) (*types.MsgDeploySystemContractsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, cosmoserror.Wrap(authoritytypes.ErrUnauthorized, "System contract deployment can only be executed by the correct policy account") + return nil, cosmoserror.Wrap( + authoritytypes.ErrUnauthorized, + "System contract deployment can only be executed by the correct policy account", + ) } // uniswap v2 factory diff --git a/x/fungible/keeper/msg_server_remove_foreign_coin.go b/x/fungible/keeper/msg_server_remove_foreign_coin.go index 5cf4617110..13ba25b43f 100644 --- a/x/fungible/keeper/msg_server_remove_foreign_coin.go +++ b/x/fungible/keeper/msg_server_remove_foreign_coin.go @@ -14,10 +14,16 @@ import ( // module's state. // // Authorized: admin policy group 2. -func (k msgServer) RemoveForeignCoin(goCtx context.Context, msg *types.MsgRemoveForeignCoin) (*types.MsgRemoveForeignCoinResponse, error) { +func (k msgServer) RemoveForeignCoin( + goCtx context.Context, + msg *types.MsgRemoveForeignCoin, +) (*types.MsgRemoveForeignCoinResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "Removal can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "Removal can only be executed by the correct policy account", + ) } index := msg.Name _, found := k.GetForeignCoins(ctx, index) diff --git a/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go b/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go index 73fd15c9af..0aade62048 100644 --- a/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go +++ b/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go @@ -12,12 +12,18 @@ import ( // UpdateZRC20LiquidityCap updates the liquidity cap for a ZRC20 token. // // Authorized: admin policy group 2. -func (k msgServer) UpdateZRC20LiquidityCap(goCtx context.Context, msg *types.MsgUpdateZRC20LiquidityCap) (*types.MsgUpdateZRC20LiquidityCapResponse, error) { +func (k msgServer) UpdateZRC20LiquidityCap( + goCtx context.Context, + msg *types.MsgUpdateZRC20LiquidityCap, +) (*types.MsgUpdateZRC20LiquidityCapResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check authorization if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "update can only be executed by group 2 policy group") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "update can only be executed by group 2 policy group", + ) } // fetch the foreign coin diff --git a/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap_test.go b/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap_test.go index 37557a6967..844b417070 100644 --- a/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap_test.go +++ b/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap_test.go @@ -54,7 +54,12 @@ func TestMsgServer_UpdateZRC20LiquidityCap(t *testing.T) { coin, found = k.GetForeignCoins(ctx, coinAddress) require.True(t, found) - require.True(t, coin.LiquidityCap.Equal(math.NewUint(4200000)), "invalid liquidity cap", coin.LiquidityCap.String()) + require.True( + t, + coin.LiquidityCap.Equal(math.NewUint(4200000)), + "invalid liquidity cap", + coin.LiquidityCap.String(), + ) keepertest.MockIsAuthorized(&authorityMock.Mock, admin, authoritytypes.PolicyType_groupOperational, true) diff --git a/x/fungible/keeper/msg_server_update_contract_bytecode.go b/x/fungible/keeper/msg_server_update_contract_bytecode.go index ff2ba01809..ed4f70b2c7 100644 --- a/x/fungible/keeper/msg_server_update_contract_bytecode.go +++ b/x/fungible/keeper/msg_server_update_contract_bytecode.go @@ -18,12 +18,18 @@ import ( // variable but cannot remove any existing variable // // Authozied: admin policy group 2 -func (k msgServer) UpdateContractBytecode(goCtx context.Context, msg *types.MsgUpdateContractBytecode) (*types.MsgUpdateContractBytecodeResponse, error) { +func (k msgServer) UpdateContractBytecode( + goCtx context.Context, + msg *types.MsgUpdateContractBytecode, +) (*types.MsgUpdateContractBytecodeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check authorization if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupAdmin) { - return nil, cosmoserror.Wrap(authoritytypes.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, cosmoserror.Wrap( + authoritytypes.ErrUnauthorized, + "Deploy can only be executed by the correct policy account", + ) } // fetch account to update @@ -46,7 +52,11 @@ func (k msgServer) UpdateContractBytecode(goCtx context.Context, msg *types.MsgU } if msg.ContractAddress != systemContract.ConnectorZevm { // not a zrc20 or wzeta connector contract, can't be updated - return nil, cosmoserror.Wrapf(types.ErrInvalidContract, "contract (%s) is neither a zrc20 nor wzeta connector", msg.ContractAddress) + return nil, cosmoserror.Wrapf( + types.ErrInvalidContract, + "contract (%s) is neither a zrc20 nor wzeta connector", + msg.ContractAddress, + ) } } diff --git a/x/fungible/keeper/msg_server_update_system_contract.go b/x/fungible/keeper/msg_server_update_system_contract.go index 1d8344125c..396ab0a3dc 100644 --- a/x/fungible/keeper/msg_server_update_system_contract.go +++ b/x/fungible/keeper/msg_server_update_system_contract.go @@ -16,14 +16,24 @@ import ( ) // UpdateSystemContract updates the system contract -func (k msgServer) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpdateSystemContract) (*types.MsgUpdateSystemContractResponse, error) { +func (k msgServer) UpdateSystemContract( + goCtx context.Context, + msg *types.MsgUpdateSystemContract, +) (*types.MsgUpdateSystemContractResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupAdmin) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "Deploy can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "Deploy can only be executed by the correct policy account", + ) } newSystemContractAddr := ethcommon.HexToAddress(msg.NewSystemContractAddress) if newSystemContractAddr == (ethcommon.Address{}) { - return nil, cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) + return nil, cosmoserrors.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid system contract address (%s)", + msg.NewSystemContractAddress, + ) } // update contracts @@ -43,18 +53,65 @@ func (k msgServer) UpdateSystemContract(goCtx context.Context, msg *types.MsgUpd k.Logger(ctx).Error("invalid zrc20 contract address", "address", fcoin.Zrc20ContractAddress) continue } - _, err = k.CallEVM(tmpCtx, *zrc20ABI, types.ModuleAddressEVM, zrc20Addr, BigIntZero, nil, true, false, "updateSystemContractAddress", newSystemContractAddr) + _, err = k.CallEVM( + tmpCtx, + *zrc20ABI, + types.ModuleAddressEVM, + zrc20Addr, + BigIntZero, + nil, + true, + false, + "updateSystemContractAddress", + newSystemContractAddr, + ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract method updateSystemContractAddress (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call zrc20 contract method updateSystemContractAddress (%s)", + err.Error(), + ) } if fcoin.CoinType == coin.CoinType_Gas { - _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasCoinZRC20", big.NewInt(fcoin.ForeignChainId), zrc20Addr) + _, err = k.CallEVM( + tmpCtx, + *sysABI, + types.ModuleAddressEVM, + newSystemContractAddr, + BigIntZero, + nil, + true, + false, + "setGasCoinZRC20", + big.NewInt(fcoin.ForeignChainId), + zrc20Addr, + ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasCoinZRC20 (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call system contract method setGasCoinZRC20 (%s)", + err.Error(), + ) } - _, err = k.CallEVM(tmpCtx, *sysABI, types.ModuleAddressEVM, newSystemContractAddr, BigIntZero, nil, true, false, "setGasZetaPool", big.NewInt(fcoin.ForeignChainId), zrc20Addr) + _, err = k.CallEVM( + tmpCtx, + *sysABI, + types.ModuleAddressEVM, + newSystemContractAddr, + BigIntZero, + nil, + true, + false, + "setGasZetaPool", + big.NewInt(fcoin.ForeignChainId), + zrc20Addr, + ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call system contract method setGasZetaPool (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call system contract method setGasZetaPool (%s)", + err.Error(), + ) } } } diff --git a/x/fungible/keeper/msg_server_update_system_contract_test.go b/x/fungible/keeper/msg_server_update_system_contract_test.go index 2d1cd30c56..60c7061aee 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -34,7 +34,17 @@ func TestKeeper_UpdateSystemContract(t *testing.T) { queryZRC20SystemContract := func(contract common.Address) string { abi, err := zrc20.ZRC20MetaData.GetAbi() require.NoError(t, err) - res, err := k.CallEVM(ctx, *abi, types.ModuleAddressEVM, contract, keeper.BigIntZero, nil, false, false, "SYSTEM_CONTRACT_ADDRESS") + res, err := k.CallEVM( + ctx, + *abi, + types.ModuleAddressEVM, + contract, + keeper.BigIntZero, + nil, + false, + false, + "SYSTEM_CONTRACT_ADDRESS", + ) require.NoError(t, err) unpacked, err := abi.Unpack("SYSTEM_CONTRACT_ADDRESS", res.Ret) require.NoError(t, err) diff --git a/x/fungible/keeper/msg_server_update_zrc20_paused_status.go b/x/fungible/keeper/msg_server_update_zrc20_paused_status.go index 9527d1cb56..8399504ca5 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_paused_status.go +++ b/x/fungible/keeper/msg_server_update_zrc20_paused_status.go @@ -33,7 +33,10 @@ func (k msgServer) UpdateZRC20PausedStatus( requiredPolicyAccount = authoritytypes.PolicyType_groupOperational } if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, requiredPolicyAccount) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "Update can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "Update can only be executed by the correct policy account", + ) } pausedStatus := true diff --git a/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go b/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go index c7d9092cac..ed983e8ac3 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go +++ b/x/fungible/keeper/msg_server_update_zrc20_paused_status_test.go @@ -34,7 +34,12 @@ func TestKeeper_UpdateZRC20PausedStatus(t *testing.T) { } // setup zrc20 - zrc20A, zrc20B, zrc20C := sample.EthAddress().String(), sample.EthAddress().String(), sample.EthAddress().String() + zrc20A, zrc20B, zrc20C := sample.EthAddress(). + String(), + sample.EthAddress(). + String(), + sample.EthAddress(). + String() k.SetForeignCoins(ctx, sample.ForeignCoins(t, zrc20A)) k.SetForeignCoins(ctx, sample.ForeignCoins(t, zrc20B)) k.SetForeignCoins(ctx, sample.ForeignCoins(t, zrc20C)) diff --git a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go index 2baf8fd547..65119edd2d 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go @@ -12,22 +12,36 @@ import ( ) // UpdateZRC20WithdrawFee updates the withdraw fee and gas limit of a zrc20 token -func (k msgServer) UpdateZRC20WithdrawFee(goCtx context.Context, msg *types.MsgUpdateZRC20WithdrawFee) (*types.MsgUpdateZRC20WithdrawFeeResponse, error) { +func (k msgServer) UpdateZRC20WithdrawFee( + goCtx context.Context, + msg *types.MsgUpdateZRC20WithdrawFee, +) (*types.MsgUpdateZRC20WithdrawFeeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check signer permission if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { - return nil, cosmoserrors.Wrap(authoritytypes.ErrUnauthorized, "deploy can only be executed by the correct policy account") + return nil, cosmoserrors.Wrap( + authoritytypes.ErrUnauthorized, + "deploy can only be executed by the correct policy account", + ) } // check the zrc20 exists zrc20Addr := ethcommon.HexToAddress(msg.Zrc20Address) if zrc20Addr == (ethcommon.Address{}) { - return nil, cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid zrc20 contract address (%s)", msg.Zrc20Address) + return nil, cosmoserrors.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid zrc20 contract address (%s)", + msg.Zrc20Address, + ) } coin, found := k.GetForeignCoins(ctx, msg.Zrc20Address) if !found { - return nil, cosmoserrors.Wrapf(types.ErrForeignCoinNotFound, "no foreign coin match requested zrc20 address (%s)", msg.Zrc20Address) + return nil, cosmoserrors.Wrapf( + types.ErrForeignCoinNotFound, + "no foreign coin match requested zrc20 address (%s)", + msg.Zrc20Address, + ) } // get the previous fee @@ -45,13 +59,21 @@ func (k msgServer) UpdateZRC20WithdrawFee(goCtx context.Context, msg *types.MsgU if !msg.NewWithdrawFee.IsNil() { _, err = k.UpdateZRC20ProtocolFlatFee(tmpCtx, zrc20Addr, msg.NewWithdrawFee.BigInt()) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract updateProtocolFlatFee method (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call zrc20 contract updateProtocolFlatFee method (%s)", + err.Error(), + ) } } if !msg.NewGasLimit.IsNil() { _, err = k.UpdateZRC20GasLimit(tmpCtx, zrc20Addr, msg.NewGasLimit.BigInt()) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call zrc20 contract updateGasLimit method (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call zrc20 contract updateGasLimit method (%s)", + err.Error(), + ) } } diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index 822bccf766..1d9f393720 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -48,7 +48,10 @@ func (k *Keeper) GetSystemContractAddress(ctx sdk.Context) (ethcommon.Address, e // set the system contract system, found := k.GetSystemContract(ctx) if !found { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrStateVariableNotFound, + "failed to get system contract variable", + ) } systemAddress := ethcommon.HexToAddress(system.SystemContract) return systemAddress, nil @@ -58,7 +61,10 @@ func (k *Keeper) GetSystemContractAddress(ctx sdk.Context) (ethcommon.Address, e func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, error) { system, found := k.GetSystemContract(ctx) if !found { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrStateVariableNotFound, + "failed to get system contract variable", + ) } systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, err := systemcontract.SystemContractMetaData.GetAbi() @@ -78,14 +84,22 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er "wZetaContractAddress", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call wZetaContractAddress (%s)", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call wZetaContractAddress (%s)", + err.Error(), + ) } type AddressResponse struct { Value ethcommon.Address } var wzetaResponse AddressResponse if err := sysABI.UnpackIntoInterface(&wzetaResponse, "wZetaContractAddress", res.Ret); err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack wZetaContractAddress: %s", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrABIUnpack, + "failed to unpack wZetaContractAddress: %s", + err.Error(), + ) } if wzetaResponse.Value == (ethcommon.Address{}) { @@ -98,7 +112,10 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, error) { system, found := k.GetSystemContract(ctx) if !found { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrStateVariableNotFound, + "failed to get system contract variable", + ) } systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, err := systemcontract.SystemContractMetaData.GetAbi() @@ -118,18 +135,29 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, "uniswapv2FactoryAddress", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call uniswapv2FactoryAddress (%s)", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call uniswapv2FactoryAddress (%s)", + err.Error(), + ) } type AddressResponse struct { Value ethcommon.Address } var uniswapFactoryResponse AddressResponse if err := sysABI.UnpackIntoInterface(&uniswapFactoryResponse, "uniswapv2FactoryAddress", res.Ret); err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2FactoryAddress: %s", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrABIUnpack, + "failed to unpack uniswapv2FactoryAddress: %s", + err.Error(), + ) } if uniswapFactoryResponse.Value == (ethcommon.Address{}) { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "uniswap factory contract invalid address") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractNotFound, + "uniswap factory contract invalid address", + ) } return uniswapFactoryResponse.Value, nil } @@ -138,7 +166,10 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address, error) { system, found := k.GetSystemContract(ctx) if !found { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrStateVariableNotFound, + "failed to get system contract variable", + ) } systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, err := systemcontract.SystemContractMetaData.GetAbi() @@ -158,18 +189,29 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address "uniswapv2Router02Address", ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call uniswapv2Router02Address (%s)", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call uniswapv2Router02Address (%s)", + err.Error(), + ) } type AddressResponse struct { Value ethcommon.Address } var routerResponse AddressResponse if err := sysABI.UnpackIntoInterface(&routerResponse, "uniswapv2Router02Address", res.Ret); err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack uniswapv2Router02Address: %s", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrABIUnpack, + "failed to unpack uniswapv2Router02Address: %s", + err.Error(), + ) } if routerResponse.Value == (ethcommon.Address{}) { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "uniswap router contract invalid address") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractNotFound, + "uniswap router contract invalid address", + ) } return routerResponse.Value, nil } @@ -246,7 +288,10 @@ func (k *Keeper) QueryWZetaBalanceOf(ctx sdk.Context, addr ethcommon.Address) (* func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.Int) (ethcommon.Address, error) { system, found := k.GetSystemContract(ctx) if !found { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrStateVariableNotFound, + "failed to get system contract variable", + ) } systemAddress := ethcommon.HexToAddress(system.SystemContract) sysABI, err := systemcontract.SystemContractMetaData.GetAbi() @@ -267,7 +312,11 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I chainid, ) if err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractCall, "failed to call gasCoinZRC20ByChainId (%s)", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to call gasCoinZRC20ByChainId (%s)", + err.Error(), + ) } type AddressResponse struct { @@ -275,7 +324,11 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I } var zrc20Res AddressResponse if err := sysABI.UnpackIntoInterface(&zrc20Res, "gasCoinZRC20ByChainId", res.Ret); err != nil { - return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrABIUnpack, "failed to unpack gasCoinZRC20ByChainId: %s", err.Error()) + return ethcommon.Address{}, cosmoserrors.Wrapf( + types.ErrABIUnpack, + "failed to unpack gasCoinZRC20ByChainId: %s", + err.Error(), + ) } if zrc20Res.Value == (ethcommon.Address{}) { return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrContractNotFound, "gas coin contract invalid address") @@ -331,7 +384,11 @@ func (k *Keeper) CallUniswapV2RouterSwapExactTokensForTokens( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactTokensForTokens (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to CallEVM method swapExactTokensForTokens (%s)", + err.Error(), + ) } amounts := new([3]*big.Int) @@ -389,7 +446,11 @@ func (k *Keeper) CallUniswapV2RouterSwapExactTokensForETH( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactTokensForETH (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to CallEVM method swapExactTokensForETH (%s)", + err.Error(), + ) } amounts := new([2]*big.Int) @@ -441,7 +502,11 @@ func (k *Keeper) CallUniswapV2RouterSwapExactETHForToken( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapExactETHForTokens (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to CallEVM method swapExactETHForTokens (%s)", + err.Error(), + ) } amounts := new([2]*big.Int) @@ -492,7 +557,11 @@ func (k *Keeper) CallUniswapV2RouterSwapEthForExactToken( big.NewInt(1e17), ) if err != nil { - return nil, cosmoserrors.Wrapf(types.ErrContractCall, "failed to CallEVM method swapETHForExactTokens (%s)", err.Error()) + return nil, cosmoserrors.Wrapf( + types.ErrContractCall, + "failed to CallEVM method swapETHForExactTokens (%s)", + err.Error(), + ) } amounts := new([2]*big.Int) @@ -504,7 +573,11 @@ func (k *Keeper) CallUniswapV2RouterSwapEthForExactToken( } // QueryUniswapV2RouterGetZetaAmountsIn returns the amount of zeta needed to buy the given amount of ZRC4 tokens -func (k *Keeper) QueryUniswapV2RouterGetZetaAmountsIn(ctx sdk.Context, amountOut *big.Int, outZRC4 ethcommon.Address) (*big.Int, error) { +func (k *Keeper) QueryUniswapV2RouterGetZetaAmountsIn( + ctx sdk.Context, + amountOut *big.Int, + outZRC4 ethcommon.Address, +) (*big.Int, error) { routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to get router abi") @@ -535,7 +608,10 @@ func (k *Keeper) QueryUniswapV2RouterGetZetaAmountsIn(ctx sdk.Context, amountOut ) if err != nil { fmt.Println(err.Error()) - return nil, cosmoserrors.Wrap(types.ErrContractCall, fmt.Sprintf("failed to CallEVM method getAmountsIn (%s)", err.Error())) + return nil, cosmoserrors.Wrap( + types.ErrContractCall, + fmt.Sprintf("failed to CallEVM method getAmountsIn (%s)", err.Error()), + ) } amounts := new([2]*big.Int) @@ -547,7 +623,11 @@ func (k *Keeper) QueryUniswapV2RouterGetZetaAmountsIn(ctx sdk.Context, amountOut } // QueryUniswapV2RouterGetZRC4AmountsIn returns the amount of ZRC4 tokens needed to buy the given amount of zeta -func (k *Keeper) QueryUniswapV2RouterGetZRC4AmountsIn(ctx sdk.Context, amountOut *big.Int, inZRC4 ethcommon.Address) (*big.Int, error) { +func (k *Keeper) QueryUniswapV2RouterGetZRC4AmountsIn( + ctx sdk.Context, + amountOut *big.Int, + inZRC4 ethcommon.Address, +) (*big.Int, error) { routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to get router abi") @@ -588,7 +668,11 @@ func (k *Keeper) QueryUniswapV2RouterGetZRC4AmountsIn(ctx sdk.Context, amountOut } // QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn returns the amount of ZRC4 tokens needed to buy another ZRC4 token, it uses the WZeta contract as a bridge -func (k *Keeper) QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx sdk.Context, amountOut *big.Int, inZRC4, outZRC4 ethcommon.Address) (*big.Int, error) { +func (k *Keeper) QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx sdk.Context, + amountOut *big.Int, + inZRC4, outZRC4 ethcommon.Address, +) (*big.Int, error) { routerABI, err := uniswapv2router02.UniswapV2Router02MetaData.GetAbi() if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to get router abi") diff --git a/x/fungible/keeper/system_contract_test.go b/x/fungible/keeper/system_contract_test.go index 10f7908807..21d43dd231 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -114,14 +114,17 @@ func TestKeeper_GetWZetaContractAddress(t *testing.T) { } func TestKeeper_GetUniswapV2FactoryAddress(t *testing.T) { - t.Run("should fail to get uniswapfactory contract address if system contracts are not deployed", func(t *testing.T) { - k, ctx, _, _ := keepertest.FungibleKeeper(t) - k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) - - _, err := k.GetUniswapV2FactoryAddress(ctx) - require.Error(t, err) - require.ErrorIs(t, err, types.ErrStateVariableNotFound) - }) + t.Run( + "should fail to get uniswapfactory contract address if system contracts are not deployed", + func(t *testing.T) { + k, ctx, _, _ := keepertest.FungibleKeeper(t) + k.GetAuthKeeper().GetModuleAccount(ctx, types.ModuleName) + + _, err := k.GetUniswapV2FactoryAddress(ctx) + require.Error(t, err) + require.ErrorIs(t, err, types.ErrStateVariableNotFound) + }, + ) t.Run("should get uniswapfactory contract address if system contracts are deployed", func(t *testing.T) { k, ctx, sdkk, _ := keepertest.FungibleKeeper(t) @@ -401,7 +404,11 @@ func TestKeeper_CallUniswapV2RouterSwapExactETHForToken(t *testing.T) { amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) require.NoError(t, err) - err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + err = sdkk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap))), + ) require.NoError(t, err) amounts, err := k.CallUniswapV2RouterSwapExactETHForToken( @@ -507,7 +514,11 @@ func TestKeeper_CallUniswapV2RouterSwapEthForExactToken(t *testing.T) { amountToSwap, err := k.QueryUniswapV2RouterGetZetaAmountsIn(ctx, tokenAmount, zrc20) require.NoError(t, err) - err = sdkk.BankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap)))) + err = sdkk.BankKeeper.MintCoins( + ctx, + types.ModuleName, + sdk.NewCoins(sdk.NewCoin("azeta", sdk.NewIntFromBigInt(amountToSwap))), + ) require.NoError(t, err) amounts, err := k.CallUniswapV2RouterSwapEthForExactToken( @@ -827,7 +838,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts except router @@ -855,7 +873,14 @@ func TestKeeper_CallUniswapV2RouterSwapExactTokensForTokens(t *testing.T) { // fail if no system contract _, err := k.CallUniswapV2RouterSwapExactTokensForTokens( - ctx, types.ModuleAddressEVM, types.ModuleAddressEVM, big.NewInt(1), sample.EthAddress(), sample.EthAddress(), true) + ctx, + types.ModuleAddressEVM, + types.ModuleAddressEVM, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + true, + ) require.Error(t, err) // deploy system contracts except router @@ -966,7 +991,12 @@ func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(t *testing.T) { deploySystemContracts(t, ctx, k, sdkk.EvmKeeper) - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + ) require.ErrorIs(t, err, types.ErrContractCall) }) @@ -980,7 +1010,12 @@ func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(t *testing.T) { DeployUniswapV2Router: true, }) - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + ) require.ErrorIs(t, err, types.ErrContractNotFound) }) @@ -994,7 +1029,12 @@ func TestKeeper_QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(t *testing.T) { DeployUniswapV2Router: false, }) - _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn(ctx, big.NewInt(1), sample.EthAddress(), sample.EthAddress()) + _, err := k.QueryUniswapV2RouterGetZRC4ToZRC4AmountsIn( + ctx, + big.NewInt(1), + sample.EthAddress(), + sample.EthAddress(), + ) require.ErrorIs(t, err, types.ErrContractNotFound) }) } @@ -1026,7 +1066,14 @@ func TestKeeper_CallZRC20Approve(t *testing.T) { deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() - err := k.CallZRC20Approve(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1), false) + err := k.CallZRC20Approve( + ctx, + types.ModuleAddressEVM, + sample.EthAddress(), + types.ModuleAddressEVM, + big.NewInt(1), + false, + ) require.ErrorIs(t, err, types.ErrContractCall) }) } @@ -1042,7 +1089,13 @@ func TestKeeper_CallZRC20Deposit(t *testing.T) { deploySystemContractsWithMockEvmKeeper(t, ctx, k, mockEVMKeeper) mockEVMKeeper.MockEVMFailCallOnce() - err := k.CallZRC20Deposit(ctx, types.ModuleAddressEVM, sample.EthAddress(), types.ModuleAddressEVM, big.NewInt(1)) + err := k.CallZRC20Deposit( + ctx, + types.ModuleAddressEVM, + sample.EthAddress(), + types.ModuleAddressEVM, + big.NewInt(1), + ) require.ErrorIs(t, err, types.ErrContractCall) }) } diff --git a/x/fungible/keeper/zevm_message_passing_test.go b/x/fungible/keeper/zevm_message_passing_test.go index fe03808e81..a19db14df3 100644 --- a/x/fungible/keeper/zevm_message_passing_test.go +++ b/x/fungible/keeper/zevm_message_passing_test.go @@ -34,7 +34,15 @@ func TestKeeper_ZEVMDepositAndCallContract(t *testing.T) { data := []byte("message") cctxIndexBytes := [32]byte{} - _, err = k.ZETADepositAndCallContract(ctx, zetaTxSender, zetaTxReceiver, inboundSenderChainID, inboundAmount, data, cctxIndexBytes) + _, err = k.ZETADepositAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + inboundSenderChainID, + inboundAmount, + data, + cctxIndexBytes, + ) require.NoError(t, err) dappAbi, err := contracts.DappMetaData.GetAbi() @@ -78,7 +86,15 @@ func TestKeeper_ZEVMDepositAndCallContract(t *testing.T) { }) require.NoError(t, err) - _, err = k.ZETADepositAndCallContract(ctx, zetaTxSender, zetaTxReceiver, inboundSenderChainID, inboundAmount, data, cctxIndexBytes) + _, err = k.ZETADepositAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + inboundSenderChainID, + inboundAmount, + data, + cctxIndexBytes, + ) require.NoError(t, err) b := sdkk.BankKeeper.GetBalance(ctx, sdk.AccAddress(zetaTxReceiver.Bytes()), config.BaseDenom) require.Equal(t, inboundAmount.Int64(), b.Amount.Int64()) @@ -95,7 +111,15 @@ func TestKeeper_ZEVMDepositAndCallContract(t *testing.T) { data := []byte("message") cctxIndexBytes := [32]byte{} - _, err := k.ZETADepositAndCallContract(ctx, zetaTxSender, zetaTxReceiver, inboundSenderChainID, inboundAmount, data, cctxIndexBytes) + _, err := k.ZETADepositAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + inboundSenderChainID, + inboundAmount, + data, + cctxIndexBytes, + ) require.NoError(t, err) b := sdkk.BankKeeper.GetBalance(ctx, sdk.AccAddress(zetaTxReceiver.Bytes()), config.BaseDenom) require.Equal(t, inboundAmount.Int64(), b.Amount.Int64()) @@ -123,7 +147,15 @@ func TestKeeper_ZEVMDepositAndCallContract(t *testing.T) { errorMint := errors.New("", 10, "error minting coins") bankMock.On("MintCoins", ctx, types.ModuleName, mock.Anything).Return(errorMint).Once() - _, err = k.ZETADepositAndCallContract(ctx, zetaTxSender, zetaTxReceiver, inboundSenderChainID, inboundAmount, data, cctxIndexBytes) + _, err = k.ZETADepositAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + inboundSenderChainID, + inboundAmount, + data, + cctxIndexBytes, + ) require.ErrorIs(t, err, errorMint) }) } @@ -146,7 +178,16 @@ func TestKeeper_ZEVMRevertAndCallContract(t *testing.T) { data := []byte("message") cctxIndexBytes := [32]byte{} - _, err = k.ZETARevertAndCallContract(ctx, zetaTxSender, zetaTxReceiver, senderChainID.Int64(), destinationChainID.Int64(), amount, data, cctxIndexBytes) + _, err = k.ZETARevertAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + senderChainID.Int64(), + destinationChainID.Int64(), + amount, + data, + cctxIndexBytes, + ) require.NoError(t, err) dappAbi, err := contracts.DappMetaData.GetAbi() @@ -191,7 +232,16 @@ func TestKeeper_ZEVMRevertAndCallContract(t *testing.T) { }) require.NoError(t, err) - _, err = k.ZETARevertAndCallContract(ctx, zetaTxSender, zetaTxReceiver, senderChainID.Int64(), destinationChainID.Int64(), amount, data, cctxIndexBytes) + _, err = k.ZETARevertAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + senderChainID.Int64(), + destinationChainID.Int64(), + amount, + data, + cctxIndexBytes, + ) require.NoError(t, err) b := sdkk.BankKeeper.GetBalance(ctx, sdk.AccAddress(zetaTxSender.Bytes()), config.BaseDenom) require.Equal(t, amount.Int64(), b.Amount.Int64()) @@ -209,7 +259,16 @@ func TestKeeper_ZEVMRevertAndCallContract(t *testing.T) { data := []byte("message") cctxIndexBytes := [32]byte{} - _, err := k.ZETARevertAndCallContract(ctx, zetaTxSender, zetaTxReceiver, senderChainID.Int64(), destinationChainID.Int64(), amount, data, cctxIndexBytes) + _, err := k.ZETARevertAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + senderChainID.Int64(), + destinationChainID.Int64(), + amount, + data, + cctxIndexBytes, + ) require.NoError(t, err) b := sdkk.BankKeeper.GetBalance(ctx, sdk.AccAddress(zetaTxSender.Bytes()), config.BaseDenom) require.Equal(t, amount.Int64(), b.Amount.Int64()) @@ -238,7 +297,16 @@ func TestKeeper_ZEVMRevertAndCallContract(t *testing.T) { errorMint := errors.New("", 101, "error minting coins") bankMock.On("MintCoins", ctx, types.ModuleName, mock.Anything).Return(errorMint).Once() - _, err = k.ZETARevertAndCallContract(ctx, zetaTxSender, zetaTxReceiver, senderChainID.Int64(), destinationChainID.Int64(), amount, data, cctxIndexBytes) + _, err = k.ZETARevertAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + senderChainID.Int64(), + destinationChainID.Int64(), + amount, + data, + cctxIndexBytes, + ) require.ErrorIs(t, err, errorMint) }) @@ -258,7 +326,16 @@ func TestKeeper_ZEVMRevertAndCallContract(t *testing.T) { data := []byte("message") cctxIndexBytes := [32]byte{} - _, err = k.ZETARevertAndCallContract(ctx, zetaTxSender, zetaTxReceiver, senderChainID.Int64(), destinationChainID.Int64(), amount, data, cctxIndexBytes) + _, err = k.ZETARevertAndCallContract( + ctx, + zetaTxSender, + zetaTxReceiver, + senderChainID.Int64(), + destinationChainID.Int64(), + amount, + data, + cctxIndexBytes, + ) require.ErrorIs(t, err, types.ErrContractNotFound) require.ErrorContains(t, err, "GetSystemContract address not found") }) diff --git a/x/fungible/keeper/zevm_msg_passing.go b/x/fungible/keeper/zevm_msg_passing.go index 827a937ae8..258df47209 100644 --- a/x/fungible/keeper/zevm_msg_passing.go +++ b/x/fungible/keeper/zevm_msg_passing.go @@ -26,7 +26,15 @@ func (k Keeper) ZETADepositAndCallContract(ctx sdk.Context, return nil, nil } // Call onReceive function of the connector contract. The connector contract will then call the onReceive function of the destination contract which is the to address - return k.CallOnReceiveZevmConnector(ctx, sender.Bytes(), big.NewInt(inboundSenderChainID), to, inboundAmount, data, indexBytes) + return k.CallOnReceiveZevmConnector( + ctx, + sender.Bytes(), + big.NewInt(inboundSenderChainID), + to, + inboundAmount, + data, + indexBytes, + ) } // ZETARevertAndCallContract deposits native ZETA to the sender address if its account or if the account does not exist yet @@ -48,5 +56,14 @@ func (k Keeper) ZETARevertAndCallContract(ctx sdk.Context, return nil, nil } // Call onRevert function of the connector contract. The connector contract will then call the onRevert function of the zetaTxSender contract which is the sender address - return k.CallOnRevertZevmConnector(ctx, sender, big.NewInt(inboundSenderChainID), to.Bytes(), big.NewInt(destinationChainID), remainingAmount, data, indexBytes) + return k.CallOnRevertZevmConnector( + ctx, + sender, + big.NewInt(inboundSenderChainID), + to.Bytes(), + big.NewInt(destinationChainID), + remainingAmount, + data, + indexBytes, + ) } diff --git a/x/fungible/types/expected_keepers.go b/x/fungible/types/expected_keepers.go index f1064b0476..b3126be46a 100644 --- a/x/fungible/types/expected_keepers.go +++ b/x/fungible/types/expected_keepers.go @@ -26,7 +26,12 @@ type AccountKeeper interface { } type BankKeeper interface { - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToAccount( + ctx sdk.Context, + senderModule string, + recipientAddr sdk.AccAddress, + amt sdk.Coins, + ) error MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error } diff --git a/x/fungible/types/message_deploy_fungible_coin_zrc20.go b/x/fungible/types/message_deploy_fungible_coin_zrc20.go index 6103b6ef35..c86d069e02 100644 --- a/x/fungible/types/message_deploy_fungible_coin_zrc20.go +++ b/x/fungible/types/message_deploy_fungible_coin_zrc20.go @@ -11,7 +11,16 @@ const TypeMsgDeployFungibleCoinZRC20 = "deploy_fungible_coin_zrc_20" var _ sdk.Msg = &MsgDeployFungibleCoinZRC20{} -func NewMsgDeployFungibleCoinZRC20(creator string, ERC20 string, foreignChainID int64, decimals uint32, name string, symbol string, coinType coin.CoinType, gasLimit int64) *MsgDeployFungibleCoinZRC20 { +func NewMsgDeployFungibleCoinZRC20( + creator string, + ERC20 string, + foreignChainID int64, + decimals uint32, + name string, + symbol string, + coinType coin.CoinType, + gasLimit int64, +) *MsgDeployFungibleCoinZRC20 { return &MsgDeployFungibleCoinZRC20{ Creator: creator, ERC20: ERC20, diff --git a/x/fungible/types/message_update_system_contract.go b/x/fungible/types/message_update_system_contract.go index 2a347baada..c613847bf6 100644 --- a/x/fungible/types/message_update_system_contract.go +++ b/x/fungible/types/message_update_system_contract.go @@ -46,7 +46,11 @@ func (msg *MsgUpdateSystemContract) ValidateBasic() error { } // check if the system contract address is valid if ethcommon.HexToAddress(msg.NewSystemContractAddress) == (ethcommon.Address{}) { - return cosmoserrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid system contract address (%s)", msg.NewSystemContractAddress) + return cosmoserrors.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid system contract address (%s)", + msg.NewSystemContractAddress, + ) } return nil diff --git a/x/fungible/types/message_update_zrc20_paused_status.go b/x/fungible/types/message_update_zrc20_paused_status.go index 9eb1b77bd5..cbffdf0324 100644 --- a/x/fungible/types/message_update_zrc20_paused_status.go +++ b/x/fungible/types/message_update_zrc20_paused_status.go @@ -11,7 +11,11 @@ const TypeMsgUpdateZRC20PausedStatus = "update_zrc20_withdraw_fee" var _ sdk.Msg = &MsgUpdateZRC20PausedStatus{} -func NewMsgUpdateZRC20PausedStatus(creator string, zrc20 []string, action UpdatePausedStatusAction) *MsgUpdateZRC20PausedStatus { +func NewMsgUpdateZRC20PausedStatus( + creator string, + zrc20 []string, + action UpdatePausedStatusAction, +) *MsgUpdateZRC20PausedStatus { return &MsgUpdateZRC20PausedStatus{ Creator: creator, Zrc20Addresses: zrc20, diff --git a/x/fungible/types/message_update_zrc20_withdraw_fee.go b/x/fungible/types/message_update_zrc20_withdraw_fee.go index fb2b98955c..622fa45e66 100644 --- a/x/fungible/types/message_update_zrc20_withdraw_fee.go +++ b/x/fungible/types/message_update_zrc20_withdraw_fee.go @@ -13,7 +13,12 @@ const TypeMsgUpdateZRC20WithdrawFee = "update_zrc20_withdraw_fee" var _ sdk.Msg = &MsgUpdateZRC20WithdrawFee{} -func NewMsgUpdateZRC20WithdrawFee(creator string, zrc20 string, newFee math.Uint, newGasLimit math.Uint) *MsgUpdateZRC20WithdrawFee { +func NewMsgUpdateZRC20WithdrawFee( + creator string, + zrc20 string, + newFee math.Uint, + newGasLimit math.Uint, +) *MsgUpdateZRC20WithdrawFee { return &MsgUpdateZRC20WithdrawFee{ Creator: creator, Zrc20Address: zrc20, diff --git a/x/lightclient/genesis_test.go b/x/lightclient/genesis_test.go index 0c7a08c97a..b8820235be 100644 --- a/x/lightclient/genesis_test.go +++ b/x/lightclient/genesis_test.go @@ -54,6 +54,10 @@ func TestGenesis(t *testing.T) { ChainStates: []types.ChainState(nil), } require.Equal(t, expected, *got) - require.Equal(t, expected.BlockHeaderVerification.HeaderSupportedChains, got.BlockHeaderVerification.HeaderSupportedChains) + require.Equal( + t, + expected.BlockHeaderVerification.HeaderSupportedChains, + got.BlockHeaderVerification.HeaderSupportedChains, + ) }) } diff --git a/x/lightclient/keeper/block_header_test.go b/x/lightclient/keeper/block_header_test.go index 8d610e621f..e02ba6c861 100644 --- a/x/lightclient/keeper/block_header_test.go +++ b/x/lightclient/keeper/block_header_test.go @@ -325,43 +325,46 @@ func TestKeeper_AddBlockHeader(t *testing.T) { require.EqualValues(t, bh.ChainId, chainState.ChainId) }) - t.Run("should add a block header and update chain state if exists and set earliest height if 0", func(t *testing.T) { - k, ctx, _, _ := keepertest.LightclientKeeper(t) - - k.SetBlockHeaderVerification(ctx, types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{ - { - ChainId: chains.SepoliaChain.ChainId, - Enabled: true, + t.Run( + "should add a block header and update chain state if exists and set earliest height if 0", + func(t *testing.T) { + k, ctx, _, _ := keepertest.LightclientKeeper(t) + + k.SetBlockHeaderVerification(ctx, types.BlockHeaderVerification{ + HeaderSupportedChains: []types.HeaderSupportedChain{ + { + ChainId: chains.SepoliaChain.ChainId, + Enabled: true, + }, }, - }, - }) - - bh, _, _ := sepoliaBlockHeaders(t) - - k.SetChainState(ctx, types.ChainState{ - ChainId: bh.ChainId, - LatestHeight: bh.Height - 1, - EarliestHeight: 0, - LatestBlockHash: bh.ParentHash, - }) - - k.AddBlockHeader(ctx, bh.ChainId, bh.Height, bh.Hash, bh.Header, bh.ParentHash) - - retrieved, found := k.GetBlockHeader(ctx, bh.Hash) - require.True(t, found) - require.EqualValues(t, bh.Header, retrieved.Header) - require.EqualValues(t, bh.Height, retrieved.Height) - require.EqualValues(t, bh.Hash, retrieved.Hash) - require.EqualValues(t, bh.ParentHash, retrieved.ParentHash) - require.EqualValues(t, bh.ChainId, retrieved.ChainId) - - // Check chain state - chainState, found := k.GetChainState(ctx, bh.ChainId) - require.True(t, found) - require.EqualValues(t, bh.Height, chainState.LatestHeight) - require.EqualValues(t, bh.Height, chainState.EarliestHeight) - require.EqualValues(t, bh.Hash, chainState.LatestBlockHash) - require.EqualValues(t, bh.ChainId, chainState.ChainId) - }) + }) + + bh, _, _ := sepoliaBlockHeaders(t) + + k.SetChainState(ctx, types.ChainState{ + ChainId: bh.ChainId, + LatestHeight: bh.Height - 1, + EarliestHeight: 0, + LatestBlockHash: bh.ParentHash, + }) + + k.AddBlockHeader(ctx, bh.ChainId, bh.Height, bh.Hash, bh.Header, bh.ParentHash) + + retrieved, found := k.GetBlockHeader(ctx, bh.Hash) + require.True(t, found) + require.EqualValues(t, bh.Header, retrieved.Header) + require.EqualValues(t, bh.Height, retrieved.Height) + require.EqualValues(t, bh.Hash, retrieved.Hash) + require.EqualValues(t, bh.ParentHash, retrieved.ParentHash) + require.EqualValues(t, bh.ChainId, retrieved.ChainId) + + // Check chain state + chainState, found := k.GetChainState(ctx, bh.ChainId) + require.True(t, found) + require.EqualValues(t, bh.Height, chainState.LatestHeight) + require.EqualValues(t, bh.Height, chainState.EarliestHeight) + require.EqualValues(t, bh.Hash, chainState.LatestBlockHash) + require.EqualValues(t, bh.ChainId, chainState.ChainId) + }, + ) } diff --git a/x/lightclient/keeper/block_header_verification_test.go b/x/lightclient/keeper/block_header_verification_test.go index 0a5e29eb6a..eaf564f7da 100644 --- a/x/lightclient/keeper/block_header_verification_test.go +++ b/x/lightclient/keeper/block_header_verification_test.go @@ -52,7 +52,11 @@ func TestKeeper_CheckVerificationFlagsEnabled(t *testing.T) { err = k.CheckBlockHeaderVerificationEnabled(ctx, chains.BtcMainnetChain.ChainId) require.Error(t, err) - require.ErrorContains(t, err, fmt.Sprintf("proof verification is disabled for chain %d", chains.BtcMainnetChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("proof verification is disabled for chain %d", chains.BtcMainnetChain.ChainId), + ) err = k.CheckBlockHeaderVerificationEnabled(ctx, 1000) require.Error(t, err) @@ -72,7 +76,11 @@ func TestKeeper_CheckVerificationFlagsEnabled(t *testing.T) { err := k.CheckBlockHeaderVerificationEnabled(ctx, chains.EthChain.ChainId) require.Error(t, err) - require.ErrorContains(t, err, fmt.Sprintf("proof verification is disabled for chain %d", chains.EthChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("proof verification is disabled for chain %d", chains.EthChain.ChainId), + ) err = k.CheckBlockHeaderVerificationEnabled(ctx, chains.BtcMainnetChain.ChainId) require.NoError(t, err) @@ -103,6 +111,10 @@ func TestKeeper_CheckVerificationFlagsEnabled(t *testing.T) { }) err := k.CheckBlockHeaderVerificationEnabled(ctx, chains.EthChain.ChainId) - require.ErrorContains(t, err, fmt.Sprintf("proof verification is disabled for chain %d", chains.EthChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("proof verification is disabled for chain %d", chains.EthChain.ChainId), + ) }) } diff --git a/x/lightclient/keeper/grpc_query_block_header.go b/x/lightclient/keeper/grpc_query_block_header.go index a17b4ef9d7..b6d3b82003 100644 --- a/x/lightclient/keeper/grpc_query_block_header.go +++ b/x/lightclient/keeper/grpc_query_block_header.go @@ -12,7 +12,10 @@ import ( ) // BlockHeaderAll queries all block headers -func (k Keeper) BlockHeaderAll(c context.Context, req *types.QueryAllBlockHeaderRequest) (*types.QueryAllBlockHeaderResponse, error) { +func (k Keeper) BlockHeaderAll( + c context.Context, + req *types.QueryAllBlockHeaderRequest, +) (*types.QueryAllBlockHeaderResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -37,7 +40,10 @@ func (k Keeper) BlockHeaderAll(c context.Context, req *types.QueryAllBlockHeader } // BlockHeader queries block header by hash -func (k Keeper) BlockHeader(c context.Context, req *types.QueryGetBlockHeaderRequest) (*types.QueryGetBlockHeaderResponse, error) { +func (k Keeper) BlockHeader( + c context.Context, + req *types.QueryGetBlockHeaderRequest, +) (*types.QueryGetBlockHeaderResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/lightclient/keeper/grpc_query_chain_state.go b/x/lightclient/keeper/grpc_query_chain_state.go index bc428bd91c..4d49ce6e0d 100644 --- a/x/lightclient/keeper/grpc_query_chain_state.go +++ b/x/lightclient/keeper/grpc_query_chain_state.go @@ -13,7 +13,10 @@ import ( ) // ChainStateAll queries all chain statess -func (k Keeper) ChainStateAll(c context.Context, req *types.QueryAllChainStateRequest) (*types.QueryAllChainStateResponse, error) { +func (k Keeper) ChainStateAll( + c context.Context, + req *types.QueryAllChainStateRequest, +) (*types.QueryAllChainStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -38,7 +41,10 @@ func (k Keeper) ChainStateAll(c context.Context, req *types.QueryAllChainStateRe } // ChainState queries chain state by chain -func (k Keeper) ChainState(c context.Context, req *types.QueryGetChainStateRequest) (*types.QueryGetChainStateResponse, error) { +func (k Keeper) ChainState( + c context.Context, + req *types.QueryGetChainStateRequest, +) (*types.QueryGetChainStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/lightclient/keeper/grpc_query_header_enabled_chains.go b/x/lightclient/keeper/grpc_query_header_enabled_chains.go index 39d5886b4c..46e77c9396 100644 --- a/x/lightclient/keeper/grpc_query_header_enabled_chains.go +++ b/x/lightclient/keeper/grpc_query_header_enabled_chains.go @@ -12,7 +12,10 @@ import ( // HeaderSupportedChains implements the Query/HeaderEnabledChains gRPC method // It returns a list for chains that support block header verification. // Some chains in this list might be disabled which is indicated by the value of the `enabled` field. -func (k Keeper) HeaderSupportedChains(c context.Context, req *types.QueryHeaderSupportedChainsRequest) (*types.QueryHeaderSupportedChainsResponse, error) { +func (k Keeper) HeaderSupportedChains( + c context.Context, + req *types.QueryHeaderSupportedChainsRequest, +) (*types.QueryHeaderSupportedChainsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -20,7 +23,9 @@ func (k Keeper) HeaderSupportedChains(c context.Context, req *types.QueryHeaderS val, found := k.GetBlockHeaderVerification(ctx) if !found { - return &types.QueryHeaderSupportedChainsResponse{}, types.ErrBlockHeaderVerificationDisabled.Wrapf("proof verification is disabled for all chains") + return &types.QueryHeaderSupportedChainsResponse{}, types.ErrBlockHeaderVerificationDisabled.Wrapf( + "proof verification is disabled for all chains", + ) } return &types.QueryHeaderSupportedChainsResponse{HeaderSupportedChains: val.GetHeaderSupportedChainsList()}, nil @@ -28,7 +33,10 @@ func (k Keeper) HeaderSupportedChains(c context.Context, req *types.QueryHeaderS // HeaderEnabledChains implements the Query/HeaderEnabledChains gRPC method // It returns a list of chains that have block header verification enabled. -func (k Keeper) HeaderEnabledChains(c context.Context, req *types.QueryHeaderEnabledChainsRequest) (*types.QueryHeaderEnabledChainsResponse, error) { +func (k Keeper) HeaderEnabledChains( + c context.Context, + req *types.QueryHeaderEnabledChainsRequest, +) (*types.QueryHeaderEnabledChainsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -36,7 +44,9 @@ func (k Keeper) HeaderEnabledChains(c context.Context, req *types.QueryHeaderEna val, found := k.GetBlockHeaderVerification(ctx) if !found { - return &types.QueryHeaderEnabledChainsResponse{}, types.ErrBlockHeaderVerificationDisabled.Wrapf("proof verification is disabled for all chains") + return &types.QueryHeaderEnabledChainsResponse{}, types.ErrBlockHeaderVerificationDisabled.Wrapf( + "proof verification is disabled for all chains", + ) } return &types.QueryHeaderEnabledChainsResponse{HeaderEnabledChains: val.GetHeaderEnabledChains()}, nil diff --git a/x/lightclient/keeper/grpc_query_prove.go b/x/lightclient/keeper/grpc_query_prove.go index 7fbbc8bf3c..b3122ee453 100644 --- a/x/lightclient/keeper/grpc_query_prove.go +++ b/x/lightclient/keeper/grpc_query_prove.go @@ -46,7 +46,10 @@ func (k Keeper) Prove(c context.Context, req *types.QueryProveRequest) (*types.Q return nil, status.Error(codes.Internal, fmt.Sprintf("failed to unmarshal evm transaction: %s", err)) } if txx.Hash().Hex() != req.TxHash { - return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("tx hash mismatch: %s != %s", txx.Hash().Hex(), req.TxHash)) + return nil, status.Error( + codes.InvalidArgument, + fmt.Sprintf("tx hash mismatch: %s != %s", txx.Hash().Hex(), req.TxHash), + ) } proven = true } else if chains.IsBitcoinChain(req.ChainId) { diff --git a/x/lightclient/keeper/msg_server_disable_block_header_verification.go b/x/lightclient/keeper/msg_server_disable_block_header_verification.go index c6f33d133a..1195137ed6 100644 --- a/x/lightclient/keeper/msg_server_disable_block_header_verification.go +++ b/x/lightclient/keeper/msg_server_disable_block_header_verification.go @@ -10,7 +10,10 @@ import ( // DisableHeaderVerification disables the verification flags for the given chain IDs // Disabled chains do not allow the submissions of block headers or using it to verify the correctness of proofs -func (k msgServer) DisableHeaderVerification(goCtx context.Context, msg *types.MsgDisableHeaderVerification) (*types.MsgDisableHeaderVerificationResponse, error) { +func (k msgServer) DisableHeaderVerification( + goCtx context.Context, + msg *types.MsgDisableHeaderVerification, +) (*types.MsgDisableHeaderVerificationResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission diff --git a/x/lightclient/keeper/proof.go b/x/lightclient/keeper/proof.go index 8b84cd7977..ed973e28ae 100644 --- a/x/lightclient/keeper/proof.go +++ b/x/lightclient/keeper/proof.go @@ -10,7 +10,13 @@ import ( // VerifyProof verifies the merkle proof for a given chain and block header // It returns the transaction bytes if the proof is valid -func (k Keeper) VerifyProof(ctx sdk.Context, proof *proofs.Proof, chainID int64, blockHash string, txIndex int64) ([]byte, error) { +func (k Keeper) VerifyProof( + ctx sdk.Context, + proof *proofs.Proof, + chainID int64, + blockHash string, + txIndex int64, +) ([]byte, error) { // check block header verification is set if err := k.CheckBlockHeaderVerificationEnabled(ctx, chainID); err != nil { return nil, err @@ -19,7 +25,12 @@ func (k Keeper) VerifyProof(ctx sdk.Context, proof *proofs.Proof, chainID int64, // get block header from the store hashBytes, err := chains.StringToHash(chainID, blockHash) if err != nil { - return nil, cosmoserror.Wrapf(types.ErrInvalidBlockHash, "block hash %s conversion failed %s", blockHash, err.Error()) + return nil, cosmoserror.Wrapf( + types.ErrInvalidBlockHash, + "block hash %s conversion failed %s", + blockHash, + err.Error(), + ) } res, found := k.GetBlockHeader(ctx, hashBytes) if !found { @@ -29,7 +40,11 @@ func (k Keeper) VerifyProof(ctx sdk.Context, proof *proofs.Proof, chainID int64, // verify merkle proof txBytes, err := proof.Verify(res.Header, int(txIndex)) if err != nil { - return nil, cosmoserror.Wrapf(types.ErrProofVerificationFailed, "failed to verify merkle proof: %s", err.Error()) + return nil, cosmoserror.Wrapf( + types.ErrProofVerificationFailed, + "failed to verify merkle proof: %s", + err.Error(), + ) } return txBytes, nil } diff --git a/x/lightclient/keeper/proof_test.go b/x/lightclient/keeper/proof_test.go index 11633f4b82..fdc18e60ff 100644 --- a/x/lightclient/keeper/proof_test.go +++ b/x/lightclient/keeper/proof_test.go @@ -68,7 +68,11 @@ func TestKeeper_VerifyProof(t *testing.T) { }) _, err := k.VerifyProof(ctx, &proofs.Proof{}, chains.ZetaPrivnetChain.ChainId, sample.Hash().String(), 1) - require.ErrorContains(t, err, fmt.Sprintf("proof verification is disabled for chain %d", chains.ZetaPrivnetChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("proof verification is disabled for chain %d", chains.ZetaPrivnetChain.ChainId), + ) }) t.Run("should error if blockhash invalid", func(t *testing.T) { diff --git a/x/lightclient/types/block_header_verification_test.go b/x/lightclient/types/block_header_verification_test.go index ec5d7cd4cc..192e05790b 100644 --- a/x/lightclient/types/block_header_verification_test.go +++ b/x/lightclient/types/block_header_verification_test.go @@ -12,13 +12,19 @@ import ( func TestBlockHeaderVerification_Validate(t *testing.T) { t.Run("should return nil if no duplicate chain id", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: 1, Enabled: true}, {ChainId: 2, Enabled: true}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: 1, Enabled: true}, + {ChainId: 2, Enabled: true}, + }} require.NoError(t, bhv.Validate()) }) t.Run("should return error if duplicate chain id", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: 1, Enabled: true}, {ChainId: 1, Enabled: true}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: 1, Enabled: true}, + {ChainId: 1, Enabled: true}, + }} require.Error(t, bhv.Validate()) }) } @@ -31,7 +37,9 @@ func TestBlockHeaderVerification_EnableChain(t *testing.T) { t.Run("should not enable chain is present", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: chains.BscMainnetChain.ChainId, Enabled: false}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: chains.BscMainnetChain.ChainId, Enabled: false}, + }} bhv.EnableChain(chains.BscMainnetChain.ChainId) require.True(t, bhv.IsChainEnabled(chains.BscMainnetChain.ChainId)) }) @@ -46,7 +54,9 @@ func TestBlockHeaderVerification_DisableChain(t *testing.T) { t.Run("should disable chain if chain present", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: chains.BscMainnetChain.ChainId, Enabled: true}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: chains.BscMainnetChain.ChainId, Enabled: true}, + }} bhv.DisableChain(chains.BscMainnetChain.ChainId) require.False(t, bhv.IsChainEnabled(chains.BscMainnetChain.ChainId)) }) @@ -81,7 +91,10 @@ func TestBlockHeaderVerification_GetEnabledChainIDList(t *testing.T) { t.Run("should return empty list if no chain is enabled", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: 1, Enabled: false}, {ChainId: 2, Enabled: false}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: 1, Enabled: false}, + {ChainId: 2, Enabled: false}, + }} enabledChains := bhv.GetHeaderEnabledChainIDs() require.Len(t, enabledChains, 0) }) @@ -104,7 +117,10 @@ func TestBlockHeaderVerification_GetEnabledChainsList(t *testing.T) { t.Run("should return empty list if no chain is enabled", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: 1, Enabled: false}, {ChainId: 2, Enabled: false}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: 1, Enabled: false}, + {ChainId: 2, Enabled: false}, + }} enabledChains := bhv.GetHeaderEnabledChains() require.Len(t, enabledChains, 0) }) @@ -133,7 +149,10 @@ func TestBlockHeaderVerification_GetSupportedChainsList(t *testing.T) { t.Run("should items even if chain is not enabled but still supported", func(t *testing.T) { bhv := types.BlockHeaderVerification{ - HeaderSupportedChains: []types.HeaderSupportedChain{{ChainId: 1, Enabled: false}, {ChainId: 2, Enabled: false}}} + HeaderSupportedChains: []types.HeaderSupportedChain{ + {ChainId: 1, Enabled: false}, + {ChainId: 2, Enabled: false}, + }} supportedChains := bhv.GetHeaderSupportedChains() require.Len(t, supportedChains, 2) require.Contains(t, supportedChains, types.HeaderSupportedChain{ChainId: 1, Enabled: false}) diff --git a/x/lightclient/types/message_disable_verification_flags.go b/x/lightclient/types/message_disable_verification_flags.go index 90779b53dd..803d2979a5 100644 --- a/x/lightclient/types/message_disable_verification_flags.go +++ b/x/lightclient/types/message_disable_verification_flags.go @@ -55,7 +55,11 @@ func (msg *MsgDisableHeaderVerification) ValidateBasic() error { } for _, chainID := range msg.ChainIdList { if !chains.ChainIDInChainList(chainID, chainListForHeaderSupport) { - return cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid chain id header not supported (%d)", chainID) + return cosmoserrors.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid chain id header not supported (%d)", + chainID, + ) } } diff --git a/x/lightclient/types/message_disable_verification_flags_test.go b/x/lightclient/types/message_disable_verification_flags_test.go index c3ca7af003..2120426c5a 100644 --- a/x/lightclient/types/message_disable_verification_flags_test.go +++ b/x/lightclient/types/message_disable_verification_flags_test.go @@ -57,7 +57,11 @@ func TestMsgDisableHeaderVerification_ValidateBasic(t *testing.T) { }, err: func(t require.TestingT, err error, i ...interface{}) { require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("invalid chain id header not supported (%d)", chains.ZetaPrivnetChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("invalid chain id header not supported (%d)", chains.ZetaPrivnetChain.ChainId), + ) }, }, { diff --git a/x/lightclient/types/message_enable_verification_flags.go b/x/lightclient/types/message_enable_verification_flags.go index 3e41a0c4fc..3de9f9aff4 100644 --- a/x/lightclient/types/message_enable_verification_flags.go +++ b/x/lightclient/types/message_enable_verification_flags.go @@ -54,7 +54,11 @@ func (msg *MsgEnableHeaderVerification) ValidateBasic() error { } for _, chainID := range msg.ChainIdList { if !chains.ChainIDInChainList(chainID, chainListForHeaderSupport) { - return cosmoserrors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid chain id header not supported (%d)", chainID) + return cosmoserrors.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid chain id header not supported (%d)", + chainID, + ) } } diff --git a/x/lightclient/types/message_enable_verification_flags_test.go b/x/lightclient/types/message_enable_verification_flags_test.go index 0f00adc989..fe76dcfb40 100644 --- a/x/lightclient/types/message_enable_verification_flags_test.go +++ b/x/lightclient/types/message_enable_verification_flags_test.go @@ -57,7 +57,11 @@ func TestMsgEnableHeaderVerification_ValidateBasic(t *testing.T) { }, err: func(t require.TestingT, err error, i ...interface{}) { require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("invalid chain id header not supported (%d)", chains.ZetaPrivnetChain.ChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf("invalid chain id header not supported (%d)", chains.ZetaPrivnetChain.ChainId), + ) }, }, { diff --git a/x/observer/abci.go b/x/observer/abci.go index 41121ced19..ee31774035 100644 --- a/x/observer/abci.go +++ b/x/observer/abci.go @@ -25,7 +25,8 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { if totalObserverCountCurrentBlock == lastBlockObserverCount.Count { return } - ctx.Logger().Error("LastBlockObserverCount does not match the number of observers found at current height", ctx.BlockHeight()) + ctx.Logger(). + Error("LastBlockObserverCount does not match the number of observers found at current height", ctx.BlockHeight()) for _, observer := range allObservers.ObserverList { ctx.Logger().Error("Observer : ", observer) } @@ -34,5 +35,8 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { k.DisableInboundOnly(ctx) k.SetKeygen(ctx, types.Keygen{BlockNumber: math.MaxInt64}) // #nosec G701 always positive - k.SetLastObserverCount(ctx, &types.LastObserverCount{Count: totalObserverCountCurrentBlock, LastChangeHeight: ctx.BlockHeight()}) + k.SetLastObserverCount( + ctx, + &types.LastObserverCount{Count: totalObserverCountCurrentBlock, LastChangeHeight: ctx.BlockHeight()}, + ) } diff --git a/x/observer/client/cli/tx_permission_flags.go b/x/observer/client/cli/tx_permission_flags.go index 71c6304e51..1087e1a5e9 100644 --- a/x/observer/client/cli/tx_permission_flags.go +++ b/x/observer/client/cli/tx_permission_flags.go @@ -29,7 +29,11 @@ func CmdUpdateCrosschainFlags() *cobra.Command { if err != nil { return err } - msg := types.NewMsgUpdateCrosschainFlags(clientCtx.GetFromAddress().String(), argIsInboundEnabled, arsIsOutboundEnabled) + msg := types.NewMsgUpdateCrosschainFlags( + clientCtx.GetFromAddress().String(), + argIsInboundEnabled, + arsIsOutboundEnabled, + ) return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, diff --git a/x/observer/genesis.go b/x/observer/genesis.go index ea63b10a24..4f95e52edd 100644 --- a/x/observer/genesis.go +++ b/x/observer/genesis.go @@ -66,7 +66,10 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) for _, ballot := range genState.Ballots { if ballot != nil { k.SetBallot(ctx, ballot) - ballotListForHeight[ballot.BallotCreationHeight] = append(ballotListForHeight[ballot.BallotCreationHeight], ballot.BallotIdentifier) + ballotListForHeight[ballot.BallotCreationHeight] = append( + ballotListForHeight[ballot.BallotCreationHeight], + ballot.BallotIdentifier, + ) } } } diff --git a/x/observer/keeper/blame.go b/x/observer/keeper/blame.go index 63e4c84809..bfec60c94d 100644 --- a/x/observer/keeper/blame.go +++ b/x/observer/keeper/blame.go @@ -35,7 +35,10 @@ func (k Keeper) GetAllBlame(ctx sdk.Context) (BlameRecords []types.Blame) { return } -func (k Keeper) GetAllBlamePaginated(ctx sdk.Context, pagination *query.PageRequest) (blameRecords []types.Blame, pageRes *query.PageResponse, err error) { +func (k Keeper) GetAllBlamePaginated( + ctx sdk.Context, + pagination *query.PageRequest, +) (blameRecords []types.Blame, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BlameKey)) pageRes, err = query.Paginate(store, pagination, func(_ []byte, value []byte) error { var blame types.Blame @@ -48,7 +51,11 @@ func (k Keeper) GetAllBlamePaginated(ctx sdk.Context, pagination *query.PageRequ return } -func (k Keeper) GetBlamesByChainAndNonce(ctx sdk.Context, chainID int64, nonce int64) (BlameRecords []*types.Blame, found bool) { +func (k Keeper) GetBlamesByChainAndNonce( + ctx sdk.Context, + chainID int64, + nonce int64, +) (BlameRecords []*types.Blame, found bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.BlameKey)) blamePrefix := types.GetBlamePrefix(chainID, nonce) iterator := sdk.KVStorePrefixIterator(store, []byte(blamePrefix)) diff --git a/x/observer/keeper/events.go b/x/observer/keeper/events.go index fc249560a1..3332f7edaa 100644 --- a/x/observer/keeper/events.go +++ b/x/observer/keeper/events.go @@ -32,7 +32,11 @@ func EmitEventKeyGenBlockUpdated(ctx sdk.Context, keygen *types.Keygen) { } } -func EmitEventAddObserver(ctx sdk.Context, observerCount uint64, operatorAddress, zetaclientGranteeAddress, zetaclientGranteePubkey string) { +func EmitEventAddObserver( + ctx sdk.Context, + observerCount uint64, + operatorAddress, zetaclientGranteeAddress, zetaclientGranteePubkey string, +) { err := ctx.EventManager().EmitTypedEvents(&types.EventNewObserverAdded{ MsgTypeUrl: sdk.MsgTypeURL(&types.MsgAddObserver{}), ObserverAddress: operatorAddress, diff --git a/x/observer/keeper/grpc_query_ballot.go b/x/observer/keeper/grpc_query_ballot.go index 4bd0e6c6ff..2f44ef27bb 100644 --- a/x/observer/keeper/grpc_query_ballot.go +++ b/x/observer/keeper/grpc_query_ballot.go @@ -27,7 +27,10 @@ func (k Keeper) HasVoted(goCtx context.Context, req *types.QueryHasVotedRequest) }, nil } -func (k Keeper) BallotByIdentifier(goCtx context.Context, req *types.QueryBallotByIdentifierRequest) (*types.QueryBallotByIdentifierResponse, error) { +func (k Keeper) BallotByIdentifier( + goCtx context.Context, + req *types.QueryBallotByIdentifierRequest, +) (*types.QueryBallotByIdentifierResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_blame.go b/x/observer/keeper/grpc_query_blame.go index e0cb709772..18b58e9d13 100644 --- a/x/observer/keeper/grpc_query_blame.go +++ b/x/observer/keeper/grpc_query_blame.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) BlameByIdentifier(goCtx context.Context, request *types.QueryBlameByIdentifierRequest) (*types.QueryBlameByIdentifierResponse, error) { +func (k Keeper) BlameByIdentifier( + goCtx context.Context, + request *types.QueryBlameByIdentifierRequest, +) (*types.QueryBlameByIdentifierResponse, error) { if request == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -24,7 +27,10 @@ func (k Keeper) BlameByIdentifier(goCtx context.Context, request *types.QueryBla }, nil } -func (k Keeper) GetAllBlameRecords(goCtx context.Context, request *types.QueryAllBlameRecordsRequest) (*types.QueryAllBlameRecordsResponse, error) { +func (k Keeper) GetAllBlameRecords( + goCtx context.Context, + request *types.QueryAllBlameRecordsRequest, +) (*types.QueryAllBlameRecordsResponse, error) { if request == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -40,7 +46,10 @@ func (k Keeper) GetAllBlameRecords(goCtx context.Context, request *types.QueryAl }, nil } -func (k Keeper) BlamesByChainAndNonce(goCtx context.Context, request *types.QueryBlameByChainAndNonceRequest) (*types.QueryBlameByChainAndNonceResponse, error) { +func (k Keeper) BlamesByChainAndNonce( + goCtx context.Context, + request *types.QueryBlameByChainAndNonceRequest, +) (*types.QueryBlameByChainAndNonceResponse, error) { if request == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_crosschain_flags.go b/x/observer/keeper/grpc_query_crosschain_flags.go index 9444ec6a3f..af90aed65b 100644 --- a/x/observer/keeper/grpc_query_crosschain_flags.go +++ b/x/observer/keeper/grpc_query_crosschain_flags.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) CrosschainFlags(c context.Context, req *types.QueryGetCrosschainFlagsRequest) (*types.QueryGetCrosschainFlagsResponse, error) { +func (k Keeper) CrosschainFlags( + c context.Context, + req *types.QueryGetCrosschainFlagsRequest, +) (*types.QueryGetCrosschainFlagsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_node_account.go b/x/observer/keeper/grpc_query_node_account.go index 44aa499757..7d4b0bb6b9 100644 --- a/x/observer/keeper/grpc_query_node_account.go +++ b/x/observer/keeper/grpc_query_node_account.go @@ -11,7 +11,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) NodeAccountAll(c context.Context, req *types.QueryAllNodeAccountRequest) (*types.QueryAllNodeAccountResponse, error) { +func (k Keeper) NodeAccountAll( + c context.Context, + req *types.QueryAllNodeAccountRequest, +) (*types.QueryAllNodeAccountResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -39,7 +42,10 @@ func (k Keeper) NodeAccountAll(c context.Context, req *types.QueryAllNodeAccount return &types.QueryAllNodeAccountResponse{NodeAccount: nodeAccounts, Pagination: pageRes}, nil } -func (k Keeper) NodeAccount(c context.Context, req *types.QueryGetNodeAccountRequest) (*types.QueryGetNodeAccountResponse, error) { +func (k Keeper) NodeAccount( + c context.Context, + req *types.QueryGetNodeAccountRequest, +) (*types.QueryGetNodeAccountResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_nonces.go b/x/observer/keeper/grpc_query_nonces.go index 80ff3a23b2..733c96bb9d 100644 --- a/x/observer/keeper/grpc_query_nonces.go +++ b/x/observer/keeper/grpc_query_nonces.go @@ -14,7 +14,10 @@ import ( // Chain nonces queries -func (k Keeper) ChainNoncesAll(c context.Context, req *types.QueryAllChainNoncesRequest) (*types.QueryAllChainNoncesResponse, error) { +func (k Keeper) ChainNoncesAll( + c context.Context, + req *types.QueryAllChainNoncesRequest, +) (*types.QueryAllChainNoncesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -42,7 +45,10 @@ func (k Keeper) ChainNoncesAll(c context.Context, req *types.QueryAllChainNonces return &types.QueryAllChainNoncesResponse{ChainNonces: chainNoncess, Pagination: pageRes}, nil } -func (k Keeper) ChainNonces(c context.Context, req *types.QueryGetChainNoncesRequest) (*types.QueryGetChainNoncesResponse, error) { +func (k Keeper) ChainNonces( + c context.Context, + req *types.QueryGetChainNoncesRequest, +) (*types.QueryGetChainNoncesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -58,7 +64,10 @@ func (k Keeper) ChainNonces(c context.Context, req *types.QueryGetChainNoncesReq // Pending nonces queries -func (k Keeper) PendingNoncesAll(c context.Context, req *types.QueryAllPendingNoncesRequest) (*types.QueryAllPendingNoncesResponse, error) { +func (k Keeper) PendingNoncesAll( + c context.Context, + req *types.QueryAllPendingNoncesRequest, +) (*types.QueryAllPendingNoncesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -74,7 +83,10 @@ func (k Keeper) PendingNoncesAll(c context.Context, req *types.QueryAllPendingNo }, nil } -func (k Keeper) PendingNoncesByChain(c context.Context, req *types.QueryPendingNoncesByChainRequest) (*types.QueryPendingNoncesByChainResponse, error) { +func (k Keeper) PendingNoncesByChain( + c context.Context, + req *types.QueryPendingNoncesByChainRequest, +) (*types.QueryPendingNoncesByChainResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_observer.go b/x/observer/keeper/grpc_query_observer.go index d588aae96e..8788922798 100644 --- a/x/observer/keeper/grpc_query_observer.go +++ b/x/observer/keeper/grpc_query_observer.go @@ -9,7 +9,10 @@ import ( "google.golang.org/grpc/status" ) -func (k Keeper) ShowObserverCount(goCtx context.Context, req *types.QueryShowObserverCountRequest) (*types.QueryShowObserverCountResponse, error) { +func (k Keeper) ShowObserverCount( + goCtx context.Context, + req *types.QueryShowObserverCountRequest, +) (*types.QueryShowObserverCountResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -26,7 +29,10 @@ func (k Keeper) ShowObserverCount(goCtx context.Context, req *types.QueryShowObs }, nil } -func (k Keeper) ObserverSet(goCtx context.Context, req *types.QueryObserverSet) (*types.QueryObserverSetResponse, error) { +func (k Keeper) ObserverSet( + goCtx context.Context, + req *types.QueryObserverSet, +) (*types.QueryObserverSetResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/grpc_query_supported_chain.go b/x/observer/keeper/grpc_query_supported_chain.go index dbd985d53c..5d5d2c7d00 100644 --- a/x/observer/keeper/grpc_query_supported_chain.go +++ b/x/observer/keeper/grpc_query_supported_chain.go @@ -7,7 +7,10 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -func (k Keeper) SupportedChains(goCtx context.Context, _ *types.QuerySupportedChains) (*types.QuerySupportedChainsResponse, error) { +func (k Keeper) SupportedChains( + goCtx context.Context, + _ *types.QuerySupportedChains, +) (*types.QuerySupportedChainsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) chains := k.GetSupportedChains(ctx) return &types.QuerySupportedChainsResponse{Chains: chains}, nil diff --git a/x/observer/keeper/grpc_query_tss.go b/x/observer/keeper/grpc_query_tss.go index 0b6f4a7614..5db1344329 100644 --- a/x/observer/keeper/grpc_query_tss.go +++ b/x/observer/keeper/grpc_query_tss.go @@ -37,7 +37,10 @@ func (k Keeper) TssHistory(c context.Context, _ *types.QueryTssHistoryRequest) ( return &types.QueryTssHistoryResponse{TssList: tssList}, nil } -func (k Keeper) GetTssAddress(goCtx context.Context, req *types.QueryGetTssAddressRequest) (*types.QueryGetTssAddressResponse, error) { +func (k Keeper) GetTssAddress( + goCtx context.Context, + req *types.QueryGetTssAddressRequest, +) (*types.QueryGetTssAddressResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -68,7 +71,10 @@ func (k Keeper) GetTssAddress(goCtx context.Context, req *types.QueryGetTssAddre }, nil } -func (k Keeper) GetTssAddressByFinalizedHeight(goCtx context.Context, req *types.QueryGetTssAddressByFinalizedHeightRequest) (*types.QueryGetTssAddressByFinalizedHeightResponse, error) { +func (k Keeper) GetTssAddressByFinalizedHeight( + goCtx context.Context, + req *types.QueryGetTssAddressByFinalizedHeightRequest, +) (*types.QueryGetTssAddressByFinalizedHeightResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/observer/keeper/hooks.go b/x/observer/keeper/hooks.go index b6955df0ce..8d1714c8ff 100644 --- a/x/observer/keeper/hooks.go +++ b/x/observer/keeper/hooks.go @@ -122,7 +122,11 @@ func (k Keeper) CheckAndCleanObserver(ctx sdk.Context, valAddress sdk.ValAddress // CheckAndCleanObserverDelegator first checks if the delegation is self delegation, // if it is, then it checks if the total delegation is sufficient after the delegation is removed, // if not it removes the observer from the set -func (k Keeper) CheckAndCleanObserverDelegator(ctx sdk.Context, valAddress sdk.ValAddress, delAddress sdk.AccAddress) error { +func (k Keeper) CheckAndCleanObserverDelegator( + ctx sdk.Context, + valAddress sdk.ValAddress, + delAddress sdk.AccAddress, +) error { accAddress, err := types.GetAccAddressFromOperatorAddress(valAddress.String()) if err != nil { return err diff --git a/x/observer/keeper/msg_server_add_blame_vote.go b/x/observer/keeper/msg_server_add_blame_vote.go index 452a15c56a..9ab3942daf 100644 --- a/x/observer/keeper/msg_server_add_blame_vote.go +++ b/x/observer/keeper/msg_server_add_blame_vote.go @@ -10,14 +10,20 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -func (k msgServer) AddBlameVote(goCtx context.Context, vote *types.MsgAddBlameVote) (*types.MsgAddBlameVoteResponse, error) { +func (k msgServer) AddBlameVote( + goCtx context.Context, + vote *types.MsgAddBlameVote, +) (*types.MsgAddBlameVoteResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) observationType := types.ObservationType_TSSKeySign // GetChainFromChainID makes sure we are getting only supported chains , if a chain support has been turned on using gov proposal, this function returns nil observationChain := k.GetSupportedChainFromChainID(ctx, vote.ChainId) if observationChain == nil { - return nil, cosmoserrors.Wrap(crosschainTypes.ErrUnsupportedChain, fmt.Sprintf("ChainID %d, Blame vote", vote.ChainId)) + return nil, cosmoserrors.Wrap( + crosschainTypes.ErrUnsupportedChain, + fmt.Sprintf("ChainID %d, Blame vote", vote.ChainId), + ) } if ok := k.IsNonTombstonedObserver(ctx, vote.Creator); !ok { diff --git a/x/observer/keeper/msg_server_add_observer.go b/x/observer/keeper/msg_server_add_observer.go index c725516ccd..89295cbedf 100644 --- a/x/observer/keeper/msg_server_add_observer.go +++ b/x/observer/keeper/msg_server_add_observer.go @@ -14,7 +14,10 @@ import ( ) // AddObserver adds an observer address to the observer set -func (k msgServer) AddObserver(goCtx context.Context, msg *types.MsgAddObserver) (*types.MsgAddObserverResponse, error) { +func (k msgServer) AddObserver( + goCtx context.Context, + msg *types.MsgAddObserver, +) (*types.MsgAddObserverResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission @@ -53,7 +56,13 @@ func (k msgServer) AddObserver(goCtx context.Context, msg *types.MsgAddObserver) observerSet, _ := k.GetObserverSet(ctx) k.SetLastObserverCount(ctx, &types.LastObserverCount{Count: observerSet.LenUint()}) - EmitEventAddObserver(ctx, observerSet.LenUint(), msg.ObserverAddress, granteeAddress.String(), msg.ZetaclientGranteePubkey) + EmitEventAddObserver( + ctx, + observerSet.LenUint(), + msg.ObserverAddress, + granteeAddress.String(), + msg.ZetaclientGranteePubkey, + ) return &types.MsgAddObserverResponse{}, nil } diff --git a/x/observer/keeper/msg_server_remove_chain_params.go b/x/observer/keeper/msg_server_remove_chain_params.go index 8124f534c7..6071ad10dd 100644 --- a/x/observer/keeper/msg_server_remove_chain_params.go +++ b/x/observer/keeper/msg_server_remove_chain_params.go @@ -9,7 +9,10 @@ import ( ) // RemoveChainParams removes chain parameters for a specific chain. -func (k msgServer) RemoveChainParams(goCtx context.Context, msg *types.MsgRemoveChainParams) (*types.MsgRemoveChainParamsResponse, error) { +func (k msgServer) RemoveChainParams( + goCtx context.Context, + msg *types.MsgRemoveChainParams, +) (*types.MsgRemoveChainParamsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission diff --git a/x/observer/keeper/msg_server_reset_chain_nonces.go b/x/observer/keeper/msg_server_reset_chain_nonces.go index 853ef1ad16..1ebf1855a7 100644 --- a/x/observer/keeper/msg_server_reset_chain_nonces.go +++ b/x/observer/keeper/msg_server_reset_chain_nonces.go @@ -10,7 +10,10 @@ import ( ) // ResetChainNonces handles resetting chain nonces -func (k msgServer) ResetChainNonces(goCtx context.Context, msg *types.MsgResetChainNonces) (*types.MsgResetChainNoncesResponse, error) { +func (k msgServer) ResetChainNonces( + goCtx context.Context, + msg *types.MsgResetChainNonces, +) (*types.MsgResetChainNoncesResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupOperational) { return &types.MsgResetChainNoncesResponse{}, authoritytypes.ErrUnauthorized diff --git a/x/observer/keeper/msg_server_update_chain_params.go b/x/observer/keeper/msg_server_update_chain_params.go index 011f5d0786..369a210eca 100644 --- a/x/observer/keeper/msg_server_update_chain_params.go +++ b/x/observer/keeper/msg_server_update_chain_params.go @@ -12,7 +12,10 @@ import ( // Chain parameters include: confirmation count, outbound transaction schedule interval, ZETA token, // connector and ERC20 custody contract addresses, etc. // Only the admin policy account is authorized to broadcast this message. -func (k msgServer) UpdateChainParams(goCtx context.Context, msg *types.MsgUpdateChainParams) (*types.MsgUpdateChainParamsResponse, error) { +func (k msgServer) UpdateChainParams( + goCtx context.Context, + msg *types.MsgUpdateChainParams, +) (*types.MsgUpdateChainParamsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission diff --git a/x/observer/keeper/msg_server_update_crosschain_flags.go b/x/observer/keeper/msg_server_update_crosschain_flags.go index cbdc2b29ac..166f165ece 100644 --- a/x/observer/keeper/msg_server_update_crosschain_flags.go +++ b/x/observer/keeper/msg_server_update_crosschain_flags.go @@ -13,7 +13,10 @@ import ( // // Aurthorized: admin policy group 1 (except enabling/disabled // inbounds/outbounds and gas price increase), admin policy group 2 (all). -func (k msgServer) UpdateCrosschainFlags(goCtx context.Context, msg *types.MsgUpdateCrosschainFlags) (*types.MsgUpdateCrosschainFlagsResponse, error) { +func (k msgServer) UpdateCrosschainFlags( + goCtx context.Context, + msg *types.MsgUpdateCrosschainFlags, +) (*types.MsgUpdateCrosschainFlagsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission diff --git a/x/observer/keeper/msg_server_update_crosschain_flags_test.go b/x/observer/keeper/msg_server_update_crosschain_flags_test.go index 4d399ba89b..e8d3819915 100644 --- a/x/observer/keeper/msg_server_update_crosschain_flags_test.go +++ b/x/observer/keeper/msg_server_update_crosschain_flags_test.go @@ -126,7 +126,11 @@ func TestMsgServer_UpdateCrosschainFlags(t *testing.T) { require.True(t, flags.IsOutboundEnabled) require.Equal(t, types.DefaultGasPriceIncreaseFlags.EpochLength, flags.GasPriceIncreaseFlags.EpochLength) require.Equal(t, types.DefaultGasPriceIncreaseFlags.RetryInterval, flags.GasPriceIncreaseFlags.RetryInterval) - require.Equal(t, types.DefaultGasPriceIncreaseFlags.GasPriceIncreasePercent, flags.GasPriceIncreaseFlags.GasPriceIncreasePercent) + require.Equal( + t, + types.DefaultGasPriceIncreaseFlags.GasPriceIncreasePercent, + flags.GasPriceIncreaseFlags.GasPriceIncreasePercent, + ) }) t.Run("cannot update crosschain flags if not authorized", func(t *testing.T) { diff --git a/x/observer/keeper/msg_server_update_keygen.go b/x/observer/keeper/msg_server_update_keygen.go index ecd76362c6..1bf4f7a47d 100644 --- a/x/observer/keeper/msg_server_update_keygen.go +++ b/x/observer/keeper/msg_server_update_keygen.go @@ -13,7 +13,10 @@ import ( // "pending keygen". // // Authorized: admin policy group 1. -func (k msgServer) UpdateKeygen(goCtx context.Context, msg *types.MsgUpdateKeygen) (*types.MsgUpdateKeygenResponse, error) { +func (k msgServer) UpdateKeygen( + goCtx context.Context, + msg *types.MsgUpdateKeygen, +) (*types.MsgUpdateKeygenResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check permission diff --git a/x/observer/keeper/msg_server_update_observer.go b/x/observer/keeper/msg_server_update_observer.go index b3046b1d9f..5f0328150f 100644 --- a/x/observer/keeper/msg_server_update_observer.go +++ b/x/observer/keeper/msg_server_update_observer.go @@ -14,7 +14,10 @@ import ( // UpdateObserver handles updating an observer address // Authorized: admin policy (admin update), old observer address (if the // reason is that the observer was tombstoned). -func (k msgServer) UpdateObserver(goCtx context.Context, msg *types.MsgUpdateObserver) (*types.MsgUpdateObserverResponse, error) { +func (k msgServer) UpdateObserver( + goCtx context.Context, + msg *types.MsgUpdateObserver, +) (*types.MsgUpdateObserverResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) ok, err := k.CheckUpdateReason(ctx, msg) @@ -22,12 +25,18 @@ func (k msgServer) UpdateObserver(goCtx context.Context, msg *types.MsgUpdateObs return nil, errorsmod.Wrap(types.ErrUpdateObserver, err.Error()) } if !ok { - return nil, errorsmod.Wrap(types.ErrUpdateObserver, fmt.Sprintf("Unable to update observer with update reason : %s", msg.UpdateReason)) + return nil, errorsmod.Wrap( + types.ErrUpdateObserver, + fmt.Sprintf("Unable to update observer with update reason : %s", msg.UpdateReason), + ) } // We do not use IsNonTombstonedObserver here because we want to allow tombstoned observers to be updated if !k.IsAddressPartOfObserverSet(ctx, msg.OldObserverAddress) { - return nil, errorsmod.Wrap(types.ErrNotObserver, fmt.Sprintf("Observer address is not authorized : %s", msg.OldObserverAddress)) + return nil, errorsmod.Wrap( + types.ErrNotObserver, + fmt.Sprintf("Observer address is not authorized : %s", msg.OldObserverAddress), + ) } err = k.IsValidator(ctx, msg.NewObserverAddress) @@ -44,7 +53,10 @@ func (k msgServer) UpdateObserver(goCtx context.Context, msg *types.MsgUpdateObs // Update the node account with the new operator address nodeAccount, found := k.GetNodeAccount(ctx, msg.OldObserverAddress) if !found { - return nil, errorsmod.Wrap(types.ErrNodeAccountNotFound, fmt.Sprintf("Observer node account not found : %s", msg.OldObserverAddress)) + return nil, errorsmod.Wrap( + types.ErrNodeAccountNotFound, + fmt.Sprintf("Observer node account not found : %s", msg.OldObserverAddress), + ) } newNodeAccount := nodeAccount newNodeAccount.Operator = msg.NewObserverAddress @@ -74,7 +86,12 @@ func (k Keeper) CheckUpdateReason(ctx sdk.Context, msg *types.MsgUpdateObserver) case types.ObserverUpdateReason_Tombstoned: { if msg.Creator != msg.OldObserverAddress { - return false, errorsmod.Wrap(types.ErrUpdateObserver, fmt.Sprintf("Creator address and old observer address need to be same for updating tombstoned observer")) + return false, errorsmod.Wrap( + types.ErrUpdateObserver, + fmt.Sprintf( + "Creator address and old observer address need to be same for updating tombstoned observer", + ), + ) } return k.IsOperatorTombstoned(ctx, msg.Creator) } diff --git a/x/observer/keeper/msg_server_vote_block_header.go b/x/observer/keeper/msg_server_vote_block_header.go index a9050e7ebc..e62babe38f 100644 --- a/x/observer/keeper/msg_server_vote_block_header.go +++ b/x/observer/keeper/msg_server_vote_block_header.go @@ -10,7 +10,10 @@ import ( ) // VoteBlockHeader vote for a new block header to the storers -func (k msgServer) VoteBlockHeader(goCtx context.Context, msg *types.MsgVoteBlockHeader) (*types.MsgVoteBlockHeaderResponse, error) { +func (k msgServer) VoteBlockHeader( + goCtx context.Context, + msg *types.MsgVoteBlockHeader, +) (*types.MsgVoteBlockHeaderResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check if the chain is enabled diff --git a/x/observer/keeper/msg_server_vote_tss.go b/x/observer/keeper/msg_server_vote_tss.go index 402a84a3db..1055249f09 100644 --- a/x/observer/keeper/msg_server_vote_tss.go +++ b/x/observer/keeper/msg_server_vote_tss.go @@ -28,7 +28,10 @@ func (k msgServer) VoteTSS(goCtx context.Context, msg *types.MsgVoteTSS) (*types // checks whether a signer is authorized to sign , by checking their address against the observer mapper which contains the observer list for the chain and type _, found := k.GetNodeAccount(ctx, msg.Creator) if !found { - return nil, errorsmod.Wrap(sdkerrors.ErrorInvalidSigner, fmt.Sprintf("signer %s does not have a node account set", msg.Creator)) + return nil, errorsmod.Wrap( + sdkerrors.ErrorInvalidSigner, + fmt.Sprintf("signer %s does not have a node account set", msg.Creator), + ) } // no need to create a ballot if keygen does not exist keygen, found := k.GetKeygen(ctx) diff --git a/x/observer/keeper/nonce_to_cctx.go b/x/observer/keeper/nonce_to_cctx.go index 6ecedd22ea..b1ac916718 100644 --- a/x/observer/keeper/nonce_to_cctx.go +++ b/x/observer/keeper/nonce_to_cctx.go @@ -22,7 +22,12 @@ func (k Keeper) SetNonceToCctx(ctx sdk.Context, nonceToCctx types.NonceToCctx) { store.Set(types.KeyPrefix(fmt.Sprintf("%s-%d-%d", nonceToCctx.Tss, nonceToCctx.ChainId, nonceToCctx.Nonce)), b) } -func (k Keeper) GetNonceToCctx(ctx sdk.Context, tss string, chainID int64, nonce int64) (val types.NonceToCctx, found bool) { +func (k Keeper) GetNonceToCctx( + ctx sdk.Context, + tss string, + chainID int64, + nonce int64, +) (val types.NonceToCctx, found bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.NonceToCctxKeyPrefix)) b := store.Get(types.KeyPrefix(fmt.Sprintf("%s-%d-%d", tss, chainID, nonce))) diff --git a/x/observer/keeper/nonce_to_cctx_test.go b/x/observer/keeper/nonce_to_cctx_test.go index e72d076a1e..554661c1ff 100644 --- a/x/observer/keeper/nonce_to_cctx_test.go +++ b/x/observer/keeper/nonce_to_cctx_test.go @@ -38,7 +38,12 @@ func TestKeeper_GetNonceToCctx(t *testing.T) { CctxIndex: "0x705b88814b2a049e75b591fd80595c53f3bd9ddfb67ad06aa6965ed91023ee9a", Tss: "zetapub1addwnpepq0akz8ene4z2mg3tghamr0m5eg3eeuqtjcfamkh5ecetua9u0pcyvjeyerd", }) - _, found := k.GetNonceToCctx(ctx, "zetapub1addwnpepq0akz8ene4z2mg3tghamr0m5eg3eeuqtjcfamkh5ecetua9u0pcyvjeyerd", 1337, 0) + _, found := k.GetNonceToCctx( + ctx, + "zetapub1addwnpepq0akz8ene4z2mg3tghamr0m5eg3eeuqtjcfamkh5ecetua9u0pcyvjeyerd", + 1337, + 0, + ) require.True(t, found) }) t.Run("Get nonce to cctx not found", func(t *testing.T) { diff --git a/x/observer/keeper/pending_nonces.go b/x/observer/keeper/pending_nonces.go index 34f241a10e..87f1f89c23 100644 --- a/x/observer/keeper/pending_nonces.go +++ b/x/observer/keeper/pending_nonces.go @@ -30,7 +30,10 @@ func (k Keeper) GetPendingNonces(ctx sdk.Context, tss string, chainID int64) (va return val, true } -func (k Keeper) GetAllPendingNoncesPaginated(ctx sdk.Context, pagination *query.PageRequest) (list []types.PendingNonces, pageRes *query.PageResponse, err error) { +func (k Keeper) GetAllPendingNoncesPaginated( + ctx sdk.Context, + pagination *query.PageRequest, +) (list []types.PendingNonces, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.PendingNoncesKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) diff --git a/x/observer/keeper/pending_nonces_test.go b/x/observer/keeper/pending_nonces_test.go index 37ff74fb22..7062c79e30 100644 --- a/x/observer/keeper/pending_nonces_test.go +++ b/x/observer/keeper/pending_nonces_test.go @@ -38,7 +38,10 @@ func TestKeeper_PendingNoncesAll(t *testing.T) { k.SetPendingNonces(ctx, nonce) } offset := 10 - rst, pageRes, err := k.GetAllPendingNoncesPaginated(ctx, &query.PageRequest{Offset: uint64(offset), CountTotal: true}) + rst, pageRes, err := k.GetAllPendingNoncesPaginated( + ctx, + &query.PageRequest{Offset: uint64(offset), CountTotal: true}, + ) require.NoError(t, err) sort.SliceStable(rst, func(i, j int) bool { return rst[i].ChainId < rst[j].ChainId diff --git a/x/observer/keeper/tss.go b/x/observer/keeper/tss.go index 43eaed47c5..b47aeed381 100644 --- a/x/observer/keeper/tss.go +++ b/x/observer/keeper/tss.go @@ -79,7 +79,10 @@ func (k Keeper) GetAllTSS(ctx sdk.Context) (list []types.TSS) { return } -func (k Keeper) GetAllTSSPaginated(ctx sdk.Context, pagination *query.PageRequest) (list []types.TSS, pageRes *query.PageResponse, err error) { +func (k Keeper) GetAllTSSPaginated( + ctx sdk.Context, + pagination *query.PageRequest, +) (list []types.TSS, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TSSHistoryKey)) pageRes, err = query.Paginate(store, pagination, func(_ []byte, value []byte) error { var tss types.TSS diff --git a/x/observer/keeper/utils.go b/x/observer/keeper/utils.go index ca3fc00f55..065b55f4ac 100644 --- a/x/observer/keeper/utils.go +++ b/x/observer/keeper/utils.go @@ -8,7 +8,12 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -func (k Keeper) AddVoteToBallot(ctx sdk.Context, ballot types.Ballot, address string, observationType types.VoteType) (types.Ballot, error) { +func (k Keeper) AddVoteToBallot( + ctx sdk.Context, + ballot types.Ballot, + address string, + observationType types.VoteType, +) (types.Ballot, error) { ballot, err := ballot.AddVote(address, observationType) if err != nil { return ballot, err diff --git a/x/observer/types/ballot.go b/x/observer/types/ballot.go index 71512c9f11..2ddab67ec6 100644 --- a/x/observer/types/ballot.go +++ b/x/observer/types/ballot.go @@ -9,7 +9,10 @@ import ( func (m Ballot) AddVote(address string, vote VoteType) (Ballot, error) { if m.HasVoted(address) { - return m, cosmoserrors.Wrap(ErrUnableToAddVote, fmt.Sprintf(" Voter : %s | Ballot :%s | Already Voted", address, m.String())) + return m, cosmoserrors.Wrap( + ErrUnableToAddVote, + fmt.Sprintf(" Voter : %s | Ballot :%s | Already Voted", address, m.String()), + ) } // `index` is the index of the `address` in the `VoterList` // `index` is used to set the vote in the `Votes` array diff --git a/x/observer/types/ballot_test.go b/x/observer/types/ballot_test.go index 322affd728..089e2e764c 100644 --- a/x/observer/types/ballot_test.go +++ b/x/observer/types/ballot_test.go @@ -33,7 +33,12 @@ func TestBallot_AddVote(t *testing.T) { {"Observer3", VoteType_SuccessObservation}, {"Observer4", VoteType_SuccessObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + }, finalStatus: BallotStatus_BallotFinalized_SuccessObservation, isFinalized: true, }, @@ -48,7 +53,12 @@ func TestBallot_AddVote(t *testing.T) { {"Observer3", VoteType_SuccessObservation}, {"Observer4", VoteType_SuccessObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + }, finalStatus: BallotStatus_BallotFinalized_SuccessObservation, isFinalized: true, }, @@ -63,14 +73,32 @@ func TestBallot_AddVote(t *testing.T) { {"Observer1", VoteType_SuccessObservation}, {"Observer1", VoteType_SuccessObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_NotYetVoted, VoteType_NotYetVoted, VoteType_NotYetVoted}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_NotYetVoted, + VoteType_NotYetVoted, + VoteType_NotYetVoted, + }, finalStatus: BallotStatus_BallotInProgress, isFinalized: false, }, { name: "Ballot finalized at threshold", threshold: sdk.MustNewDecFromStr("0.66"), - voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4", "Observer5", "Observer6", "Observer7", "Observer8", "Observer9", "Observer10", "Observer11", "Observer12"}, + voterList: []string{ + "Observer1", + "Observer2", + "Observer3", + "Observer4", + "Observer5", + "Observer6", + "Observer7", + "Observer8", + "Observer9", + "Observer10", + "Observer11", + "Observer12", + }, votes: []votes{ {"Observer1", VoteType_SuccessObservation}, {"Observer2", VoteType_SuccessObservation}, @@ -104,7 +132,20 @@ func TestBallot_AddVote(t *testing.T) { { name: "Ballot finalized at threshold but more votes added after", threshold: sdk.MustNewDecFromStr("0.66"), - voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4", "Observer5", "Observer6", "Observer7", "Observer8", "Observer9", "Observer10", "Observer11", "Observer12"}, + voterList: []string{ + "Observer1", + "Observer2", + "Observer3", + "Observer4", + "Observer5", + "Observer6", + "Observer7", + "Observer8", + "Observer9", + "Observer10", + "Observer11", + "Observer12", + }, votes: []votes{ {"Observer1", VoteType_SuccessObservation}, {"Observer2", VoteType_SuccessObservation}, @@ -157,7 +198,12 @@ func TestBallot_AddVote(t *testing.T) { {"Observer3", VoteType_SuccessObservation}, {"Observer4", VoteType_FailureObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_FailureObservation}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_FailureObservation, + }, finalStatus: BallotStatus_BallotFinalized_FailureObservation, isFinalized: true, }, @@ -171,7 +217,12 @@ func TestBallot_AddVote(t *testing.T) { {"Observer3", VoteType_SuccessObservation}, {"Observer4", VoteType_SuccessObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_FailureObservation, VoteType_SuccessObservation, VoteType_SuccessObservation}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_FailureObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + }, finalStatus: BallotStatus_BallotFinalized_FailureObservation, isFinalized: true, }, @@ -185,7 +236,12 @@ func TestBallot_AddVote(t *testing.T) { {"Observer3", VoteType_SuccessObservation}, {"Observer4", VoteType_SuccessObservation}, }, - finalVotes: []VoteType{VoteType_SuccessObservation, VoteType_FailureObservation, VoteType_SuccessObservation, VoteType_SuccessObservation}, + finalVotes: []VoteType{ + VoteType_SuccessObservation, + VoteType_FailureObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + }, finalStatus: BallotStatus_BallotInProgress, isFinalized: false, }, @@ -370,9 +426,14 @@ func Test_BuildRewardsDistribution(t *testing.T) { expectedMap map[string]int64 }{ { - name: "BallotFinalized_SuccessObservation", - voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4"}, - votes: []VoteType{VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_FailureObservation}, + name: "BallotFinalized_SuccessObservation", + voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4"}, + votes: []VoteType{ + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_FailureObservation, + }, ballotStatus: BallotStatus_BallotFinalized_SuccessObservation, expectedMap: map[string]int64{ "Observer1": 1, @@ -382,9 +443,14 @@ func Test_BuildRewardsDistribution(t *testing.T) { }, }, { - name: "BallotFinalized_FailureObservation", - voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4"}, - votes: []VoteType{VoteType_SuccessObservation, VoteType_SuccessObservation, VoteType_FailureObservation, VoteType_FailureObservation}, + name: "BallotFinalized_FailureObservation", + voterList: []string{"Observer1", "Observer2", "Observer3", "Observer4"}, + votes: []VoteType{ + VoteType_SuccessObservation, + VoteType_SuccessObservation, + VoteType_FailureObservation, + VoteType_FailureObservation, + }, ballotStatus: BallotStatus_BallotFinalized_FailureObservation, expectedMap: map[string]int64{ "Observer1": -1, diff --git a/x/observer/types/chain_params.go b/x/observer/types/chain_params.go index 7dd2e5335e..5b0d2d39a3 100644 --- a/x/observer/types/chain_params.go +++ b/x/observer/types/chain_params.go @@ -76,27 +76,51 @@ func ValidateChainParams(params *ChainParams) error { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutTxTicker %d out of range", params.OutTxTicker) } if params.OutboundTxScheduleInterval == 0 || params.OutboundTxScheduleInterval > 100 { // 600 secs - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutboundTxScheduleInterval %d out of range", params.OutboundTxScheduleInterval) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "OutboundTxScheduleInterval %d out of range", + params.OutboundTxScheduleInterval, + ) } if params.OutboundTxScheduleLookahead == 0 || params.OutboundTxScheduleLookahead > 500 { // 500 cctxs - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutboundTxScheduleLookahead %d out of range", params.OutboundTxScheduleLookahead) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "OutboundTxScheduleLookahead %d out of range", + params.OutboundTxScheduleLookahead, + ) } // chain type specific checks if chains.IsBitcoinChain(params.ChainId) { if params.WatchUtxoTicker == 0 || params.WatchUtxoTicker > 300 { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "WatchUtxoTicker %d out of range", params.WatchUtxoTicker) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "WatchUtxoTicker %d out of range", + params.WatchUtxoTicker, + ) } } if chains.IsEVMChain(params.ChainId) { if !validChainContractAddress(params.ZetaTokenContractAddress) { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "invalid ZetaTokenContractAddress %s", params.ZetaTokenContractAddress) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid ZetaTokenContractAddress %s", + params.ZetaTokenContractAddress, + ) } if !validChainContractAddress(params.ConnectorContractAddress) { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "invalid ConnectorContractAddress %s", params.ConnectorContractAddress) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid ConnectorContractAddress %s", + params.ConnectorContractAddress, + ) } if !validChainContractAddress(params.Erc20CustodyContractAddress) { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "invalid Erc20CustodyContractAddress %s", params.Erc20CustodyContractAddress) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid Erc20CustodyContractAddress %s", + params.Erc20CustodyContractAddress, + ) } } diff --git a/x/observer/types/errors.go b/x/observer/types/errors.go index 1c03f9bbf9..6485e613ed 100644 --- a/x/observer/types/errors.go +++ b/x/observer/types/errors.go @@ -12,13 +12,29 @@ var ( ErrSupportedChains = errorsmod.Register(ModuleName, 1102, "chain not supported") ErrInvalidStatus = errorsmod.Register(ModuleName, 1103, "invalid Voting Status") - ErrNotValidator = errorsmod.Register(ModuleName, 1106, "user needs to be a validator before applying to become an observer") - ErrValidatorStatus = errorsmod.Register(ModuleName, 1107, "corresponding validator needs to be bonded and not jailed") - ErrInvalidAddress = errorsmod.Register(ModuleName, 1108, "invalid Address") - ErrSelfDelegation = errorsmod.Register(ModuleName, 1109, "self Delegation for operator not found") - ErrKeygenNotFound = errorsmod.Register(ModuleName, 1113, "Keygen not found, Keygen block can only be updated,New keygen cannot be set") - ErrKeygenBlockTooLow = errorsmod.Register(ModuleName, 1114, "please set a block number at-least 10 blocks higher than the current block number") - ErrKeygenCompleted = errorsmod.Register(ModuleName, 1115, "keygen already completed") + ErrNotValidator = errorsmod.Register( + ModuleName, + 1106, + "user needs to be a validator before applying to become an observer", + ) + ErrValidatorStatus = errorsmod.Register( + ModuleName, + 1107, + "corresponding validator needs to be bonded and not jailed", + ) + ErrInvalidAddress = errorsmod.Register(ModuleName, 1108, "invalid Address") + ErrSelfDelegation = errorsmod.Register(ModuleName, 1109, "self Delegation for operator not found") + ErrKeygenNotFound = errorsmod.Register( + ModuleName, + 1113, + "Keygen not found, Keygen block can only be updated,New keygen cannot be set", + ) + ErrKeygenBlockTooLow = errorsmod.Register( + ModuleName, + 1114, + "please set a block number at-least 10 blocks higher than the current block number", + ) + ErrKeygenCompleted = errorsmod.Register(ModuleName, 1115, "keygen already completed") ErrLastObserverCountNotFound = errorsmod.Register(ModuleName, 1123, "last observer count not found") ErrUpdateObserver = errorsmod.Register(ModuleName, 1124, "unable to update observer") diff --git a/x/observer/types/expected_keepers.go b/x/observer/types/expected_keepers.go index 74f839c4ee..f46eea7d3d 100644 --- a/x/observer/types/expected_keepers.go +++ b/x/observer/types/expected_keepers.go @@ -10,7 +10,11 @@ import ( type StakingKeeper interface { GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - GetDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation stakingtypes.Delegation, found bool) + GetDelegation( + ctx sdk.Context, + delAddr sdk.AccAddress, + valAddr sdk.ValAddress, + ) (delegation stakingtypes.Delegation, found bool) SetValidator(ctx sdk.Context, validator stakingtypes.Validator) } diff --git a/x/observer/types/message_add_observer.go b/x/observer/types/message_add_observer.go index 087636b10a..98819bbca5 100644 --- a/x/observer/types/message_add_observer.go +++ b/x/observer/types/message_add_observer.go @@ -11,7 +11,12 @@ const TypeMsgAddObserver = "add_observer" var _ sdk.Msg = &MsgAddObserver{} -func NewMsgAddObserver(creator string, observerAdresss string, zetaclientGranteePubKey string, addNodeAccountOnly bool) *MsgAddObserver { +func NewMsgAddObserver( + creator string, + observerAdresss string, + zetaclientGranteePubKey string, + addNodeAccountOnly bool, +) *MsgAddObserver { return &MsgAddObserver{ Creator: creator, ObserverAddress: observerAdresss, diff --git a/x/observer/types/message_reset_chain_nonces.go b/x/observer/types/message_reset_chain_nonces.go index c7bb615040..6deae85e79 100644 --- a/x/observer/types/message_reset_chain_nonces.go +++ b/x/observer/types/message_reset_chain_nonces.go @@ -14,7 +14,12 @@ const TypeMsgResetChainNonces = "reset_chain_nonces" var _ sdk.Msg = &MsgResetChainNonces{} -func NewMsgResetChainNonces(creator string, chainID int64, chainNonceLow int64, chainNonceHigh int64) *MsgResetChainNonces { +func NewMsgResetChainNonces( + creator string, + chainID int64, + chainNonceLow int64, + chainNonceHigh int64, +) *MsgResetChainNonces { return &MsgResetChainNonces{ Creator: creator, ChainId: chainID, diff --git a/x/observer/types/message_update_observer.go b/x/observer/types/message_update_observer.go index c6db5a1206..47c1eb33bb 100644 --- a/x/observer/types/message_update_observer.go +++ b/x/observer/types/message_update_observer.go @@ -10,7 +10,12 @@ const TypeMsgUpdateObserver = "update_observer" var _ sdk.Msg = &MsgUpdateObserver{} -func NewMsgUpdateObserver(creator string, oldObserverAddress string, newObserverAddress string, updateReason ObserverUpdateReason) *MsgUpdateObserver { +func NewMsgUpdateObserver( + creator string, + oldObserverAddress string, + newObserverAddress string, + updateReason ObserverUpdateReason, +) *MsgUpdateObserver { return &MsgUpdateObserver{ Creator: creator, OldObserverAddress: oldObserverAddress, diff --git a/x/observer/types/message_vote_block_header.go b/x/observer/types/message_vote_block_header.go index 0cc70776da..9a2863aef6 100644 --- a/x/observer/types/message_vote_block_header.go +++ b/x/observer/types/message_vote_block_header.go @@ -16,7 +16,13 @@ const ( TypeMsgVoteBlockHeader = "vote_block_header" ) -func NewMsgVoteBlockHeader(creator string, chainID int64, blockHash []byte, height int64, header proofs.HeaderData) *MsgVoteBlockHeader { +func NewMsgVoteBlockHeader( + creator string, + chainID int64, + blockHash []byte, + height int64, + header proofs.HeaderData, +) *MsgVoteBlockHeader { return &MsgVoteBlockHeader{ Creator: creator, ChainId: chainID, diff --git a/zetaclient/chains/bitcoin/fee.go b/zetaclient/chains/bitcoin/fee.go index fadabf9128..8eea83b531 100644 --- a/zetaclient/chains/bitcoin/fee.go +++ b/zetaclient/chains/bitcoin/fee.go @@ -211,7 +211,12 @@ func CalcBlockAvgFeeRate(blockVb *btcjson.GetBlockVerboseTxResult, netParams *ch } // CalcDepositorFee calculates the depositor fee for a given block -func CalcDepositorFee(blockVb *btcjson.GetBlockVerboseTxResult, chainID int64, netParams *chaincfg.Params, logger zerolog.Logger) float64 { +func CalcDepositorFee( + blockVb *btcjson.GetBlockVerboseTxResult, + chainID int64, + netParams *chaincfg.Params, + logger zerolog.Logger, +) float64 { // use default fee for regnet if chains.IsBitcoinRegnet(chainID) { return DefaultDepositorFee diff --git a/zetaclient/chains/bitcoin/fee_test.go b/zetaclient/chains/bitcoin/fee_test.go index c866efe378..9d27f9798c 100644 --- a/zetaclient/chains/bitcoin/fee_test.go +++ b/zetaclient/chains/bitcoin/fee_test.go @@ -244,7 +244,9 @@ func TestOutTxSizeXIn3Out(t *testing.T) { // Estimate the tx size // #nosec G701 always positive - vError := uint64(0.25 + float64(x)/4) // 1st witness incurs 0.25 more vByte error than others (which incurs 1/4 vByte per witness) + vError := uint64( + 0.25 + float64(x)/4, + ) // 1st witness incurs 0.25 more vByte error than others (which incurs 1/4 vByte per witness) vBytes := uint64(blockchain.GetTransactionWeight(btcutil.NewTx(tx)) / blockchain.WitnessScaleFactor) vBytesEstimated, err := EstimateOuttxSize(uint64(len(exampleTxids[:x])), []btcutil.Address{payee}) require.NoError(t, err) diff --git a/zetaclient/chains/bitcoin/observer/inbound.go b/zetaclient/chains/bitcoin/observer/inbound.go index d4ac1d727c..38ba06d8b4 100644 --- a/zetaclient/chains/bitcoin/observer/inbound.go +++ b/zetaclient/chains/bitcoin/observer/inbound.go @@ -65,7 +65,11 @@ func (ob *Observer) ObserveInTx() error { return fmt.Errorf("observeInTxBTC: block number is negative: %d", cnt) } if cnt < ob.GetLastBlockHeight() { - return fmt.Errorf("observeInTxBTC: block number should not decrease: current %d last %d", cnt, ob.GetLastBlockHeight()) + return fmt.Errorf( + "observeInTxBTC: block number should not decrease: current %d last %d", + cnt, + ob.GetLastBlockHeight(), + ) } ob.SetLastBlockHeight(cnt) @@ -129,7 +133,9 @@ func (ob *Observer) ObserveInTx() error { depositorFee, ) if err != nil { - ob.logger.InTx.Error().Err(err).Msgf("observeInTxBTC: error filtering incoming txs for block %d", blockNumber) + ob.logger.InTx.Error(). + Err(err). + Msgf("observeInTxBTC: error filtering incoming txs for block %d", blockNumber) return err // we have to re-scan this block next time } @@ -137,9 +143,15 @@ func (ob *Observer) ObserveInTx() error { for _, inTx := range inTxs { msg := ob.GetInboundVoteMessageFromBtcEvent(inTx) if msg != nil { - zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound(zetacore.PostVoteInboundGasLimit, zetacore.PostVoteInboundExecutionGasLimit, msg) + zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound( + zetacore.PostVoteInboundGasLimit, + zetacore.PostVoteInboundExecutionGasLimit, + msg, + ) if err != nil { - ob.logger.InTx.Error().Err(err).Msgf("observeInTxBTC: error posting to zetacore for tx %s", inTx.TxHash) + ob.logger.InTx.Error(). + Err(err). + Msgf("observeInTxBTC: error posting to zetacore for tx %s", inTx.TxHash) return err // we have to re-scan this block next time } else if zetaHash != "" { ob.logger.InTx.Info().Msgf("observeInTxBTC: PostVoteInbound zeta tx hash: %s inTx %s ballot %s fee %v", @@ -163,7 +175,9 @@ func (ob *Observer) ObserveInTx() error { depositorFee, ) if err != nil { - ob.logger.InTx.Error().Err(err).Msgf("observeInTxBTC: error filtering incoming txs for block %d", blockNumber) + ob.logger.InTx.Error(). + Err(err). + Msgf("observeInTxBTC: error filtering incoming txs for block %d", blockNumber) return err // we have to re-scan this block next time } @@ -171,9 +185,15 @@ func (ob *Observer) ObserveInTx() error { for _, inTx := range inTxs { msg := ob.GetInboundVoteMessageFromBtcEvent(inTx) if msg != nil { - zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound(zetacore.PostVoteInboundGasLimit, zetacore.PostVoteInboundExecutionGasLimit, msg) + zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound( + zetacore.PostVoteInboundGasLimit, + zetacore.PostVoteInboundExecutionGasLimit, + msg, + ) if err != nil { - ob.logger.InTx.Error().Err(err).Msgf("observeInTxBTC: error posting to zetacore for tx %s", inTx.TxHash) + ob.logger.InTx.Error(). + Err(err). + Msgf("observeInTxBTC: error posting to zetacore for tx %s", inTx.TxHash) return err // we have to re-scan this block next time } else if zetaHash != "" { ob.logger.InTx.Info().Msgf("observeInTxBTC: PostVoteInbound zeta tx hash: %s inTx %s ballot %s fee %v", @@ -229,12 +249,14 @@ func (ob *Observer) ProcessInboundTrackers() error { } for _, tracker := range trackers { - ob.logger.InTx.Info().Msgf("checking tracker with hash :%s and coin-type :%s ", tracker.TxHash, tracker.CoinType) + ob.logger.InTx.Info(). + Msgf("checking tracker with hash :%s and coin-type :%s ", tracker.TxHash, tracker.CoinType) ballotIdentifier, err := ob.CheckReceiptForBtcTxHash(tracker.TxHash, true) if err != nil { return err } - ob.logger.InTx.Info().Msgf("Vote submitted for inbound Tracker, Chain : %s,Ballot Identifier : %s, coin-type %s", ob.chain.ChainName, ballotIdentifier, coin.CoinType_Gas.String()) + ob.logger.InTx.Info(). + Msgf("Vote submitted for inbound Tracker, Chain : %s,Ballot Identifier : %s, coin-type %s", ob.chain.ChainName, ballotIdentifier, coin.CoinType_Gas.String()) } return nil @@ -273,7 +295,15 @@ func (ob *Observer) CheckReceiptForBtcTxHash(txHash string, vote bool) (string, } // #nosec G701 always positive - event, err := GetBtcEvent(ob.rpcClient, *tx, tss, uint64(blockVb.Height), ob.logger.InTx, ob.netParams, depositorFee) + event, err := GetBtcEvent( + ob.rpcClient, + *tx, + tss, + uint64(blockVb.Height), + ob.logger.InTx, + ob.netParams, + depositorFee, + ) if err != nil { return "", err } @@ -291,7 +321,11 @@ func (ob *Observer) CheckReceiptForBtcTxHash(txHash string, vote bool) (string, return msg.Digest(), nil } - zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound(zetacore.PostVoteInboundGasLimit, zetacore.PostVoteInboundExecutionGasLimit, msg) + zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound( + zetacore.PostVoteInboundGasLimit, + zetacore.PostVoteInboundExecutionGasLimit, + msg, + ) if err != nil { ob.logger.InTx.Error().Err(err).Msg("error posting to zetacore") return "", err @@ -414,7 +448,8 @@ func GetBtcEvent( // deposit amount has to be no less than the minimum depositor fee if vout0.Value < depositorFee { - logger.Info().Msgf("GetBtcEvent: btc deposit amount %v in txid %s is less than depositor fee %v", vout0.Value, tx.Txid, depositorFee) + logger.Info(). + Msgf("GetBtcEvent: btc deposit amount %v in txid %s is less than depositor fee %v", vout0.Value, tx.Txid, depositorFee) return nil, nil } value = vout0.Value - depositorFee diff --git a/zetaclient/chains/bitcoin/observer/inbound_test.go b/zetaclient/chains/bitcoin/observer/inbound_test.go index 7df65048b4..474242cb08 100644 --- a/zetaclient/chains/bitcoin/observer/inbound_test.go +++ b/zetaclient/chains/bitcoin/observer/inbound_test.go @@ -41,11 +41,19 @@ func createRPCClientAndLoadTx(t *testing.T, chainId int64, txHash string) *mocks func TestAvgFeeRateBlock828440(t *testing.T) { // load archived block 828440 var blockVb btcjson.GetBlockVerboseTxResult - testutils.LoadObjectFromJSONFile(t, &blockVb, path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json")) + testutils.LoadObjectFromJSONFile( + t, + &blockVb, + path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json"), + ) // https://mempool.space/block/000000000000000000025ca01d2c1094b8fd3bacc5468cc3193ced6a14618c27 var blockMb testutils.MempoolBlock - testutils.LoadObjectFromJSONFile(t, &blockMb, path.Join(TestDataDir, testutils.TestDataPathBTC, "block_mempool.space_8332_828440.json")) + testutils.LoadObjectFromJSONFile( + t, + &blockMb, + path.Join(TestDataDir, testutils.TestDataPathBTC, "block_mempool.space_8332_828440.json"), + ) gasRate, err := bitcoin.CalcBlockAvgFeeRate(&blockVb, &chaincfg.MainNetParams) require.NoError(t, err) @@ -55,7 +63,11 @@ func TestAvgFeeRateBlock828440(t *testing.T) { func TestAvgFeeRateBlock828440Errors(t *testing.T) { // load archived block 828440 var blockVb btcjson.GetBlockVerboseTxResult - testutils.LoadObjectFromJSONFile(t, &blockVb, path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json")) + testutils.LoadObjectFromJSONFile( + t, + &blockVb, + path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json"), + ) t.Run("block has no transactions", func(t *testing.T) { emptyVb := btcjson.GetBlockVerboseTxResult{Tx: []btcjson.TxRawResult{}} @@ -141,7 +153,11 @@ func TestAvgFeeRateBlock828440Errors(t *testing.T) { func TestCalcDepositorFee828440(t *testing.T) { // load archived block 828440 var blockVb btcjson.GetBlockVerboseTxResult - testutils.LoadObjectFromJSONFile(t, &blockVb, path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json")) + testutils.LoadObjectFromJSONFile( + t, + &blockVb, + path.Join(TestDataDir, testutils.TestDataPathBTC, "block_trimmed_8332_828440.json"), + ) avgGasRate := float64(32.0) // #nosec G701 test - always in range gasRate := int64(avgGasRate * clientcommon.BTCOuttxGasPriceMultiplier) @@ -236,7 +252,11 @@ func TestGetSenderAddressByVin(t *testing.T) { // vin from the archived P2PKH tx // https://mempool.space/tx/781fc8d41b476dbceca283ebff9573fda52c8fdbba5e78152aeb4432286836a7 txHash := "781fc8d41b476dbceca283ebff9573fda52c8fdbba5e78152aeb4432286836a7" - nameMsgTx := path.Join(TestDataDir, testutils.TestDataPathBTC, testutils.FileNameBTCMsgTx(chain.ChainId, txHash)) + nameMsgTx := path.Join( + TestDataDir, + testutils.TestDataPathBTC, + testutils.FileNameBTCMsgTx(chain.ChainId, txHash), + ) var msgTx wire.MsgTx testutils.LoadObjectFromJSONFile(t, &msgTx, nameMsgTx) diff --git a/zetaclient/chains/bitcoin/observer/live_test.go b/zetaclient/chains/bitcoin/observer/live_test.go index 1d9cfa1f5d..698d80d5e8 100644 --- a/zetaclient/chains/bitcoin/observer/live_test.go +++ b/zetaclient/chains/bitcoin/observer/live_test.go @@ -110,7 +110,11 @@ func getRPCClient(chainID int64) (*rpcclient.Client, error) { return rpcclient.New(connCfg, nil) } -func getFeeRate(client *rpcclient.Client, confTarget int64, estimateMode *btcjson.EstimateSmartFeeMode) (*big.Int, error) { +func getFeeRate( + client *rpcclient.Client, + confTarget int64, + estimateMode *btcjson.EstimateSmartFeeMode, +) (*big.Int, error) { feeResult, err := client.EstimateSmartFee(confTarget, estimateMode) if err != nil { return nil, err @@ -249,8 +253,18 @@ func LiveTestBitcoinFeeRate(t *testing.T) { if errEco2 != nil { t.Error(errEco2) } - fmt.Printf("Block: %d, Conservative-1 fee rate: %d, Economical-1 fee rate: %d\n", bn, feeRateConservative1.Uint64(), feeRateEconomical1.Uint64()) - fmt.Printf("Block: %d, Conservative-2 fee rate: %d, Economical-2 fee rate: %d\n", bn, feeRateConservative2.Uint64(), feeRateEconomical2.Uint64()) + fmt.Printf( + "Block: %d, Conservative-1 fee rate: %d, Economical-1 fee rate: %d\n", + bn, + feeRateConservative1.Uint64(), + feeRateEconomical1.Uint64(), + ) + fmt.Printf( + "Block: %d, Conservative-2 fee rate: %d, Economical-2 fee rate: %d\n", + bn, + feeRateConservative2.Uint64(), + feeRateEconomical2.Uint64(), + ) // monitor fee rate every 5 minutes for { @@ -267,8 +281,18 @@ func LiveTestBitcoinFeeRate(t *testing.T) { require.True(t, feeRateConservative2.Uint64() >= feeRateEconomical2.Uint64()) require.True(t, feeRateConservative1.Uint64() >= feeRateConservative2.Uint64()) require.True(t, feeRateEconomical1.Uint64() >= feeRateEconomical2.Uint64()) - fmt.Printf("Block: %d, Conservative-1 fee rate: %d, Economical-1 fee rate: %d\n", bn, feeRateConservative1.Uint64(), feeRateEconomical1.Uint64()) - fmt.Printf("Block: %d, Conservative-2 fee rate: %d, Economical-2 fee rate: %d\n", bn, feeRateConservative2.Uint64(), feeRateEconomical2.Uint64()) + fmt.Printf( + "Block: %d, Conservative-1 fee rate: %d, Economical-1 fee rate: %d\n", + bn, + feeRateConservative1.Uint64(), + feeRateEconomical1.Uint64(), + ) + fmt.Printf( + "Block: %d, Conservative-2 fee rate: %d, Economical-2 fee rate: %d\n", + bn, + feeRateConservative2.Uint64(), + feeRateEconomical2.Uint64(), + ) } } diff --git a/zetaclient/chains/bitcoin/observer/observer.go b/zetaclient/chains/bitcoin/observer/observer.go index 3008757393..e86602dbe4 100644 --- a/zetaclient/chains/bitcoin/observer/observer.go +++ b/zetaclient/chains/bitcoin/observer/observer.go @@ -320,16 +320,21 @@ func (ob *Observer) WatchRPCStatus() { tssAddr := ob.Tss.BTCAddressWitnessPubkeyHash() res, err := ob.rpcClient.ListUnspentMinMaxAddresses(0, 1000000, []btcutil.Address{tssAddr}) if err != nil { - ob.logger.Chain.Error().Err(err).Msg("RPC status check: can't list utxos of TSS address; wallet or loaded? TSS address is not imported? ") + ob.logger.Chain.Error(). + Err(err). + Msg("RPC status check: can't list utxos of TSS address; wallet or loaded? TSS address is not imported? ") continue } if len(res) == 0 { - ob.logger.Chain.Error().Err(err).Msg("RPC status check: TSS address has no utxos; TSS address is not imported? ") + ob.logger.Chain.Error(). + Err(err). + Msg("RPC status check: TSS address has no utxos; TSS address is not imported? ") continue } - ob.logger.Chain.Info().Msgf("[OK] RPC status check: latest block number %d, timestamp %s (%.fs ago), tss addr %s, #utxos: %d", bn, blockTime, elapsedSeconds, tssAddr, len(res)) + ob.logger.Chain.Info(). + Msgf("[OK] RPC status check: latest block number %d, timestamp %s (%.fs ago), tss addr %s, #utxos: %d", bn, blockTime, elapsedSeconds, tssAddr, len(res)) case <-ob.stop: return @@ -620,13 +625,18 @@ func (ob *Observer) SaveBroadcastedTx(txHash string, nonce uint64) { broadcastEntry := clienttypes.ToOutTxHashSQLType(txHash, outTxID) if err := ob.db.Save(&broadcastEntry).Error; err != nil { - ob.logger.OutTx.Error().Err(err).Msgf("SaveBroadcastedTx: error saving broadcasted txHash %s for outTx %s", txHash, outTxID) + ob.logger.OutTx.Error(). + Err(err). + Msgf("SaveBroadcastedTx: error saving broadcasted txHash %s for outTx %s", txHash, outTxID) } ob.logger.OutTx.Info().Msgf("SaveBroadcastedTx: saved broadcasted txHash %s for outTx %s", txHash, outTxID) } // GetTxResultByHash gets the transaction result by hash -func GetTxResultByHash(rpcClient interfaces.BTCRPCClient, txID string) (*chainhash.Hash, *btcjson.GetTransactionResult, error) { +func GetTxResultByHash( + rpcClient interfaces.BTCRPCClient, + txID string, +) (*chainhash.Hash, *btcjson.GetTransactionResult, error) { hash, err := chainhash.NewHashFromStr(txID) if err != nil { return nil, nil, errors.Wrapf(err, "GetTxResultByHash: error NewHashFromStr: %s", txID) @@ -641,11 +651,19 @@ func GetTxResultByHash(rpcClient interfaces.BTCRPCClient, txID string) (*chainha } // GetRawTxResult gets the raw tx result -func GetRawTxResult(rpcClient interfaces.BTCRPCClient, hash *chainhash.Hash, res *btcjson.GetTransactionResult) (btcjson.TxRawResult, error) { +func GetRawTxResult( + rpcClient interfaces.BTCRPCClient, + hash *chainhash.Hash, + res *btcjson.GetTransactionResult, +) (btcjson.TxRawResult, error) { if res.Confirmations == 0 { // for pending tx, we query the raw tx directly rawResult, err := rpcClient.GetRawTransactionVerbose(hash) // for pending tx, we query the raw tx if err != nil { - return btcjson.TxRawResult{}, errors.Wrapf(err, "getRawTxResult: error GetRawTransactionVerbose %s", res.TxID) + return btcjson.TxRawResult{}, errors.Wrapf( + err, + "getRawTxResult: error GetRawTransactionVerbose %s", + res.TxID, + ) } return *rawResult, nil } else if res.Confirmations > 0 { // for confirmed tx, we query the block diff --git a/zetaclient/chains/bitcoin/observer/outbound.go b/zetaclient/chains/bitcoin/observer/outbound.go index 87f5a9a69d..00e72ff0e1 100644 --- a/zetaclient/chains/bitcoin/observer/outbound.go +++ b/zetaclient/chains/bitcoin/observer/outbound.go @@ -45,7 +45,9 @@ func (ob *Observer) WatchOutTx() { } trackers, err := ob.zetacoreClient.GetAllOutTxTrackerByChain(ob.chain.ChainId, interfaces.Ascending) if err != nil { - ob.logger.OutTx.Error().Err(err).Msgf("WatchOutTx: error GetAllOutTxTrackerByChain for chain %d", ob.chain.ChainId) + ob.logger.OutTx.Error(). + Err(err). + Msgf("WatchOutTx: error GetAllOutTxTrackerByChain for chain %d", ob.chain.ChainId) continue } for _, tracker := range trackers { @@ -53,18 +55,22 @@ func (ob *Observer) WatchOutTx() { outTxID := ob.GetTxID(tracker.Nonce) cctx, err := ob.zetacoreClient.GetCctxByNonce(ob.chain.ChainId, tracker.Nonce) if err != nil { - ob.logger.OutTx.Info().Err(err).Msgf("WatchOutTx: can't find cctx for chain %d nonce %d", ob.chain.ChainId, tracker.Nonce) + ob.logger.OutTx.Info(). + Err(err). + Msgf("WatchOutTx: can't find cctx for chain %d nonce %d", ob.chain.ChainId, tracker.Nonce) break } nonce := cctx.GetCurrentOutTxParam().OutboundTxTssNonce if tracker.Nonce != nonce { // Tanmay: it doesn't hurt to check - ob.logger.OutTx.Error().Msgf("WatchOutTx: tracker nonce %d not match cctx nonce %d", tracker.Nonce, nonce) + ob.logger.OutTx.Error(). + Msgf("WatchOutTx: tracker nonce %d not match cctx nonce %d", tracker.Nonce, nonce) break } if len(tracker.HashList) > 1 { - ob.logger.OutTx.Warn().Msgf("WatchOutTx: oops, outTxID %s got multiple (%d) outTx hashes", outTxID, len(tracker.HashList)) + ob.logger.OutTx.Warn(). + Msgf("WatchOutTx: oops, outTxID %s got multiple (%d) outTx hashes", outTxID, len(tracker.HashList)) } // iterate over all txHashes to find the truly included one. @@ -76,7 +82,8 @@ func (ob *Observer) WatchOutTx() { if result != nil && !inMempool { // included txCount++ txResult = result - ob.logger.OutTx.Info().Msgf("WatchOutTx: included outTx %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, tracker.Nonce) + ob.logger.OutTx.Info(). + Msgf("WatchOutTx: included outTx %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, tracker.Nonce) if txCount > 1 { ob.logger.OutTx.Error().Msgf( "WatchOutTx: checkIncludedTx passed, txCount %d chain %d nonce %d result %v", txCount, ob.chain.ChainId, tracker.Nonce, result) @@ -168,7 +175,9 @@ func (ob *Observer) IsOutboundProcessed(cctx *crosschaintypes.CrossChainTx, logg coin.CoinType_Gas, ) if err != nil { - logger.Error().Err(err).Msgf("IsOutboundProcessed: error confirming bitcoin outTx %s, nonce %d ballot %s", res.TxID, nonce, ballot) + logger.Error(). + Err(err). + Msgf("IsOutboundProcessed: error confirming bitcoin outTx %s, nonce %d ballot %s", res.TxID, nonce, ballot) } else if zetaHash != "" { logger.Info().Msgf("IsOutboundProcessed: confirmed Bitcoin outTx %s, zeta tx hash %s nonce %d ballot %s", res.TxID, zetaHash, nonce, ballot) } @@ -246,7 +255,11 @@ func (ob *Observer) SelectUTXOs( } } if total < amount { - return nil, 0, 0, 0, fmt.Errorf("SelectUTXOs: not enough btc in reserve - available : %v , tx amount : %v", total, amount) + return nil, 0, 0, 0, fmt.Errorf( + "SelectUTXOs: not enough btc in reserve - available : %v , tx amount : %v", + total, + amount, + ) } // consolidate biggest possible UTXOs to maximize consolidated value @@ -297,7 +310,8 @@ func (ob *Observer) refreshPendingNonce() { ob.Mu.Lock() defer ob.Mu.Unlock() ob.pendingNonce = nonceLow - ob.logger.Chain.Info().Msgf("refreshPendingNonce: increase pending nonce to %d with txid %s", ob.pendingNonce, txid) + ob.logger.Chain.Info(). + Msgf("refreshPendingNonce: increase pending nonce to %d with txid %s", ob.pendingNonce, txid) } } @@ -321,7 +335,12 @@ func (ob *Observer) getOutTxidByNonce(nonce uint64, test bool) (string, error) { // make sure it's a real Bitcoin txid _, getTxResult, err := GetTxResultByHash(ob.rpcClient, txid) if err != nil { - return "", errors.Wrapf(err, "getOutTxidByNonce: error getting outTx result for nonce %d hash %s", nonce, txid) + return "", errors.Wrapf( + err, + "getOutTxidByNonce: error getting outTx result for nonce %d hash %s", + nonce, + txid, + ) } if getTxResult.Confirmations <= 0 { // just a double check return "", fmt.Errorf("getOutTxidByNonce: outTx txid %s for nonce %d is not included", txid, nonce) @@ -340,7 +359,8 @@ func (ob *Observer) findNonceMarkUTXO(nonce uint64, txid string) (int, error) { ob.logger.OutTx.Error().Err(err).Msgf("findNonceMarkUTXO: error getting satoshis for utxo %v", utxo) } if utxo.Address == tssAddress && sats == amount && utxo.TxID == txid && utxo.Vout == 0 { - ob.logger.OutTx.Info().Msgf("findNonceMarkUTXO: found nonce-mark utxo with txid %s, amount %d satoshi", utxo.TxID, sats) + ob.logger.OutTx.Info(). + Msgf("findNonceMarkUTXO: found nonce-mark utxo with txid %s, amount %d satoshi", utxo.TxID, sats) return i, nil } } @@ -349,7 +369,10 @@ func (ob *Observer) findNonceMarkUTXO(nonce uint64, txid string) (int, error) { // checkIncludedTx checks if a txHash is included and returns (txResult, inMempool) // Note: if txResult is nil, then inMempool flag should be ignored. -func (ob *Observer) checkIncludedTx(cctx *crosschaintypes.CrossChainTx, txHash string) (*btcjson.GetTransactionResult, bool) { +func (ob *Observer) checkIncludedTx( + cctx *crosschaintypes.CrossChainTx, + txHash string, +) (*btcjson.GetTransactionResult, bool) { outTxID := ob.GetTxID(cctx.GetCurrentOutTxParam().OutboundTxTssNonce) hash, getTxResult, err := GetTxResultByHash(ob.rpcClient, txHash) if err != nil { @@ -358,14 +381,17 @@ func (ob *Observer) checkIncludedTx(cctx *crosschaintypes.CrossChainTx, txHash s } if txHash != getTxResult.TxID { // just in case, we'll use getTxResult.TxID later - ob.logger.OutTx.Error().Msgf("checkIncludedTx: inconsistent txHash %s and getTxResult.TxID %s", txHash, getTxResult.TxID) + ob.logger.OutTx.Error(). + Msgf("checkIncludedTx: inconsistent txHash %s and getTxResult.TxID %s", txHash, getTxResult.TxID) return nil, false } if getTxResult.Confirmations >= 0 { // check included tx only err = ob.checkTssOutTxResult(cctx, hash, getTxResult) if err != nil { - ob.logger.OutTx.Error().Err(err).Msgf("checkIncludedTx: error verify bitcoin outTx %s outTxID %s", txHash, outTxID) + ob.logger.OutTx.Error(). + Err(err). + Msgf("checkIncludedTx: error verify bitcoin outTx %s outTxID %s", txHash, outTxID) return nil, false } return getTxResult, false // included @@ -388,7 +414,8 @@ func (ob *Observer) setIncludedTx(nonce uint64, getTxResult *btcjson.GetTransact if nonce >= ob.pendingNonce { // try increasing pending nonce on every newly included outTx ob.pendingNonce = nonce + 1 } - ob.logger.OutTx.Info().Msgf("setIncludedTx: included new bitcoin outTx %s outTxID %s pending nonce %d", txHash, outTxID, ob.pendingNonce) + ob.logger.OutTx.Info(). + Msgf("setIncludedTx: included new bitcoin outTx %s outTxID %s pending nonce %d", txHash, outTxID, ob.pendingNonce) } else if txHash == res.TxID { // found same hash. ob.includedTxResults[outTxID] = getTxResult // update tx result as confirmations may increase if getTxResult.Confirmations > res.Confirmations { @@ -424,7 +451,11 @@ func (ob *Observer) removeIncludedTx(nonce uint64) { // - check if all inputs are segwit && TSS inputs // // Returns: true if outTx passes basic checks. -func (ob *Observer) checkTssOutTxResult(cctx *crosschaintypes.CrossChainTx, hash *chainhash.Hash, res *btcjson.GetTransactionResult) error { +func (ob *Observer) checkTssOutTxResult( + cctx *crosschaintypes.CrossChainTx, + hash *chainhash.Hash, + res *btcjson.GetTransactionResult, +) error { params := cctx.GetCurrentOutTxParam() nonce := params.OutboundTxTssNonce rawResult, err := GetRawTxResult(ob.rpcClient, hash, res) @@ -440,7 +471,12 @@ func (ob *Observer) checkTssOutTxResult(cctx *crosschaintypes.CrossChainTx, hash if compliance.IsCctxRestricted(cctx) { err = ob.checkTSSVoutCancelled(params, rawResult.Vout) if err != nil { - return errors.Wrapf(err, "checkTssOutTxResult: invalid TSS Vout in cancelled outTx %s nonce %d", hash, nonce) + return errors.Wrapf( + err, + "checkTssOutTxResult: invalid TSS Vout in cancelled outTx %s nonce %d", + hash, + nonce, + ) } } else { err = ob.checkTSSVout(params, rawResult.Vout) @@ -476,7 +512,12 @@ func (ob *Observer) checkTSSVin(vins []btcjson.Vin, nonce uint64) error { } // nonce-mark MUST the 1st output that comes from prior TSS outTx if vin.Txid != preTxid || vin.Vout != 0 { - return fmt.Errorf("checkTSSVin: invalid nonce-mark txid %s vout %d, expected txid %s vout 0", vin.Txid, vin.Vout, preTxid) + return fmt.Errorf( + "checkTSSVin: invalid nonce-mark txid %s vout %d, expected txid %s vout 0", + vin.Txid, + vin.Vout, + preTxid, + ) } } } @@ -509,14 +550,26 @@ func (ob *Observer) checkTSSVout(params *crosschaintypes.OutboundTxParams, vouts switch vout.N { case 0: // 1st vout: nonce-mark if receiverVout != tssAddress { - return fmt.Errorf("checkTSSVout: nonce-mark address %s not match TSS address %s", receiverVout, tssAddress) + return fmt.Errorf( + "checkTSSVout: nonce-mark address %s not match TSS address %s", + receiverVout, + tssAddress, + ) } if amount != chains.NonceMarkAmount(nonce) { - return fmt.Errorf("checkTSSVout: nonce-mark amount %d not match nonce-mark amount %d", amount, chains.NonceMarkAmount(nonce)) + return fmt.Errorf( + "checkTSSVout: nonce-mark amount %d not match nonce-mark amount %d", + amount, + chains.NonceMarkAmount(nonce), + ) } case 1: // 2nd vout: payment to recipient if receiverVout != params.Receiver { - return fmt.Errorf("checkTSSVout: output address %s not match params receiver %s", receiverVout, params.Receiver) + return fmt.Errorf( + "checkTSSVout: output address %s not match params receiver %s", + receiverVout, + params.Receiver, + ) } // #nosec G701 always positive if uint64(amount) != params.Amount.Uint64() { @@ -551,14 +604,26 @@ func (ob *Observer) checkTSSVoutCancelled(params *crosschaintypes.OutboundTxPara switch vout.N { case 0: // 1st vout: nonce-mark if receiverVout != tssAddress { - return fmt.Errorf("checkTSSVoutCancelled: nonce-mark address %s not match TSS address %s", receiverVout, tssAddress) + return fmt.Errorf( + "checkTSSVoutCancelled: nonce-mark address %s not match TSS address %s", + receiverVout, + tssAddress, + ) } if amount != chains.NonceMarkAmount(nonce) { - return fmt.Errorf("checkTSSVoutCancelled: nonce-mark amount %d not match nonce-mark amount %d", amount, chains.NonceMarkAmount(nonce)) + return fmt.Errorf( + "checkTSSVoutCancelled: nonce-mark amount %d not match nonce-mark amount %d", + amount, + chains.NonceMarkAmount(nonce), + ) } case 1: // 2nd vout: change to TSS (optional) if receiverVout != tssAddress { - return fmt.Errorf("checkTSSVoutCancelled: change address %s not match TSS address %s", receiverVout, tssAddress) + return fmt.Errorf( + "checkTSSVoutCancelled: change address %s not match TSS address %s", + receiverVout, + tssAddress, + ) } } } diff --git a/zetaclient/chains/bitcoin/observer/outbound_test.go b/zetaclient/chains/bitcoin/observer/outbound_test.go index aaeab7366e..b506269c21 100644 --- a/zetaclient/chains/bitcoin/observer/outbound_test.go +++ b/zetaclient/chains/bitcoin/observer/outbound_test.go @@ -65,7 +65,11 @@ func mineTxNSetNonceMark(ob *Observer, nonce uint64, txid string, preMarkIndex i // Set nonce mark tssAddress := ob.Tss.BTCAddressWitnessPubkeyHash().EncodeAddress() - nonceMark := btcjson.ListUnspentResult{TxID: txid, Address: tssAddress, Amount: float64(chains.NonceMarkAmount(nonce)) * 1e-8} + nonceMark := btcjson.ListUnspentResult{ + TxID: txid, + Address: tssAddress, + Amount: float64(chains.NonceMarkAmount(nonce)) * 1e-8, + } if preMarkIndex >= 0 { // replace nonce-mark utxo ob.utxos[preMarkIndex] = nonceMark @@ -314,7 +318,11 @@ func TestSelectUTXOs(t *testing.T) { require.NotNil(t, err) require.Nil(t, result) require.Zero(t, amount) - require.Equal(t, "SelectUTXOs: not enough btc in reserve - available : 21.63107432 , tx amount : 21.64", err.Error()) + require.Equal( + t, + "SelectUTXOs: not enough btc in reserve - available : 21.63107432 , tx amount : 21.64", + err.Error(), + ) } func TestUTXOConsolidation(t *testing.T) { @@ -388,7 +396,12 @@ func TestUTXOConsolidation(t *testing.T) { t.Run("should consolidate 3 utxos sparse", func(t *testing.T) { ob := createObserverWithUTXOs(t) - mineTxNSetNonceMark(ob, 24105431, dummyTxID, -1) // mine a transaction and set nonce-mark utxo for nonce 24105431 + mineTxNSetNonceMark( + ob, + 24105431, + dummyTxID, + -1, + ) // mine a transaction and set nonce-mark utxo for nonce 24105431 // input: utxoCap = 5, amount = 0.13, nonce = 24105432, rank = 5 // output: [0.24107431, 0.01, 0.12, 1.26, 0.5, 0.24], 2.37107431 @@ -406,7 +419,12 @@ func TestUTXOConsolidation(t *testing.T) { t.Run("should consolidate all utxos sparse", func(t *testing.T) { ob := createObserverWithUTXOs(t) - mineTxNSetNonceMark(ob, 24105431, dummyTxID, -1) // mine a transaction and set nonce-mark utxo for nonce 24105431 + mineTxNSetNonceMark( + ob, + 24105431, + dummyTxID, + -1, + ) // mine a transaction and set nonce-mark utxo for nonce 24105431 // input: utxoCap = 12, amount = 0.13, nonce = 24105432, rank = 1 // output: [0.24107431, 0.01, 0.12, 8.72, 5.16, 3.28, 2.97, 1.26, 0.5, 0.24, 0.18], 22.68107431 diff --git a/zetaclient/chains/bitcoin/signer/signer.go b/zetaclient/chains/bitcoin/signer/signer.go index fb8746f411..5b9cdfa5a0 100644 --- a/zetaclient/chains/bitcoin/signer/signer.go +++ b/zetaclient/chains/bitcoin/signer/signer.go @@ -185,7 +185,13 @@ func (signer *Signer) SignWithdrawTx( } // select N UTXOs to cover the total expense - prevOuts, total, consolidatedUtxo, consolidatedValue, err := observer.SelectUTXOs(amount+estimateFee+float64(nonceMark)*1e-8, maxNoOfInputsPerTx, nonce, consolidationRank, false) + prevOuts, total, consolidatedUtxo, consolidatedValue, err := observer.SelectUTXOs( + amount+estimateFee+float64(nonceMark)*1e-8, + maxNoOfInputsPerTx, + nonce, + consolidationRank, + false, + ) if err != nil { return nil, err } @@ -209,14 +215,17 @@ func (signer *Signer) SignWithdrawTx( return nil, err } if sizeLimit < bitcoin.BtcOutTxBytesWithdrawer { // ZRC20 'withdraw' charged less fee from end user - signer.logger.Info().Msgf("sizeLimit %d is less than BtcOutTxBytesWithdrawer %d for nonce %d", sizeLimit, txSize, nonce) + signer.logger.Info(). + Msgf("sizeLimit %d is less than BtcOutTxBytesWithdrawer %d for nonce %d", sizeLimit, txSize, nonce) } if txSize < bitcoin.OutTxBytesMin { // outbound shouldn't be blocked a low sizeLimit - signer.logger.Warn().Msgf("txSize %d is less than outTxBytesMin %d; use outTxBytesMin", txSize, bitcoin.OutTxBytesMin) + signer.logger.Warn(). + Msgf("txSize %d is less than outTxBytesMin %d; use outTxBytesMin", txSize, bitcoin.OutTxBytesMin) txSize = bitcoin.OutTxBytesMin } if txSize > bitcoin.OutTxBytesMax { // in case of accident - signer.logger.Warn().Msgf("txSize %d is greater than outTxBytesMax %d; use outTxBytesMax", txSize, bitcoin.OutTxBytesMax) + signer.logger.Warn(). + Msgf("txSize %d is greater than outTxBytesMax %d; use outTxBytesMax", txSize, bitcoin.OutTxBytesMax) txSize = bitcoin.OutTxBytesMax } @@ -389,19 +398,25 @@ func (signer *Signer) TryProcessOutTx( cancelTx, ) if err != nil { - logger.Warn().Err(err).Msgf("SignOutboundTx error: nonce %d chain %d", outboundTxTssNonce, params.ReceiverChainId) + logger.Warn(). + Err(err). + Msgf("SignOutboundTx error: nonce %d chain %d", outboundTxTssNonce, params.ReceiverChainId) return } - logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundTxParams.SenderChainId, chain.ChainName, outboundTxTssNonce) + logger.Info(). + Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundTxParams.SenderChainId, chain.ChainName, outboundTxTssNonce) // FIXME: add prometheus metrics _, err = zetacoreClient.GetObserverList() if err != nil { - logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", outboundTxTssNonce, observertypes.ObservationType_OutBoundTx.String()) + logger.Warn(). + Err(err). + Msgf("unable to get observer list: chain %d observation %s", outboundTxTssNonce, observertypes.ObservationType_OutBoundTx.String()) } if tx != nil { outTxHash := tx.TxHash().String() - logger.Info().Msgf("on chain %s nonce %d, outTxHash %s signer %s", chain.ChainName, outboundTxTssNonce, outTxHash, myid) + logger.Info(). + Msgf("on chain %s nonce %d, outTxHash %s signer %s", chain.ChainName, outboundTxTssNonce, outTxHash, myid) // TODO: pick a few broadcasters. //if len(signers) == 0 || myid == signers[send.OutboundTxParams.Broadcaster] || myid == signers[int(send.OutboundTxParams.Broadcaster+1)%len(signers)] { // retry loop: 1s, 2s, 4s, 8s, 16s in case of RPC error @@ -410,13 +425,24 @@ func (signer *Signer) TryProcessOutTx( time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond) //random delay to avoid sychronized broadcast err := signer.Broadcast(tx) if err != nil { - logger.Warn().Err(err).Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, chain.ChainName, outboundTxTssNonce, i) + logger.Warn(). + Err(err). + Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, chain.ChainName, outboundTxTssNonce, i) continue } - logger.Info().Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", outboundTxTssNonce, chain.String(), outTxHash) - zetaHash, err := zetacoreClient.AddTxHashToOutTxTracker(chain.ChainId, outboundTxTssNonce, outTxHash, nil, "", -1) + logger.Info(). + Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", outboundTxTssNonce, chain.String(), outTxHash) + zetaHash, err := zetacoreClient.AddTxHashToOutTxTracker( + chain.ChainId, + outboundTxTssNonce, + outTxHash, + nil, + "", + -1, + ) if err != nil { - logger.Err(err).Msgf("Unable to add to tracker on zetacore: nonce %d chain %s outTxHash %s", outboundTxTssNonce, chain.ChainName, outTxHash) + logger.Err(err). + Msgf("Unable to add to tracker on zetacore: nonce %d chain %s outTxHash %s", outboundTxTssNonce, chain.ChainName, outTxHash) } logger.Info().Msgf("Broadcast to core successful %s", zetaHash) diff --git a/zetaclient/chains/bitcoin/signer/signer_keysign_test.go b/zetaclient/chains/bitcoin/signer/signer_keysign_test.go index 0329d5b1d9..b9318fcd2c 100644 --- a/zetaclient/chains/bitcoin/signer/signer_keysign_test.go +++ b/zetaclient/chains/bitcoin/signer/signer_keysign_test.go @@ -107,7 +107,16 @@ func buildTX() (*wire.MsgTx, *txscript.TxSigHashes, int, int64, []byte, *btcec.P return tx, txSigHashes, int(0), int64(65236), pkScript, &privKey, wif.CompressPubKey, nil } -func getWalletTX(tx *wire.MsgTx, sigHashes *txscript.TxSigHashes, idx int, amt int64, subscript []byte, hashType txscript.SigHashType, privKey *btcec.PrivateKey, compress bool) (string, error) { +func getWalletTX( + tx *wire.MsgTx, + sigHashes *txscript.TxSigHashes, + idx int, + amt int64, + subscript []byte, + hashType txscript.SigHashType, + privKey *btcec.PrivateKey, + compress bool, +) (string, error) { txWitness, err := txscript.WitnessSignature(tx, sigHashes, idx, amt, subscript, hashType, privKey, compress) if err != nil { return "", err @@ -123,7 +132,15 @@ func getWalletTX(tx *wire.MsgTx, sigHashes *txscript.TxSigHashes, idx int, amt i return walletTx, nil } -func getTSSTX(tss interfaces.TSSSigner, tx *wire.MsgTx, sigHashes *txscript.TxSigHashes, idx int, amt int64, subscript []byte, hashType txscript.SigHashType) (string, error) { +func getTSSTX( + tss interfaces.TSSSigner, + tx *wire.MsgTx, + sigHashes *txscript.TxSigHashes, + idx int, + amt int64, + subscript []byte, + hashType txscript.SigHashType, +) (string, error) { witnessHash, err := txscript.CalcWitnessSigHash(subscript, sigHashes, txscript.SigHashAll, tx, idx, amt) if err != nil { return "", err diff --git a/zetaclient/chains/bitcoin/signer/signer_test.go b/zetaclient/chains/bitcoin/signer/signer_test.go index e2627cdf63..8caf74fa22 100644 --- a/zetaclient/chains/bitcoin/signer/signer_test.go +++ b/zetaclient/chains/bitcoin/signer/signer_test.go @@ -173,7 +173,16 @@ func (s *BTCSignerSuite) TestP2WPH(c *C) { c.Assert(err, IsNil) { - txWitness, err := txscript.WitnessSignature(redeemTx, txSigHashes, 0, 100000000, pkScript, txscript.SigHashAll, privKey, true) + txWitness, err := txscript.WitnessSignature( + redeemTx, + txSigHashes, + 0, + 100000000, + pkScript, + txscript.SigHashAll, + privKey, + true, + ) c.Assert(err, IsNil) redeemTx.TxIn[0].Witness = txWitness // Prove that the transaction has been validly signed by executing the @@ -190,7 +199,14 @@ func (s *BTCSignerSuite) TestP2WPH(c *C) { } { - witnessHash, err := txscript.CalcWitnessSigHash(pkScript, txSigHashes, txscript.SigHashAll, redeemTx, 0, 100000000) + witnessHash, err := txscript.CalcWitnessSigHash( + pkScript, + txSigHashes, + txscript.SigHashAll, + redeemTx, + 0, + 100000000, + ) c.Assert(err, IsNil) sig, err := privKey.Sign(witnessHash) c.Assert(err, IsNil) @@ -213,7 +229,13 @@ func (s *BTCSignerSuite) TestP2WPH(c *C) { func TestAddWithdrawTxOutputs(t *testing.T) { // Create test signer and receiver address - signer, err := NewSigner(config.BTCConfig{}, mocks.NewTSSMainnet(), clientcommon.DefaultLoggers(), &metrics.TelemetryServer{}, nil) + signer, err := NewSigner( + config.BTCConfig{}, + mocks.NewTSSMainnet(), + clientcommon.DefaultLoggers(), + &metrics.TelemetryServer{}, + nil, + ) require.NoError(t, err) // tss address and script diff --git a/zetaclient/chains/evm/observer/inbound.go b/zetaclient/chains/evm/observer/inbound.go index 9008be9102..4e29e0c464 100644 --- a/zetaclient/chains/evm/observer/inbound.go +++ b/zetaclient/chains/evm/observer/inbound.go @@ -34,7 +34,10 @@ import ( // WatchInTx watches evm chain for incoming txs and post votes to zetacore func (ob *Observer) WatchInTx() { - ticker, err := clienttypes.NewDynamicTicker(fmt.Sprintf("EVM_WatchInTx_%d", ob.chain.ChainId), ob.GetChainParams().InTxTicker) + ticker, err := clienttypes.NewDynamicTicker( + fmt.Sprintf("EVM_WatchInTx_%d", ob.chain.ChainId), + ob.GetChainParams().InTxTicker, + ) if err != nil { ob.logger.InTx.Error().Err(err).Msg("error creating ticker") return @@ -139,7 +142,11 @@ func (ob *Observer) ObserveInTX(sampledLogger zerolog.Logger) error { return err } if blockNumber < ob.GetLastBlockHeight() { - return fmt.Errorf("observeInTX: block number should not decrease: current %d last %d", blockNumber, ob.GetLastBlockHeight()) + return fmt.Errorf( + "observeInTX: block number should not decrease: current %d last %d", + blockNumber, + ob.GetLastBlockHeight(), + ) } ob.SetLastBlockHeight(blockNumber) @@ -155,7 +162,8 @@ func (ob *Observer) ObserveInTX(sampledLogger zerolog.Logger) error { // skip if no new block is confirmed lastScanned := ob.GetLastBlockHeightScanned() if lastScanned >= confirmedBlockNum { - sampledLogger.Debug().Msgf("observeInTX: skipping observer, no new block is produced for chain %d", ob.chain.ChainId) + sampledLogger.Debug(). + Msgf("observeInTX: skipping observer, no new block is produced for chain %d", ob.chain.ChainId) return nil } @@ -183,11 +191,14 @@ func (ob *Observer) ObserveInTX(sampledLogger zerolog.Logger) error { // update last scanned block height for all 3 events (ZetaSent, Deposited, TssRecvd), ignore db error if lastScannedLowest > lastScanned { - sampledLogger.Info().Msgf("observeInTX: lasstScanned heights for chain %d ZetaSent %d ERC20Deposited %d TssRecvd %d", - ob.chain.ChainId, lastScannedZetaSent, lastScannedDeposited, lastScannedTssRecvd) + sampledLogger.Info(). + Msgf("observeInTX: lasstScanned heights for chain %d ZetaSent %d ERC20Deposited %d TssRecvd %d", + ob.chain.ChainId, lastScannedZetaSent, lastScannedDeposited, lastScannedTssRecvd) ob.SetLastBlockHeightScanned(lastScannedLowest) if err := ob.db.Save(clienttypes.ToLastBlockSQLType(lastScannedLowest)).Error; err != nil { - ob.logger.InTx.Error().Err(err).Msgf("observeInTX: error writing lastScannedLowest %d to db", lastScannedLowest) + ob.logger.InTx.Error(). + Err(err). + Msgf("observeInTX: error writing lastScannedLowest %d to db", lastScannedLowest) } } return nil @@ -248,14 +259,19 @@ func (ob *Observer) ObserveZetaSent(startBlock, toBlock uint64) uint64 { } // guard against multiple events in the same tx if guard[event.Raw.TxHash.Hex()] { - ob.logger.InTx.Warn().Msgf("ObserveZetaSent: multiple remote call events detected in tx %s", event.Raw.TxHash) + ob.logger.InTx.Warn(). + Msgf("ObserveZetaSent: multiple remote call events detected in tx %s", event.Raw.TxHash) continue } guard[event.Raw.TxHash.Hex()] = true msg := ob.BuildInboundVoteMsgForZetaSentEvent(event) if msg != nil { - _, err = ob.PostVoteInbound(msg, coin.CoinType_Zeta, zetacore.PostVoteInboundMessagePassingExecutionGasLimit) + _, err = ob.PostVoteInbound( + msg, + coin.CoinType_Zeta, + zetacore.PostVoteInboundMessagePassingExecutionGasLimit, + ) if err != nil { return beingScanned - 1 // we have to re-scan from this block next time } @@ -295,8 +311,10 @@ func (ob *Observer) ObserveERC20Deposited(startBlock, toBlock uint64) uint64 { events = append(events, iter.Event) continue } - ob.logger.InTx.Warn().Err(err).Msgf("ObserveERC20Deposited: invalid Deposited event in tx %s on chain %d at height %d", - iter.Event.Raw.TxHash.Hex(), ob.chain.ChainId, iter.Event.Raw.BlockNumber) + ob.logger.InTx.Warn(). + Err(err). + Msgf("ObserveERC20Deposited: invalid Deposited event in tx %s on chain %d at height %d", + iter.Event.Raw.TxHash.Hex(), ob.chain.ChainId, iter.Event.Raw.BlockNumber) } sort.SliceStable(events, func(i, j int) bool { if events[i].Raw.BlockNumber == events[j].Raw.BlockNumber { @@ -329,7 +347,8 @@ func (ob *Observer) ObserveERC20Deposited(startBlock, toBlock uint64) uint64 { // guard against multiple events in the same tx if guard[event.Raw.TxHash.Hex()] { - ob.logger.InTx.Warn().Msgf("ObserveERC20Deposited: multiple remote call events detected in tx %s", event.Raw.TxHash) + ob.logger.InTx.Warn(). + Msgf("ObserveERC20Deposited: multiple remote call events detected in tx %s", event.Raw.TxHash) continue } guard[event.Raw.TxHash.Hex()] = true @@ -368,7 +387,9 @@ func (ob *Observer) ObserverTSSReceive(startBlock, toBlock uint64) uint64 { // observe TSS received gas token in block 'bn' err := ob.ObserveTSSReceiveInBlock(bn) if err != nil { - ob.logger.InTx.Error().Err(err).Msgf("ObserverTSSReceive: error observing TSS received token in block %d for chain %d", bn, ob.chain.ChainId) + ob.logger.InTx.Error(). + Err(err). + Msgf("ObserverTSSReceive: error observing TSS received token in block %d for chain %d", bn, ob.chain.ChainId) return bn - 1 // we have to re-scan from this block next time } } @@ -377,10 +398,18 @@ func (ob *Observer) ObserverTSSReceive(startBlock, toBlock uint64) uint64 { } // CheckAndVoteInboundTokenZeta checks and votes on the given inbound Zeta token -func (ob *Observer) CheckAndVoteInboundTokenZeta(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) { +func (ob *Observer) CheckAndVoteInboundTokenZeta( + tx *ethrpc.Transaction, + receipt *ethtypes.Receipt, + vote bool, +) (string, error) { // check confirmations if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed { - return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "intx %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // get zeta connector contract @@ -418,10 +447,18 @@ func (ob *Observer) CheckAndVoteInboundTokenZeta(tx *ethrpc.Transaction, receipt } // CheckAndVoteInboundTokenERC20 checks and votes on the given inbound ERC20 token -func (ob *Observer) CheckAndVoteInboundTokenERC20(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) { +func (ob *Observer) CheckAndVoteInboundTokenERC20( + tx *ethrpc.Transaction, + receipt *ethtypes.Receipt, + vote bool, +) (string, error) { // check confirmations if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed { - return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "intx %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // get erc20 custody contract @@ -460,10 +497,18 @@ func (ob *Observer) CheckAndVoteInboundTokenERC20(tx *ethrpc.Transaction, receip } // CheckAndVoteInboundTokenGas checks and votes on the given inbound gas token -func (ob *Observer) CheckAndVoteInboundTokenGas(tx *ethrpc.Transaction, receipt *ethtypes.Receipt, vote bool) (string, error) { +func (ob *Observer) CheckAndVoteInboundTokenGas( + tx *ethrpc.Transaction, + receipt *ethtypes.Receipt, + vote bool, +) (string, error) { // check confirmations if confirmed := ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()); !confirmed { - return "", fmt.Errorf("intx %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "intx %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // checks receiver and tx status @@ -490,12 +535,17 @@ func (ob *Observer) CheckAndVoteInboundTokenGas(tx *ethrpc.Transaction, receipt } // PostVoteInbound posts a vote for the given vote message -func (ob *Observer) PostVoteInbound(msg *types.MsgVoteOnObservedInboundTx, coinType coin.CoinType, retryGasLimit uint64) (string, error) { +func (ob *Observer) PostVoteInbound( + msg *types.MsgVoteOnObservedInboundTx, + coinType coin.CoinType, + retryGasLimit uint64, +) (string, error) { txHash := msg.InTxHash chainID := ob.chain.ChainId zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound(zetacore.PostVoteInboundGasLimit, retryGasLimit, msg) if err != nil { - ob.logger.InTx.Err(err).Msgf("intx detected: error posting vote for chain %d token %s intx %s", chainID, coinType, txHash) + ob.logger.InTx.Err(err). + Msgf("intx detected: error posting vote for chain %d token %s intx %s", chainID, coinType, txHash) return "", err } else if zetaHash != "" { ob.logger.InTx.Info().Msgf("intx detected: chain %d token %s intx %s vote %s ballot %s", chainID, coinType, txHash, zetaHash, ballot) @@ -513,7 +563,10 @@ func (ob *Observer) HasEnoughConfirmations(receipt *ethtypes.Receipt, lastHeight } // BuildInboundVoteMsgForDepositedEvent builds a inbound vote message for a Deposited event -func (ob *Observer) BuildInboundVoteMsgForDepositedEvent(event *erc20custody.ERC20CustodyDeposited, sender ethcommon.Address) *types.MsgVoteOnObservedInboundTx { +func (ob *Observer) BuildInboundVoteMsgForDepositedEvent( + event *erc20custody.ERC20CustodyDeposited, + sender ethcommon.Address, +) *types.MsgVoteOnObservedInboundTx { // compliance check maybeReceiver := "" parsedAddress, _, err := chains.ParseAddressAndData(hex.EncodeToString(event.Message)) @@ -521,19 +574,29 @@ func (ob *Observer) BuildInboundVoteMsgForDepositedEvent(event *erc20custody.ERC maybeReceiver = parsedAddress.Hex() } if config.ContainRestrictedAddress(sender.Hex(), clienttypes.BytesToEthHex(event.Recipient), maybeReceiver) { - compliance.PrintComplianceLog(ob.logger.InTx, ob.logger.Compliance, - false, ob.chain.ChainId, event.Raw.TxHash.Hex(), sender.Hex(), clienttypes.BytesToEthHex(event.Recipient), "ERC20") + compliance.PrintComplianceLog( + ob.logger.InTx, + ob.logger.Compliance, + false, + ob.chain.ChainId, + event.Raw.TxHash.Hex(), + sender.Hex(), + clienttypes.BytesToEthHex(event.Recipient), + "ERC20", + ) return nil } // donation check if bytes.Equal(event.Message, []byte(constant.DonationMessage)) { - ob.logger.InTx.Info().Msgf("thank you rich folk for your donation! tx %s chain %d", event.Raw.TxHash.Hex(), ob.chain.ChainId) + ob.logger.InTx.Info(). + Msgf("thank you rich folk for your donation! tx %s chain %d", event.Raw.TxHash.Hex(), ob.chain.ChainId) return nil } message := hex.EncodeToString(event.Message) - ob.logger.InTx.Info().Msgf("ERC20CustodyDeposited inTx detected on chain %d tx %s block %d from %s value %s message %s", - ob.chain.ChainId, event.Raw.TxHash.Hex(), event.Raw.BlockNumber, sender.Hex(), event.Amount.String(), message) + ob.logger.InTx.Info(). + Msgf("ERC20CustodyDeposited inTx detected on chain %d tx %s block %d from %s value %s message %s", + ob.chain.ChainId, event.Raw.TxHash.Hex(), event.Raw.BlockNumber, sender.Hex(), event.Amount.String(), message) return zetacore.GetInBoundVoteMessage( sender.Hex(), @@ -554,7 +617,9 @@ func (ob *Observer) BuildInboundVoteMsgForDepositedEvent(event *erc20custody.ERC } // BuildInboundVoteMsgForZetaSentEvent builds a inbound vote message for a ZetaSent event -func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent(event *zetaconnector.ZetaConnectorNonEthZetaSent) *types.MsgVoteOnObservedInboundTx { +func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent( + event *zetaconnector.ZetaConnectorNonEthZetaSent, +) *types.MsgVoteOnObservedInboundTx { destChain := chains.GetChainFromChainID(event.DestinationChainId.Int64()) if destChain == nil { ob.logger.InTx.Warn().Msgf("chain id not supported %d", event.DestinationChainId.Int64()) @@ -578,7 +643,8 @@ func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent(event *zetaconnector.Zet } if strings.EqualFold(destAddr, paramsDest.ZetaTokenContractAddress) { - ob.logger.InTx.Warn().Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr) + ob.logger.InTx.Warn(). + Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr) return nil } } @@ -605,7 +671,11 @@ func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent(event *zetaconnector.Zet } // BuildInboundVoteMsgForTokenSentToTSS builds a inbound vote message for a token sent to TSS -func (ob *Observer) BuildInboundVoteMsgForTokenSentToTSS(tx *ethrpc.Transaction, sender ethcommon.Address, blockNumber uint64) *types.MsgVoteOnObservedInboundTx { +func (ob *Observer) BuildInboundVoteMsgForTokenSentToTSS( + tx *ethrpc.Transaction, + sender ethcommon.Address, + blockNumber uint64, +) *types.MsgVoteOnObservedInboundTx { message := tx.Input // compliance check @@ -665,7 +735,12 @@ func (ob *Observer) ObserveTSSReceiveInBlock(blockNumber uint64) error { _, err = ob.CheckAndVoteInboundTokenGas(&tx, receipt, true) if err != nil { - return errors.Wrapf(err, "error checking and voting inbound gas asset for intx %s chain %d", tx.Hash, ob.chain.ChainId) + return errors.Wrapf( + err, + "error checking and voting inbound gas asset for intx %s chain %d", + tx.Hash, + ob.chain.ChainId, + ) } } } diff --git a/zetaclient/chains/evm/observer/inbound_test.go b/zetaclient/chains/evm/observer/inbound_test.go index 517624ea0a..38820d7a1f 100644 --- a/zetaclient/chains/evm/observer/inbound_test.go +++ b/zetaclient/chains/evm/observer/inbound_test.go @@ -288,7 +288,13 @@ func Test_BuildInboundVoteMsgForTokenSentToTSS(t *testing.T) { // load archived gas token donation to TSS // https://etherscan.io/tx/0x52f214cf7b10be71f4d274193287d47bc9632b976e69b9d2cdeb527c2ba32155 inTxHashDonation := "0x52f214cf7b10be71f4d274193287d47bc9632b976e69b9d2cdeb527c2ba32155" - txDonation, receiptDonation := testutils.LoadEVMIntxNReceiptDonation(t, TestDataDir, chainID, inTxHashDonation, coin.CoinType_Gas) + txDonation, receiptDonation := testutils.LoadEVMIntxNReceiptDonation( + t, + TestDataDir, + chainID, + inTxHashDonation, + coin.CoinType_Gas, + ) require.NoError(t, evm.ValidateEvmTransaction(txDonation)) // create test compliance config @@ -298,14 +304,22 @@ func Test_BuildInboundVoteMsgForTokenSentToTSS(t *testing.T) { } t.Run("should return vote msg for archived gas token transfer to TSS", func(t *testing.T) { - msg := ob.BuildInboundVoteMsgForTokenSentToTSS(tx, ethcommon.HexToAddress(tx.From), receipt.BlockNumber.Uint64()) + msg := ob.BuildInboundVoteMsgForTokenSentToTSS( + tx, + ethcommon.HexToAddress(tx.From), + receipt.BlockNumber.Uint64(), + ) require.NotNil(t, msg) require.Equal(t, cctx.InboundTxParams.InboundTxBallotIndex, msg.Digest()) }) t.Run("should return nil msg if sender is restricted", func(t *testing.T) { cfg.ComplianceConfig.RestrictedAddresses = []string{tx.From} config.LoadComplianceConfig(cfg) - msg := ob.BuildInboundVoteMsgForTokenSentToTSS(tx, ethcommon.HexToAddress(tx.From), receipt.BlockNumber.Uint64()) + msg := ob.BuildInboundVoteMsgForTokenSentToTSS( + tx, + ethcommon.HexToAddress(tx.From), + receipt.BlockNumber.Uint64(), + ) require.Nil(t, msg) }) t.Run("should return nil msg if receiver is restricted", func(t *testing.T) { @@ -315,7 +329,11 @@ func Test_BuildInboundVoteMsgForTokenSentToTSS(t *testing.T) { txCopy.Input = message // use other address as receiver cfg.ComplianceConfig.RestrictedAddresses = []string{testutils.OtherAddress1} config.LoadComplianceConfig(cfg) - msg := ob.BuildInboundVoteMsgForTokenSentToTSS(txCopy, ethcommon.HexToAddress(txCopy.From), receipt.BlockNumber.Uint64()) + msg := ob.BuildInboundVoteMsgForTokenSentToTSS( + txCopy, + ethcommon.HexToAddress(txCopy.From), + receipt.BlockNumber.Uint64(), + ) require.Nil(t, msg) }) t.Run("should return nil msg on donation transaction", func(t *testing.T) { diff --git a/zetaclient/chains/evm/observer/observer.go b/zetaclient/chains/evm/observer/observer.go index bec85dc5a9..e624e8a280 100644 --- a/zetaclient/chains/evm/observer/observer.go +++ b/zetaclient/chains/evm/observer/observer.go @@ -250,19 +250,31 @@ func (ob *Observer) GetERC20CustodyContract() (ethcommon.Address, *erc20custody. return addr, contract, err } -func FetchConnectorContract(addr ethcommon.Address, client interfaces.EVMRPCClient) (*zetaconnector.ZetaConnectorNonEth, error) { +func FetchConnectorContract( + addr ethcommon.Address, + client interfaces.EVMRPCClient, +) (*zetaconnector.ZetaConnectorNonEth, error) { return zetaconnector.NewZetaConnectorNonEth(addr, client) } -func FetchConnectorContractEth(addr ethcommon.Address, client interfaces.EVMRPCClient) (*zetaconnectoreth.ZetaConnectorEth, error) { +func FetchConnectorContractEth( + addr ethcommon.Address, + client interfaces.EVMRPCClient, +) (*zetaconnectoreth.ZetaConnectorEth, error) { return zetaconnectoreth.NewZetaConnectorEth(addr, client) } -func FetchZetaZetaNonEthTokenContract(addr ethcommon.Address, client interfaces.EVMRPCClient) (*zeta.ZetaNonEth, error) { +func FetchZetaZetaNonEthTokenContract( + addr ethcommon.Address, + client interfaces.EVMRPCClient, +) (*zeta.ZetaNonEth, error) { return zeta.NewZetaNonEth(addr, client) } -func FetchERC20CustodyContract(addr ethcommon.Address, client interfaces.EVMRPCClient) (*erc20custody.ERC20Custody, error) { +func FetchERC20CustodyContract( + addr ethcommon.Address, + client interfaces.EVMRPCClient, +) (*erc20custody.ERC20Custody, error) { return erc20custody.NewERC20Custody(addr, client) } @@ -313,10 +325,12 @@ func (ob *Observer) WatchRPCStatus() { blockTime := time.Unix(int64(header.Time), 0).UTC() elapsedSeconds := time.Since(blockTime).Seconds() if elapsedSeconds > 100 { - ob.logger.Chain.Warn().Msgf("RPC Status Check warning: RPC stale or chain stuck (check explorer)? Latest block %d timestamp is %.0fs ago", bn, elapsedSeconds) + ob.logger.Chain.Warn(). + Msgf("RPC Status Check warning: RPC stale or chain stuck (check explorer)? Latest block %d timestamp is %.0fs ago", bn, elapsedSeconds) continue } - ob.logger.Chain.Info().Msgf("[OK] RPC status: latest block num %d, timestamp %s ( %.0fs ago), suggested gas price %d", header.Number, blockTime.String(), elapsedSeconds, gasPrice.Uint64()) + ob.logger.Chain.Info(). + Msgf("[OK] RPC status: latest block num %d, timestamp %s ( %.0fs ago), suggested gas price %d", header.Number, blockTime.String(), elapsedSeconds, gasPrice.Uint64()) case <-ob.stop: return } @@ -376,7 +390,8 @@ func (ob *Observer) GetTxNReceipt(nonce uint64) (*ethtypes.Receipt, *ethtypes.Tr func (ob *Observer) IsTxConfirmed(nonce uint64) bool { ob.Mu.Lock() defer ob.Mu.Unlock() - return ob.outTXConfirmedReceipts[ob.GetTxID(nonce)] != nil && ob.outTXConfirmedTransactions[ob.GetTxID(nonce)] != nil + return ob.outTXConfirmedReceipts[ob.GetTxID(nonce)] != nil && + ob.outTXConfirmedTransactions[ob.GetTxID(nonce)] != nil } // CheckTxInclusion returns nil only if tx is included at the position indicated by the receipt ([block, index]) @@ -441,7 +456,10 @@ func (ob *Observer) WatchGasPrice() { } // start gas price ticker - ticker, err := clienttypes.NewDynamicTicker(fmt.Sprintf("EVM_WatchGasPrice_%d", ob.chain.ChainId), ob.GetChainParams().GasPriceTicker) + ticker, err := clienttypes.NewDynamicTicker( + fmt.Sprintf("EVM_WatchGasPrice_%d", ob.chain.ChainId), + ob.GetChainParams().GasPriceTicker, + ) if err != nil { ob.logger.GasPrice.Error().Err(err).Msg("NewDynamicTicker error") return diff --git a/zetaclient/chains/evm/observer/observer_test.go b/zetaclient/chains/evm/observer/observer_test.go index 500cdfea90..5991f14350 100644 --- a/zetaclient/chains/evm/observer/observer_test.go +++ b/zetaclient/chains/evm/observer/observer_test.go @@ -28,7 +28,10 @@ import ( var TestDataDir = "../../../" // getAppContext creates an app context for unit tests -func getAppContext(evmChain chains.Chain, evmChainParams *observertypes.ChainParams) (*context.AppContext, config.EVMConfig) { +func getAppContext( + evmChain chains.Chain, + evmChainParams *observertypes.ChainParams, +) (*context.AppContext, config.EVMConfig) { // create config cfg := config.NewConfig() cfg.EVMChainConfigs[evmChain.ChainId] = config.EVMConfig{ diff --git a/zetaclient/chains/evm/observer/outbound.go b/zetaclient/chains/evm/observer/outbound.go index 4f29360790..f1655471f3 100644 --- a/zetaclient/chains/evm/observer/outbound.go +++ b/zetaclient/chains/evm/observer/outbound.go @@ -34,7 +34,10 @@ func (ob *Observer) GetTxID(nonce uint64) string { // WatchOutTx watches evm chain for outgoing txs status func (ob *Observer) WatchOutTx() { - ticker, err := clienttypes.NewDynamicTicker(fmt.Sprintf("EVM_WatchOutTx_%d", ob.chain.ChainId), ob.GetChainParams().OutTxTicker) + ticker, err := clienttypes.NewDynamicTicker( + fmt.Sprintf("EVM_WatchOutTx_%d", ob.chain.ChainId), + ob.GetChainParams().OutTxTicker, + ) if err != nil { ob.logger.OutTx.Error().Err(err).Msg("error creating ticker") return @@ -67,7 +70,8 @@ func (ob *Observer) WatchOutTx() { txCount++ outtxReceipt = receipt outtx = tx - ob.logger.OutTx.Info().Msgf("WatchOutTx: confirmed outTx %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, nonceInt) + ob.logger.OutTx.Info(). + Msgf("WatchOutTx: confirmed outTx %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, nonceInt) if txCount > 1 { ob.logger.OutTx.Error().Msgf( "WatchOutTx: checkConfirmedTx passed, txCount %d chain %d nonce %d receipt %v transaction %v", txCount, ob.chain.ChainId, nonceInt, outtxReceipt, outtx) @@ -114,7 +118,9 @@ func (ob *Observer) PostVoteOutbound( cointype, ) if err != nil { - logger.Error().Err(err).Msgf("PostVoteOutbound: error posting vote for chain %d nonce %d outtx %s ", chainID, nonce, receipt.TxHash) + logger.Error(). + Err(err). + Msgf("PostVoteOutbound: error posting vote for chain %d nonce %d outtx %s ", chainID, nonce, receipt.TxHash) } else if zetaTxHash != "" { logger.Info().Msgf("PostVoteOutbound: posted vote for chain %d nonce %d outtx %s vote %s ballot %s", chainID, nonce, receipt.TxHash, zetaTxHash, ballot) } @@ -160,9 +166,20 @@ func (ob *Observer) IsOutboundProcessed(cctx *crosschaintypes.CrossChainTx, logg } // parse the received value from the outtx receipt - receiveValue, receiveStatus, err = ParseOuttxReceivedValue(cctx, receipt, transaction, cointype, connectorAddr, connector, custodyAddr, custody) + receiveValue, receiveStatus, err = ParseOuttxReceivedValue( + cctx, + receipt, + transaction, + cointype, + connectorAddr, + connector, + custodyAddr, + custody, + ) if err != nil { - logger.Error().Err(err).Msgf("IsOutboundProcessed: error parsing outtx event for chain %d txhash %s", ob.chain.ChainId, receipt.TxHash) + logger.Error(). + Err(err). + Msgf("IsOutboundProcessed: error parsing outtx event for chain %d txhash %s", ob.chain.ChainId, receipt.TxHash) return false, false, err } @@ -209,7 +226,10 @@ func ParseAndCheckZetaEvent( if err != nil { return nil, nil, errors.Wrap(err, "error validating ZetaReverted event") } - if !strings.EqualFold(ethcommon.BytesToAddress(reverted.DestinationAddress[:]).Hex(), cctx.InboundTxParams.Sender) { + if !strings.EqualFold( + ethcommon.BytesToAddress(reverted.DestinationAddress[:]).Hex(), + cctx.InboundTxParams.Sender, + ) { return nil, nil, fmt.Errorf("receiver address mismatch in ZetaReverted event, want %s got %s", cctx.InboundTxParams.Sender, ethcommon.BytesToAddress(reverted.DestinationAddress[:]).Hex()) } @@ -322,7 +342,9 @@ func (ob *Observer) checkConfirmedTx(txHash string, nonce uint64) (*ethtypes.Rec // query transaction transaction, isPending, err := ob.evmClient.TransactionByHash(ctxt, ethcommon.HexToHash(txHash)) if err != nil { - log.Error().Err(err).Msgf("confirmTxByHash: error getting transaction for outtx %s chain %d", txHash, ob.chain.ChainId) + log.Error(). + Err(err). + Msgf("confirmTxByHash: error getting transaction for outtx %s chain %d", txHash, ob.chain.ChainId) return nil, nil, false } if transaction == nil { // should not happen @@ -334,7 +356,9 @@ func (ob *Observer) checkConfirmedTx(txHash string, nonce uint64) (*ethtypes.Rec signer := ethtypes.NewLondonSigner(big.NewInt(ob.chain.ChainId)) from, err := signer.Sender(transaction) if err != nil { - log.Error().Err(err).Msgf("confirmTxByHash: local recovery of sender address failed for outtx %s chain %d", transaction.Hash().Hex(), ob.chain.ChainId) + log.Error(). + Err(err). + Msgf("confirmTxByHash: local recovery of sender address failed for outtx %s chain %d", transaction.Hash().Hex(), ob.chain.ChainId) return nil, nil, false } if from != ob.Tss.EVMAddress() { // must be TSS address @@ -343,7 +367,8 @@ func (ob *Observer) checkConfirmedTx(txHash string, nonce uint64) (*ethtypes.Rec return nil, nil, false } if transaction.Nonce() != nonce { // must match cctx nonce - log.Error().Msgf("confirmTxByHash: outtx %s nonce mismatch: wanted %d, got tx nonce %d", txHash, nonce, transaction.Nonce()) + log.Error(). + Msgf("confirmTxByHash: outtx %s nonce mismatch: wanted %d, got tx nonce %d", txHash, nonce, transaction.Nonce()) return nil, nil, false } @@ -368,8 +393,9 @@ func (ob *Observer) checkConfirmedTx(txHash string, nonce uint64) (*ethtypes.Rec // check confirmations if !ob.HasEnoughConfirmations(receipt, ob.GetLastBlockHeight()) { - log.Debug().Msgf("confirmTxByHash: txHash %s nonce %d included but not confirmed: receipt block %d, current block %d", - txHash, nonce, receipt.BlockNumber, ob.GetLastBlockHeight()) + log.Debug(). + Msgf("confirmTxByHash: txHash %s nonce %d included but not confirmed: receipt block %d, current block %d", + txHash, nonce, receipt.BlockNumber, ob.GetLastBlockHeight()) return nil, nil, false } diff --git a/zetaclient/chains/evm/observer/outbound_test.go b/zetaclient/chains/evm/observer/outbound_test.go index a0db7067a5..0b41c9c896 100644 --- a/zetaclient/chains/evm/observer/outbound_test.go +++ b/zetaclient/chains/evm/observer/outbound_test.go @@ -19,7 +19,9 @@ import ( ) // getContractsByChainID is a helper func to get contracts and addresses by chainID -func getContractsByChainID(chainID int64) (*zetaconnector.ZetaConnectorNonEth, ethcommon.Address, *erc20custody.ERC20Custody, ethcommon.Address) { +func getContractsByChainID( + chainID int64, +) (*zetaconnector.ZetaConnectorNonEth, ethcommon.Address, *erc20custody.ERC20Custody, ethcommon.Address) { connector := mocks.MockConnectorNonEth(chainID) connectorAddress := testutils.ConnectorAddresses[chainID] custody := mocks.MockERC20Custody(chainID) @@ -36,8 +38,21 @@ func Test_IsOutboundProcessed(t *testing.T) { chainParam := mocks.MockChainParams(chain.ChainId, 1) outtxHash := "0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f" cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_Zeta, testutils.EventZetaReceived) - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) t.Run("should post vote and return true if outtx is processed", func(t *testing.T) { // create evm client and set outtx and receipt @@ -113,8 +128,21 @@ func Test_IsOutboundProcessed_ContractError(t *testing.T) { chainParam := mocks.MockChainParams(chain.ChainId, 1) outtxHash := "0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f" cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_Zeta, testutils.EventZetaReceived) - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) t.Run("should fail if unable to get connector/custody contract", func(t *testing.T) { // create evm client and set outtx and receipt @@ -148,7 +176,13 @@ func Test_PostVoteOutbound(t *testing.T) { chain := chains.EthChain nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chain.ChainId, nonce, testutils.EventZetaReceived) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chain.ChainId, + nonce, + testutils.EventZetaReceived, + ) t.Run("post vote outbound successfully", func(t *testing.T) { // the amount and status to be used for vote @@ -158,11 +192,29 @@ func Test_PostVoteOutbound(t *testing.T) { // create evm client using mock zetacore client and post outbound vote zetacoreClient := mocks.NewMockZetaCoreClient() client := MockEVMObserver(t, chain, nil, nil, zetacoreClient, nil, 1, observertypes.ChainParams{}) - client.PostVoteOutbound(cctx.Index, receipt, outtx, receiveValue, receiveStatus, nonce, coinType, zerolog.Logger{}) + client.PostVoteOutbound( + cctx.Index, + receipt, + outtx, + receiveValue, + receiveStatus, + nonce, + coinType, + zerolog.Logger{}, + ) // pause the mock zetacore client to simulate error posting vote zetacoreClient.Pause() - client.PostVoteOutbound(cctx.Index, receipt, outtx, receiveValue, receiveStatus, nonce, coinType, zerolog.Logger{}) + client.PostVoteOutbound( + cctx.Index, + receipt, + outtx, + receiveValue, + receiveStatus, + nonce, + coinType, + zerolog.Logger{}, + ) }) } @@ -175,7 +227,14 @@ func Test_ParseZetaReceived(t *testing.T) { connector := mocks.MockConnectorNonEth(chainID) connectorAddress := testutils.ConnectorAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_Zeta, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) t.Run("should parse ZetaReceived event from archived outtx receipt", func(t *testing.T) { receivedLog, revertedLog, err := observer.ParseAndCheckZetaEvent(cctx, receipt, connectorAddress, connector) @@ -219,7 +278,14 @@ func Test_ParseZetaReceived(t *testing.T) { }) t.Run("should fail if no event found in receipt", func(t *testing.T) { // load receipt and remove ZetaReceived event from logs - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_Zeta, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) receipt.Logs = receipt.Logs[:1] // the 2nd log is ZetaReceived event receivedLog, revertedLog, err := observer.ParseAndCheckZetaEvent(cctx, receipt, connectorAddress, connector) require.ErrorContains(t, err, "no ZetaReceived/ZetaReverted event") @@ -236,7 +302,14 @@ func Test_ParseZetaReverted(t *testing.T) { connector := mocks.MockConnectorNonEth(chainID) connectorAddress := testutils.ConnectorAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_Zeta, testutils.EventZetaReverted) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_Zeta, + testutils.EventZetaReverted, + ) t.Run("should parse ZetaReverted event from archived outtx receipt", func(t *testing.T) { receivedLog, revertedLog, err := observer.ParseAndCheckZetaEvent(cctx, receipt, connectorAddress, connector) @@ -288,7 +361,14 @@ func Test_ParseERC20WithdrawnEvent(t *testing.T) { custody := mocks.MockERC20Custody(chainID) custodyAddress := testutils.CustodyAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_ERC20, testutils.EventERC20Withdraw) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_ERC20, + testutils.EventERC20Withdraw, + ) t.Run("should parse ERC20 Withdrawn event from archived outtx receipt", func(t *testing.T) { withdrawn, err := observer.ParseAndCheckWithdrawnEvent(cctx, receipt, custodyAddress, custody) @@ -329,7 +409,14 @@ func Test_ParseERC20WithdrawnEvent(t *testing.T) { }) t.Run("should fail if no Withdrawn event found in receipt", func(t *testing.T) { // load receipt and remove Withdrawn event from logs - receipt := testutils.LoadEVMOuttxReceipt(t, TestDataDir, chainID, outtxHash, coin.CoinType_ERC20, testutils.EventERC20Withdraw) + receipt := testutils.LoadEVMOuttxReceipt( + t, + TestDataDir, + chainID, + outtxHash, + coin.CoinType_ERC20, + testutils.EventERC20Withdraw, + ) receipt.Logs = receipt.Logs[:1] // the 2nd log is Withdrawn event withdrawn, err := observer.ParseAndCheckWithdrawnEvent(cctx, receipt, custodyAddress, custody) require.ErrorContains(t, err, "no ERC20 Withdrawn event") @@ -346,9 +433,24 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) params := cctx.GetCurrentOutTxParam() - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + connectorAddr, + connector, + custodyAddr, + custody, + ) require.NoError(t, err) require.True(t, params.Amount.BigInt().Cmp(value) == 0) require.Equal(t, chains.ReceiveStatus_success, status) @@ -360,7 +462,13 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { nonce := uint64(14) coinType := coin.CoinType_Zeta connectorLocal, connectorAddrLocal, custodyLocal, custodyAddrLocal := getContractsByChainID(localChainID) - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, localChainID, nonce, testutils.EventZetaReverted) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + localChainID, + nonce, + testutils.EventZetaReverted, + ) params := cctx.GetCurrentOutTxParam() value, status, err := observer.ParseOuttxReceivedValue( cctx, receipt, outtx, coinType, connectorAddrLocal, connectorLocal, custodyAddrLocal, custodyLocal) @@ -373,9 +481,24 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { // https://etherscan.io/tx/0xd2eba7ac3da1b62800165414ea4bcaf69a3b0fb9b13a0fc32f4be11bfef79146 nonce := uint64(8014) coinType := coin.CoinType_ERC20 - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventERC20Withdraw) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventERC20Withdraw, + ) params := cctx.GetCurrentOutTxParam() - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + connectorAddr, + connector, + custodyAddr, + custody, + ) require.NoError(t, err) require.True(t, params.Amount.BigInt().Cmp(value) == 0) require.Equal(t, chains.ReceiveStatus_success, status) @@ -387,7 +510,16 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { coinType := coin.CoinType_Gas cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, "") params := cctx.GetCurrentOutTxParam() - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + connectorAddr, + connector, + custodyAddr, + custody, + ) require.NoError(t, err) require.True(t, params.Amount.BigInt().Cmp(value) == 0) require.Equal(t, chains.ReceiveStatus_success, status) @@ -397,8 +529,23 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType(5) // unknown coin type - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, connectorAddr, connector, custodyAddr, custody) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + connectorAddr, + connector, + custodyAddr, + custody, + ) require.ErrorContains(t, err, "unknown coin type") require.Nil(t, value) require.Equal(t, chains.ReceiveStatus_failed, status) @@ -408,11 +555,26 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) // use an arbitrary address to make event parsing fail fakeConnectorAddress := sample.EthAddress() - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, fakeConnectorAddress, connector, custodyAddr, custody) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + fakeConnectorAddress, + connector, + custodyAddr, + custody, + ) require.Error(t, err) require.Nil(t, value) require.Equal(t, chains.ReceiveStatus_failed, status) @@ -422,11 +584,26 @@ func Test_ParseOuttxReceivedValue(t *testing.T) { // https://etherscan.io/tx/0xd2eba7ac3da1b62800165414ea4bcaf69a3b0fb9b13a0fc32f4be11bfef79146 nonce := uint64(8014) coinType := coin.CoinType_ERC20 - cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt(t, TestDataDir, chainID, nonce, testutils.EventERC20Withdraw) + cctx, outtx, receipt := testutils.LoadEVMCctxNOuttxNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventERC20Withdraw, + ) // use an arbitrary address to make event parsing fail fakeCustodyAddress := sample.EthAddress() - value, status, err := observer.ParseOuttxReceivedValue(cctx, receipt, outtx, coinType, connectorAddr, connector, fakeCustodyAddress, custody) + value, status, err := observer.ParseOuttxReceivedValue( + cctx, + receipt, + outtx, + coinType, + connectorAddr, + connector, + fakeCustodyAddress, + custody, + ) require.Error(t, err) require.Nil(t, value) require.Equal(t, chains.ReceiveStatus_failed, status) diff --git a/zetaclient/chains/evm/signer/outbound_tx_data.go b/zetaclient/chains/evm/signer/outbound_tx_data.go index c0c3a33cd1..99123be25a 100644 --- a/zetaclient/chains/evm/signer/outbound_tx_data.go +++ b/zetaclient/chains/evm/signer/outbound_tx_data.go @@ -74,11 +74,13 @@ func (txData *OutboundTransactionData) SetupGas( txData.gasLimit = cctx.GetCurrentOutTxParam().OutboundTxGasLimit if txData.gasLimit < MinGasLimit { txData.gasLimit = MinGasLimit - logger.Warn().Msgf("gasLimit %d is too low; set to %d", cctx.GetCurrentOutTxParam().OutboundTxGasLimit, txData.gasLimit) + logger.Warn(). + Msgf("gasLimit %d is too low; set to %d", cctx.GetCurrentOutTxParam().OutboundTxGasLimit, txData.gasLimit) } if txData.gasLimit > MaxGasLimit { txData.gasLimit = MaxGasLimit - logger.Warn().Msgf("gasLimit %d is too high; set to %d", cctx.GetCurrentOutTxParam().OutboundTxGasLimit, txData.gasLimit) + logger.Warn(). + Msgf("gasLimit %d is too high; set to %d", cctx.GetCurrentOutTxParam().OutboundTxGasLimit, txData.gasLimit) } // use dynamic gas price for ethereum chains. @@ -152,7 +154,8 @@ func NewOutBoundTransactionData( } // Get sendHash - logger.Info().Msgf("chain %s minting %d to %s, nonce %d, finalized zeta bn %d", toChain, cctx.InboundTxParams.Amount, txData.to.Hex(), nonce, cctx.InboundTxParams.InboundTxFinalizedZetaHeight) + logger.Info(). + Msgf("chain %s minting %d to %s, nonce %d, finalized zeta bn %d", toChain, cctx.InboundTxParams.Amount, txData.to.Hex(), nonce, cctx.InboundTxParams.InboundTxFinalizedZetaHeight) sendHash, err := hex.DecodeString(cctx.Index[2:]) // remove the leading 0x if err != nil || len(sendHash) != 32 { return nil, true, fmt.Errorf("decode CCTX %s error", cctx.Index) @@ -163,7 +166,8 @@ func NewOutBoundTransactionData( pendingTx := evmObserver.GetPendingTx(nonce) if pendingTx != nil { if txData.gasPrice.Cmp(pendingTx.GasPrice()) > 0 { - logger.Info().Msgf("replace pending outTx %s nonce %d using gas price %d", pendingTx.Hash().Hex(), nonce, txData.gasPrice) + logger.Info(). + Msgf("replace pending outTx %s nonce %d using gas price %d", pendingTx.Hash().Hex(), nonce, txData.gasPrice) } else { logger.Info().Msgf("please wait for pending outTx %s nonce %d to be included", pendingTx.Hash().Hex(), nonce) return nil, true, nil diff --git a/zetaclient/chains/evm/signer/signer.go b/zetaclient/chains/evm/signer/signer.go index 0f3569bc3f..9ec587cefa 100644 --- a/zetaclient/chains/evm/signer/signer.go +++ b/zetaclient/chains/evm/signer/signer.go @@ -314,7 +314,11 @@ func (signer *Signer) SignWithdrawTx(txData *OutboundTransactionData) (*ethtypes // // cmd_whitelist_erc20 // cmd_migrate_tss_funds -func (signer *Signer) SignCommandTx(txData *OutboundTransactionData, cmd string, params string) (*ethtypes.Transaction, error) { +func (signer *Signer) SignCommandTx( + txData *OutboundTransactionData, + cmd string, + params string, +) (*ethtypes.Transaction, error) { switch cmd { case constant.CmdWhitelistERC20: return signer.SignWhitelistERC20Cmd(txData, params) @@ -340,7 +344,8 @@ func (signer *Signer) TryProcessOutTx( Str("SendHash", cctx.Index). Logger() logger.Info().Msgf("start processing outTxID %s", outTxID) - logger.Info().Msgf("EVM Chain TryProcessOutTx: %s, value %d to %s", cctx.Index, cctx.GetCurrentOutTxParam().Amount.BigInt(), cctx.GetCurrentOutTxParam().Receiver) + logger.Info(). + Msgf("EVM Chain TryProcessOutTx: %s, value %d to %s", cctx.Index, cctx.GetCurrentOutTxParam().Amount.BigInt(), cctx.GetCurrentOutTxParam().Receiver) defer func() { outTxProc.EndTryProcess(outTxID) @@ -372,8 +377,16 @@ func (signer *Signer) TryProcessOutTx( var tx *ethtypes.Transaction // compliance check goes first if compliance.IsCctxRestricted(cctx) { - compliance.PrintComplianceLog(logger, signer.logger.Compliance, - true, evmObserver.Chain().ChainId, cctx.Index, cctx.InboundTxParams.Sender, txData.to.Hex(), cctx.GetCurrentOutTxParam().CoinType.String()) + compliance.PrintComplianceLog( + logger, + signer.logger.Compliance, + true, + evmObserver.Chain().ChainId, + cctx.Index, + cctx.InboundTxParams.Sender, + txData.to.Hex(), + cctx.GetCurrentOutTxParam().CoinType.String(), + ) tx, err = signer.SignCancelTx(txData.nonce, txData.gasPrice, height) // cancel the tx if err != nil { logger.Warn().Err(err).Msg(ErrorMsg(cctx)) @@ -454,7 +467,8 @@ func (signer *Signer) TryProcessOutTx( } } - logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundTxParams.SenderChainId, toChain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) + logger.Info(). + Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundTxParams.SenderChainId, toChain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce) // Broadcast Signed Tx signer.BroadcastOutTx(tx, cctx, logger, myID, zetacoreClient, txData) @@ -476,18 +490,25 @@ func (signer *Signer) BroadcastOutTx( // Try to broadcast transaction if tx != nil { outTxHash := tx.Hash().Hex() - logger.Info().Msgf("on chain %s nonce %d, outTxHash %s signer %s", signer.chain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce, outTxHash, myID) + logger.Info(). + Msgf("on chain %s nonce %d, outTxHash %s signer %s", signer.chain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce, outTxHash, myID) //if len(signers) == 0 || myid == signers[send.OutboundTxParams.Broadcaster] || myid == signers[int(send.OutboundTxParams.Broadcaster+1)%len(signers)] { backOff := 1000 * time.Millisecond // retry loop: 1s, 2s, 4s, 8s, 16s in case of RPC error for i := 0; i < 5; i++ { - logger.Info().Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, toChain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce, i) + logger.Info(). + Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, toChain, cctx.GetCurrentOutTxParam().OutboundTxTssNonce, i) // #nosec G404 randomness is not a security issue here time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond) // FIXME: use backoff err := signer.Broadcast(tx) if err != nil { log.Warn().Err(err).Msgf("OutTx Broadcast error") - retry, report := zetacore.HandleBroadcastError(err, strconv.FormatUint(cctx.GetCurrentOutTxParam().OutboundTxTssNonce, 10), toChain.String(), outTxHash) + retry, report := zetacore.HandleBroadcastError( + err, + strconv.FormatUint(cctx.GetCurrentOutTxParam().OutboundTxTssNonce, 10), + toChain.String(), + outTxHash, + ) if report { signer.reportToOutTxTracker(zetacoreClient, toChain.ChainId, tx.Nonce(), outTxHash, logger) } @@ -497,7 +518,8 @@ func (signer *Signer) BroadcastOutTx( backOff *= 2 continue } - logger.Info().Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", cctx.GetCurrentOutTxParam().OutboundTxTssNonce, toChain, outTxHash) + logger.Info(). + Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", cctx.GetCurrentOutTxParam().OutboundTxTssNonce, toChain, outTxHash) signer.reportToOutTxTracker(zetacoreClient, toChain.ChainId, tx.Nonce(), outTxHash, logger) break // successful broadcast; no need to retry } @@ -518,7 +540,14 @@ func (signer *Signer) SignERC20WithdrawTx(txData *OutboundTransactionData) (*eth return nil, fmt.Errorf("pack error: %w", err) } - tx, _, _, err := signer.Sign(data, signer.er20CustodyAddress, txData.gasLimit, txData.gasPrice, txData.nonce, txData.height) + tx, _, _, err := signer.Sign( + data, + signer.er20CustodyAddress, + txData.gasLimit, + txData.gasPrice, + txData.nonce, + txData.height, + ) if err != nil { return nil, fmt.Errorf("sign error: %w", err) } @@ -576,16 +605,27 @@ func (signer *Signer) EvmSigner() ethtypes.Signer { return signer.ethSigner } -func IsSenderZetaChain(cctx *types.CrossChainTx, zetacoreClient interfaces.ZetacoreClient, flags *observertypes.CrosschainFlags) bool { +func IsSenderZetaChain( + cctx *types.CrossChainTx, + zetacoreClient interfaces.ZetacoreClient, + flags *observertypes.CrosschainFlags, +) bool { return cctx.InboundTxParams.SenderChainId == zetacoreClient.Chain().ChainId && cctx.CctxStatus.Status == types.CctxStatus_PendingOutbound && flags.IsOutboundEnabled } func ErrorMsg(cctx *types.CrossChainTx) string { - return fmt.Sprintf("signer SignOutbound error: nonce %d chain %d", cctx.GetCurrentOutTxParam().OutboundTxTssNonce, cctx.GetCurrentOutTxParam().ReceiverChainId) + return fmt.Sprintf( + "signer SignOutbound error: nonce %d chain %d", + cctx.GetCurrentOutTxParam().OutboundTxTssNonce, + cctx.GetCurrentOutTxParam().ReceiverChainId, + ) } -func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundTransactionData, params string) (*ethtypes.Transaction, error) { +func (signer *Signer) SignWhitelistERC20Cmd( + txData *OutboundTransactionData, + params string, +) (*ethtypes.Transaction, error) { outboundParams := txData.outboundParams erc20 := ethcommon.HexToAddress(params) if erc20 == (ethcommon.Address{}) { @@ -599,7 +639,14 @@ func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundTransactionData, par if err != nil { return nil, err } - tx, _, _, err := signer.Sign(data, txData.to, txData.gasLimit, txData.gasPrice, outboundParams.OutboundTxTssNonce, txData.height) + tx, _, _, err := signer.Sign( + data, + txData.to, + txData.gasLimit, + txData.gasPrice, + outboundParams.OutboundTxTssNonce, + txData.height, + ) if err != nil { return nil, fmt.Errorf("sign error: %w", err) } @@ -608,7 +655,14 @@ func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundTransactionData, par func (signer *Signer) SignMigrateTssFundsCmd(txData *OutboundTransactionData) (*ethtypes.Transaction, error) { outboundParams := txData.outboundParams - tx, _, _, err := signer.Sign(nil, txData.to, txData.gasLimit, txData.gasPrice, outboundParams.OutboundTxTssNonce, txData.height) + tx, _, _, err := signer.Sign( + nil, + txData.to, + txData.gasLimit, + txData.gasPrice, + outboundParams.OutboundTxTssNonce, + txData.height, + ) if err != nil { return nil, err } @@ -616,12 +670,19 @@ func (signer *Signer) SignMigrateTssFundsCmd(txData *OutboundTransactionData) (* } // reportToOutTxTracker reports outTxHash to tracker only when tx receipt is available -func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreClient, chainID int64, nonce uint64, outTxHash string, logger zerolog.Logger) { +func (signer *Signer) reportToOutTxTracker( + zetacoreClient interfaces.ZetacoreClient, + chainID int64, + nonce uint64, + outTxHash string, + logger zerolog.Logger, +) { // skip if already being reported signer.mu.Lock() defer signer.mu.Unlock() if _, found := signer.outTxHashBeingReported[outTxHash]; found { - logger.Info().Msgf("reportToOutTxTracker: outTxHash %s for chain %d nonce %d is being reported", outTxHash, chainID, nonce) + logger.Info(). + Msgf("reportToOutTxTracker: outTxHash %s for chain %d nonce %d is being reported", outTxHash, chainID, nonce) return } signer.outTxHashBeingReported[outTxHash] = true // mark as being reported @@ -649,13 +710,16 @@ func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreCli if isPending { report = true // probably will be included later } - logger.Info().Msgf("reportToOutTxTracker: timeout waiting tx inclusion for chain %d nonce %d outTxHash %s report %v", chainID, nonce, outTxHash, report) + logger.Info(). + Msgf("reportToOutTxTracker: timeout waiting tx inclusion for chain %d nonce %d outTxHash %s report %v", chainID, nonce, outTxHash, report) break } // try getting the tx _, isPending, err = signer.client.TransactionByHash(context.TODO(), ethcommon.HexToHash(outTxHash)) if err != nil { - logger.Info().Err(err).Msgf("reportToOutTxTracker: error getting tx for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) + logger.Info(). + Err(err). + Msgf("reportToOutTxTracker: error getting tx for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) continue } // if tx is include in a block, try getting receipt @@ -663,7 +727,9 @@ func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreCli report = true // included receipt, err := signer.client.TransactionReceipt(context.TODO(), ethcommon.HexToHash(outTxHash)) if err != nil { - logger.Info().Err(err).Msgf("reportToOutTxTracker: error getting receipt for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) + logger.Info(). + Err(err). + Msgf("reportToOutTxTracker: error getting receipt for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) } if receipt != nil { blockNumber = receipt.BlockNumber.Uint64() @@ -671,7 +737,8 @@ func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreCli break } // keep monitoring pending tx - logger.Info().Msgf("reportToOutTxTracker: tx has not been included yet for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) + logger.Info(). + Msgf("reportToOutTxTracker: tx has not been included yet for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) } // try adding to outTx tracker for 10 minutes @@ -680,13 +747,15 @@ func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreCli for { // give up after 10 minutes of retrying if time.Since(tStart) > evm.OutTxTrackerReportTimeout { - logger.Info().Msgf("reportToOutTxTracker: timeout adding outtx tracker for chain %d nonce %d outTxHash %s, please add manually", chainID, nonce, outTxHash) + logger.Info(). + Msgf("reportToOutTxTracker: timeout adding outtx tracker for chain %d nonce %d outTxHash %s, please add manually", chainID, nonce, outTxHash) break } // stop if the cctx is already finalized cctx, err := zetacoreClient.GetCctxByNonce(chainID, nonce) if err != nil { - logger.Err(err).Msgf("reportToOutTxTracker: error getting cctx for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) + logger.Err(err). + Msgf("reportToOutTxTracker: error getting cctx for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) } else if !crosschainkeeper.IsPending(cctx) { logger.Info().Msgf("reportToOutTxTracker: cctx already finalized for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) break @@ -694,7 +763,8 @@ func (signer *Signer) reportToOutTxTracker(zetacoreClient interfaces.ZetacoreCli // report to outTx tracker zetaHash, err := zetacoreClient.AddTxHashToOutTxTracker(chainID, nonce, outTxHash, nil, "", -1) if err != nil { - logger.Err(err).Msgf("reportToOutTxTracker: error adding to outtx tracker for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) + logger.Err(err). + Msgf("reportToOutTxTracker: error adding to outtx tracker for chain %d nonce %d outTxHash %s", chainID, nonce, outTxHash) } else if zetaHash != "" { logger.Info().Msgf("reportToOutTxTracker: added outTxHash to core successful %s, chain %d nonce %d outTxHash %s block %d", zetaHash, chainID, nonce, outTxHash, blockNumber) diff --git a/zetaclient/chains/evm/signer/signer_test.go b/zetaclient/chains/evm/signer/signer_test.go index 532deb344b..6eede31ab2 100644 --- a/zetaclient/chains/evm/signer/signer_test.go +++ b/zetaclient/chains/evm/signer/signer_test.go @@ -297,7 +297,14 @@ func TestSigner_BroadcastOutTx(t *testing.T) { tx, err := evmSigner.SignERC20WithdrawTx(txData) require.NoError(t, err) - evmSigner.BroadcastOutTx(tx, cctx, zerolog.Logger{}, sdktypes.AccAddress{}, mocks.NewMockZetaCoreClient(), txData) + evmSigner.BroadcastOutTx( + tx, + cctx, + zerolog.Logger{}, + sdktypes.AccAddress{}, + mocks.NewMockZetaCoreClient(), + txData, + ) //Check if cctx was signed and broadcasted list := evmSigner.GetReportedTxList() diff --git a/zetaclient/chains/interfaces/interfaces.go b/zetaclient/chains/interfaces/interfaces.go index e64884bf1c..f5714fd730 100644 --- a/zetaclient/chains/interfaces/interfaces.go +++ b/zetaclient/chains/interfaces/interfaces.go @@ -63,7 +63,10 @@ type ChainSigner interface { // ZetacoreClient is the client interface to interact with zetacore type ZetacoreClient interface { - PostVoteInbound(gasLimit, retryGasLimit uint64, msg *crosschaintypes.MsgVoteOnObservedInboundTx) (string, string, error) + PostVoteInbound( + gasLimit, retryGasLimit uint64, + msg *crosschaintypes.MsgVoteOnObservedInboundTx, + ) (string, string, error) PostVoteOutbound( sendHash string, outTxHash string, @@ -144,7 +147,12 @@ type EVMRPCClient interface { HeaderByNumber(ctx context.Context, number *big.Int) (*ethtypes.Header, error) TransactionByHash(ctx context.Context, hash ethcommon.Hash) (tx *ethtypes.Transaction, isPending bool, err error) TransactionReceipt(ctx context.Context, txHash ethcommon.Hash) (*ethtypes.Receipt, error) - TransactionSender(ctx context.Context, tx *ethtypes.Transaction, block ethcommon.Hash, index uint) (ethcommon.Address, error) + TransactionSender( + ctx context.Context, + tx *ethtypes.Transaction, + block ethcommon.Hash, + index uint, + ) (ethcommon.Address, error) } // EVMJSONRPCClient is the interface for EVM JSON RPC client diff --git a/zetaclient/compliance/compliance.go b/zetaclient/compliance/compliance.go index db7db6bcc4..ece872371c 100644 --- a/zetaclient/compliance/compliance.go +++ b/zetaclient/compliance/compliance.go @@ -29,8 +29,20 @@ func PrintComplianceLog( if outbound { // we print cctx for outbound tx logMsg = "Restricted address detected in cctx" - inboundLoggerWithFields = inboundLogger.With().Int64("chain", chainID).Str("cctx", identifier).Str("sender", sender).Str("receiver", receiver).Str("token", token).Logger() - complianceLoggerWithFields = complianceLogger.With().Int64("chain", chainID).Str("cctx", identifier).Str("sender", sender).Str("receiver", receiver).Str("token", token).Logger() + inboundLoggerWithFields = inboundLogger.With(). + Int64("chain", chainID). + Str("cctx", identifier). + Str("sender", sender). + Str("receiver", receiver). + Str("token", token). + Logger() + complianceLoggerWithFields = complianceLogger.With(). + Int64("chain", chainID). + Str("cctx", identifier). + Str("sender", sender). + Str("receiver", receiver). + Str("token", token). + Logger() } else { // we print intx for inbound tx logMsg = "Restricted address detected in intx" diff --git a/zetaclient/config/types.go b/zetaclient/config/types.go index ce05817398..b14cc8191b 100644 --- a/zetaclient/config/types.go +++ b/zetaclient/config/types.go @@ -19,10 +19,10 @@ const ( // ClientConfiguration is a subset of zetaclient config that is used by zetacore client type ClientConfiguration struct { - ChainHost string `json:"chain_host" mapstructure:"chain_host"` - ChainRPC string `json:"chain_rpc" mapstructure:"chain_rpc"` + ChainHost string `json:"chain_host" mapstructure:"chain_host"` + ChainRPC string `json:"chain_rpc" mapstructure:"chain_rpc"` ChainHomeFolder string `json:"chain_home_folder" mapstructure:"chain_home_folder"` - SignerName string `json:"signer_name" mapstructure:"signer_name"` + SignerName string `json:"signer_name" mapstructure:"signer_name"` SignerPasswd string `json:"signer_passwd"` HsmMode bool `json:"hsm_mode"` } diff --git a/zetaclient/context/zetacore_context_test.go b/zetaclient/context/zetacore_context_test.go index c21148fd80..5561f12f4c 100644 --- a/zetaclient/context/zetacore_context_test.go +++ b/zetaclient/context/zetacore_context_test.go @@ -221,110 +221,113 @@ func TestUpdateZetacoreContext(t *testing.T) { require.Equal(t, verificationFlags, verFlags) }) - t.Run("should update zetacore context after being created from config with evm and btc chain params", func(t *testing.T) { - testCfg := config.NewConfig() - testCfg.EVMChainConfigs = map[int64]config.EVMConfig{ - 1: { - Chain: chains.Chain{ + t.Run( + "should update zetacore context after being created from config with evm and btc chain params", + func(t *testing.T) { + testCfg := config.NewConfig() + testCfg.EVMChainConfigs = map[int64]config.EVMConfig{ + 1: { + Chain: chains.Chain{ + ChainName: 1, + ChainId: 1, + }, + }, + 2: { + Chain: chains.Chain{ + ChainName: 2, + ChainId: 2, + }, + }, + } + testCfg.BitcoinConfig = config.BTCConfig{ + RPCUsername: "test username", + RPCPassword: "test password", + RPCHost: "test host", + RPCParams: "test params", + } + + zetaContext := context.NewZetacoreContext(testCfg) + require.NotNil(t, zetaContext) + + keyGenToUpdate := observertypes.Keygen{ + Status: observertypes.KeygenStatus_KeyGenSuccess, + GranteePubkeys: []string{"testpubkey1"}, + } + enabledChainsToUpdate := []chains.Chain{ + { ChainName: 1, ChainId: 1, }, - }, - 2: { - Chain: chains.Chain{ + { ChainName: 2, ChainId: 2, }, - }, - } - testCfg.BitcoinConfig = config.BTCConfig{ - RPCUsername: "test username", - RPCPassword: "test password", - RPCHost: "test host", - RPCParams: "test params", - } - - zetaContext := context.NewZetacoreContext(testCfg) - require.NotNil(t, zetaContext) - - keyGenToUpdate := observertypes.Keygen{ - Status: observertypes.KeygenStatus_KeyGenSuccess, - GranteePubkeys: []string{"testpubkey1"}, - } - enabledChainsToUpdate := []chains.Chain{ - { - ChainName: 1, - ChainId: 1, - }, - { - ChainName: 2, - ChainId: 2, - }, - } - evmChainParamsToUpdate := map[int64]*observertypes.ChainParams{ - 1: { - ChainId: 1, - }, - 2: { - ChainId: 2, - }, - } - - testBtcChain := chains.BtcTestNetChain - btcChainParamsToUpdate := &observertypes.ChainParams{ - ChainId: testBtcChain.ChainId, - } - tssPubKeyToUpdate := "tsspubkeytest" - crosschainFlags := sample.CrosschainFlags() - verificationFlags := sample.HeaderSupportedChains() - require.NotNil(t, crosschainFlags) - loggers := clientcommon.DefaultLoggers() - zetaContext.Update( - &keyGenToUpdate, - enabledChainsToUpdate, - evmChainParamsToUpdate, - btcChainParamsToUpdate, - tssPubKeyToUpdate, - *crosschainFlags, - verificationFlags, - false, - loggers.Std, - ) - - // assert keygen updated - keyGen := zetaContext.GetKeygen() - require.Equal(t, keyGenToUpdate, keyGen) - - // assert enabled chains updated - require.Equal(t, enabledChainsToUpdate, zetaContext.GetEnabledChains()) - - // assert current tss pubkey updated - require.Equal(t, tssPubKeyToUpdate, zetaContext.GetCurrentTssPubkey()) - - // assert btc chain params - chain, btcChainParams, btcChainParamsFound := zetaContext.GetBTCChainParams() - require.Equal(t, testBtcChain, chain) - require.True(t, btcChainParamsFound) - require.Equal(t, btcChainParamsToUpdate, btcChainParams) - - // assert evm chain params - allEVMChainParams := zetaContext.GetAllEVMChainParams() - require.Equal(t, evmChainParamsToUpdate, allEVMChainParams) - - evmChainParams1, found := zetaContext.GetEVMChainParams(1) - require.True(t, found) - require.Equal(t, evmChainParamsToUpdate[1], evmChainParams1) - - evmChainParams2, found := zetaContext.GetEVMChainParams(2) - require.True(t, found) - require.Equal(t, evmChainParamsToUpdate[2], evmChainParams2) - - ccFlags := zetaContext.GetCrossChainFlags() - require.Equal(t, ccFlags, *crosschainFlags) - - verFlags := zetaContext.GetAllHeaderEnabledChains() - require.Equal(t, verFlags, verificationFlags) - }) + } + evmChainParamsToUpdate := map[int64]*observertypes.ChainParams{ + 1: { + ChainId: 1, + }, + 2: { + ChainId: 2, + }, + } + + testBtcChain := chains.BtcTestNetChain + btcChainParamsToUpdate := &observertypes.ChainParams{ + ChainId: testBtcChain.ChainId, + } + tssPubKeyToUpdate := "tsspubkeytest" + crosschainFlags := sample.CrosschainFlags() + verificationFlags := sample.HeaderSupportedChains() + require.NotNil(t, crosschainFlags) + loggers := clientcommon.DefaultLoggers() + zetaContext.Update( + &keyGenToUpdate, + enabledChainsToUpdate, + evmChainParamsToUpdate, + btcChainParamsToUpdate, + tssPubKeyToUpdate, + *crosschainFlags, + verificationFlags, + false, + loggers.Std, + ) + + // assert keygen updated + keyGen := zetaContext.GetKeygen() + require.Equal(t, keyGenToUpdate, keyGen) + + // assert enabled chains updated + require.Equal(t, enabledChainsToUpdate, zetaContext.GetEnabledChains()) + + // assert current tss pubkey updated + require.Equal(t, tssPubKeyToUpdate, zetaContext.GetCurrentTssPubkey()) + + // assert btc chain params + chain, btcChainParams, btcChainParamsFound := zetaContext.GetBTCChainParams() + require.Equal(t, testBtcChain, chain) + require.True(t, btcChainParamsFound) + require.Equal(t, btcChainParamsToUpdate, btcChainParams) + + // assert evm chain params + allEVMChainParams := zetaContext.GetAllEVMChainParams() + require.Equal(t, evmChainParamsToUpdate, allEVMChainParams) + + evmChainParams1, found := zetaContext.GetEVMChainParams(1) + require.True(t, found) + require.Equal(t, evmChainParamsToUpdate[1], evmChainParams1) + + evmChainParams2, found := zetaContext.GetEVMChainParams(2) + require.True(t, found) + require.Equal(t, evmChainParamsToUpdate[2], evmChainParams2) + + ccFlags := zetaContext.GetCrossChainFlags() + require.Equal(t, ccFlags, *crosschainFlags) + + verFlags := zetaContext.GetAllHeaderEnabledChains() + require.Equal(t, verFlags, verificationFlags) + }, + ) } func TestIsOutboundObservationEnabled(t *testing.T) { diff --git a/zetaclient/hsm/hsm_signer.go b/zetaclient/hsm/hsm_signer.go index 06cb9e092b..a6d513a353 100644 --- a/zetaclient/hsm/hsm_signer.go +++ b/zetaclient/hsm/hsm_signer.go @@ -32,7 +32,11 @@ func Sign(config *crypto11.Config, msg []byte, label string) (signature []byte, } // GenerateKey This generates a new key using one of the supported algorithms and a label identifier through the HSM -func GenerateKey(label string, algorithm keystone.KeygenAlgorithm, config *crypto11.Config) (*keystone.CryptoKey, error) { +func GenerateKey( + label string, + algorithm keystone.KeygenAlgorithm, + config *crypto11.Config, +) (*keystone.CryptoKey, error) { keyring, err := keystone.NewPkcs11(config) if err != nil { return nil, err diff --git a/zetaclient/keys/keys.go b/zetaclient/keys/keys.go index c709f8e6f8..9f346b77ca 100644 --- a/zetaclient/keys/keys.go +++ b/zetaclient/keys/keys.go @@ -34,7 +34,12 @@ type Keys struct { } // NewKeysWithKeybase create a new instance of Keys -func NewKeysWithKeybase(kb ckeys.Keyring, granterAddress sdk.AccAddress, granteeName string, hotkeyPassword string) *Keys { +func NewKeysWithKeybase( + kb ckeys.Keyring, + granterAddress sdk.AccAddress, + granteeName string, + hotkeyPassword string, +) *Keys { return &Keys{ signerName: granteeName, kb: kb, @@ -76,7 +81,8 @@ func GetKeyringKeybase(cfg config.Config, hotkeyPassword string) (ckeys.Keyring, }() os.Stdin = nil - logger.Debug().Msgf("Checking for Hotkey Key: %s \nFolder %s\nBackend %s", granteeName, chainHomeFolder, kb.Backend()) + logger.Debug(). + Msgf("Checking for Hotkey Key: %s \nFolder %s\nBackend %s", granteeName, chainHomeFolder, kb.Backend()) rc, err := kb.Key(granteeName) if err != nil { return nil, "", fmt.Errorf("key not in backend %s present with name (%s): %w", kb.Backend(), granteeName, err) diff --git a/zetaclient/keys/keys_test.go b/zetaclient/keys/keys_test.go index 1eaf8ed3e5..fb8bf38594 100644 --- a/zetaclient/keys/keys_test.go +++ b/zetaclient/keys/keys_test.go @@ -67,7 +67,13 @@ func (*KeysSuite) setupKeysForTest(c *C) string { kb, err := cKeys.New(sdk.KeyringServiceName(), cKeys.BackendTest, metaCliDir, buf, cdc) c.Assert(err, IsNil) - _, _, err = kb.NewMnemonic(GetGranteeKeyName(signerNameForTest), cKeys.English, cmd.ZetaChainHDPath, password, hd.Secp256k1) + _, _, err = kb.NewMnemonic( + GetGranteeKeyName(signerNameForTest), + cKeys.English, + cmd.ZetaChainHDPath, + password, + hd.Secp256k1, + ) c.Assert(err, IsNil) return metaCliDir } diff --git a/zetaclient/orchestrator/orchestrator.go b/zetaclient/orchestrator/orchestrator.go index 1ef669b301..9651f4bfa2 100644 --- a/zetaclient/orchestrator/orchestrator.go +++ b/zetaclient/orchestrator/orchestrator.go @@ -110,7 +110,10 @@ func (oc *Orchestrator) MonitorCore(appContext *context.AppContext) { } // GetUpdatedSigner returns signer with updated chain parameters -func (oc *Orchestrator) GetUpdatedSigner(coreContext *context.ZetacoreContext, chainID int64) (interfaces.ChainSigner, error) { +func (oc *Orchestrator) GetUpdatedSigner( + coreContext *context.ZetacoreContext, + chainID int64, +) (interfaces.ChainSigner, error) { signer, found := oc.signerMap[chainID] if !found { return nil, fmt.Errorf("signer not found for chainID %d", chainID) @@ -138,7 +141,10 @@ func (oc *Orchestrator) GetUpdatedSigner(coreContext *context.ZetacoreContext, c } // GetUpdatedChainObserver returns chain observer with updated chain parameters -func (oc *Orchestrator) GetUpdatedChainObserver(coreContext *context.ZetacoreContext, chainID int64) (interfaces.ChainObserver, error) { +func (oc *Orchestrator) GetUpdatedChainObserver( + coreContext *context.ZetacoreContext, + chainID int64, +) (interfaces.ChainObserver, error) { observer, found := oc.observerMap[chainID] if !found { return nil, fmt.Errorf("chain observer not found for chainID %d", chainID) @@ -165,7 +171,9 @@ func (oc *Orchestrator) GetUpdatedChainObserver(coreContext *context.ZetacoreCon } // GetPendingCctxsWithinRatelimit get pending cctxs across foreign chains within rate limit -func (oc *Orchestrator) GetPendingCctxsWithinRatelimit(foreignChains []chains.Chain) (map[int64][]*types.CrossChainTx, error) { +func (oc *Orchestrator) GetPendingCctxsWithinRatelimit( + foreignChains []chains.Chain, +) (map[int64][]*types.CrossChainTx, error) { // get rate limiter flags rateLimitFlags, err := oc.zetacoreClient.GetRateLimiterFlags() if err != nil { @@ -277,12 +285,16 @@ func (oc *Orchestrator) StartCctxScheduler(appContext *context.AppContext) { // update chain parameters for signer and chain observer signer, err := oc.GetUpdatedSigner(coreContext, c.ChainId) if err != nil { - oc.logger.Std.Error().Err(err).Msgf("StartCctxScheduler: GetUpdatedSigner failed for chain %d", c.ChainId) + oc.logger.Std.Error(). + Err(err). + Msgf("StartCctxScheduler: GetUpdatedSigner failed for chain %d", c.ChainId) continue } ob, err := oc.GetUpdatedChainObserver(coreContext, c.ChainId) if err != nil { - oc.logger.Std.Error().Err(err).Msgf("StartCctxScheduler: GetUpdatedChainObserver failed for chain %d", c.ChainId) + oc.logger.Std.Error(). + Err(err). + Msgf("StartCctxScheduler: GetUpdatedChainObserver failed for chain %d", c.ChainId) continue } if !context.IsOutboundObservationEnabled(coreContext, ob.GetChainParams()) { @@ -339,7 +351,8 @@ func (oc *Orchestrator) ScheduleCctxEVM( outTxID := outtxprocessor.ToOutTxID(cctx.Index, params.ReceiverChainId, nonce) if params.ReceiverChainId != chainID { - oc.logger.Std.Error().Msgf("ScheduleCctxEVM: outtx %s chainid mismatch: want %d, got %d", outTxID, chainID, params.ReceiverChainId) + oc.logger.Std.Error(). + Msgf("ScheduleCctxEVM: outtx %s chainid mismatch: want %d, got %d", outTxID, chainID, params.ReceiverChainId) continue } if params.OutboundTxTssNonce > cctxList[0].GetCurrentOutTxParam().OutboundTxTssNonce+outboundScheduleLookback { @@ -351,7 +364,9 @@ func (oc *Orchestrator) ScheduleCctxEVM( // try confirming the outtx included, _, err := observer.IsOutboundProcessed(cctx, oc.logger.Std) if err != nil { - oc.logger.Std.Error().Err(err).Msgf("ScheduleCctxEVM: IsOutboundProcessed faild for chain %d nonce %d", chainID, nonce) + oc.logger.Std.Error(). + Err(err). + Msgf("ScheduleCctxEVM: IsOutboundProcessed faild for chain %d nonce %d", chainID, nonce) continue } if included { @@ -381,9 +396,11 @@ func (oc *Orchestrator) ScheduleCctxEVM( } // otherwise, the normal interval is used - if nonce%outboundScheduleInterval == zetaHeight%outboundScheduleInterval && !oc.outTxProc.IsOutTxActive(outTxID) { + if nonce%outboundScheduleInterval == zetaHeight%outboundScheduleInterval && + !oc.outTxProc.IsOutTxActive(outTxID) { oc.outTxProc.StartTryProcess(outTxID) - oc.logger.Std.Debug().Msgf("ScheduleCctxEVM: sign outtx %s with value %d\n", outTxID, cctx.GetCurrentOutTxParam().Amount) + oc.logger.Std.Debug(). + Msgf("ScheduleCctxEVM: sign outtx %s with value %d\n", outTxID, cctx.GetCurrentOutTxParam().Amount) go signer.TryProcessOutTx(cctx, oc.outTxProc, outTxID, observer, oc.zetacoreClient, zetaHeight) } @@ -421,13 +438,16 @@ func (oc *Orchestrator) ScheduleCctxBTC( outTxID := outtxprocessor.ToOutTxID(cctx.Index, params.ReceiverChainId, nonce) if params.ReceiverChainId != chainID { - oc.logger.Std.Error().Msgf("ScheduleCctxBTC: outtx %s chainid mismatch: want %d, got %d", outTxID, chainID, params.ReceiverChainId) + oc.logger.Std.Error(). + Msgf("ScheduleCctxBTC: outtx %s chainid mismatch: want %d, got %d", outTxID, chainID, params.ReceiverChainId) continue } // try confirming the outtx included, confirmed, err := btcObserver.IsOutboundProcessed(cctx, oc.logger.Std) if err != nil { - oc.logger.Std.Error().Err(err).Msgf("ScheduleCctxBTC: IsOutboundProcessed faild for chain %d nonce %d", chainID, nonce) + oc.logger.Std.Error(). + Err(err). + Msgf("ScheduleCctxBTC: IsOutboundProcessed faild for chain %d nonce %d", chainID, nonce) continue } if included || confirmed { @@ -440,8 +460,11 @@ func (oc *Orchestrator) ScheduleCctxBTC( break } // stop if lookahead is reached - if int64(idx) >= lookahead { // 2 bitcoin confirmations span is 20 minutes on average. We look ahead up to 100 pending cctx to target TPM of 5. - oc.logger.Std.Warn().Msgf("ScheduleCctxBTC: lookahead reached, signing %d, earliest pending %d", nonce, cctxList[0].GetCurrentOutTxParam().OutboundTxTssNonce) + if int64( + idx, + ) >= lookahead { // 2 bitcoin confirmations span is 20 minutes on average. We look ahead up to 100 pending cctx to target TPM of 5. + oc.logger.Std.Warn(). + Msgf("ScheduleCctxBTC: lookahead reached, signing %d, earliest pending %d", nonce, cctxList[0].GetCurrentOutTxParam().OutboundTxTssNonce) break } // try confirming the outtx or scheduling a keysign diff --git a/zetaclient/orchestrator/orchestrator_test.go b/zetaclient/orchestrator/orchestrator_test.go index e28b4ee565..0f90db9b33 100644 --- a/zetaclient/orchestrator/orchestrator_test.go +++ b/zetaclient/orchestrator/orchestrator_test.go @@ -52,7 +52,10 @@ func MockOrchestrator( return orchestrator } -func CreateCoreContext(evmChain, btcChain chains.Chain, evmChainParams, btcChainParams *observertypes.ChainParams) *context.ZetacoreContext { +func CreateCoreContext( + evmChain, btcChain chains.Chain, + evmChainParams, btcChainParams *observertypes.ChainParams, +) *context.ZetacoreContext { // new config cfg := config.NewConfig() cfg.EVMChainConfigs[evmChain.ChainId] = config.EVMConfig{ @@ -214,13 +217,49 @@ func Test_GetPendingCctxsWithinRatelimit(t *testing.T) { btcChainParams := &observertypes.ChainParams{ChainId: btcChain.ChainId} // create 10 missed and 90 pending cctxs for eth chain, the coinType/amount does not matter for this test - ethCctxsMissed := sample.CustomCctxsInBlockRange(t, 1, 10, ethChain.ChainId, coin.CoinType_Gas, "", uint64(2e14), crosschaintypes.CctxStatus_PendingOutbound) - ethCctxsPending := sample.CustomCctxsInBlockRange(t, 11, 100, ethChain.ChainId, coin.CoinType_Gas, "", uint64(2e14), crosschaintypes.CctxStatus_PendingOutbound) + ethCctxsMissed := sample.CustomCctxsInBlockRange( + t, + 1, + 10, + ethChain.ChainId, + coin.CoinType_Gas, + "", + uint64(2e14), + crosschaintypes.CctxStatus_PendingOutbound, + ) + ethCctxsPending := sample.CustomCctxsInBlockRange( + t, + 11, + 100, + ethChain.ChainId, + coin.CoinType_Gas, + "", + uint64(2e14), + crosschaintypes.CctxStatus_PendingOutbound, + ) ethCctxsAll := append(append([]*crosschaintypes.CrossChainTx{}, ethCctxsMissed...), ethCctxsPending...) // create 10 missed and 90 pending cctxs for btc chain, the coinType/amount does not matter for this test - btcCctxsMissed := sample.CustomCctxsInBlockRange(t, 1, 10, btcChain.ChainId, coin.CoinType_Gas, "", 2000, crosschaintypes.CctxStatus_PendingOutbound) - btcCctxsPending := sample.CustomCctxsInBlockRange(t, 11, 100, btcChain.ChainId, coin.CoinType_Gas, "", 2000, crosschaintypes.CctxStatus_PendingOutbound) + btcCctxsMissed := sample.CustomCctxsInBlockRange( + t, + 1, + 10, + btcChain.ChainId, + coin.CoinType_Gas, + "", + 2000, + crosschaintypes.CctxStatus_PendingOutbound, + ) + btcCctxsPending := sample.CustomCctxsInBlockRange( + t, + 11, + 100, + btcChain.ChainId, + coin.CoinType_Gas, + "", + 2000, + crosschaintypes.CctxStatus_PendingOutbound, + ) btcCctxsAll := append(append([]*crosschaintypes.CrossChainTx{}, btcCctxsMissed...), btcCctxsPending...) // all missed cctxs and all pending cctxs across all foreign chains diff --git a/zetaclient/outtxprocessor/out_tx_processor.go b/zetaclient/outtxprocessor/out_tx_processor.go index d5dbec77ee..66445694ca 100644 --- a/zetaclient/outtxprocessor/out_tx_processor.go +++ b/zetaclient/outtxprocessor/out_tx_processor.go @@ -43,7 +43,8 @@ func (outTxProc *Processor) EndTryProcess(outTxID string) { outTxProc.outTxEndTime[outTxID] = time.Now() delete(outTxProc.outTxActive, outTxID) outTxProc.numActiveProcessor-- - outTxProc.Logger.Info().Msgf("EndTryProcess %s, numActiveProcessor %d, time elapsed %s", outTxID, outTxProc.numActiveProcessor, time.Since(outTxProc.outTxStartTime[outTxID])) + outTxProc.Logger.Info(). + Msgf("EndTryProcess %s, numActiveProcessor %d, time elapsed %s", outTxID, outTxProc.numActiveProcessor, time.Since(outTxProc.outTxStartTime[outTxID])) } func (outTxProc *Processor) IsOutTxActive(outTxID string) bool { diff --git a/zetaclient/ratelimiter/rate_limiter_test.go b/zetaclient/ratelimiter/rate_limiter_test.go index 0f6c3a0e73..e83db0db57 100644 --- a/zetaclient/ratelimiter/rate_limiter_test.go +++ b/zetaclient/ratelimiter/rate_limiter_test.go @@ -117,14 +117,50 @@ func Test_ApplyRateLimiter(t *testing.T) { // create 10 missed and 90 pending cctxs for eth chain, the coinType/amount does not matter for this test // but we still use a proper cctx value (0.5 ZETA) to make the test more realistic - ethCctxsMissed := sample.CustomCctxsInBlockRange(t, 1, 10, ethChainID, coin.CoinType_Gas, "", uint64(2e14), crosschaintypes.CctxStatus_PendingOutbound) - ethCctxsPending := sample.CustomCctxsInBlockRange(t, 11, 100, ethChainID, coin.CoinType_Gas, "", uint64(2e14), crosschaintypes.CctxStatus_PendingOutbound) + ethCctxsMissed := sample.CustomCctxsInBlockRange( + t, + 1, + 10, + ethChainID, + coin.CoinType_Gas, + "", + uint64(2e14), + crosschaintypes.CctxStatus_PendingOutbound, + ) + ethCctxsPending := sample.CustomCctxsInBlockRange( + t, + 11, + 100, + ethChainID, + coin.CoinType_Gas, + "", + uint64(2e14), + crosschaintypes.CctxStatus_PendingOutbound, + ) ethCctxsAll := append(append([]*crosschaintypes.CrossChainTx{}, ethCctxsMissed...), ethCctxsPending...) // create 10 missed and 90 pending cctxs for btc chain, the coinType/amount does not matter for this test // but we still use a proper cctx value (0.5 ZETA) to make the test more realistic - btcCctxsMissed := sample.CustomCctxsInBlockRange(t, 1, 10, btcChainID, coin.CoinType_Gas, "", 2000, crosschaintypes.CctxStatus_PendingOutbound) - btcCctxsPending := sample.CustomCctxsInBlockRange(t, 11, 100, btcChainID, coin.CoinType_Gas, "", 2000, crosschaintypes.CctxStatus_PendingOutbound) + btcCctxsMissed := sample.CustomCctxsInBlockRange( + t, + 1, + 10, + btcChainID, + coin.CoinType_Gas, + "", + 2000, + crosschaintypes.CctxStatus_PendingOutbound, + ) + btcCctxsPending := sample.CustomCctxsInBlockRange( + t, + 11, + 100, + btcChainID, + coin.CoinType_Gas, + "", + 2000, + crosschaintypes.CctxStatus_PendingOutbound, + ) btcCctxsAll := append(append([]*crosschaintypes.CrossChainTx{}, btcCctxsMissed...), btcCctxsPending...) // all missed cctxs and all pending cctxs across all chains @@ -202,9 +238,11 @@ func Test_ApplyRateLimiter(t *testing.T) { ethChainID: ethCctxsMissed, btcChainID: btcCctxsMissed, }, - CurrentWithdrawWindow: 100, // height [1, 100] - CurrentWithdrawRate: sdk.NewInt(101e16), // (11 + 90) / 100 = 1.01 ZETA/block (exceeds 0.99 ZETA/block) - RateLimitExceeded: true, + CurrentWithdrawWindow: 100, // height [1, 100] + CurrentWithdrawRate: sdk.NewInt( + 101e16, + ), // (11 + 90) / 100 = 1.01 ZETA/block (exceeds 0.99 ZETA/block) + RateLimitExceeded: true, }, }, { @@ -224,9 +262,12 @@ func Test_ApplyRateLimiter(t *testing.T) { ethChainID: ethCctxsMissed, btcChainID: btcCctxsMissed, }, - CurrentWithdrawWindow: 90, // [LowestPendingCctxHeight, Height] = [11, 100] - CurrentWithdrawRate: sdk.NewInt(91).Mul(sdk.NewInt(1e18)).Quo(sdk.NewInt(90)), // 91 / 90 = 1.011111111111111111 ZETA/block - RateLimitExceeded: true, + CurrentWithdrawWindow: 90, // [LowestPendingCctxHeight, Height] = [11, 100] + CurrentWithdrawRate: sdk.NewInt(91). + Mul(sdk.NewInt(1e18)). + Quo(sdk.NewInt(90)), + // 91 / 90 = 1.011111111111111111 ZETA/block + RateLimitExceeded: true, }, }, { @@ -246,9 +287,12 @@ func Test_ApplyRateLimiter(t *testing.T) { ethChainID: ethCctxsAll, btcChainID: btcCctxsAll, }, - CurrentWithdrawWindow: 91, // [LowestPendingCctxHeight, Height] = [11, 101] - CurrentWithdrawRate: sdk.NewInt(91).Mul(sdk.NewInt(1e18)).Quo(sdk.NewInt(91)), // 91 / 91 = 1.011 ZETA/block - RateLimitExceeded: false, + CurrentWithdrawWindow: 91, // [LowestPendingCctxHeight, Height] = [11, 101] + CurrentWithdrawRate: sdk.NewInt(91). + Mul(sdk.NewInt(1e18)). + Quo(sdk.NewInt(91)), + // 91 / 91 = 1.011 ZETA/block + RateLimitExceeded: false, }, }, } diff --git a/zetaclient/supplychecker/validate.go b/zetaclient/supplychecker/validate.go index 089a34777e..d70bda8c34 100644 --- a/zetaclient/supplychecker/validate.go +++ b/zetaclient/supplychecker/validate.go @@ -5,7 +5,10 @@ import ( "github.com/rs/zerolog" ) -func ValidateZetaSupply(logger zerolog.Logger, abortedTxAmounts, zetaInTransit, genesisAmounts, externalChainTotalSupply, zetaTokenSupplyOnNode, ethLockedAmount sdkmath.Int) bool { +func ValidateZetaSupply( + logger zerolog.Logger, + abortedTxAmounts, zetaInTransit, genesisAmounts, externalChainTotalSupply, zetaTokenSupplyOnNode, ethLockedAmount sdkmath.Int, +) bool { lhs := ethLockedAmount.Sub(abortedTxAmounts) rhs := zetaTokenSupplyOnNode.Add(zetaInTransit).Add(externalChainTotalSupply).Sub(genesisAmounts) diff --git a/zetaclient/supplychecker/zeta_supply_checker.go b/zetaclient/supplychecker/zeta_supply_checker.go index 60438213c5..bd1fb37584 100644 --- a/zetaclient/supplychecker/zeta_supply_checker.go +++ b/zetaclient/supplychecker/zeta_supply_checker.go @@ -85,7 +85,8 @@ func NewZetaSupplyChecker( } zetaSupplyChecker.genesisSupply = balances.Add(tokensMintedAtBeginBlock) - logger.Info().Msgf("zeta supply checker initialized , external chains : %v ,ethereum chain :%v", zetaSupplyChecker.externalEvmChain, zetaSupplyChecker.ethereumChain) + logger.Info(). + Msgf("zeta supply checker initialized , external chains : %v ,ethereum chain :%v", zetaSupplyChecker.externalEvmChain, zetaSupplyChecker.ethereumChain) return zetaSupplyChecker, nil } @@ -147,7 +148,10 @@ func (zs *ZetaSupplyChecker) CheckZetaTokenSupply() error { ethConnectorAddressString := evmChainParams.ConnectorContractAddress ethConnectorAddress := ethcommon.HexToAddress(ethConnectorAddressString) - ethConnectorContract, err := observer.FetchConnectorContractEth(ethConnectorAddress, zs.evmClient[zs.ethereumChain.ChainId]) + ethConnectorContract, err := observer.FetchConnectorContractEth( + ethConnectorAddress, + zs.evmClient[zs.ethereumChain.ChainId], + ) if err != nil { return err } @@ -173,7 +177,15 @@ func (zs *ZetaSupplyChecker) CheckZetaTokenSupply() error { return err } - ValidateZetaSupply(zs.logger, abortedAmount, zetaInTransit, zs.genesisSupply, externalChainTotalSupply, zetaTokenSupplyOnNode, ethLockedAmountInt) + ValidateZetaSupply( + zs.logger, + abortedAmount, + zetaInTransit, + zs.genesisSupply, + externalChainTotalSupply, + zetaTokenSupplyOnNode, + ethLockedAmountInt, + ) return nil } diff --git a/zetaclient/supplychecker/zeta_supply_checker_test.go b/zetaclient/supplychecker/zeta_supply_checker_test.go index 73e3afd32d..3ddf5c917b 100644 --- a/zetaclient/supplychecker/zeta_supply_checker_test.go +++ b/zetaclient/supplychecker/zeta_supply_checker_test.go @@ -46,7 +46,18 @@ func TestZetaSupplyChecker_ValidateZetaSupply(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { logger := zerolog.New(os.Stdout).With().Timestamp().Logger() - tc.validate(t, ValidateZetaSupply(logger, tc.abortedTxAmount, tc.zetaInTransit, tc.genesisAmounts, tc.externalChainTotalSupply, tc.zetaTokenSupplyOnNode, tc.ethLockedAmount)) + tc.validate( + t, + ValidateZetaSupply( + logger, + tc.abortedTxAmount, + tc.zetaInTransit, + tc.genesisAmounts, + tc.externalChainTotalSupply, + tc.zetaTokenSupplyOnNode, + tc.ethLockedAmount, + ), + ) }) } } diff --git a/zetaclient/testutils/evm.go b/zetaclient/testutils/evm.go index 5b252a9ecb..3007fa6035 100644 --- a/zetaclient/testutils/evm.go +++ b/zetaclient/testutils/evm.go @@ -7,7 +7,10 @@ import ( ) // ParseReceiptZetaSent parses a ZetaSent event from a receipt -func ParseReceiptZetaSent(receipt *ethtypes.Receipt, connector *zetaconnector.ZetaConnectorNonEth) *zetaconnector.ZetaConnectorNonEthZetaSent { +func ParseReceiptZetaSent( + receipt *ethtypes.Receipt, + connector *zetaconnector.ZetaConnectorNonEth, +) *zetaconnector.ZetaConnectorNonEthZetaSent { for _, log := range receipt.Logs { event, err := connector.ParseZetaSent(*log) if err == nil && event != nil { @@ -18,7 +21,10 @@ func ParseReceiptZetaSent(receipt *ethtypes.Receipt, connector *zetaconnector.Ze } // ParseReceiptERC20Deposited parses an Deposited event from a receipt -func ParseReceiptERC20Deposited(receipt *ethtypes.Receipt, custody *erc20custody.ERC20Custody) *erc20custody.ERC20CustodyDeposited { +func ParseReceiptERC20Deposited( + receipt *ethtypes.Receipt, + custody *erc20custody.ERC20Custody, +) *erc20custody.ERC20CustodyDeposited { for _, log := range receipt.Logs { event, err := custody.ParseDeposited(*log) if err == nil && event != nil { diff --git a/zetaclient/testutils/mocks/btc_rpc.go b/zetaclient/testutils/mocks/btc_rpc.go index 7b96010b8a..93044e8a03 100644 --- a/zetaclient/testutils/mocks/btc_rpc.go +++ b/zetaclient/testutils/mocks/btc_rpc.go @@ -59,11 +59,18 @@ func (c *MockBTCRPCClient) ListUnspent() ([]btcjson.ListUnspentResult, error) { return nil, errors.New("not implemented") } -func (c *MockBTCRPCClient) ListUnspentMinMaxAddresses(_ int, _ int, _ []btcutil.Address) ([]btcjson.ListUnspentResult, error) { +func (c *MockBTCRPCClient) ListUnspentMinMaxAddresses( + _ int, + _ int, + _ []btcutil.Address, +) ([]btcjson.ListUnspentResult, error) { return nil, errors.New("not implemented") } -func (c *MockBTCRPCClient) EstimateSmartFee(_ int64, _ *btcjson.EstimateSmartFeeMode) (*btcjson.EstimateSmartFeeResult, error) { +func (c *MockBTCRPCClient) EstimateSmartFee( + _ int64, + _ *btcjson.EstimateSmartFeeMode, +) (*btcjson.EstimateSmartFeeResult, error) { return nil, errors.New("not implemented") } diff --git a/zetaclient/testutils/mocks/evm_rpc.go b/zetaclient/testutils/mocks/evm_rpc.go index 054f43461c..05216976b6 100644 --- a/zetaclient/testutils/mocks/evm_rpc.go +++ b/zetaclient/testutils/mocks/evm_rpc.go @@ -38,7 +38,11 @@ func NewMockEvmClient() *MockEvmClient { return client.Reset() } -func (e *MockEvmClient) SubscribeFilterLogs(_ context.Context, _ ethereum.FilterQuery, _ chan<- ethtypes.Log) (ethereum.Subscription, error) { +func (e *MockEvmClient) SubscribeFilterLogs( + _ context.Context, + _ ethereum.FilterQuery, + _ chan<- ethtypes.Log, +) (ethereum.Subscription, error) { return subscription{}, nil } @@ -92,7 +96,10 @@ func (e *MockEvmClient) BlockByNumber(_ context.Context, _ *big.Int) (*ethtypes. return ðtypes.Block{}, nil } -func (e *MockEvmClient) TransactionByHash(_ context.Context, _ ethcommon.Hash) (tx *ethtypes.Transaction, isPending bool, err error) { +func (e *MockEvmClient) TransactionByHash( + _ context.Context, + _ ethcommon.Hash, +) (tx *ethtypes.Transaction, isPending bool, err error) { return ðtypes.Transaction{}, false, nil } @@ -106,7 +113,12 @@ func (e *MockEvmClient) TransactionReceipt(_ context.Context, _ ethcommon.Hash) return nil, errors.New("no receipt found") } -func (e *MockEvmClient) TransactionSender(_ context.Context, _ *ethtypes.Transaction, _ ethcommon.Hash, _ uint) (ethcommon.Address, error) { +func (e *MockEvmClient) TransactionSender( + _ context.Context, + _ *ethtypes.Transaction, + _ ethcommon.Hash, + _ uint, +) (ethcommon.Address, error) { return ethcommon.Address{}, nil } diff --git a/zetaclient/testutils/mocks/keyring.go b/zetaclient/testutils/mocks/keyring.go index 383a9d5887..4e04cca0ea 100644 --- a/zetaclient/testutils/mocks/keyring.go +++ b/zetaclient/testutils/mocks/keyring.go @@ -54,7 +54,12 @@ func (m Keyring) Rename(_ string, _ string) error { return nil } -func (m Keyring) NewMnemonic(_ string, _ ckeys.Language, _, _ string, _ ckeys.SignatureAlgo) (*ckeys.Record, string, error) { +func (m Keyring) NewMnemonic( + _ string, + _ ckeys.Language, + _, _ string, + _ ckeys.SignatureAlgo, +) (*ckeys.Record, string, error) { return nil, "", nil } diff --git a/zetaclient/testutils/mocks/tss_signer.go b/zetaclient/testutils/mocks/tss_signer.go index 626e41785a..e14a6768c8 100644 --- a/zetaclient/testutils/mocks/tss_signer.go +++ b/zetaclient/testutils/mocks/tss_signer.go @@ -112,7 +112,10 @@ func (s *TSS) BTCAddressWitnessPubkeyHash() *btcutil.AddressWitnessPubKeyHash { // witness program: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#Witness_program // The HASH160 of the public key must match the 20-byte witness program. - addrWPKH, err := btcutil.NewAddressWitnessPubKeyHash(btcutil.Hash160(pk.SerializeCompressed()), &chaincfg.TestNet3Params) + addrWPKH, err := btcutil.NewAddressWitnessPubKeyHash( + btcutil.Hash160(pk.SerializeCompressed()), + &chaincfg.TestNet3Params, + ) if err != nil { fmt.Printf("error NewAddressWitnessPubKeyHash: %v", err) return nil diff --git a/zetaclient/testutils/mocks/zetacore_client.go b/zetaclient/testutils/mocks/zetacore_client.go index 0e479a2c7f..7330c35323 100644 --- a/zetaclient/testutils/mocks/zetacore_client.go +++ b/zetaclient/testutils/mocks/zetacore_client.go @@ -51,14 +51,29 @@ func NewMockZetaCoreClient() *MockZetaCoreClient { } } -func (z *MockZetaCoreClient) PostVoteInbound(_, _ uint64, _ *crosschaintypes.MsgVoteOnObservedInboundTx) (string, string, error) { +func (z *MockZetaCoreClient) PostVoteInbound( + _, _ uint64, + _ *crosschaintypes.MsgVoteOnObservedInboundTx, +) (string, string, error) { if z.paused { return "", "", errors.New(ErrMsgPaused) } return "", "", nil } -func (z *MockZetaCoreClient) PostVoteOutbound(_ string, _ string, _ uint64, _ uint64, _ *big.Int, _ uint64, _ *big.Int, _ chains.ReceiveStatus, _ chains.Chain, _ uint64, _ coin.CoinType) (string, string, error) { +func (z *MockZetaCoreClient) PostVoteOutbound( + _ string, + _ string, + _ uint64, + _ uint64, + _ *big.Int, + _ uint64, + _ *big.Int, + _ chains.ReceiveStatus, + _ chains.Chain, + _ uint64, + _ coin.CoinType, +) (string, string, error) { if z.paused { return "", "", errors.New(ErrMsgPaused) } @@ -93,7 +108,14 @@ func (z *MockZetaCoreClient) PostBlameData(_ *blame.Blame, _ int64, _ string) (s return "", nil } -func (z *MockZetaCoreClient) AddTxHashToOutTxTracker(_ int64, _ uint64, _ string, _ *proofs.Proof, _ string, _ int64) (string, error) { +func (z *MockZetaCoreClient) AddTxHashToOutTxTracker( + _ int64, + _ uint64, + _ string, + _ *proofs.Proof, + _ string, + _ int64, +) (string, error) { if z.paused { return "", errors.New(ErrMsgPaused) } @@ -178,7 +200,10 @@ func (z *MockZetaCoreClient) GetOutTxTracker(_ chains.Chain, _ uint64) (*crossch return &crosschaintypes.OutTxTracker{}, nil } -func (z *MockZetaCoreClient) GetAllOutTxTrackerByChain(_ int64, _ interfaces.Order) ([]crosschaintypes.OutTxTracker, error) { +func (z *MockZetaCoreClient) GetAllOutTxTrackerByChain( + _ int64, + _ interfaces.Order, +) ([]crosschaintypes.OutTxTracker, error) { if z.paused { return nil, errors.New(ErrMsgPaused) } @@ -252,7 +277,9 @@ func (z *MockZetaCoreClient) WithRateLimiterFlags(flags *crosschaintypes.RateLim return z } -func (z *MockZetaCoreClient) WithRateLimiterInput(input *crosschaintypes.QueryRateLimiterInputResponse) *MockZetaCoreClient { +func (z *MockZetaCoreClient) WithRateLimiterInput( + input *crosschaintypes.QueryRateLimiterInputResponse, +) *MockZetaCoreClient { z.input = input return z } diff --git a/zetaclient/testutils/testdata.go b/zetaclient/testutils/testdata.go index 22b508c36b..1ed42f58a3 100644 --- a/zetaclient/testutils/testdata.go +++ b/zetaclient/testutils/testdata.go @@ -109,7 +109,12 @@ func LoadBTCIntxRawResult(t *testing.T, dir string, chainID int64, txHash string } // LoadBTCTxRawResultNCctx loads archived Bitcoin outtx raw result and corresponding cctx -func LoadBTCTxRawResultNCctx(t *testing.T, dir string, chainID int64, nonce uint64) (*btcjson.TxRawResult, *crosschaintypes.CrossChainTx) { +func LoadBTCTxRawResultNCctx( + t *testing.T, + dir string, + chainID int64, + nonce uint64, +) (*btcjson.TxRawResult, *crosschaintypes.CrossChainTx) { nameTx := path.Join(dir, TestDataPathBTC, FileNameBTCOuttx(chainID, nonce)) rawResult := &btcjson.TxRawResult{} LoadObjectFromJSONFile(t, rawResult, nameTx) diff --git a/zetaclient/tss/tss_signer.go b/zetaclient/tss/tss_signer.go index 610b93faf5..30c5ef24c8 100644 --- a/zetaclient/tss/tss_signer.go +++ b/zetaclient/tss/tss_signer.go @@ -213,7 +213,13 @@ func (tss *TSS) Pubkey() []byte { // Sign signs a digest // digest should be Hashes of some data // NOTE: Specify optionalPubkey to use a different pubkey than the current pubkey set during keygen -func (tss *TSS) Sign(digest []byte, height uint64, nonce uint64, chain *chains.Chain, optionalPubKey string) ([65]byte, error) { +func (tss *TSS) Sign( + digest []byte, + height uint64, + nonce uint64, + chain *chains.Chain, + optionalPubKey string, +) ([65]byte, error) { H := digest log.Debug().Msgf("hash of digest is %s", H) @@ -223,7 +229,13 @@ func (tss *TSS) Sign(digest []byte, height uint64, nonce uint64, chain *chains.C } // #nosec G701 always in range - keysignReq := keysign.NewRequest(tssPubkey, []string{base64.StdEncoding.EncodeToString(H)}, int64(height), nil, "0.14.0") + keysignReq := keysign.NewRequest( + tssPubkey, + []string{base64.StdEncoding.EncodeToString(H)}, + int64(height), + nil, + "0.14.0", + ) tss.KeysignsTracker.StartMsgSign() ksRes, err := tss.Server.KeySign(keysignReq) tss.KeysignsTracker.EndMsgSign() @@ -333,7 +345,9 @@ func (tss *TSS) SignBatch(digests [][]byte, height uint64, nonce uint64, chain * // 32B msg hash, 32B R, 32B S, 1B RC if len(signatures) != len(digests) { - log.Warn().Err(err).Msgf("signature has length (%d) not equal to length of digests (%d)", len(signatures), len(digests)) + log.Warn(). + Err(err). + Msgf("signature has length (%d) not equal to length of digests (%d)", len(signatures), len(digests)) return [][65]byte{}, fmt.Errorf("keysign fail: %s", err) } @@ -374,7 +388,8 @@ func (tss *TSS) SignBatch(digests [][]byte, height uint64, nonce uint64, chain * } compressedPubkey := crypto.CompressPubkey(sigPublicKey) if !bytes.Equal(pubkey.Bytes(), compressedPubkey) { - log.Warn().Msgf("%d-th pubkey %s recovered pubkey %s", j, pubkey.String(), hex.EncodeToString(compressedPubkey)) + log.Warn(). + Msgf("%d-th pubkey %s recovered pubkey %s", j, pubkey.String(), hex.EncodeToString(compressedPubkey)) return [][65]byte{}, fmt.Errorf("signuature verification fail") } } @@ -548,7 +563,13 @@ func TestKeysign(tssPubkey string, tssServer *tss.TssServer) error { H := crypto.Keccak256Hash(data) log.Info().Msgf("hash of data (hello meta) is %s", H) - keysignReq := keysign.NewRequest(tssPubkey, []string{base64.StdEncoding.EncodeToString(H.Bytes())}, 10, nil, "0.14.0") + keysignReq := keysign.NewRequest( + tssPubkey, + []string{base64.StdEncoding.EncodeToString(H.Bytes())}, + 10, + nil, + "0.14.0", + ) ksRes, err := tssServer.KeySign(keysignReq) if err != nil { log.Warn().Msg("keysign fail") diff --git a/zetaclient/zetacore/broadcast.go b/zetaclient/zetacore/broadcast.go index d160fdd1c6..f1c81a8821 100644 --- a/zetaclient/zetacore/broadcast.go +++ b/zetaclient/zetacore/broadcast.go @@ -40,7 +40,12 @@ var ( ) // BroadcastToZetaCore is the default broadcast function used to send transactions to zetacore -func BroadcastToZetaCore(client *Client, gasLimit uint64, authzWrappedMsg sdktypes.Msg, authzSigner authz.Signer) (string, error) { +func BroadcastToZetaCore( + client *Client, + gasLimit uint64, + authzWrappedMsg sdktypes.Msg, + authzSigner authz.Signer, +) (string, error) { return client.Broadcast(gasLimit, authzWrappedMsg, authzSigner) } @@ -138,7 +143,8 @@ func (c *Client) Broadcast(gaslimit uint64, authzWrappedMsg sdktypes.Msg, authzS return "", err } c.seqNumber[authzSigner.KeyType] = expectedSeq - c.logger.Warn().Msgf("Reset seq number to %d (from err msg) from %d", c.seqNumber[authzSigner.KeyType], gotSeq) + c.logger.Warn(). + Msgf("Reset seq number to %d (from err msg) from %d", c.seqNumber[authzSigner.KeyType], gotSeq) } return commit.TxHash, fmt.Errorf("fail to broadcast to zetachain,code:%d, log:%s", commit.Code, commit.RawLog) } @@ -223,7 +229,9 @@ func (c *Client) QueryTxResult(hash string) (*sdktypes.TxResponse, error) { // returns (bool retry, bool report) func HandleBroadcastError(err error, nonce, toChain, outTxHash string) (bool, bool) { if strings.Contains(err.Error(), "nonce too low") { - log.Warn().Err(err).Msgf("nonce too low! this might be a unnecessary key-sign. increase re-try interval and awaits outTx confirmation") + log.Warn(). + Err(err). + Msgf("nonce too low! this might be a unnecessary key-sign. increase re-try interval and awaits outTx confirmation") return false, false } if strings.Contains(err.Error(), "replacement transaction underpriced") { diff --git a/zetaclient/zetacore/broadcast_test.go b/zetaclient/zetacore/broadcast_test.go index fbf9c756cf..f4f19d7adf 100644 --- a/zetaclient/zetacore/broadcast_test.go +++ b/zetaclient/zetacore/broadcast_test.go @@ -79,7 +79,13 @@ func TestBroadcast(t *testing.T) { client.EnableMockSDKClient(mocks.NewSDKClientWithErr(nil, 0)) blockHash, err := hex.DecodeString(ethBlockHash) require.NoError(t, err) - msg := observerTypes.NewMsgVoteBlockHeader(address.String(), chains.EthChain.ChainId, blockHash, 18495266, getHeaderData(t)) + msg := observerTypes.NewMsgVoteBlockHeader( + address.String(), + chains.EthChain.ChainId, + blockHash, + 18495266, + getHeaderData(t), + ) authzMsg, authzSigner, err := client.WrapMessageWithAuthz(msg) require.NoError(t, err) _, err = BroadcastToZetaCore(client, 10000, authzMsg, authzSigner) @@ -87,10 +93,18 @@ func TestBroadcast(t *testing.T) { }) t.Run("broadcast failed", func(t *testing.T) { - client.EnableMockSDKClient(mocks.NewSDKClientWithErr(errors.New("account sequence mismatch, expected 5 got 4"), 32)) + client.EnableMockSDKClient( + mocks.NewSDKClientWithErr(errors.New("account sequence mismatch, expected 5 got 4"), 32), + ) blockHash, err := hex.DecodeString(ethBlockHash) require.NoError(t, err) - msg := observerTypes.NewMsgVoteBlockHeader(address.String(), chains.EthChain.ChainId, blockHash, 18495266, getHeaderData(t)) + msg := observerTypes.NewMsgVoteBlockHeader( + address.String(), + chains.EthChain.ChainId, + blockHash, + 18495266, + getHeaderData(t), + ) authzMsg, authzSigner, err := client.WrapMessageWithAuthz(msg) require.NoError(t, err) _, err = BroadcastToZetaCore(client, 10000, authzMsg, authzSigner) diff --git a/zetaclient/zetacore/client.go b/zetaclient/zetacore/client.go index 0fb3d9bdc6..53f1e4cabc 100644 --- a/zetaclient/zetacore/client.go +++ b/zetaclient/zetacore/client.go @@ -182,7 +182,11 @@ func (c *Client) WaitForCoreToCreateBlocks() { // UpdateZetacoreContext updates zetacore context // zetacore stores zetacore context for all clients -func (c *Client) UpdateZetacoreContext(coreContext *context.ZetacoreContext, init bool, sampledLogger zerolog.Logger) error { +func (c *Client) UpdateZetacoreContext( + coreContext *context.ZetacoreContext, + init bool, + sampledLogger zerolog.Logger, +) error { bn, err := c.GetBlockHeight() if err != nil { return fmt.Errorf("failed to get zetablock height: %w", err) @@ -193,8 +197,9 @@ func (c *Client) UpdateZetacoreContext(coreContext *context.ZetacoreContext, ini return fmt.Errorf("failed to get upgrade plan: %w", err) } if plan != nil && bn == plan.Height-1 { // stop zetaclients; notify operator to upgrade and restart - c.logger.Warn().Msgf("Active upgrade plan detected and upgrade height reached: %s at height %d; ZetaClient is stopped;"+ - "please kill this process, replace zetaclientd binary with upgraded version, and restart zetaclientd", plan.Name, plan.Height) + c.logger.Warn(). + Msgf("Active upgrade plan detected and upgrade height reached: %s at height %d; ZetaClient is stopped;"+ + "please kill this process, replace zetaclientd binary with upgraded version, and restart zetaclientd", plan.Name, plan.Height) c.pause <- struct{}{} // notify Orchestrator to stop Observers, Signers, and Orchestrator itself } diff --git a/zetaclient/zetacore/query.go b/zetaclient/zetacore/query.go index e1ed7c25f2..f6575358e0 100644 --- a/zetaclient/zetacore/query.go +++ b/zetaclient/zetacore/query.go @@ -53,7 +53,10 @@ func (c *Client) GetRateLimiterFlags() (crosschaintypes.RateLimiterFlags, error) func (c *Client) GetChainParamsForChainID(externalChainID int64) (*observertypes.ChainParams, error) { client := observertypes.NewQueryClient(c.grpcConn) - resp, err := client.GetChainParamsForChain(context.Background(), &observertypes.QueryGetChainParamsForChainRequest{ChainId: externalChainID}) + resp, err := client.GetChainParamsForChain( + context.Background(), + &observertypes.QueryGetChainParamsForChainRequest{ChainId: externalChainID}, + ) if err != nil { return &observertypes.ChainParams{}, err } @@ -252,7 +255,10 @@ func (c *Client) GetNodeInfo() (*tmservice.GetNodeInfoResponse, error) { func (c *Client) GetLastBlockHeightByChain(chain chains.Chain) (*crosschaintypes.LastBlockHeight, error) { client := crosschaintypes.NewQueryClient(c.grpcConn) - resp, err := client.LastBlockHeight(context.Background(), &crosschaintypes.QueryGetLastBlockHeightRequest{Index: chain.ChainName.String()}) + resp, err := client.LastBlockHeight( + context.Background(), + &crosschaintypes.QueryGetLastBlockHeightRequest{Index: chain.ChainName.String()}, + ) if err != nil { return nil, err } @@ -289,7 +295,10 @@ func (c *Client) GetBallotByID(id string) (*observertypes.QueryBallotByIdentifie func (c *Client) GetNonceByChain(chain chains.Chain) (observertypes.ChainNonces, error) { client := observertypes.NewQueryClient(c.grpcConn) - resp, err := client.ChainNonces(context.Background(), &observertypes.QueryGetChainNoncesRequest{Index: chain.ChainName.String()}) + resp, err := client.ChainNonces( + context.Background(), + &observertypes.QueryGetChainNoncesRequest{Index: chain.ChainName.String()}, + ) if err != nil { return observertypes.ChainNonces{}, err } @@ -333,7 +342,10 @@ func (c *Client) GetBallot(ballotIdentifier string) (*observertypes.QueryBallotB func (c *Client) GetInboundTrackersForChain(chainID int64) ([]crosschaintypes.InTxTracker, error) { client := crosschaintypes.NewQueryClient(c.grpcConn) - resp, err := client.InTxTrackerAllByChain(context.Background(), &crosschaintypes.QueryAllInTxTrackerByChainRequest{ChainId: chainID}) + resp, err := client.InTxTrackerAllByChain( + context.Background(), + &crosschaintypes.QueryAllInTxTrackerByChainRequest{ChainId: chainID}, + ) if err != nil { return nil, err } @@ -390,18 +402,24 @@ func (c *Client) GetOutTxTracker(chain chains.Chain, nonce uint64) (*crosschaint return &resp.OutTxTracker, nil } -func (c *Client) GetAllOutTxTrackerByChain(chainID int64, order interfaces.Order) ([]crosschaintypes.OutTxTracker, error) { +func (c *Client) GetAllOutTxTrackerByChain( + chainID int64, + order interfaces.Order, +) ([]crosschaintypes.OutTxTracker, error) { client := crosschaintypes.NewQueryClient(c.grpcConn) - resp, err := client.OutTxTrackerAllByChain(context.Background(), &crosschaintypes.QueryAllOutTxTrackerByChainRequest{ - Chain: chainID, - Pagination: &query.PageRequest{ - Key: nil, - Offset: 0, - Limit: 2000, - CountTotal: false, - Reverse: false, + resp, err := client.OutTxTrackerAllByChain( + context.Background(), + &crosschaintypes.QueryAllOutTxTrackerByChainRequest{ + Chain: chainID, + Pagination: &query.PageRequest{ + Key: nil, + Offset: 0, + Limit: 2000, + CountTotal: false, + Reverse: false, + }, }, - }) + ) if err != nil { return nil, err } @@ -420,7 +438,10 @@ func (c *Client) GetAllOutTxTrackerByChain(chainID int64, order interfaces.Order func (c *Client) GetPendingNoncesByChain(chainID int64) (observertypes.PendingNonces, error) { client := observertypes.NewQueryClient(c.grpcConn) - resp, err := client.PendingNoncesByChain(context.Background(), &observertypes.QueryPendingNoncesByChainRequest{ChainId: chainID}) + resp, err := client.PendingNoncesByChain( + context.Background(), + &observertypes.QueryPendingNoncesByChainRequest{ChainId: chainID}, + ) if err != nil { return observertypes.PendingNonces{}, err } @@ -454,7 +475,13 @@ func (c *Client) GetPendingNonces() (*observertypes.QueryAllPendingNoncesRespons return resp, nil } -func (c *Client) Prove(blockHash string, txHash string, txIndex int64, proof *proofs.Proof, chainID int64) (bool, error) { +func (c *Client) Prove( + blockHash string, + txHash string, + txIndex int64, + proof *proofs.Proof, + chainID int64, +) (bool, error) { client := lightclienttypes.NewQueryClient(c.grpcConn) resp, err := client.Prove(context.Background(), &lightclienttypes.QueryProveRequest{ BlockHash: blockHash, diff --git a/zetaclient/zetacore/query_test.go b/zetaclient/zetacore/query_test.go index 8bf1174341..8d64ddaea7 100644 --- a/zetaclient/zetacore/query_test.go +++ b/zetaclient/zetacore/query_test.go @@ -126,16 +126,18 @@ func TestZetacore_GetRateLimiterFlags(t *testing.T) { } func TestZetacore_HeaderEnabledChains(t *testing.T) { - expectedOutput := lightclienttypes.QueryHeaderEnabledChainsResponse{HeaderEnabledChains: []lightclienttypes.HeaderSupportedChain{ - { - ChainId: chains.EthChain.ChainId, - Enabled: true, - }, - { - ChainId: chains.BtcMainnetChain.ChainId, - Enabled: true, + expectedOutput := lightclienttypes.QueryHeaderEnabledChainsResponse{ + HeaderEnabledChains: []lightclienttypes.HeaderSupportedChain{ + { + ChainId: chains.EthChain.ChainId, + Enabled: true, + }, + { + ChainId: chains.BtcMainnetChain.ChainId, + Enabled: true, + }, }, - }} + } input := lightclienttypes.QueryHeaderEnabledChainsRequest{} method := "/zetachain.zetacore.lightclient.Query/HeaderEnabledChains" server := setupMockServer(t, lightclienttypes.RegisterQueryServer, method, input, expectedOutput) @@ -242,7 +244,9 @@ func TestZetacore_GetCctxByHash(t *testing.T) { expectedOutput := crosschainTypes.QueryGetCctxResponse{CrossChainTx: &crosschainTypes.CrossChainTx{ Index: "9c8d02b6956b9c78ecb6090a8160faaa48e7aecfd0026fcdf533721d861436a3", }} - input := crosschainTypes.QueryGetCctxRequest{Index: "9c8d02b6956b9c78ecb6090a8160faaa48e7aecfd0026fcdf533721d861436a3"} + input := crosschainTypes.QueryGetCctxRequest{ + Index: "9c8d02b6956b9c78ecb6090a8160faaa48e7aecfd0026fcdf533721d861436a3", + } method := "/zetachain.zetacore.crosschain.Query/Cctx" server := setupMockServer(t, crosschainTypes.RegisterQueryServer, method, input, expectedOutput) server.Serve() diff --git a/zetaclient/zetacore/tx.go b/zetaclient/zetacore/tx.go index e0851f5664..dfcc19dbad 100644 --- a/zetaclient/zetacore/tx.go +++ b/zetaclient/zetacore/tx.go @@ -210,7 +210,12 @@ func (c *Client) PostBlameData(blame *blame.Blame, chainID int64, index string) return "", fmt.Errorf("post blame data failed after %d retries", DefaultRetryCount) } -func (c *Client) PostVoteBlockHeader(chainID int64, blockHash []byte, height int64, header proofs.HeaderData) (string, error) { +func (c *Client) PostVoteBlockHeader( + chainID int64, + blockHash []byte, + height int64, + header proofs.HeaderData, +) (string, error) { signerAddress := c.keys.GetOperatorAddress().String() msg := observertypes.NewMsgVoteBlockHeader(signerAddress, chainID, blockHash, height, header) @@ -235,7 +240,10 @@ func (c *Client) PostVoteBlockHeader(chainID int64, blockHash []byte, height int // PostVoteInbound posts a vote on an observed inbound tx // retryGasLimit is the gas limit used to resend the tx if it fails because of insufficient gas // it is used when the ballot is finalized and the inbound tx needs to be processed -func (c *Client) PostVoteInbound(gasLimit, retryGasLimit uint64, msg *types.MsgVoteOnObservedInboundTx) (string, string, error) { +func (c *Client) PostVoteInbound( + gasLimit, retryGasLimit uint64, + msg *types.MsgVoteOnObservedInboundTx, +) (string, string, error) { authzMsg, authzSigner, err := c.WrapMessageWithAuthz(msg) if err != nil { return "", "", err @@ -245,7 +253,12 @@ func (c *Client) PostVoteInbound(gasLimit, retryGasLimit uint64, msg *types.MsgV ballotIndex := msg.Digest() hasVoted, err := c.HasVoted(ballotIndex, msg.Creator) if err != nil { - return "", ballotIndex, errors.Wrapf(err, "PostVoteInbound: unable to check if already voted for ballot %s voter %s", ballotIndex, msg.Creator) + return "", ballotIndex, errors.Wrapf( + err, + "PostVoteInbound: unable to check if already voted for ballot %s voter %s", + ballotIndex, + msg.Creator, + ) } if hasVoted { return "", ballotIndex, nil @@ -268,7 +281,11 @@ func (c *Client) PostVoteInbound(gasLimit, retryGasLimit uint64, msg *types.MsgV // MonitorVoteInboundTxResult monitors the result of a vote inbound tx // retryGasLimit is the gas limit used to resend the tx if it fails because of insufficient gas // if retryGasLimit is 0, the tx is not resent -func (c *Client) MonitorVoteInboundTxResult(zetaTxHash string, retryGasLimit uint64, msg *types.MsgVoteOnObservedInboundTx) { +func (c *Client) MonitorVoteInboundTxResult( + zetaTxHash string, + retryGasLimit uint64, + msg *types.MsgVoteOnObservedInboundTx, +) { var lastErr error for i := 0; i < MonitorVoteInboundTxResultRetryCount; i++ { @@ -360,7 +377,10 @@ func (c *Client) PostVoteOutbound( } // PostVoteOutboundFromMsg posts a vote on an observed outbound tx from a MsgVoteOnObservedOutboundTx -func (c *Client) PostVoteOutboundFromMsg(gasLimit, retryGasLimit uint64, msg *types.MsgVoteOnObservedOutboundTx) (string, string, error) { +func (c *Client) PostVoteOutboundFromMsg( + gasLimit, retryGasLimit uint64, + msg *types.MsgVoteOnObservedOutboundTx, +) (string, string, error) { authzMsg, authzSigner, err := c.WrapMessageWithAuthz(msg) if err != nil { return "", "", err @@ -370,7 +390,12 @@ func (c *Client) PostVoteOutboundFromMsg(gasLimit, retryGasLimit uint64, msg *ty ballotIndex := msg.Digest() hasVoted, err := c.HasVoted(ballotIndex, msg.Creator) if err != nil { - return "", ballotIndex, errors.Wrapf(err, "PostVoteOutbound: unable to check if already voted for ballot %s voter %s", ballotIndex, msg.Creator) + return "", ballotIndex, errors.Wrapf( + err, + "PostVoteOutbound: unable to check if already voted for ballot %s voter %s", + ballotIndex, + msg.Creator, + ) } if hasVoted { return "", ballotIndex, nil @@ -392,7 +417,11 @@ func (c *Client) PostVoteOutboundFromMsg(gasLimit, retryGasLimit uint64, msg *ty // MonitorVoteOutboundTxResult monitors the result of a vote outbound tx // retryGasLimit is the gas limit used to resend the tx if it fails because of insufficient gas // if retryGasLimit is 0, the tx is not resent -func (c *Client) MonitorVoteOutboundTxResult(zetaTxHash string, retryGasLimit uint64, msg *types.MsgVoteOnObservedOutboundTx) { +func (c *Client) MonitorVoteOutboundTxResult( + zetaTxHash string, + retryGasLimit uint64, + msg *types.MsgVoteOnObservedOutboundTx, +) { var lastErr error for i := 0; i < MonitorVoteOutboundTxResultRetryCount; i++ {