From 9df63f819749849adb6b87a803859927b1c89c62 Mon Sep 17 00:00:00 2001 From: Lucas Bertrand Date: Wed, 22 May 2024 11:20:54 +0200 Subject: [PATCH 1/2] chore: improve Go formatting with imports standardization and max line length to 120 (#2226) * add go lines fmt * add import fmt * add import and golines to makefile * add golines for all files * run make generate * changelog * remove mocks verbose * fix format --- Makefile | 16 +- app/ante/ante.go | 1 + app/ante/ante_test.go | 1 + app/ante/authz.go | 7 +- app/ante/fees.go | 31 +- app/ante/handler_options.go | 49 ++- app/ante/interfaces.go | 1 - app/ante/system_tx_priority_decorator_test.go | 1 + app/app.go | 82 +++-- app/config.go | 56 ++- app/custom_proposal_handler.go | 2 +- app/encoding.go | 3 +- app/export.go | 7 +- app/init_genesis.go | 1 + app/mempool/priority_nonce_mempool.go | 10 +- app/prefix.go | 1 + app/setup_handlers.go | 27 +- app/upgrade_tracker_test.go | 1 + changelog.md | 1 + cmd/zetaclientd-supervisor/lib.go | 19 +- cmd/zetaclientd-supervisor/main.go | 3 +- cmd/zetaclientd/debug.go | 4 +- cmd/zetaclientd/hsm.go | 4 +- cmd/zetaclientd/init.go | 28 +- cmd/zetaclientd/keygen_tss.go | 15 +- cmd/zetaclientd/main.go | 27 +- cmd/zetaclientd/p2p_diagnostics.go | 24 +- cmd/zetaclientd/start.go | 22 +- cmd/zetaclientd/start_utils.go | 3 +- cmd/zetaclientd/utils.go | 7 +- cmd/zetaclientd/version.go | 1 + cmd/zetacore_utils/main.go | 48 ++- cmd/zetacored/add_observer_list.go | 11 +- cmd/zetacored/collect_observer_info.go | 1 + cmd/zetacored/flags_test.go | 1 + cmd/zetacored/genaccounts.go | 13 +- cmd/zetacored/get_pubkey.go | 1 + cmd/zetacored/main.go | 1 + cmd/zetacored/parse_genesis.go | 13 +- cmd/zetacored/parse_genesis_test.go | 1 + cmd/zetacored/parsers_test.go | 11 +- cmd/zetacored/root.go | 46 ++- cmd/zetae2e/balances.go | 1 + cmd/zetae2e/bitcoin_address.go | 1 + cmd/zetae2e/config/clients.go | 7 +- cmd/zetae2e/config/config.go | 1 + cmd/zetae2e/config/contracts.go | 1 + cmd/zetae2e/init.go | 7 +- cmd/zetae2e/list_tests.go | 1 + cmd/zetae2e/local/admin.go | 2 +- cmd/zetae2e/local/bitcoin.go | 1 + cmd/zetae2e/local/config.go | 1 + cmd/zetae2e/local/erc20.go | 1 + cmd/zetae2e/local/ethereum.go | 1 + cmd/zetae2e/local/local.go | 4 +- cmd/zetae2e/local/misc.go | 2 +- cmd/zetae2e/local/monitor_priority_txs.go | 1 + cmd/zetae2e/local/performance.go | 1 + cmd/zetae2e/local/test_runner.go | 1 + cmd/zetae2e/local/zeta.go | 1 + cmd/zetae2e/local/zevm_mp.go | 1 + cmd/zetae2e/root.go | 1 + cmd/zetae2e/run.go | 1 + cmd/zetae2e/setup_bitcoin.go | 1 + cmd/zetae2e/show_tss.go | 1 + cmd/zetae2e/stress.go | 50 ++- cmd/zetatool/filterdeposit/btc.go | 1 + cmd/zetatool/filterdeposit/evm.go | 1 + cmd/zetatool/filterdeposit/filterdeposit.go | 4 +- .../filterdeposit/filterdeposit_test.go | 1 + cmd/zetatool/main.go | 4 +- contrib/rpctest/main.go | 14 +- docs/main.go | 1 + e2e/config/config.go | 1 - e2e/e2etests/helper_bitcoin.go | 7 +- e2e/e2etests/helper_erc20.go | 1 + .../test_bitcoin_withdraw_invalid_address.go | 1 + e2e/e2etests/test_bitcoin_withdraw_legacy.go | 1 + e2e/e2etests/test_bitcoin_withdraw_p2sh.go | 1 + e2e/e2etests/test_bitcoin_withdraw_p2wsh.go | 1 + ...est_bitcoin_withdraw_restricted_address.go | 6 +- e2e/e2etests/test_bitcoin_withdraw_segwit.go | 1 + e2e/e2etests/test_context_upgrade.go | 1 + e2e/e2etests/test_crosschain_swap.go | 15 +- e2e/e2etests/test_erc20_deposit_refund.go | 9 +- .../test_erc20_deposit_restricted_address.go | 1 + e2e/e2etests/test_erc20_multiple_deposits.go | 10 +- e2e/e2etests/test_erc20_multiple_withdraws.go | 14 +- e2e/e2etests/test_eth_deposit_call.go | 13 +- .../test_eth_deposit_liquidity_cap.go | 2 +- e2e/e2etests/test_eth_deposit_refund.go | 9 +- .../test_eth_withdraw_restricted_address.go | 1 + .../test_message_passing_evm_to_zevm.go | 1 + ...test_message_passing_evm_to_zevm_revert.go | 5 +- ...message_passing_evm_to_zevm_revert_fail.go | 1 + .../test_message_passing_external_chains.go | 1 + ..._message_passing_external_chains_revert.go | 1 + ...age_passing_external_chains_revert_fail.go | 9 +- .../test_message_passing_zevm_to_evm.go | 1 + ...test_message_passing_zevm_to_evm_revert.go | 1 + ...message_passing_zevm_to_evm_revert_fail.go | 5 +- e2e/e2etests/test_migrate_chain_support.go | 6 +- e2e/e2etests/test_rate_limiter.go | 11 +- e2e/e2etests/test_stress_btc_deposit.go | 3 +- e2e/e2etests/test_stress_btc_withdraw.go | 7 +- e2e/e2etests/test_stress_eth_deposit.go | 3 +- e2e/e2etests/test_stress_eth_withdraw.go | 9 +- .../test_update_bytecode_connector.go | 1 + e2e/e2etests/test_update_bytecode_zrc20.go | 1 + .../test_zeta_deposit_restricted_address.go | 1 + .../test_zeta_withdraw_bitcoin_revert.go | 1 + e2e/e2etests/test_zrc20_swap.go | 1 + e2e/runner/accounting.go | 6 +- e2e/runner/bitcoin.go | 54 ++- e2e/runner/e2etest.go | 5 +- e2e/runner/evm.go | 7 +- e2e/runner/logger.go | 4 +- e2e/runner/report.go | 1 + e2e/runner/runner.go | 1 + e2e/runner/setup_evm.go | 20 +- e2e/runner/setup_zeta.go | 34 +- e2e/runner/zeta.go | 9 +- e2e/txserver/zeta_tx_server.go | 23 +- e2e/utils/zetacore.go | 1 + pkg/chains/address_taproot_test.go | 6 +- pkg/chains/address_test.go | 25 +- pkg/chains/chains_test.go | 62 +++- pkg/chains/status_test.go | 1 + pkg/chains/utils_test.go | 16 +- pkg/crypto/pubkey.go | 4 +- pkg/crypto/pubkey_test.go | 2 +- pkg/crypto/tss.go | 6 +- pkg/crypto/tss_test.go | 1 + pkg/proofs/bitcoin/proof_test.go | 1 + pkg/proofs/ethereum/proof_test.go | 1 + pkg/proofs/headers.go | 1 + pkg/proofs/headers_test.go | 1 + pkg/proofs/proof.go | 1 + pkg/proofs/proof_test.go | 34 +- rpc/apis.go | 1 + rpc/backend/account_info.go | 19 +- rpc/backend/backend.go | 47 ++- rpc/backend/blocks.go | 50 ++- rpc/backend/call_tx.go | 24 +- rpc/backend/chain_info.go | 5 +- rpc/backend/node_info.go | 1 + rpc/backend/sign_tx.go | 13 +- rpc/backend/tracing.go | 11 +- rpc/backend/tx_info.go | 42 ++- rpc/backend/utils.go | 29 +- rpc/ethereum/pubsub/pubsub.go | 3 +- rpc/namespaces/ethereum/debug/api.go | 6 +- rpc/namespaces/ethereum/eth/api.go | 57 ++- rpc/namespaces/ethereum/eth/filters/api.go | 31 +- .../ethereum/eth/filters/filter_system.go | 1 + .../ethereum/eth/filters/filters.go | 17 +- rpc/namespaces/ethereum/eth/filters/utils.go | 7 +- rpc/namespaces/ethereum/miner/api.go | 1 + rpc/namespaces/ethereum/personal/api.go | 20 +- rpc/namespaces/ethereum/txpool/api.go | 1 + rpc/namespaces/ethereum/web3/api.go | 9 +- rpc/types/block.go | 15 +- rpc/types/block_test.go | 16 +- rpc/types/events.go | 29 +- rpc/types/query_client.go | 5 +- rpc/types/utils.go | 11 +- rpc/websockets.go | 24 +- scripts/fmt-golines.sh | 10 + scripts/fmt-imports.sh | 10 + scripts/mocks-generate.sh | 2 +- server/config/config.go | 6 +- server/flags/flags.go | 15 +- server/indexer_cmd.go | 3 +- server/indexer_service.go | 1 - server/json_rpc.go | 9 +- server/start.go | 125 ++++--- server/util.go | 15 +- testutil/keeper/authority.go | 1 + testutil/keeper/codec.go | 1 + testutil/keeper/crosschain.go | 74 +++- testutil/keeper/emissions.go | 1 + testutil/keeper/fungible.go | 6 +- testutil/keeper/ibccrosschain.go | 1 + testutil/keeper/keeper.go | 40 ++- testutil/keeper/lightclient.go | 6 +- testutil/keeper/observer.go | 6 +- testutil/network/genesis_state.go | 54 ++- testutil/network/network_setup.go | 21 +- testutil/network/util.go | 10 +- testutil/sample/crosschain.go | 17 +- testutil/sample/crypto.go | 1 + testutil/sample/emissions.go | 1 + testutil/sample/lightclient.go | 1 + testutil/sample/observer.go | 1 + testutil/sample/sample.go | 15 +- testutil/simapp/simapp.go | 59 +++- x/authority/client/cli/query.go | 1 + x/authority/client/cli/query_policies.go | 1 + x/authority/client/cli/tx.go | 1 + x/authority/client/cli/tx_update_policies.go | 1 + x/authority/genesis.go | 1 + x/authority/genesis_test.go | 1 + x/authority/keeper/grpc_query_policies.go | 8 +- .../keeper/grpc_query_policies_test.go | 1 + x/authority/keeper/keeper.go | 1 + .../keeper/msg_server_update_policies.go | 6 +- .../keeper/msg_server_update_policies_test.go | 4 +- x/authority/keeper/policies.go | 1 + x/authority/keeper/policies_test.go | 4 +- x/authority/module.go | 1 + x/authority/types/genesis_test.go | 1 + .../types/message_update_policies_test.go | 2 +- x/authority/types/policies.go | 3 +- x/authority/types/policies_test.go | 1 + x/crosschain/client/cli/cli_gas_price.go | 9 +- .../client/cli/cli_last_block_height.go | 1 + x/crosschain/client/cli/cli_refund_aborted.go | 1 + x/crosschain/client/cli/cli_tss.go | 1 + .../client/cli/cli_whitelist_erc20.go | 1 + x/crosschain/client/cli/cli_zeta_height.go | 1 + x/crosschain/client/cli/query.go | 1 + x/crosschain/client/cli/query_cctx.go | 1 + .../client/cli/query_cctx_rate_limit.go | 1 + .../client/cli/query_inbound_hash_to_cctx.go | 1 + .../client/cli/query_inbound_tracker.go | 1 + .../client/cli/query_outbound_tracker.go | 1 + .../client/cli/query_rate_limiter_flags.go | 1 + .../client/cli/query_zeta_accounting.go | 1 + x/crosschain/client/cli/tx.go | 1 - .../client/cli/tx_add_inbound_tracker.go | 1 + .../client/cli/tx_add_outbound_tracker.go | 1 + .../client/cli/tx_remove_outbound_tracker.go | 1 + x/crosschain/client/cli/tx_vote_inbound.go | 2 +- x/crosschain/client/cli/tx_vote_outbound.go | 2 +- x/crosschain/client/cli/tx_vote_stuck_cctx.go | 1 + x/crosschain/client/querytests/cctx.go | 5 +- x/crosschain/client/querytests/cli_test.go | 4 +- x/crosschain/client/querytests/gas_price.go | 5 +- .../client/querytests/inbound_hash.go | 7 +- .../client/querytests/inbound_tracker.go | 1 + .../client/querytests/last_block_height.go | 5 +- .../client/querytests/outbound_tracker.go | 1 + x/crosschain/client/querytests/suite.go | 1 + x/crosschain/genesis.go | 1 + x/crosschain/genesis_test.go | 1 + x/crosschain/keeper/abci.go | 4 +- x/crosschain/keeper/abci_test.go | 31 +- x/crosschain/keeper/cctx.go | 4 +- x/crosschain/keeper/cctx_test.go | 31 +- x/crosschain/keeper/cctx_utils.go | 27 +- x/crosschain/keeper/cctx_utils_test.go | 24 +- x/crosschain/keeper/events.go | 4 +- x/crosschain/keeper/evm_deposit.go | 11 +- x/crosschain/keeper/evm_deposit_test.go | 333 +++++++++--------- x/crosschain/keeper/evm_hooks.go | 47 ++- x/crosschain/keeper/evm_hooks_test.go | 162 +++++++-- x/crosschain/keeper/finalized_inbounds.go | 1 + .../keeper/finalized_inbounds_test.go | 7 +- x/crosschain/keeper/foreign_coins.go | 1 + x/crosschain/keeper/foreign_coins_test.go | 1 + x/crosschain/keeper/gas_payment.go | 87 +++-- x/crosschain/keeper/gas_payment_test.go | 53 ++- x/crosschain/keeper/gas_price.go | 1 + x/crosschain/keeper/gas_price_test.go | 1 + x/crosschain/keeper/grpc_query_cctx.go | 33 +- .../keeper/grpc_query_cctx_rate_limit.go | 43 ++- .../keeper/grpc_query_cctx_rate_limit_test.go | 293 ++++++++++++--- x/crosschain/keeper/grpc_query_cctx_test.go | 1 + x/crosschain/keeper/grpc_query_gas_price.go | 13 +- .../keeper/grpc_query_gas_price_test.go | 5 +- .../keeper/grpc_query_inbound_hash_to_cctx.go | 18 +- .../grpc_query_inbound_hash_to_cctx_test.go | 3 +- .../keeper/grpc_query_inbound_tracker.go | 14 +- .../keeper/grpc_query_inbound_tracker_test.go | 1 + .../keeper/grpc_query_last_block_height.go | 13 +- .../grpc_query_last_block_height_test.go | 5 +- .../keeper/grpc_query_last_zeta_height.go | 8 +- .../grpc_query_last_zeta_height_test.go | 1 + x/crosschain/keeper/grpc_query_legacy.go | 40 ++- .../keeper/grpc_query_outbound_tracker.go | 18 +- .../grpc_query_outbound_tracker_test.go | 1 + .../keeper/grpc_query_rate_limiter_flags.go | 8 +- .../grpc_query_rate_limiter_flags_test.go | 1 + .../keeper/grpc_query_zeta_conversion_rate.go | 15 +- .../grpc_query_zeta_conversion_rate_test.go | 1 + x/crosschain/keeper/inbound_hash_to_cctx.go | 1 + .../keeper/inbound_hash_to_cctx_test.go | 4 +- x/crosschain/keeper/inbound_tracker.go | 19 +- x/crosschain/keeper/inbound_tracker_test.go | 21 +- x/crosschain/keeper/keeper.go | 1 + x/crosschain/keeper/last_block_height.go | 1 + x/crosschain/keeper/last_block_height_test.go | 1 + x/crosschain/keeper/migrator.go | 8 +- .../keeper/msg_server_abort_stuck_cctx.go | 1 + .../msg_server_abort_stuck_cctx_test.go | 1 + .../keeper/msg_server_add_inbound_tracker.go | 6 +- .../msg_server_add_inbound_tracker_test.go | 28 +- .../keeper/msg_server_add_outbound_tracker.go | 13 +- .../msg_server_add_outbound_tracker_test.go | 16 +- .../keeper/msg_server_migrate_tss_funds.go | 60 +++- .../msg_server_migrate_tss_funds_test.go | 77 ++-- .../keeper/msg_server_refund_aborted_tx.go | 8 +- .../msg_server_refund_aborted_tx_test.go | 61 +++- .../msg_server_remove_outbound_tracker.go | 6 +- ...msg_server_remove_outbound_tracker_test.go | 1 + .../msg_server_update_rate_limiter_flags.go | 6 +- ...g_server_update_rate_limiter_flags_test.go | 1 + x/crosschain/keeper/msg_server_update_tss.go | 26 +- .../keeper/msg_server_update_tss_test.go | 43 ++- .../keeper/msg_server_vote_gas_price.go | 7 +- .../keeper/msg_server_vote_gas_price_test.go | 1 + .../keeper/msg_server_vote_inbound_tx.go | 13 +- .../keeper/msg_server_vote_inbound_tx_test.go | 30 +- .../keeper/msg_server_vote_outbound_tx.go | 41 ++- .../msg_server_vote_outbound_tx_test.go | 78 +++- .../keeper/msg_server_whitelist_erc20.go | 23 +- .../keeper/msg_server_whitelist_erc20_test.go | 4 +- x/crosschain/keeper/outbound_tracker.go | 1 + x/crosschain/keeper/outbound_tracker_test.go | 1 + x/crosschain/keeper/process_inbound.go | 8 + x/crosschain/keeper/process_inbound_test.go | 308 +++++++++------- x/crosschain/keeper/process_outbound.go | 14 +- x/crosschain/keeper/process_outbound_test.go | 74 +++- x/crosschain/keeper/rate_limiter_flags.go | 5 +- .../keeper/rate_limiter_flags_test.go | 31 +- x/crosschain/keeper/refund.go | 31 +- x/crosschain/keeper/refund_test.go | 21 +- x/crosschain/keeper/utils_test.go | 8 +- x/crosschain/keeper/zeta_accounting.go | 1 + x/crosschain/keeper/zeta_accounting_test.go | 1 + x/crosschain/migrations/v2/migrate.go | 1 + x/crosschain/migrations/v3/migrate.go | 1 + x/crosschain/migrations/v4/migrate.go | 1 + x/crosschain/migrations/v4/migrate_test.go | 6 +- x/crosschain/migrations/v5/migrate.go | 9 +- x/crosschain/migrations/v5/migrate_test.go | 16 +- x/crosschain/module.go | 10 +- x/crosschain/module_simulation.go | 1 + x/crosschain/types/authz.go | 1 + x/crosschain/types/authz_test.go | 1 + x/crosschain/types/cctx.go | 16 +- x/crosschain/types/cctx_test.go | 1 + x/crosschain/types/errors.go | 30 +- x/crosschain/types/expected_keepers.go | 40 ++- x/crosschain/types/genesis_test.go | 1 + x/crosschain/types/inbound_params.go | 1 + x/crosschain/types/inbound_params_test.go | 1 + x/crosschain/types/keys.go | 8 +- .../types/message_abort_stuck_cctx_test.go | 1 + .../types/message_add_inbound_tracker.go | 7 +- .../types/message_add_inbound_tracker_test.go | 7 +- .../types/message_add_outbound_tracker.go | 1 + .../message_add_outbound_tracker_test.go | 1 + .../types/message_migrate_tss_funds.go | 1 + .../types/message_migrate_tss_funds_test.go | 1 + .../types/message_refund_aborted_test.go | 7 +- .../message_remove_outbound_tracker_test.go | 2 +- .../message_update_rate_limiter_flags_test.go | 1 + .../types/message_update_tss_address.go | 1 + .../types/message_update_tss_address_test.go | 1 + x/crosschain/types/message_vote_gas_price.go | 1 + .../types/message_vote_gas_price_test.go | 1 + x/crosschain/types/message_vote_inbound.go | 1 + .../types/message_vote_inbound_test.go | 4 +- x/crosschain/types/message_vote_outbound.go | 1 + .../types/message_vote_outbound_test.go | 1 + x/crosschain/types/message_whitelist_erc20.go | 1 + .../types/message_whitelist_erc20_test.go | 1 + x/crosschain/types/outbound_params.go | 1 + x/crosschain/types/outbound_params_test.go | 1 + x/crosschain/types/rate_limiter_flags.go | 1 + x/crosschain/types/rate_limiter_flags_test.go | 1 + x/crosschain/types/status.go | 7 +- x/crosschain/types/status_test.go | 107 +++++- x/crosschain/types/tx_body_verification.go | 1 + .../types/tx_body_verification_test.go | 1 + x/crosschain/types/validate.go | 1 + x/crosschain/types/validate_test.go | 89 ++++- x/emissions/abci.go | 20 +- x/emissions/abci_test.go | 130 +++++-- x/emissions/client/cli/query.go | 7 +- .../client/cli/query_get_emmisons_factors.go | 1 + x/emissions/client/cli/query_list_balances.go | 1 + x/emissions/client/cli/query_params.go | 1 + .../cli/query_show_available_emissions.go | 1 + x/emissions/client/cli/tx.go | 4 +- .../client/cli/tx_withdraw_emissions..go | 1 + x/emissions/genesis.go | 1 + x/emissions/genesis_test.go | 1 + .../keeper/block_rewards_components.go | 1 + .../keeper/block_rewards_components_test.go | 1 + .../keeper/grpc_query_get_emmisons_factors.go | 8 +- .../grpc_query_get_emmisons_factors_test.go | 6 +- .../keeper/grpc_query_list_balances.go | 16 +- .../keeper/grpc_query_list_balances_test.go | 1 + x/emissions/keeper/grpc_query_params.go | 3 +- .../grpc_query_show_available_emissions.go | 11 +- ...rpc_query_show_available_emissions_test.go | 1 + x/emissions/keeper/keeper.go | 7 +- x/emissions/keeper/migrator.go | 1 + .../keeper/msg_server_update_params.go | 13 +- .../keeper/msg_server_update_params_test.go | 1 + .../keeper/msg_server_withdraw_emissions.go | 25 +- .../msg_server_withdraw_emissions_test.go | 101 ++++-- x/emissions/keeper/params.go | 1 + x/emissions/keeper/params_test.go | 1 + x/emissions/keeper/withdrawable_emissions.go | 1 + .../keeper/withdrawable_emissions_test.go | 1 + x/emissions/migrations/v3/migrate.go | 1 + x/emissions/migrations/v3/migrate_test.go | 4 +- x/emissions/module.go | 15 +- x/emissions/types/distributions_test.go | 1 + x/emissions/types/errors.go | 10 +- x/emissions/types/events.go | 5 +- x/emissions/types/expected_keepers.go | 8 +- x/emissions/types/genesis_test.go | 1 + .../types/message_update_params_test.go | 1 + .../types/message_withdraw_emissons_test.go | 1 + x/emissions/types/params_legacy.go | 24 +- x/emissions/types/params_test.go | 16 +- x/fungible/client/cli/query.go | 1 + x/fungible/client/cli/query_code_hash.go | 1 + x/fungible/client/cli/query_foreign_coins.go | 1 + .../client/cli/query_gas_stability_pool.go | 11 +- .../client/cli/query_system_contract.go | 1 + x/fungible/client/cli/tx.go | 1 + .../cli/tx_deploy_fungible_coin_zrc_4.go | 4 +- .../client/cli/tx_deploy_system_contracts.go | 1 + .../client/cli/tx_remove_foreign_coin.go | 1 + .../client/cli/tx_update_contract_bytecode.go | 1 + .../client/cli/tx_update_system_contract.go | 1 + .../cli/tx_update_zrc20_liquidity_cap.go | 1 + .../cli/tx_update_zrc20_paused_status.go | 1 + .../cli/tx_update_zrc20_withdraw_fee.go | 1 + x/fungible/genesis.go | 1 + x/fungible/genesis_test.go | 1 + x/fungible/keeper/deposits.go | 1 + x/fungible/keeper/deposits_test.go | 1 + x/fungible/keeper/evm.go | 47 ++- x/fungible/keeper/evm_hooks.go | 1 + x/fungible/keeper/evm_hooks_test.go | 1 + x/fungible/keeper/evm_test.go | 35 +- x/fungible/keeper/foreign_coins.go | 1 + x/fungible/keeper/foreign_coins_test.go | 4 +- x/fungible/keeper/gas_coin_and_pool.go | 92 ++++- x/fungible/keeper/gas_coin_and_pool_test.go | 4 +- x/fungible/keeper/gas_price.go | 43 ++- x/fungible/keeper/gas_price_test.go | 27 +- x/fungible/keeper/gas_stability_pool.go | 1 + x/fungible/keeper/gas_stability_pool_test.go | 1 + x/fungible/keeper/grpc_query_code_hash.go | 4 +- .../keeper/grpc_query_code_hash_test.go | 1 + x/fungible/keeper/grpc_query_foreign_coins.go | 13 +- .../keeper/grpc_query_gas_stability_pool.go | 3 +- .../grpc_query_gas_stability_pool_test.go | 1 + .../keeper/grpc_query_system_contract.go | 8 +- .../keeper/grpc_query_system_contract_test.go | 1 + x/fungible/keeper/keeper.go | 1 + .../msg_server_deploy_fungible_coin_zrc20.go | 20 +- ..._server_deploy_fungible_coin_zrc20_test.go | 1 + .../msg_server_deploy_system_contract.go | 11 +- .../msg_server_deploy_system_contract_test.go | 1 + .../keeper/msg_server_remove_foreign_coin.go | 11 +- .../msg_server_remove_foreign_coin_test.go | 1 + .../msg_server_udpate_zrc20_liquidity_cap.go | 11 +- ..._server_udpate_zrc20_liquidity_cap_test.go | 11 +- .../msg_server_update_contract_bytecode.go | 17 +- ...sg_server_update_contract_bytecode_test.go | 1 + .../msg_server_update_system_contract.go | 76 +++- .../msg_server_update_system_contract_test.go | 13 +- .../msg_server_update_zrc20_paused_status.go | 10 +- ..._server_update_zrc20_paused_status_test.go | 8 +- .../msg_server_update_zrc20_withdraw_fee.go | 35 +- ...g_server_update_zrc20_withdraw_fee_test.go | 1 + x/fungible/keeper/system_contract.go | 131 +++++-- x/fungible/keeper/system_contract_test.go | 88 ++++- x/fungible/keeper/zeta.go | 1 + x/fungible/keeper/zeta_test.go | 1 + .../keeper/zevm_message_passing_test.go | 96 ++++- x/fungible/keeper/zevm_msg_passing.go | 21 +- x/fungible/module.go | 9 +- x/fungible/module_simulation.go | 1 + x/fungible/types/evm_test.go | 1 + x/fungible/types/expected_keepers.go | 8 +- x/fungible/types/gas_stablity_pool_test.go | 1 + x/fungible/types/genesis_test.go | 1 + .../message_deploy_fungible_coin_zrc20.go | 12 +- ...message_deploy_fungible_coin_zrc20_test.go | 1 + .../message_deploy_system_contracts_test.go | 1 + .../types/message_remove_foreign_coin_test.go | 1 + .../types/message_update_contract_bytecode.go | 1 - .../message_update_contract_bytecode_test.go | 1 + .../types/message_update_system_contract.go | 6 +- .../message_update_system_contract_test.go | 1 + ...message_update_zrc20_liquidity_cap_test.go | 2 +- .../message_update_zrc20_paused_status.go | 6 +- ...message_update_zrc20_paused_status_test.go | 1 + .../message_update_zrc20_withdraw_fee.go | 8 +- .../message_update_zrc20_withdraw_fee_test.go | 2 +- x/fungible/types/zrc20_test.go | 1 + x/ibccrosschain/client/cli/query.go | 1 + x/ibccrosschain/client/cli/tx.go | 1 + x/ibccrosschain/genesis.go | 1 + x/ibccrosschain/ibc_module.go | 1 + x/ibccrosschain/keeper/keeper.go | 1 + x/ibccrosschain/module.go | 1 + x/lightclient/client/cli/query.go | 1 + .../client/cli/query_block_header.go | 1 + x/lightclient/client/cli/query_chain_state.go | 1 + .../client/cli/query_verification_flags.go | 1 + x/lightclient/client/cli/tx.go | 1 + .../cli/tx_disable_verification_flags.go | 1 + .../cli/tx_enable_verification_flags.go | 1 + x/lightclient/genesis.go | 1 + x/lightclient/genesis_test.go | 7 +- x/lightclient/keeper/block_header.go | 1 + x/lightclient/keeper/block_header_test.go | 80 +++-- .../keeper/block_header_verification.go | 1 + .../keeper/block_header_verification_test.go | 19 +- x/lightclient/keeper/chain_state.go | 1 + x/lightclient/keeper/chain_state_test.go | 1 + .../keeper/grpc_query_block_header.go | 15 +- .../keeper/grpc_query_block_header_test.go | 1 + .../keeper/grpc_query_chain_state.go | 13 +- .../keeper/grpc_query_chain_state_test.go | 1 + .../grpc_query_header_enabled_chains.go | 21 +- .../grpc_query_header_enabled_chains_test.go | 1 + x/lightclient/keeper/grpc_query_prove.go | 10 +- x/lightclient/keeper/grpc_query_prove_test.go | 1 + x/lightclient/keeper/keeper.go | 1 + ...disable_block_header_verification._test.go | 1 + ...erver_disable_block_header_verification.go | 6 +- ...server_enable_block_header_verification.go | 1 + ...r_enable_block_header_verification_test.go | 1 + x/lightclient/keeper/proof.go | 22 +- x/lightclient/keeper/proof_test.go | 7 +- x/lightclient/module.go | 1 + .../types/block_header_verification_test.go | 34 +- x/lightclient/types/expected_keepers.go | 1 + x/lightclient/types/genesis_test.go | 4 +- .../message_disable_verification_flags.go | 7 +- ...message_disable_verification_flags_test.go | 7 +- .../message_enable_verification_flags.go | 7 +- .../message_enable_verification_flags_test.go | 7 +- .../types/verification_flags_test.go | 1 + x/observer/abci.go | 9 +- x/observer/abci_test.go | 1 + x/observer/client/cli/query.go | 6 +- x/observer/client/cli/query_ballot.go | 1 + x/observer/client/cli/query_blame.go | 1 + x/observer/client/cli/query_chain_nonce.go | 1 + x/observer/client/cli/query_chain_params.go | 1 + .../client/cli/query_get_tss_address.go | 1 + x/observer/client/cli/query_keygen.go | 1 + x/observer/client/cli/query_node_account.go | 1 + x/observer/client/cli/query_observers.go | 1 + x/observer/client/cli/query_pending_nonces.go | 1 + .../client/cli/query_permission_flags.go | 1 + .../client/cli/query_show_observer_count.go | 1 + .../client/cli/query_supported_chains.go | 1 + x/observer/client/cli/query_tss.go | 1 + x/observer/client/cli/tx.go | 1 - x/observer/client/cli/tx_add_blame_vote.go | 1 + x/observer/client/cli/tx_add_observer.go | 1 + x/observer/client/cli/tx_permission_flags.go | 7 +- .../client/cli/tx_remove_chain_params.go | 1 + .../client/cli/tx_reset_chain_nonces.go | 1 + .../client/cli/tx_update_chain_params.go | 1 + x/observer/client/cli/tx_update_keygen.go | 1 + x/observer/client/cli/tx_update_observer.go | 1 + x/observer/client/cli/tx_vote_tss.go | 1 + x/observer/client/querytests/chain_nonces.go | 5 +- x/observer/client/querytests/cli_test.go | 4 +- .../client/querytests/crosschain_flags.go | 3 +- x/observer/client/querytests/keygen.go | 3 +- x/observer/client/querytests/node_account.go | 5 +- x/observer/client/querytests/suite.go | 1 + x/observer/client/querytests/tss.go | 3 +- x/observer/genesis.go | 6 +- x/observer/genesis_test.go | 1 + x/observer/keeper/ballot.go | 1 + x/observer/keeper/ballot_test.go | 1 + x/observer/keeper/blame.go | 12 +- x/observer/keeper/blame_test.go | 1 + x/observer/keeper/chain_nonces.go | 1 + x/observer/keeper/chain_nonces_test.go | 1 + x/observer/keeper/chain_params.go | 1 + x/observer/keeper/chain_params_test.go | 1 + x/observer/keeper/crosschain_flags.go | 1 + x/observer/keeper/crosschain_flags_test.go | 1 + x/observer/keeper/events.go | 6 +- x/observer/keeper/grpc_query_ballot.go | 8 +- x/observer/keeper/grpc_query_ballot_test.go | 1 + x/observer/keeper/grpc_query_blame.go | 18 +- x/observer/keeper/grpc_query_blame_test.go | 1 + x/observer/keeper/grpc_query_chain_params.go | 3 +- .../keeper/grpc_query_chain_params_test.go | 1 + .../keeper/grpc_query_crosschain_flags.go | 8 +- .../grpc_query_crosschain_flags_test.go | 1 + x/observer/keeper/grpc_query_keygen.go | 3 +- x/observer/keeper/grpc_query_keygen_test.go | 4 +- x/observer/keeper/grpc_query_node_account.go | 13 +- .../keeper/grpc_query_node_account_test.go | 5 +- x/observer/keeper/grpc_query_nonces.go | 23 +- x/observer/keeper/grpc_query_nonces_test.go | 5 +- x/observer/keeper/grpc_query_observer.go | 13 +- x/observer/keeper/grpc_query_observer_test.go | 1 + .../keeper/grpc_query_supported_chain.go | 6 +- .../keeper/grpc_query_supported_chain_test.go | 1 + x/observer/keeper/grpc_query_tss.go | 15 +- x/observer/keeper/grpc_query_tss_test.go | 5 +- x/observer/keeper/hooks.go | 7 +- x/observer/keeper/hooks_test.go | 1 + x/observer/keeper/keeper.go | 1 + x/observer/keeper/keygen.go | 1 + x/observer/keeper/last_observer_count.go | 1 + .../keeper/msg_server_add_blame_vote.go | 11 +- .../keeper/msg_server_add_blame_vote_test.go | 1 + x/observer/keeper/msg_server_add_observer.go | 19 +- .../keeper/msg_server_add_observer_test.go | 1 + .../keeper/msg_server_remove_chain_params.go | 6 +- .../msg_server_remove_chain_params_test.go | 1 + .../keeper/msg_server_reset_chain_nonces.go | 6 +- .../msg_server_reset_chain_nonces_test.go | 1 + .../keeper/msg_server_update_chain_params.go | 6 +- .../msg_server_update_chain_params_test.go | 6 +- .../msg_server_update_crosschain_flags.go | 9 +- ...msg_server_update_crosschain_flags_test.go | 7 +- x/observer/keeper/msg_server_update_keygen.go | 9 +- .../keeper/msg_server_update_keygen_test.go | 1 + .../keeper/msg_server_update_observer.go | 31 +- .../keeper/msg_server_update_observer_test.go | 1 + .../keeper/msg_server_vote_block_header.go | 6 +- .../msg_server_vote_block_header_test.go | 1 + x/observer/keeper/msg_server_vote_tss.go | 6 +- x/observer/keeper/msg_server_vote_tss_test.go | 1 + x/observer/keeper/node_account.go | 1 + x/observer/keeper/node_account_test.go | 1 + x/observer/keeper/nonce_to_cctx.go | 8 +- x/observer/keeper/nonce_to_cctx_test.go | 8 +- x/observer/keeper/nonces_test.go | 1 + x/observer/keeper/observer_set.go | 1 + x/observer/keeper/observer_set_test.go | 1 + x/observer/keeper/pending_nonces.go | 6 +- x/observer/keeper/pending_nonces_test.go | 6 +- x/observer/keeper/tss.go | 6 +- x/observer/keeper/tss_funds_migrator.go | 1 + x/observer/keeper/tss_funds_migrator_test.go | 1 + x/observer/keeper/tss_test.go | 1 + x/observer/keeper/utils.go | 8 +- x/observer/keeper/utils_test.go | 1 + x/observer/keeper/vote_inbound.go | 1 + x/observer/keeper/vote_inbound_test.go | 1 + x/observer/keeper/vote_outbound.go | 1 + x/observer/keeper/vote_outbound_test.go | 1 + x/observer/module.go | 9 +- x/observer/module_simulation.go | 1 + x/observer/types/ballot.go | 5 +- x/observer/types/ballot_test.go | 94 ++++- x/observer/types/chain_params.go | 40 ++- x/observer/types/chain_params_test.go | 3 +- x/observer/types/crosschain_flags_test.go | 1 + x/observer/types/errors.go | 30 +- x/observer/types/expected_keepers.go | 7 +- x/observer/types/genesis_test.go | 1 + x/observer/types/message_add_blame_vote.go | 1 + .../types/message_add_blame_vote_test.go | 1 + x/observer/types/message_add_observer.go | 8 +- x/observer/types/message_add_observer_test.go | 1 + .../types/message_remove_chain_params.go | 4 +- .../types/message_remove_chain_params_test.go | 1 + .../types/message_reset_chain_nonces.go | 11 +- .../types/message_reset_chain_nonces_test.go | 1 + .../types/message_update_chain_params.go | 1 - .../types/message_update_chain_params_test.go | 1 + .../types/message_update_crosschain_flags.go | 5 +- .../message_update_crosschain_flags_test.go | 1 + .../types/message_update_keygen_test.go | 1 + x/observer/types/message_update_observer.go | 7 +- .../types/message_update_observer_test.go | 1 + x/observer/types/message_vote_block_header.go | 10 +- .../types/message_vote_block_header_test.go | 1 + x/observer/types/message_vote_tss.go | 1 + x/observer/types/message_vote_tss_test.go | 1 + x/observer/types/observer_set.go | 1 + x/observer/types/observer_set_test.go | 1 + x/observer/types/parsers.go | 1 + x/observer/types/parsers_test.go | 1 + x/observer/types/utils_test.go | 1 + zetaclient/authz/authz_signer.go | 1 + zetaclient/chains/bitcoin/fee.go | 8 +- zetaclient/chains/bitcoin/fee_test.go | 5 +- zetaclient/chains/bitcoin/observer/inbound.go | 57 ++- .../chains/bitcoin/observer/inbound_test.go | 31 +- .../chains/bitcoin/observer/live_test.go | 35 +- .../chains/bitcoin/observer/observer.go | 39 +- .../chains/bitcoin/observer/observer_test.go | 5 +- .../chains/bitcoin/observer/outbound.go | 115 ++++-- .../chains/bitcoin/observer/outbound_test.go | 27 +- zetaclient/chains/bitcoin/signer/signer.go | 50 ++- .../bitcoin/signer/signer_keysign_test.go | 22 +- .../chains/bitcoin/signer/signer_test.go | 31 +- zetaclient/chains/bitcoin/tx_script.go | 3 +- zetaclient/chains/bitcoin/tx_script_test.go | 1 + zetaclient/chains/evm/observer/inbound.go | 165 +++++++-- .../chains/evm/observer/inbound_test.go | 99 +++++- zetaclient/chains/evm/observer/observer.go | 43 ++- .../chains/evm/observer/observer_db_test.go | 3 +- .../chains/evm/observer/observer_test.go | 7 +- zetaclient/chains/evm/observer/outbound.go | 52 ++- .../chains/evm/observer/outbound_test.go | 229 ++++++++++-- zetaclient/chains/evm/signer/outbound_data.go | 13 +- .../chains/evm/signer/outbound_data_test.go | 1 + zetaclient/chains/evm/signer/signer.go | 82 ++++- zetaclient/chains/evm/signer/signer_test.go | 10 +- zetaclient/chains/evm/validation_test.go | 1 + zetaclient/chains/interfaces/interfaces.go | 8 +- zetaclient/compliance/compliance.go | 17 +- zetaclient/compliance/compliance_test.go | 1 + zetaclient/config/types.go | 6 +- zetaclient/context/zetacore_context.go | 1 + zetaclient/context/zetacore_context_test.go | 200 +++++------ zetaclient/hsm/hsm_signer.go | 6 +- zetaclient/hsm/hsm_signer_test.go | 3 +- zetaclient/keys/keys.go | 11 +- zetaclient/keys/keys_test.go | 11 +- zetaclient/metrics/metrics.go | 1 - zetaclient/orchestrator/orchestrator.go | 56 ++- zetaclient/orchestrator/orchestrator_test.go | 50 ++- .../outbound_processor_manager.go | 3 +- zetaclient/ratelimiter/rate_limiter.go | 1 + zetaclient/ratelimiter/rate_limiter_test.go | 71 +++- zetaclient/supplychecker/logger.go | 1 + zetaclient/supplychecker/validate.go | 5 +- .../supplychecker/zeta_supply_checker.go | 19 +- .../supplychecker/zeta_supply_checker_test.go | 13 +- .../testdata/cctx/chain_1337_cctx_14.go | 1 + zetaclient/testdata/cctx/chain_1_cctx_6270.go | 1 + zetaclient/testdata/cctx/chain_1_cctx_7260.go | 1 + zetaclient/testdata/cctx/chain_1_cctx_8014.go | 1 + zetaclient/testdata/cctx/chain_1_cctx_9718.go | 1 + ...c3b990e076e2a4bffeb616035b239b7d33843da.go | 1 + ...e01cbdf59154fd793ea7a22c297f7c3a722c532.go | 1 + ...71ffc40ca898e134525c42c2ae3cbc5725f9d76.go | 1 + .../testdata/cctx/chain_56_cctx_68270.go | 1 + .../testdata/cctx/chain_8332_cctx_148.go | 1 + zetaclient/testutils/evm.go | 10 +- zetaclient/testutils/mocks/btc_rpc.go | 12 +- zetaclient/testutils/mocks/chain_clients.go | 1 + zetaclient/testutils/mocks/chain_params.go | 1 + zetaclient/testutils/mocks/chain_signer.go | 1 + zetaclient/testutils/mocks/evm_json_rpc.go | 1 + zetaclient/testutils/mocks/evm_rpc.go | 21 +- zetaclient/testutils/mocks/keyring.go | 7 +- zetaclient/testutils/mocks/tss_signer.go | 6 +- zetaclient/testutils/mocks/zetacore_client.go | 33 +- zetaclient/testutils/testdata.go | 16 +- zetaclient/tss/concurrent_keysigns_tracker.go | 1 + zetaclient/tss/tss_signer.go | 32 +- zetaclient/tss/tss_signer_test.go | 1 + zetaclient/zetacore/broadcast.go | 23 +- zetaclient/zetacore/broadcast_test.go | 25 +- zetaclient/zetacore/client.go | 14 +- zetaclient/zetacore/query.go | 62 +++- zetaclient/zetacore/query_test.go | 29 +- zetaclient/zetacore/tx.go | 27 +- zetaclient/zetacore/tx_test.go | 5 +- 767 files changed, 7362 insertions(+), 2174 deletions(-) create mode 100644 scripts/fmt-golines.sh create mode 100644 scripts/fmt-imports.sh diff --git a/Makefile b/Makefile index d5446322db..6508b07b50 100644 --- a/Makefile +++ b/Makefile @@ -141,6 +141,19 @@ lint-cosmos-gosec: gosec: gosec -exclude-dir=localnet ./... +############################################################################### +### Formatting ### +############################################################################### + +fmt-import: + @bash ./scripts/fmt-imports.sh +@PHONY: fmt-import + +fmt-golines: + @echo "--> Formatting Go lines" + @bash ./scripts/fmt-golines.sh +.PHONY: fmt-golines + ############################################################################### ### Generation commands ### ############################################################################### @@ -185,7 +198,8 @@ mocks: @bash ./scripts/mocks-generate.sh .PHONY: mocks -generate: proto-gen openapi specs typescript docs-zetacored mocks +# generate also includes Go code formatting +generate: proto-gen openapi specs typescript docs-zetacored mocks fmt-import fmt-golines .PHONY: generate ############################################################################### diff --git a/app/ante/ante.go b/app/ante/ante.go index e8c919ee3f..48e2b634eb 100644 --- a/app/ante/ante.go +++ b/app/ante/ante.go @@ -26,6 +26,7 @@ import ( authante "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/authz" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/app/ante/ante_test.go b/app/ante/ante_test.go index 558bcb92fc..da67472dfb 100644 --- a/app/ante/ante_test.go +++ b/app/ante/ante_test.go @@ -8,6 +8,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/app/ante" "github.com/zeta-chain/zetacore/testutil/sample" 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..71d77de243 100644 --- a/app/ante/handler_options.go +++ b/app/ante/handler_options.go @@ -19,8 +19,6 @@ package ante import ( "fmt" - observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" - cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -34,6 +32,8 @@ import ( ethante "github.com/evmos/ethermint/app/ante" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + + observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" ) type HandlerOptions struct { @@ -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/ante/interfaces.go b/app/ante/interfaces.go index 5c1b5861e2..af423e6592 100644 --- a/app/ante/interfaces.go +++ b/app/ante/interfaces.go @@ -24,7 +24,6 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/params" - "github.com/evmos/ethermint/x/evm/statedb" evmtypes "github.com/evmos/ethermint/x/evm/types" evm "github.com/evmos/ethermint/x/evm/vm" diff --git a/app/ante/system_tx_priority_decorator_test.go b/app/ante/system_tx_priority_decorator_test.go index f777a98ba1..6f267bf5e2 100644 --- a/app/ante/system_tx_priority_decorator_test.go +++ b/app/ante/system_tx_priority_decorator_test.go @@ -9,6 +9,7 @@ import ( simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/app/ante" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/app/app.go b/app/app.go index b88d2c01a7..a402121156 100644 --- a/app/app.go +++ b/app/app.go @@ -7,10 +7,6 @@ import ( "time" cosmoserrors "cosmossdk.io/errors" - "github.com/gorilla/mux" - "github.com/rakyll/statik/fs" - "github.com/spf13/cast" - appparams "cosmossdk.io/simapp/params" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" @@ -19,6 +15,7 @@ import ( tmos "github.com/cometbft/cometbft/libs/os" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" + nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" @@ -47,6 +44,8 @@ import ( capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" "github.com/cosmos/cosmos-sdk/x/consensus" + consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" "github.com/cosmos/cosmos-sdk/x/crisis" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" @@ -100,41 +99,34 @@ import ( "github.com/evmos/ethermint/x/feemarket" feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" + "github.com/gorilla/mux" + "github.com/rakyll/statik/fs" + "github.com/spf13/cast" "github.com/zeta-chain/zetacore/app/ante" "github.com/zeta-chain/zetacore/docs/openapi" srvflags "github.com/zeta-chain/zetacore/server/flags" - authoritymodule "github.com/zeta-chain/zetacore/x/authority" authoritykeeper "github.com/zeta-chain/zetacore/x/authority/keeper" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - - lightclientmodule "github.com/zeta-chain/zetacore/x/lightclient" - lightclientkeeper "github.com/zeta-chain/zetacore/x/lightclient/keeper" - lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" - crosschainmodule "github.com/zeta-chain/zetacore/x/crosschain" crosschainkeeper "github.com/zeta-chain/zetacore/x/crosschain/keeper" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - emissionsmodule "github.com/zeta-chain/zetacore/x/emissions" emissionskeeper "github.com/zeta-chain/zetacore/x/emissions/keeper" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" - fungiblemodule "github.com/zeta-chain/zetacore/x/fungible" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" - - nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" - consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" - consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" - observermodule "github.com/zeta-chain/zetacore/x/observer" - observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" - observertypes "github.com/zeta-chain/zetacore/x/observer/types" - "github.com/zeta-chain/zetacore/x/ibccrosschain" ibccrosschainkeeper "github.com/zeta-chain/zetacore/x/ibccrosschain/keeper" ibccrosschaintypes "github.com/zeta-chain/zetacore/x/ibccrosschain/types" + lightclientmodule "github.com/zeta-chain/zetacore/x/lightclient" + lightclientkeeper "github.com/zeta-chain/zetacore/x/lightclient/keeper" + lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" + observermodule "github.com/zeta-chain/zetacore/x/observer" + observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) const Name = "zetacore" @@ -526,7 +518,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 +681,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 +825,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 +1004,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/custom_proposal_handler.go b/app/custom_proposal_handler.go index e6f9e4512f..107fee5803 100644 --- a/app/custom_proposal_handler.go +++ b/app/custom_proposal_handler.go @@ -9,9 +9,9 @@ import ( "github.com/cockroachdb/errors" abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/mempool" + zetamempool "github.com/zeta-chain/zetacore/app/mempool" ) diff --git a/app/encoding.go b/app/encoding.go index 9535c2ce66..5d4e7f5305 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -1,9 +1,8 @@ package app import ( - evmenc "github.com/evmos/ethermint/encoding" - //"github.com/zeta-chain/zetacore/app/params" "cosmossdk.io/simapp/params" + evmenc "github.com/evmos/ethermint/encoding" ) // MakeEncodingConfig creates an EncodingConfig for testing diff --git a/app/export.go b/app/export.go index feea997869..d75de64514 100644 --- a/app/export.go +++ b/app/export.go @@ -5,7 +5,6 @@ import ( "log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -87,7 +86,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/init_genesis.go b/app/init_genesis.go index d8ab948f6b..c838f760e7 100644 --- a/app/init_genesis.go +++ b/app/init_genesis.go @@ -21,6 +21,7 @@ import ( ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" emissionsModuleTypes "github.com/zeta-chain/zetacore/x/emissions/types" diff --git a/app/mempool/priority_nonce_mempool.go b/app/mempool/priority_nonce_mempool.go index cb6ed8748f..ebff9b7f82 100644 --- a/app/mempool/priority_nonce_mempool.go +++ b/app/mempool/priority_nonce_mempool.go @@ -9,10 +9,9 @@ import ( "fmt" "math" - "github.com/huandu/skiplist" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/mempool" + "github.com/huandu/skiplist" ) var ( @@ -103,7 +102,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 +204,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/prefix.go b/app/prefix.go index 9e32547f94..7a96bc6292 100644 --- a/app/prefix.go +++ b/app/prefix.go @@ -3,6 +3,7 @@ package app import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcfg "github.com/evmos/ethermint/cmd/config" + cmdcfg "github.com/zeta-chain/zetacore/cmd/zetacored/config" ) diff --git a/app/setup_handlers.go b/app/setup_handlers.go index d178f5a599..2ca71ca0ae 100644 --- a/app/setup_handlers.go +++ b/app/setup_handlers.go @@ -3,8 +3,6 @@ package app import ( "os" - "golang.org/x/exp/slices" - "github.com/cosmos/cosmos-sdk/baseapp" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -23,6 +21,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/upgrade/types" ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + "golang.org/x/exp/slices" + "github.com/zeta-chain/zetacore/pkg/constant" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" ibccrosschaintypes "github.com/zeta-chain/zetacore/x/ibccrosschain/types" @@ -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/app/upgrade_tracker_test.go b/app/upgrade_tracker_test.go index 924ba4e053..28e312abf9 100644 --- a/app/upgrade_tracker_test.go +++ b/app/upgrade_tracker_test.go @@ -9,6 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/stretchr/testify/require" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/changelog.md b/changelog.md index 49cf98f8f3..5f165d0d2a 100644 --- a/changelog.md +++ b/changelog.md @@ -28,6 +28,7 @@ * [2150](https://github.com/zeta-chain/node/pull/2150) - created `chains` `zetacore` `orchestrator` packages in zetaclient and reorganized source files accordingly * [2210](https://github.com/zeta-chain/node/pull/2210) - removed uncessary panics in the zetaclientd process * [2205](https://github.com/zeta-chain/node/pull/2205) - remove deprecated variables pre-v17 +* [2226](https://github.com/zeta-chain/node/pull/2226) - improve Go formatting with imports standardization and max line length to 120 ### Tests diff --git a/cmd/zetaclientd-supervisor/lib.go b/cmd/zetaclientd-supervisor/lib.go index cb943b4557..e8f1b54470 100644 --- a/cmd/zetaclientd-supervisor/lib.go +++ b/cmd/zetaclientd-supervisor/lib.go @@ -18,8 +18,9 @@ import ( upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" "github.com/hashicorp/go-getter" "github.com/rs/zerolog" - "github.com/zeta-chain/zetacore/zetaclient/config" "google.golang.org/grpc" + + "github.com/zeta-chain/zetacore/zetaclient/config" ) const zetaclientdBinaryName = "zetaclientd" @@ -46,7 +47,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 +68,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 +160,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-supervisor/main.go b/cmd/zetaclientd-supervisor/main.go index e3a1c301e5..6017050986 100644 --- a/cmd/zetaclientd-supervisor/main.go +++ b/cmd/zetaclientd-supervisor/main.go @@ -10,9 +10,10 @@ import ( "syscall" "time" + "golang.org/x/sync/errgroup" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/zetaclient/config" - "golang.org/x/sync/errgroup" ) func main() { diff --git a/cmd/zetaclientd/debug.go b/cmd/zetaclientd/debug.go index 8d64e77f29..881997d0ec 100644 --- a/cmd/zetaclientd/debug.go +++ b/cmd/zetaclientd/debug.go @@ -15,6 +15,7 @@ import ( "github.com/onrik/ethrpc" "github.com/rs/zerolog" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" @@ -37,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..99fae253c1 100644 --- a/cmd/zetaclientd/hsm.go +++ b/cmd/zetaclientd/hsm.go @@ -7,6 +7,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" keystone "github.com/zeta-chain/keystone/keys" + "github.com/zeta-chain/zetacore/cmd" "github.com/zeta-chain/zetacore/pkg/cosmos" "github.com/zeta-chain/zetacore/zetaclient/hsm" @@ -49,7 +50,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..c41f669c44 100644 --- a/cmd/zetaclientd/init.go +++ b/cmd/zetaclientd/init.go @@ -3,6 +3,7 @@ package main import ( "github.com/rs/zerolog" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/testutils" ) @@ -41,24 +42,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..6f04ccdead 100644 --- a/cmd/zetaclientd/keygen_tss.go +++ b/cmd/zetaclientd/keygen_tss.go @@ -12,13 +12,14 @@ import ( tsscommon "github.com/zeta-chain/go-tss/common" "github.com/zeta-chain/go-tss/keygen" "github.com/zeta-chain/go-tss/p2p" + "golang.org/x/crypto/sha3" + "github.com/zeta-chain/zetacore/pkg/chains" observertypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/context" "github.com/zeta-chain/zetacore/zetaclient/metrics" mc "github.com/zeta-chain/zetacore/zetaclient/tss" "github.com/zeta-chain/zetacore/zetaclient/zetacore" - "golang.org/x/crypto/sha3" ) func GenerateTss( @@ -99,7 +100,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 +128,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 +149,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..fdac54a7d0 100644 --- a/cmd/zetaclientd/main.go +++ b/cmd/zetaclientd/main.go @@ -1,27 +1,22 @@ package main import ( + "math/rand" + "os" "path/filepath" - - "github.com/rs/zerolog/log" + "time" ecdsakeygen "github.com/binance-chain/tss-lib/ecdsa/keygen" "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/rs/zerolog" - clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" - "github.com/zeta-chain/zetacore/zetaclient/config" - - "github.com/zeta-chain/zetacore/cmd" - - //mcconfig "github.com/Meta-Protocol/zetacore/metaclient/config" "github.com/cosmos/cosmos-sdk/types" - - "math/rand" - "os" - "time" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/zeta-chain/zetacore/app" + "github.com/zeta-chain/zetacore/cmd" + clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" + "github.com/zeta-chain/zetacore/zetaclient/config" ) const ( @@ -73,7 +68,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 0c112861e1..9816c16eab 100644 --- a/cmd/zetaclientd/p2p_diagnostics.go +++ b/cmd/zetaclientd/p2p_diagnostics.go @@ -7,8 +7,6 @@ import ( "sync" "time" - "github.com/zeta-chain/zetacore/zetaclient/metrics" - "github.com/cometbft/cometbft/crypto/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" libp2p "github.com/libp2p/go-libp2p" @@ -22,11 +20,18 @@ import ( maddr "github.com/multiformats/go-multiaddr" "github.com/rs/zerolog" "github.com/zeta-chain/go-tss/p2p" + "github.com/zeta-chain/zetacore/pkg/cosmos" "github.com/zeta-chain/zetacore/zetaclient/config" + "github.com/zeta-chain/zetacore/zetaclient/metrics" ) -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) @@ -178,7 +183,12 @@ func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, hotkeyPk cry } // write a message to the stream - 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) @@ -208,13 +218,15 @@ func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, hotkeyPk cry // check if the message is echoed correctly 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) } return nil } diff --git a/cmd/zetaclientd/start.go b/cmd/zetaclientd/start.go index 3448db3ed3..9c964ea26e 100644 --- a/cmd/zetaclientd/start.go +++ b/cmd/zetaclientd/start.go @@ -20,6 +20,7 @@ import ( "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/zeta-chain/go-tss/p2p" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/constant" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -122,7 +123,8 @@ func start(_ *cobra.Command, _ []string) error { } if strings.Compare(res.GetDefaultNodeInfo().Network, cfg.ChainID) != 0 { - startLogger.Warn().Msgf("chain id mismatch, zetacore chain id %s, zetaclient configured chain id %s; reset zetaclient chain id", res.GetDefaultNodeInfo().Network, cfg.ChainID) + startLogger.Warn(). + Msgf("chain id mismatch, zetacore chain id %s, zetaclient configured chain id %s; reset zetaclient chain id", res.GetDefaultNodeInfo().Network, cfg.ChainID) cfg.ChainID = res.GetDefaultNodeInfo().Network err := zetacoreClient.UpdateChainID(cfg.ChainID) if err != nil { @@ -198,7 +200,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 } @@ -235,7 +247,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()) } @@ -275,7 +288,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/start_utils.go b/cmd/zetaclientd/start_utils.go index ed81bc36f4..10f0b0beea 100644 --- a/cmd/zetaclientd/start_utils.go +++ b/cmd/zetaclientd/start_utils.go @@ -9,8 +9,9 @@ import ( "github.com/pkg/errors" "github.com/rs/zerolog" - "github.com/zeta-chain/zetacore/zetaclient/config" "google.golang.org/grpc" + + "github.com/zeta-chain/zetacore/zetaclient/config" ) func waitForZetaCore(config config.Config, logger zerolog.Logger) { diff --git a/cmd/zetaclientd/utils.go b/cmd/zetaclientd/utils.go index af8af41f1c..7c37c00380 100644 --- a/cmd/zetaclientd/utils.go +++ b/cmd/zetaclientd/utils.go @@ -3,6 +3,7 @@ package main import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/zetaclient/authz" btcobserver "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin/observer" btcsigner "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin/signer" @@ -21,7 +22,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/zetaclientd/version.go b/cmd/zetaclientd/version.go index 0cdc1ac59e..817d2752f7 100644 --- a/cmd/zetaclientd/version.go +++ b/cmd/zetaclientd/version.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/constant" ) diff --git a/cmd/zetacore_utils/main.go b/cmd/zetacore_utils/main.go index 74395a51b8..efef638bb8 100644 --- a/cmd/zetacore_utils/main.go +++ b/cmd/zetacore_utils/main.go @@ -11,6 +11,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" ) @@ -59,7 +60,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()) @@ -86,8 +99,23 @@ func main() { args := []string{"tx", "bank", "multi-send", signer} args = append(args, addresses...) - 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...) @@ -103,7 +131,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/add_observer_list.go b/cmd/zetacored/add_observer_list.go index c77bd651cb..fd614efbef 100644 --- a/cmd/zetacored/add_observer_list.go +++ b/cmd/zetacored/add_observer_list.go @@ -21,6 +21,7 @@ import ( ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/crypto" @@ -351,7 +352,9 @@ func addStakingGrants(grants []authz.GrantAuthorization, info ObserverInfoReader 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}, @@ -403,7 +406,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/collect_observer_info.go b/cmd/zetacored/collect_observer_info.go index 743b1b9425..170b6d0196 100644 --- a/cmd/zetacored/collect_observer_info.go +++ b/cmd/zetacored/collect_observer_info.go @@ -6,6 +6,7 @@ import ( "path/filepath" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" ) diff --git a/cmd/zetacored/flags_test.go b/cmd/zetacored/flags_test.go index 1fbdc4d4d0..a8d8d43596 100644 --- a/cmd/zetacored/flags_test.go +++ b/cmd/zetacored/flags_test.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/stretchr/testify/require" + zetacore "github.com/zeta-chain/zetacore/cmd/zetacored" ) diff --git a/cmd/zetacored/genaccounts.go b/cmd/zetacored/genaccounts.go index 43a20abe10..f97ac4d17a 100644 --- a/cmd/zetacored/genaccounts.go +++ b/cmd/zetacored/genaccounts.go @@ -5,12 +5,6 @@ import ( "errors" "fmt" - "github.com/ethereum/go-ethereum/common" - ethermint "github.com/evmos/ethermint/types" - evmtypes "github.com/evmos/ethermint/x/evm/types" - - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" @@ -20,6 +14,10 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/ethereum/go-ethereum/common" + ethermint "github.com/evmos/ethermint/types" + evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/spf13/cobra" ) const ( @@ -174,7 +172,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/get_pubkey.go b/cmd/zetacored/get_pubkey.go index 4743a5dd14..569d28dd0f 100644 --- a/cmd/zetacored/get_pubkey.go +++ b/cmd/zetacored/get_pubkey.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/cosmos" zetacrypto "github.com/zeta-chain/zetacore/pkg/crypto" ) diff --git a/cmd/zetacored/main.go b/cmd/zetacored/main.go index 4b12f153c7..b00e3dd337 100644 --- a/cmd/zetacored/main.go +++ b/cmd/zetacored/main.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" + "github.com/zeta-chain/zetacore/app" cmdcfg "github.com/zeta-chain/zetacore/cmd/zetacored/config" ) diff --git a/cmd/zetacored/parse_genesis.go b/cmd/zetacored/parse_genesis.go index cd81702127..b2a4258995 100644 --- a/cmd/zetacored/parse_genesis.go +++ b/cmd/zetacored/parse_genesis.go @@ -28,6 +28,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" @@ -152,7 +153,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.InboundHashToCctxList = importedCrossChainGenState.InboundHashToCctxList[:math.Min(MaxItemsForList, len(importedCrossChainGenState.InboundHashToCctxList))] @@ -167,7 +172,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/parse_genesis_test.go b/cmd/zetacored/parse_genesis_test.go index 6ac20be65b..7eb75f4a0f 100644 --- a/cmd/zetacored/parse_genesis_test.go +++ b/cmd/zetacored/parse_genesis_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/app" zetacored "github.com/zeta-chain/zetacore/cmd/zetacored" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" diff --git a/cmd/zetacored/parsers_test.go b/cmd/zetacored/parsers_test.go index a2c963214c..3b8e0a05d8 100644 --- a/cmd/zetacored/parsers_test.go +++ b/cmd/zetacored/parsers_test.go @@ -4,14 +4,13 @@ import ( "encoding/json" "io/ioutil" "os" + "testing" "github.com/cometbft/cometbft/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/zeta-chain/zetacore/app" - //"os" - "testing" + "github.com/zeta-chain/zetacore/app" ) func TestParsefileToObserverMapper(t *testing.T) { @@ -25,7 +24,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 a2d765f954..9c3756f2b3 100644 --- a/cmd/zetacored/root.go +++ b/cmd/zetacored/root.go @@ -6,22 +6,19 @@ import ( "io" "os" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/snapshot" - appparams "cosmossdk.io/simapp/params" + rosettaCmd "cosmossdk.io/tools/rosetta/cmd" + dbm "github.com/cometbft/cometbft-db" tmcfg "github.com/cometbft/cometbft/config" - "github.com/evmos/ethermint/crypto/hd" - "github.com/zeta-chain/zetacore/app" - zetacoredconfig "github.com/zeta-chain/zetacore/cmd/zetacored/config" - zevmserver "github.com/zeta-chain/zetacore/server" - servercfg "github.com/zeta-chain/zetacore/server/config" - + tmcli "github.com/cometbft/cometbft/libs/cli" + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/snapshot" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -31,15 +28,16 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - - rosettaCmd "cosmossdk.io/tools/rosetta/cmd" - dbm "github.com/cometbft/cometbft-db" - tmcli "github.com/cometbft/cometbft/libs/cli" - "github.com/cometbft/cometbft/libs/log" ethermintclient "github.com/evmos/ethermint/client" + "github.com/evmos/ethermint/crypto/hd" "github.com/spf13/cast" "github.com/spf13/cobra" + + "github.com/zeta-chain/zetacore/app" zetamempool "github.com/zeta-chain/zetacore/app/mempool" + zetacoredconfig "github.com/zeta-chain/zetacore/cmd/zetacored/config" + zevmserver "github.com/zeta-chain/zetacore/server" + servercfg "github.com/zeta-chain/zetacore/server/config" ) const EnvPrefix = "zetacore" @@ -128,8 +126,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), AddObserverListCmd(), @@ -145,7 +152,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/balances.go b/cmd/zetae2e/balances.go index 3815613781..a325621621 100644 --- a/cmd/zetae2e/balances.go +++ b/cmd/zetae2e/balances.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" diff --git a/cmd/zetae2e/bitcoin_address.go b/cmd/zetae2e/bitcoin_address.go index 77df85d116..b2a4525637 100644 --- a/cmd/zetae2e/bitcoin_address.go +++ b/cmd/zetae2e/bitcoin_address.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" diff --git a/cmd/zetae2e/config/clients.go b/cmd/zetae2e/config/clients.go index 061520df01..ae56eaa9dd 100644 --- a/cmd/zetae2e/config/clients.go +++ b/cmd/zetae2e/config/clients.go @@ -10,12 +10,13 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" + "google.golang.org/grpc" + "github.com/zeta-chain/zetacore/e2e/config" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc" ) // getClientsFromConfig get clients from config @@ -41,7 +42,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/config/config.go b/cmd/zetae2e/config/config.go index da8ef55cda..561a8eb6f0 100644 --- a/cmd/zetae2e/config/config.go +++ b/cmd/zetae2e/config/config.go @@ -5,6 +5,7 @@ import ( "fmt" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/txserver" diff --git a/cmd/zetae2e/config/contracts.go b/cmd/zetae2e/config/contracts.go index bc9d0e39f1..317054af19 100644 --- a/cmd/zetae2e/config/contracts.go +++ b/cmd/zetae2e/config/contracts.go @@ -13,6 +13,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-core/contracts/uniswapv2factory.sol" uniswapv2router "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/contracts/contextapp" "github.com/zeta-chain/zetacore/e2e/contracts/erc20" diff --git a/cmd/zetae2e/init.go b/cmd/zetae2e/init.go index f3308da4ca..b35f42ff97 100644 --- a/cmd/zetae2e/init.go +++ b/cmd/zetae2e/init.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetae2e/local" "github.com/zeta-chain/zetacore/e2e/config" ) @@ -20,8 +21,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/list_tests.go b/cmd/zetae2e/list_tests.go index 3fdf120eed..ec050e12e4 100644 --- a/cmd/zetae2e/list_tests.go +++ b/cmd/zetae2e/list_tests.go @@ -5,6 +5,7 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" ) diff --git a/cmd/zetae2e/local/admin.go b/cmd/zetae2e/local/admin.go index fa2df0b75c..6b360ecb7d 100644 --- a/cmd/zetae2e/local/admin.go +++ b/cmd/zetae2e/local/admin.go @@ -2,11 +2,11 @@ package local import ( "fmt" - "runtime" "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/bitcoin.go b/cmd/zetae2e/local/bitcoin.go index e7470518a9..d0f4d8bb12 100644 --- a/cmd/zetae2e/local/bitcoin.go +++ b/cmd/zetae2e/local/bitcoin.go @@ -6,6 +6,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/config.go b/cmd/zetae2e/local/config.go index 46a8953dc1..98ece83ac0 100644 --- a/cmd/zetae2e/local/config.go +++ b/cmd/zetae2e/local/config.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/e2e/config" ) diff --git a/cmd/zetae2e/local/erc20.go b/cmd/zetae2e/local/erc20.go index a453770842..5d0e7a5ac9 100644 --- a/cmd/zetae2e/local/erc20.go +++ b/cmd/zetae2e/local/erc20.go @@ -6,6 +6,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/ethereum.go b/cmd/zetae2e/local/ethereum.go index d5745472bd..efb37f1fa1 100644 --- a/cmd/zetae2e/local/ethereum.go +++ b/cmd/zetae2e/local/ethereum.go @@ -6,6 +6,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/local.go b/cmd/zetae2e/local/local.go index 4513901a24..e9213e17b5 100644 --- a/cmd/zetae2e/local/local.go +++ b/cmd/zetae2e/local/local.go @@ -6,10 +6,10 @@ import ( "path/filepath" "time" - "golang.org/x/sync/errgroup" - "github.com/fatih/color" "github.com/spf13/cobra" + "golang.org/x/sync/errgroup" + zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" diff --git a/cmd/zetae2e/local/misc.go b/cmd/zetae2e/local/misc.go index bc5240e571..081905b5ee 100644 --- a/cmd/zetae2e/local/misc.go +++ b/cmd/zetae2e/local/misc.go @@ -2,11 +2,11 @@ package local import ( "fmt" - "runtime" "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/monitor_priority_txs.go b/cmd/zetae2e/local/monitor_priority_txs.go index 147a9de28e..e58cbab513 100644 --- a/cmd/zetae2e/local/monitor_priority_txs.go +++ b/cmd/zetae2e/local/monitor_priority_txs.go @@ -9,6 +9,7 @@ import ( "github.com/cometbft/cometbft/abci/types" rpchttp "github.com/cometbft/cometbft/rpc/client/http" coretypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/zeta-chain/zetacore/e2e/config" ) diff --git a/cmd/zetae2e/local/performance.go b/cmd/zetae2e/local/performance.go index 3f01d80b6c..4b83d66307 100644 --- a/cmd/zetae2e/local/performance.go +++ b/cmd/zetae2e/local/performance.go @@ -9,6 +9,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/test_runner.go b/cmd/zetae2e/local/test_runner.go index 30d759a09f..6896c4c865 100644 --- a/cmd/zetae2e/local/test_runner.go +++ b/cmd/zetae2e/local/test_runner.go @@ -2,6 +2,7 @@ package local import ( ethcommon "github.com/ethereum/go-ethereum/common" + zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/zeta.go b/cmd/zetae2e/local/zeta.go index a24ee3872e..1f95c5f6d6 100644 --- a/cmd/zetae2e/local/zeta.go +++ b/cmd/zetae2e/local/zeta.go @@ -6,6 +6,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/local/zevm_mp.go b/cmd/zetae2e/local/zevm_mp.go index 6200ee512c..969dcfda64 100644 --- a/cmd/zetae2e/local/zevm_mp.go +++ b/cmd/zetae2e/local/zevm_mp.go @@ -6,6 +6,7 @@ import ( "time" "github.com/fatih/color" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/e2etests" "github.com/zeta-chain/zetacore/e2e/runner" diff --git a/cmd/zetae2e/root.go b/cmd/zetae2e/root.go index 4568358512..d9adf800f0 100644 --- a/cmd/zetae2e/root.go +++ b/cmd/zetae2e/root.go @@ -2,6 +2,7 @@ package main import ( "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetae2e/local" ) diff --git a/cmd/zetae2e/run.go b/cmd/zetae2e/run.go index a297d6cac8..e97e9e576b 100644 --- a/cmd/zetae2e/run.go +++ b/cmd/zetae2e/run.go @@ -9,6 +9,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" diff --git a/cmd/zetae2e/setup_bitcoin.go b/cmd/zetae2e/setup_bitcoin.go index 15e9877164..407a80e429 100644 --- a/cmd/zetae2e/setup_bitcoin.go +++ b/cmd/zetae2e/setup_bitcoin.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" diff --git a/cmd/zetae2e/show_tss.go b/cmd/zetae2e/show_tss.go index 1d610eb150..6c1ed0092c 100644 --- a/cmd/zetae2e/show_tss.go +++ b/cmd/zetae2e/show_tss.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" diff --git a/cmd/zetae2e/stress.go b/cmd/zetae2e/stress.go index 98dca87ff8..20e7ff494f 100644 --- a/cmd/zetae2e/stress.go +++ b/cmd/zetae2e/stress.go @@ -16,13 +16,14 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "google.golang.org/grpc" + "github.com/zeta-chain/zetacore/app" zetae2econfig "github.com/zeta-chain/zetacore/cmd/zetae2e/config" "github.com/zeta-chain/zetacore/cmd/zetae2e/local" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "google.golang.org/grpc" ) const ( @@ -52,11 +53,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 +117,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 +260,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 +274,20 @@ func EchoNetworkMetrics(runner *runner.E2ERunner) { return sends[i].GetCurrentOutboundParam().TssNonce < sends[j].GetCurrentOutboundParam().TssNonce }) if len(sends) > 0 { - fmt.Printf("pending nonces %d to %d\n", sends[0].GetCurrentOutboundParam().TssNonce, sends[len(sends)-1].GetCurrentOutboundParam().TssNonce) + fmt.Printf( + "pending nonces %d to %d\n", + sends[0].GetCurrentOutboundParam().TssNonce, + sends[len(sends)-1].GetCurrentOutboundParam().TssNonce, + ) } else { continue } // // Get all trackers - trackerResp, err := runner.CctxClient.OutboundTrackerAll(context.Background(), &crosschaintypes.QueryAllOutboundTrackerRequest{}) + trackerResp, err := runner.CctxClient.OutboundTrackerAll( + context.Background(), + &crosschaintypes.QueryAllOutboundTrackerRequest{}, + ) if err != nil { continue } @@ -293,7 +311,15 @@ func EchoNetworkMetrics(runner *runner.E2ERunner) { numPending := len(cctxResp.CrossChainTx) numTrackers := len(trackerResp.OutboundTracker) - 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/btc.go b/cmd/zetatool/filterdeposit/btc.go index 684bb4b428..c8d8ddd11a 100644 --- a/cmd/zetatool/filterdeposit/btc.go +++ b/cmd/zetatool/filterdeposit/btc.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetatool/config" "github.com/zeta-chain/zetacore/pkg/constant" ) diff --git a/cmd/zetatool/filterdeposit/evm.go b/cmd/zetatool/filterdeposit/evm.go index 50c39119c8..dadaeb4377 100644 --- a/cmd/zetatool/filterdeposit/evm.go +++ b/cmd/zetatool/filterdeposit/evm.go @@ -15,6 +15,7 @@ import ( "github.com/spf13/cobra" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + "github.com/zeta-chain/zetacore/cmd/zetatool/config" "github.com/zeta-chain/zetacore/pkg/constant" "github.com/zeta-chain/zetacore/zetaclient/chains/evm" diff --git a/cmd/zetatool/filterdeposit/filterdeposit.go b/cmd/zetatool/filterdeposit/filterdeposit.go index 6dfa6d6c11..ccab8e6273 100644 --- a/cmd/zetatool/filterdeposit/filterdeposit.go +++ b/cmd/zetatool/filterdeposit/filterdeposit.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetatool/config" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -27,7 +28,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/cmd/zetatool/filterdeposit/filterdeposit_test.go b/cmd/zetatool/filterdeposit/filterdeposit_test.go index 2140a43c08..d1ef644c1c 100644 --- a/cmd/zetatool/filterdeposit/filterdeposit_test.go +++ b/cmd/zetatool/filterdeposit/filterdeposit_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetatool/config" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/cmd/zetatool/main.go b/cmd/zetatool/main.go index 584d21b747..cb36479573 100644 --- a/cmd/zetatool/main.go +++ b/cmd/zetatool/main.go @@ -4,10 +4,10 @@ import ( "fmt" "os" - "github.com/zeta-chain/zetacore/cmd/zetatool/filterdeposit" - "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetatool/config" + "github.com/zeta-chain/zetacore/cmd/zetatool/filterdeposit" ) var rootCmd = &cobra.Command{ 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/docs/main.go b/docs/main.go index b86d583726..3e62a0e0b7 100644 --- a/docs/main.go +++ b/docs/main.go @@ -15,6 +15,7 @@ import ( "time" "github.com/gorilla/mux" + "github.com/zeta-chain/zetacore/docs/openapi" ) diff --git a/e2e/config/config.go b/e2e/config/config.go index e8f51dbf9a..6f33da7104 100644 --- a/e2e/config/config.go +++ b/e2e/config/config.go @@ -6,7 +6,6 @@ import ( "os" "github.com/btcsuite/btcd/chaincfg" - "gopkg.in/yaml.v2" ) diff --git a/e2e/e2etests/helper_bitcoin.go b/e2e/e2etests/helper_bitcoin.go index f889bd76e2..84d6dac246 100644 --- a/e2e/e2etests/helper_bitcoin.go +++ b/e2e/e2etests/helper_bitcoin.go @@ -8,6 +8,7 @@ import ( "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/pkg/chains" @@ -45,7 +46,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/helper_erc20.go b/e2e/e2etests/helper_erc20.go index 4e72308fc8..fd4630067b 100644 --- a/e2e/e2etests/helper_erc20.go +++ b/e2e/e2etests/helper_erc20.go @@ -2,6 +2,7 @@ package e2etests import ( ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go b/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go index e4ff720549..77cde7ad64 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go +++ b/e2e/e2etests/test_bitcoin_withdraw_invalid_address.go @@ -6,6 +6,7 @@ import ( "strconv" "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" ) diff --git a/e2e/e2etests/test_bitcoin_withdraw_legacy.go b/e2e/e2etests/test_bitcoin_withdraw_legacy.go index b2b1a4840b..a40fc0e852 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_legacy.go +++ b/e2e/e2etests/test_bitcoin_withdraw_legacy.go @@ -2,6 +2,7 @@ package e2etests import ( "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" ) diff --git a/e2e/e2etests/test_bitcoin_withdraw_p2sh.go b/e2e/e2etests/test_bitcoin_withdraw_p2sh.go index 12bb23e28a..086f45a4dc 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_p2sh.go +++ b/e2e/e2etests/test_bitcoin_withdraw_p2sh.go @@ -2,6 +2,7 @@ package e2etests import ( "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" ) diff --git a/e2e/e2etests/test_bitcoin_withdraw_p2wsh.go b/e2e/e2etests/test_bitcoin_withdraw_p2wsh.go index 9cd54ed867..524db32cda 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_p2wsh.go +++ b/e2e/e2etests/test_bitcoin_withdraw_p2wsh.go @@ -2,6 +2,7 @@ package e2etests import ( "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" ) diff --git a/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go b/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go index 7f4c37646f..b33f724b90 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go +++ b/e2e/e2etests/test_bitcoin_withdraw_restricted_address.go @@ -6,6 +6,7 @@ import ( "strconv" "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/testutils" @@ -34,7 +35,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_bitcoin_withdraw_segwit.go b/e2e/e2etests/test_bitcoin_withdraw_segwit.go index d996bf6b8f..9f85044f89 100644 --- a/e2e/e2etests/test_bitcoin_withdraw_segwit.go +++ b/e2e/e2etests/test_bitcoin_withdraw_segwit.go @@ -2,6 +2,7 @@ package e2etests import ( "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/e2e/runner" ) diff --git a/e2e/e2etests/test_context_upgrade.go b/e2e/e2etests/test_context_upgrade.go index eeb9c62ea9..fc1e7599de 100644 --- a/e2e/e2etests/test_context_upgrade.go +++ b/e2e/e2etests/test_context_upgrade.go @@ -6,6 +6,7 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" ) diff --git a/e2e/e2etests/test_crosschain_swap.go b/e2e/e2etests/test_crosschain_swap.go index e3876be8bf..fb5e9b97de 100644 --- a/e2e/e2etests/test_crosschain_swap.go +++ b/e2e/e2etests/test_crosschain_swap.go @@ -7,6 +7,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -79,7 +80,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 +99,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 f2a7b029ec..684adf3d6f 100644 --- a/e2e/e2etests/test_erc20_deposit_refund.go +++ b/e2e/e2etests/test_erc20_deposit_refund.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -58,7 +59,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_deposit_restricted_address.go b/e2e/e2etests/test_erc20_deposit_restricted_address.go index 885cf86200..1823f9236d 100644 --- a/e2e/e2etests/test_erc20_deposit_restricted_address.go +++ b/e2e/e2etests/test_erc20_deposit_restricted_address.go @@ -4,6 +4,7 @@ import ( "math/big" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/zetaclient/testutils" ) diff --git a/e2e/e2etests/test_erc20_multiple_deposits.go b/e2e/e2etests/test_erc20_multiple_deposits.go index 65df963e4b..b09c363c8d 100644 --- a/e2e/e2etests/test_erc20_multiple_deposits.go +++ b/e2e/e2etests/test_erc20_multiple_deposits.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" testcontract "github.com/zeta-chain/zetacore/testutil/contracts" @@ -32,7 +33,14 @@ func TestMultipleERC20Deposit(r *runner.E2ERunner, args []string) { } txhash := multipleDeposits(r, depositAmount, numberOfDeposits) - cctxs := utils.WaitCctxsMinedByInboundHash(r.Ctx, txhash.Hex(), r.CctxClient, int(numberOfDeposits.Int64()), r.Logger, r.CctxTimeout) + cctxs := utils.WaitCctxsMinedByInboundHash( + 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 318b7f3eb1..de13c7b6b8 100644 --- a/e2e/e2etests/test_erc20_multiple_withdraws.go +++ b/e2e/e2etests/test_erc20_multiple_withdraws.go @@ -5,6 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" testcontract "github.com/zeta-chain/zetacore/testutil/contracts" @@ -13,7 +14,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 +90,14 @@ func TestMultipleERC20Withdraws(r *runner.E2ERunner, args []string) { panic("withdraw failed") } - cctxs := utils.WaitCctxsMinedByInboundHash(r.Ctx, tx.Hash().Hex(), r.CctxClient, int(numberOfWithdrawals.Int64()), r.Logger, r.CctxTimeout) + cctxs := utils.WaitCctxsMinedByInboundHash( + 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 e592824012..dc6cc5cb32 100644 --- a/e2e/e2etests/test_eth_deposit_call.go +++ b/e2e/e2etests/test_eth_deposit_call.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" testcontract "github.com/zeta-chain/zetacore/testutil/contracts" @@ -79,7 +80,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 +134,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_liquidity_cap.go b/e2e/e2etests/test_eth_deposit_liquidity_cap.go index b0c1a74178..a132fdd35e 100644 --- a/e2e/e2etests/test_eth_deposit_liquidity_cap.go +++ b/e2e/e2etests/test_eth_deposit_liquidity_cap.go @@ -5,8 +5,8 @@ import ( "math/big" "cosmossdk.io/math" - "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/e2e/e2etests/test_eth_deposit_refund.go b/e2e/e2etests/test_eth_deposit_refund.go index adfc3aae6b..2de41965ea 100644 --- a/e2e/e2etests/test_eth_deposit_refund.go +++ b/e2e/e2etests/test_eth_deposit_refund.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -103,7 +104,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_eth_withdraw_restricted_address.go b/e2e/e2etests/test_eth_withdraw_restricted_address.go index 8c0e38123f..8f17cb4edb 100644 --- a/e2e/e2etests/test_eth_withdraw_restricted_address.go +++ b/e2e/e2etests/test_eth_withdraw_restricted_address.go @@ -4,6 +4,7 @@ import ( "math/big" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/e2e/e2etests/test_message_passing_evm_to_zevm.go b/e2e/e2etests/test_message_passing_evm_to_zevm.go index 3c3f697a2f..bedfd50965 100644 --- a/e2e/e2etests/test_message_passing_evm_to_zevm.go +++ b/e2e/e2etests/test_message_passing_evm_to_zevm.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" 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 3462b352ef..3c12711aed 100644 --- a/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go +++ b/e2e/e2etests/test_message_passing_evm_to_zevm_revert.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" @@ -101,7 +102,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_evm_to_zevm_revert_fail.go b/e2e/e2etests/test_message_passing_evm_to_zevm_revert_fail.go index 40bd428828..352fe959a8 100644 --- a/e2e/e2etests/test_message_passing_evm_to_zevm_revert_fail.go +++ b/e2e/e2etests/test_message_passing_evm_to_zevm_revert_fail.go @@ -5,6 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/contracts/testdappnorevert" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" diff --git a/e2e/e2etests/test_message_passing_external_chains.go b/e2e/e2etests/test_message_passing_external_chains.go index 6bdd7355c1..5a6fed227e 100644 --- a/e2e/e2etests/test_message_passing_external_chains.go +++ b/e2e/e2etests/test_message_passing_external_chains.go @@ -6,6 +6,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" zetaconnectoreth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.eth.sol" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" cctxtypes "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/e2e/e2etests/test_message_passing_external_chains_revert.go b/e2e/e2etests/test_message_passing_external_chains_revert.go index c1ebc56026..fee09b3bb0 100644 --- a/e2e/e2etests/test_message_passing_external_chains_revert.go +++ b/e2e/e2etests/test_message_passing_external_chains_revert.go @@ -5,6 +5,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" 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 69e02f4782..e9bdeb0c7e 100644 --- a/e2e/e2etests/test_message_passing_external_chains_revert_fail.go +++ b/e2e/e2etests/test_message_passing_external_chains_revert_fail.go @@ -5,6 +5,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" zetaconnectoreth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.eth.sol" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" cctxtypes "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -44,9 +45,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) diff --git a/e2e/e2etests/test_message_passing_zevm_to_evm.go b/e2e/e2etests/test_message_passing_zevm_to_evm.go index df855e3fb9..0e7c888be2 100644 --- a/e2e/e2etests/test_message_passing_zevm_to_evm.go +++ b/e2e/e2etests/test_message_passing_zevm_to_evm.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" 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 2dc6302bb8..0badfefdcb 100644 --- a/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go +++ b/e2e/e2etests/test_message_passing_zevm_to_evm_revert.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" 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 0aff9a71f5..bf9c50a89c 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 @@ -5,6 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/contracts/testdappnorevert" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" @@ -120,6 +121,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 99f0895057..df30e84713 100644 --- a/e2e/e2etests/test_migrate_chain_support.go +++ b/e2e/e2etests/test_migrate_chain_support.go @@ -13,6 +13,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/fatih/color" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/txserver" "github.com/zeta-chain/zetacore/e2e/utils" @@ -88,7 +89,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 009c190228..db8d67f348 100644 --- a/e2e/e2etests/test_rate_limiter.go +++ b/e2e/e2etests/test_rate_limiter.go @@ -8,10 +8,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethtypes "github.com/ethereum/go-ethereum/core/types" + "golang.org/x/sync/errgroup" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "golang.org/x/sync/errgroup" ) // WithdrawType is the type of withdraw to perform in the test @@ -150,7 +151,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.WaitCctxMinedByInboundHash(ctx, tx.Hash().Hex(), r.CctxClient, r.Logger, r.CctxTimeout) r.Logger.CCTX(*cctx, "withdraw") diff --git a/e2e/e2etests/test_stress_btc_deposit.go b/e2e/e2etests/test_stress_btc_deposit.go index f920c283fa..51e1b8857f 100644 --- a/e2e/e2etests/test_stress_btc_deposit.go +++ b/e2e/e2etests/test_stress_btc_deposit.go @@ -6,10 +6,11 @@ import ( "time" "github.com/btcsuite/btcd/chaincfg/chainhash" + "golang.org/x/sync/errgroup" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "golang.org/x/sync/errgroup" ) // TestStressBTCDeposit tests the stressing deposit of BTC diff --git a/e2e/e2etests/test_stress_btc_withdraw.go b/e2e/e2etests/test_stress_btc_withdraw.go index c34fbb5402..28ccb77178 100644 --- a/e2e/e2etests/test_stress_btc_withdraw.go +++ b/e2e/e2etests/test_stress_btc_withdraw.go @@ -8,16 +8,19 @@ import ( "github.com/btcsuite/btcutil" ethtypes "github.com/ethereum/go-ethereum/core/types" + "golang.org/x/sync/errgroup" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "golang.org/x/sync/errgroup" ) // 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_deposit.go b/e2e/e2etests/test_stress_eth_deposit.go index 776c89f7a2..f3b1e94dc8 100644 --- a/e2e/e2etests/test_stress_eth_deposit.go +++ b/e2e/e2etests/test_stress_eth_deposit.go @@ -7,10 +7,11 @@ import ( "time" ethcommon "github.com/ethereum/go-ethereum/common" + "golang.org/x/sync/errgroup" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "golang.org/x/sync/errgroup" ) // TestStressEtherDeposit tests the stressing deposit of ether diff --git a/e2e/e2etests/test_stress_eth_withdraw.go b/e2e/e2etests/test_stress_eth_withdraw.go index b82091a689..7f73e863a0 100644 --- a/e2e/e2etests/test_stress_eth_withdraw.go +++ b/e2e/e2etests/test_stress_eth_withdraw.go @@ -2,14 +2,13 @@ package e2etests import ( "fmt" - "strconv" - "math/big" + "strconv" "time" + ethtypes "github.com/ethereum/go-ethereum/core/types" "golang.org/x/sync/errgroup" - ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -18,7 +17,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/e2etests/test_update_bytecode_connector.go b/e2e/e2etests/test_update_bytecode_connector.go index a14461b052..6b88e14972 100644 --- a/e2e/e2etests/test_update_bytecode_connector.go +++ b/e2e/e2etests/test_update_bytecode_connector.go @@ -5,6 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/contracts/testconnectorzevm" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" diff --git a/e2e/e2etests/test_update_bytecode_zrc20.go b/e2e/e2etests/test_update_bytecode_zrc20.go index d5730415bf..4762ec94bb 100644 --- a/e2e/e2etests/test_update_bytecode_zrc20.go +++ b/e2e/e2etests/test_update_bytecode_zrc20.go @@ -4,6 +4,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/zeta-chain/zetacore/e2e/contracts/testzrc20" "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" diff --git a/e2e/e2etests/test_zeta_deposit_restricted_address.go b/e2e/e2etests/test_zeta_deposit_restricted_address.go index aa24ac01f2..e6a9d4f23b 100644 --- a/e2e/e2etests/test_zeta_deposit_restricted_address.go +++ b/e2e/e2etests/test_zeta_deposit_restricted_address.go @@ -4,6 +4,7 @@ import ( "math/big" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/zetaclient/testutils" ) diff --git a/e2e/e2etests/test_zeta_withdraw_bitcoin_revert.go b/e2e/e2etests/test_zeta_withdraw_bitcoin_revert.go index 48fa7f8b5b..ac4525881b 100644 --- a/e2e/e2etests/test_zeta_withdraw_bitcoin_revert.go +++ b/e2e/e2etests/test_zeta_withdraw_bitcoin_revert.go @@ -4,6 +4,7 @@ import ( "math/big" connectorzevm "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zetaconnectorzevm.sol" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/pkg/chains" diff --git a/e2e/e2etests/test_zrc20_swap.go b/e2e/e2etests/test_zrc20_swap.go index 0954fb0b7d..4dfea02cf1 100644 --- a/e2e/e2etests/test_zrc20_swap.go +++ b/e2e/e2etests/test_zrc20_swap.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/e2e/runner" "github.com/zeta-chain/zetacore/e2e/utils" ) 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 a90cea8f39..f976253474 100644 --- a/e2e/runner/bitcoin.go +++ b/e2e/runner/bitcoin.go @@ -15,6 +15,7 @@ import ( "github.com/btcsuite/btcutil" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/rs/zerolog/log" + "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/constant" @@ -33,7 +34,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 +62,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 +114,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 +152,13 @@ func (runner *E2ERunner) DepositBTC(testHeader bool) { runner.Logger.Info("testing if the deposit into BTC ZRC20 is successful...") - cctx := utils.WaitCctxMinedByInboundHash(runner.Ctx, txHash2.String(), runner.CctxClient, runner.Logger, runner.CctxTimeout) + cctx := utils.WaitCctxMinedByInboundHash( + 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 +189,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 +420,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..cfa944418d 100644 --- a/e2e/runner/evm.go +++ b/e2e/runner/evm.go @@ -9,6 +9,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rpc" + "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -78,7 +79,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/logger.go b/e2e/runner/logger.go index f4820cadd7..49ab8af29c 100644 --- a/e2e/runner/logger.go +++ b/e2e/runner/logger.go @@ -5,10 +5,10 @@ import ( "sync" ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/fatih/color" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" - crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" - "github.com/fatih/color" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) const ( diff --git a/e2e/runner/report.go b/e2e/runner/report.go index e798eadd4b..a25360a109 100644 --- a/e2e/runner/report.go +++ b/e2e/runner/report.go @@ -8,6 +8,7 @@ import ( sdkmath "cosmossdk.io/math" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/e2e/txserver" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/e2e/runner/runner.go b/e2e/runner/runner.go index da8944c7d9..d8df023057 100644 --- a/e2e/runner/runner.go +++ b/e2e/runner/runner.go @@ -22,6 +22,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-core/contracts/uniswapv2factory.sol" uniswapv2router "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/e2e/contracts/contextapp" "github.com/zeta-chain/zetacore/e2e/contracts/erc20" "github.com/zeta-chain/zetacore/e2e/contracts/zevmswap" diff --git a/e2e/runner/setup_evm.go b/e2e/runner/setup_evm.go index 01188c759a..2bc0aeb70d 100644 --- a/e2e/runner/setup_evm.go +++ b/e2e/runner/setup_evm.go @@ -8,6 +8,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" zetaeth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zeta.eth.sol" zetaconnectoreth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.eth.sol" + "github.com/zeta-chain/zetacore/e2e/config" "github.com/zeta-chain/zetacore/e2e/contracts/erc20" "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" @@ -62,7 +63,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 +103,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 +136,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..b5f454d38a 100644 --- a/e2e/runner/setup_zeta.go +++ b/e2e/runner/setup_zeta.go @@ -13,6 +13,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-core/contracts/uniswapv2factory.sol" uniswapv2router "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/e2e/contracts/contextapp" "github.com/zeta-chain/zetacore/e2e/contracts/testdapp" "github.com/zeta-chain/zetacore/e2e/contracts/zevmswap" @@ -143,7 +144,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 +172,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 +202,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 +222,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 6b02673c9a..104fb4900f 100644 --- a/e2e/runner/zeta.go +++ b/e2e/runner/zeta.go @@ -8,6 +8,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" zetaconnectoreth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.eth.sol" connectorzevm "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zetaconnectorzevm.sol" + "github.com/zeta-chain/zetacore/e2e/utils" "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -32,7 +33,13 @@ func (runner *E2ERunner) WaitForMinedCCTX(txHash ethcommon.Hash) { }() runner.Lock() - cctx := utils.WaitCctxMinedByInboundHash(runner.Ctx, txHash.Hex(), runner.CctxClient, runner.Logger, runner.CctxTimeout) + cctx := utils.WaitCctxMinedByInboundHash( + 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..6e6d12545e 100644 --- a/e2e/txserver/zeta_tx_server.go +++ b/e2e/txserver/zeta_tx_server.go @@ -36,6 +36,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" etherminttypes "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" @@ -272,7 +273,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 +294,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 +320,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/e2e/utils/zetacore.go b/e2e/utils/zetacore.go index 55c7a54dda..093ff4314f 100644 --- a/e2e/utils/zetacore.go +++ b/e2e/utils/zetacore.go @@ -7,6 +7,7 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" coretypes "github.com/cometbft/cometbft/rpc/core/types" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) 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..ee974dcd69 100644 --- a/pkg/chains/address_test.go +++ b/pkg/chains/address_test.go @@ -6,7 +6,6 @@ import ( "github.com/btcsuite/btcutil" "github.com/stretchr/testify/require" - . "gopkg.in/check.v1" ) @@ -22,11 +21,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 +83,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/status_test.go b/pkg/chains/status_test.go index a26170f97c..3f4061efb3 100644 --- a/pkg/chains/status_test.go +++ b/pkg/chains/status_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" ) 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/pubkey.go b/pkg/crypto/pubkey.go index 703d0bdad4..8c893664b0 100644 --- a/pkg/crypto/pubkey.go +++ b/pkg/crypto/pubkey.go @@ -8,11 +8,9 @@ import ( "strings" secp256k1 "github.com/btcsuite/btcd/btcec/v2" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - + sdk "github.com/cosmos/cosmos-sdk/types" eth "github.com/ethereum/go-ethereum/crypto" "github.com/zeta-chain/zetacore/pkg/chains" diff --git a/pkg/crypto/pubkey_test.go b/pkg/crypto/pubkey_test.go index 0089ba34d7..db7674cb40 100644 --- a/pkg/crypto/pubkey_test.go +++ b/pkg/crypto/pubkey_test.go @@ -10,9 +10,9 @@ import ( "github.com/cometbft/cometbft/crypto/secp256k1" "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/testutil/testdata" + "github.com/stretchr/testify/require" . "gopkg.in/check.v1" - "github.com/stretchr/testify/require" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/cosmos" ) diff --git a/pkg/crypto/tss.go b/pkg/crypto/tss.go index fc3c36ed8a..44e0987710 100644 --- a/pkg/crypto/tss.go +++ b/pkg/crypto/tss.go @@ -5,6 +5,7 @@ import ( "github.com/btcsuite/btcutil" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/cosmos" ) @@ -35,7 +36,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/crypto/tss_test.go b/pkg/crypto/tss_test.go index 10497f1e85..b9315d6ec2 100644 --- a/pkg/crypto/tss_test.go +++ b/pkg/crypto/tss_test.go @@ -9,6 +9,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/cosmos" ) diff --git a/pkg/proofs/bitcoin/proof_test.go b/pkg/proofs/bitcoin/proof_test.go index 7ad3199493..23444e22d6 100644 --- a/pkg/proofs/bitcoin/proof_test.go +++ b/pkg/proofs/bitcoin/proof_test.go @@ -12,6 +12,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/testdata" ) diff --git a/pkg/proofs/ethereum/proof_test.go b/pkg/proofs/ethereum/proof_test.go index 1fc3dc1c51..b6c676b0ee 100644 --- a/pkg/proofs/ethereum/proof_test.go +++ b/pkg/proofs/ethereum/proof_test.go @@ -5,6 +5,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/testdata" ) diff --git a/pkg/proofs/headers.go b/pkg/proofs/headers.go index 64d2a6b2f1..666d55cf6e 100644 --- a/pkg/proofs/headers.go +++ b/pkg/proofs/headers.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/btcutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs/bitcoin" ) diff --git a/pkg/proofs/headers_test.go b/pkg/proofs/headers_test.go index 9b10450fb0..5d992a4686 100644 --- a/pkg/proofs/headers_test.go +++ b/pkg/proofs/headers_test.go @@ -16,6 +16,7 @@ import ( "github.com/btcsuite/btcd/wire" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/testdata" ) diff --git a/pkg/proofs/proof.go b/pkg/proofs/proof.go index 85b62d6bd0..76383ed857 100644 --- a/pkg/proofs/proof.go +++ b/pkg/proofs/proof.go @@ -8,6 +8,7 @@ import ( "github.com/btcsuite/btcutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" + "github.com/zeta-chain/zetacore/pkg/proofs/bitcoin" "github.com/zeta-chain/zetacore/pkg/proofs/ethereum" ) diff --git a/pkg/proofs/proof_test.go b/pkg/proofs/proof_test.go index e52d2a1cb3..b9210e9260 100644 --- a/pkg/proofs/proof_test.go +++ b/pkg/proofs/proof_test.go @@ -1,25 +1,24 @@ package proofs import ( - "errors" - "testing" - "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" + "testing" + "github.com/btcsuite/btcd/blockchain" + "github.com/btcsuite/btcd/btcjson" + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/proofs/bitcoin" "github.com/zeta-chain/zetacore/pkg/proofs/ethereum" "github.com/zeta-chain/zetacore/pkg/testdata" - - "github.com/btcsuite/btcd/blockchain" - "github.com/btcsuite/btcd/btcjson" - "github.com/btcsuite/btcd/wire" - "github.com/btcsuite/btcutil" ) const ( @@ -136,11 +135,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, outboundID string, tssAddress string, nonce uint64) { +func validateBitcoinBlock( + t *testing.T, + _ *wire.BlockHeader, + headerBytes []byte, + blockVerbose *btcjson.GetBlockVerboseTxResult, + outboundID string, + tssAddress string, + nonce uint64, +) { // Deserialization should work for each transaction in the block txns := []*btcutil.Tx{} txBodies := [][]byte{} diff --git a/rpc/apis.go b/rpc/apis.go index b845ba7bb0..2cc5c4b9a9 100644 --- a/rpc/apis.go +++ b/rpc/apis.go @@ -23,6 +23,7 @@ import ( "github.com/cosmos/cosmos-sdk/server" "github.com/ethereum/go-ethereum/rpc" ethermint "github.com/evmos/ethermint/types" + "github.com/zeta-chain/zetacore/rpc/backend" "github.com/zeta-chain/zetacore/rpc/namespaces/ethereum/debug" "github.com/zeta-chain/zetacore/rpc/namespaces/ethereum/eth" diff --git a/rpc/backend/account_info.go b/rpc/backend/account_info.go index b6175b5cd1..4711074c89 100644 --- a/rpc/backend/account_info.go +++ b/rpc/backend/account_info.go @@ -29,6 +29,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -52,7 +53,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 +93,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 +143,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..2890cae40b 100644 --- a/rpc/backend/backend.go +++ b/rpc/backend/backend.go @@ -34,6 +34,7 @@ import ( "github.com/ethereum/go-ethereum/signer/core/apitypes" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" "github.com/zeta-chain/zetacore/server/config" ) @@ -64,7 +65,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 +93,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 +130,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 +144,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 +164,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..361c53e318 100644 --- a/rpc/backend/blocks.go +++ b/rpc/backend/blocks.go @@ -32,9 +32,10 @@ import ( "github.com/ethereum/go-ethereum/trie" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" - rpctypes "github.com/zeta-chain/zetacore/rpc/types" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) // BlockNumber returns the current block number in abci app state. Because abci @@ -51,7 +52,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 +112,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 +344,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 +380,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 +422,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 +553,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..9df59ffd06 100644 --- a/rpc/backend/call_tx.go +++ b/rpc/backend/call_tx.go @@ -32,14 +32,19 @@ import ( ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" - rpctypes "github.com/zeta-chain/zetacore/rpc/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) // 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 +215,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 +261,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 +319,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..bb993054d8 100644 --- a/rpc/backend/chain_info.go +++ b/rpc/backend/chain_info.go @@ -32,6 +32,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/pkg/errors" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -297,7 +298,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/node_info.go b/rpc/backend/node_info.go index f2dd727a3d..2b7a99a267 100644 --- a/rpc/backend/node_info.go +++ b/rpc/backend/node_info.go @@ -38,6 +38,7 @@ import ( "github.com/evmos/ethermint/server/config" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) diff --git a/rpc/backend/sign_tx.go b/rpc/backend/sign_tx.go index 0c16da0c34..a5e004dc45 100644 --- a/rpc/backend/sign_tx.go +++ b/rpc/backend/sign_tx.go @@ -29,7 +29,6 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/signer/core/apitypes" - evmtypes "github.com/evmos/ethermint/x/evm/types" ) @@ -39,11 +38,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..e86d2ed8a4 100644 --- a/rpc/backend/tracing.go +++ b/rpc/backend/tracing.go @@ -25,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -52,7 +53,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..612097b0a1 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -29,6 +29,7 @@ import ( ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" + rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -92,7 +93,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 +316,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 +341,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 +384,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 +412,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 +441,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 +489,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..38a53c3d3c 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -22,22 +22,20 @@ import ( "sort" "strings" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/proto/tendermint/crypto" + tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/consensus/misc" ethtypes "github.com/ethereum/go-ethereum/core/types" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" - tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" - - "github.com/cometbft/cometbft/proto/tendermint/crypto" evmtypes "github.com/evmos/ethermint/x/evm/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/rpc/types" ) @@ -61,7 +59,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 +155,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/ethereum/pubsub/pubsub.go b/rpc/ethereum/pubsub/pubsub.go index a90ec84039..a8117a8fbb 100644 --- a/rpc/ethereum/pubsub/pubsub.go +++ b/rpc/ethereum/pubsub/pubsub.go @@ -19,9 +19,8 @@ import ( "sync" "sync/atomic" - "github.com/pkg/errors" - coretypes "github.com/cometbft/cometbft/rpc/core/types" + "github.com/pkg/errors" ) type UnsubscribeFunc func() diff --git a/rpc/namespaces/ethereum/debug/api.go b/rpc/namespaces/ethereum/debug/api.go index bbc037d423..3496da92d8 100644 --- a/rpc/namespaces/ethereum/debug/api.go +++ b/rpc/namespaces/ethereum/debug/api.go @@ -36,6 +36,7 @@ import ( "github.com/ethereum/go-ethereum/rlp" evmtypes "github.com/evmos/ethermint/x/evm/types" stderrors "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/rpc/backend" rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -79,7 +80,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..982f5655ae 100644 --- a/rpc/namespaces/ethereum/eth/api.go +++ b/rpc/namespaces/ethereum/eth/api.go @@ -25,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/rpc/backend" rpctypes "github.com/zeta-chain/zetacore/rpc/types" ) @@ -53,7 +54,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 +75,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 +97,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 +122,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 +197,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 +229,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 +273,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 +342,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..a18ba4402e 100644 --- a/rpc/namespaces/ethereum/eth/filters/api.go +++ b/rpc/namespaces/ethereum/eth/filters/api.go @@ -31,6 +31,7 @@ import ( "github.com/ethereum/go-ethereum/eth/filters" "github.com/ethereum/go-ethereum/rpc" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/rpc/types" ) @@ -89,7 +90,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 +291,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 +434,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 +526,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/filter_system.go b/rpc/namespaces/ethereum/eth/filters/filter_system.go index 2c672472ba..35004b0138 100644 --- a/rpc/namespaces/ethereum/eth/filters/filter_system.go +++ b/rpc/namespaces/ethereum/eth/filters/filter_system.go @@ -34,6 +34,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/rpc/ethereum/pubsub" ) diff --git a/rpc/namespaces/ethereum/eth/filters/filters.go b/rpc/namespaces/ethereum/eth/filters/filters.go index 6ddbcc420e..59874611db 100644 --- a/rpc/namespaces/ethereum/eth/filters/filters.go +++ b/rpc/namespaces/ethereum/eth/filters/filters.go @@ -28,6 +28,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/filters" "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/rpc/backend" "github.com/zeta-chain/zetacore/rpc/types" ) @@ -57,7 +58,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 +125,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/miner/api.go b/rpc/namespaces/ethereum/miner/api.go index cad1fa3c4e..c1a21f5518 100644 --- a/rpc/namespaces/ethereum/miner/api.go +++ b/rpc/namespaces/ethereum/miner/api.go @@ -20,6 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/server" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/zeta-chain/zetacore/rpc/backend" ) diff --git a/rpc/namespaces/ethereum/personal/api.go b/rpc/namespaces/ethereum/personal/api.go index 0123aed713..71f1aa5271 100644 --- a/rpc/namespaces/ethereum/personal/api.go +++ b/rpc/namespaces/ethereum/personal/api.go @@ -31,6 +31,7 @@ import ( "github.com/evmos/ethermint/crypto/hd" ethermint "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/rpc/backend" ) @@ -106,7 +107,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 +128,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 +146,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/txpool/api.go b/rpc/namespaces/ethereum/txpool/api.go index 5eae3b3f75..521025cf6a 100644 --- a/rpc/namespaces/ethereum/txpool/api.go +++ b/rpc/namespaces/ethereum/txpool/api.go @@ -18,6 +18,7 @@ package txpool import ( "github.com/cometbft/cometbft/libs/log" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/zeta-chain/zetacore/rpc/types" ) diff --git a/rpc/namespaces/ethereum/web3/api.go b/rpc/namespaces/ethereum/web3/api.go index de40837ee1..6d3a8f970b 100644 --- a/rpc/namespaces/ethereum/web3/api.go +++ b/rpc/namespaces/ethereum/web3/api.go @@ -21,6 +21,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/constant" ) @@ -34,7 +35,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..3e9f1b012b 100644 --- a/rpc/types/block.go +++ b/rpc/types/block.go @@ -24,15 +24,12 @@ import ( "math/big" "strings" - "github.com/spf13/cast" - "google.golang.org/grpc/metadata" - + grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - - grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" - ethermint "github.com/evmos/ethermint/types" + "github.com/spf13/cast" + "google.golang.org/grpc/metadata" ) // BlockNumber represents decoding hex string to block values @@ -70,7 +67,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/types/query_client.go b/rpc/types/query_client.go index d8d991352e..cda2962f18 100644 --- a/rpc/types/query_client.go +++ b/rpc/types/query_client.go @@ -18,13 +18,10 @@ package types import ( "fmt" - "github.com/cosmos/cosmos-sdk/types/tx" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/proto/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client" - + "github.com/cosmos/cosmos-sdk/types/tx" evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" ) diff --git a/rpc/types/utils.go b/rpc/types/utils.go index b142e18240..650a0d52ff 100644 --- a/rpc/types/utils.go +++ b/rpc/types/utils.go @@ -21,22 +21,19 @@ import ( "math/big" "strings" + errorsmod "cosmossdk.io/errors" abci "github.com/cometbft/cometbft/abci/types" + tmrpcclient "github.com/cometbft/cometbft/rpc/client" tmtypes "github.com/cometbft/cometbft/types" - - errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" errortypes "github.com/cosmos/cosmos-sdk/types/errors" - - evmtypes "github.com/evmos/ethermint/x/evm/types" - feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" - - tmrpcclient "github.com/cometbft/cometbft/rpc/client" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/params" + evmtypes "github.com/evmos/ethermint/x/evm/types" + feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" ) // ExceedBlockGasLimitError defines the error message when tx execution exceeds the block gas limit. diff --git a/rpc/websockets.go b/rpc/websockets.go index 3cb6af3977..b2470e0203 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -40,6 +40,7 @@ import ( "github.com/gorilla/mux" "github.com/gorilla/websocket" "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/rpc/ethereum/pubsub" rpcfilters "github.com/zeta-chain/zetacore/rpc/namespaces/ethereum/eth/filters" "github.com/zeta-chain/zetacore/rpc/types" @@ -98,7 +99,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 +471,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 +630,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/scripts/fmt-golines.sh b/scripts/fmt-golines.sh new file mode 100644 index 0000000000..a24b264d81 --- /dev/null +++ b/scripts/fmt-golines.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Install golines +go install github.com/segmentio/golines@v0.12.2 + +# Run golines in Cosmos modules and ZetaClient codebase +find . -type f -name '*.go' -exec golines -w --max-len=120 {} + > /dev/null 2>&1 + +# Print a message to indicate completion +echo "Go source code lines formatted." \ No newline at end of file diff --git a/scripts/fmt-imports.sh b/scripts/fmt-imports.sh new file mode 100644 index 0000000000..6e9df43948 --- /dev/null +++ b/scripts/fmt-imports.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Install goimports-revise +go install github.com/incu6us/goimports-reviser/v3@v3.6.4 + +# Run goimports-revise on all Go files +find . -name '*.go' -exec goimports-reviser -project-name github.com/zeta-chain/zetacore -file-path {} \; > /dev/null 2>&1 + +# Print a message to indicate completion +echo "Go imports formatted." \ No newline at end of file diff --git a/scripts/mocks-generate.sh b/scripts/mocks-generate.sh index 15c3482857..5001091ca5 100644 --- a/scripts/mocks-generate.sh +++ b/scripts/mocks-generate.sh @@ -5,7 +5,7 @@ go install github.com/vektra/mockery/v2@v2.38.0 # Run generate command for mocks cd ./testutil/keeper/mocks -go generate "mocks.go" +go generate "mocks.go" > /dev/null 2>&1 # Print a message to indicate completion echo "Mocks generated." \ No newline at end of file diff --git a/server/config/config.go b/server/config/config.go index 212f7c16fd..e62bdfd74a 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -21,13 +21,11 @@ import ( "path" "time" - "github.com/spf13/viper" - - "github.com/cometbft/cometbft/libs/strings" - errorsmod "cosmossdk.io/errors" + "github.com/cometbft/cometbft/libs/strings" "github.com/cosmos/cosmos-sdk/server/config" errortypes "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/spf13/viper" ) const ( 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/indexer_cmd.go b/server/indexer_cmd.go index 2d19489232..65d4d2b9e3 100644 --- a/server/indexer_cmd.go +++ b/server/indexer_cmd.go @@ -18,14 +18,13 @@ package server import ( "fmt" - "github.com/spf13/cobra" - tmnode "github.com/cometbft/cometbft/node" sm "github.com/cometbft/cometbft/state" tmstore "github.com/cometbft/cometbft/store" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/evmos/ethermint/indexer" + "github.com/spf13/cobra" ) func NewIndexTxCmd() *cobra.Command { diff --git a/server/indexer_service.go b/server/indexer_service.go index 2edbc02aa5..d996eac6ba 100644 --- a/server/indexer_service.go +++ b/server/indexer_service.go @@ -22,7 +22,6 @@ import ( "github.com/cometbft/cometbft/libs/service" rpcclient "github.com/cometbft/cometbft/rpc/client" "github.com/cometbft/cometbft/types" - ethermint "github.com/evmos/ethermint/types" ) diff --git a/server/json_rpc.go b/server/json_rpc.go index 4869e2d1fb..9abe6b9ecc 100644 --- a/server/json_rpc.go +++ b/server/json_rpc.go @@ -19,17 +19,16 @@ import ( "net/http" "time" - "github.com/gorilla/mux" - "github.com/rs/cors" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/types" ethlog "github.com/ethereum/go-ethereum/log" ethrpc "github.com/ethereum/go-ethereum/rpc" - "github.com/zeta-chain/zetacore/rpc" - ethermint "github.com/evmos/ethermint/types" + "github.com/gorilla/mux" + "github.com/rs/cors" + + "github.com/zeta-chain/zetacore/rpc" "github.com/zeta-chain/zetacore/server/config" ) diff --git a/server/start.go b/server/start.go index b2c5a46a4a..64bb1db4e6 100644 --- a/server/start.go +++ b/server/start.go @@ -26,15 +26,9 @@ import ( "runtime/pprof" "time" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/telemetry" - - "github.com/spf13/cobra" - - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/tools/rosetta" + crgserver "cosmossdk.io/tools/rosetta/lib/server" dbm "github.com/cometbft/cometbft-db" abciserver "github.com/cometbft/cometbft/abci/server" tcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" @@ -45,25 +39,25 @@ import ( "github.com/cometbft/cometbft/proxy" rpcclient "github.com/cometbft/cometbft/rpc/client" "github.com/cometbft/cometbft/rpc/client/local" - - "cosmossdk.io/tools/rosetta" - crgserver "cosmossdk.io/tools/rosetta/lib/server" - - ethmetricsexp "github.com/ethereum/go-ethereum/metrics/exp" - - errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" + "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - + ethmetricsexp "github.com/ethereum/go-ethereum/metrics/exp" "github.com/evmos/ethermint/indexer" ethermint "github.com/evmos/ethermint/types" + "github.com/spf13/cobra" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + ethdebug "github.com/zeta-chain/zetacore/rpc/namespaces/ethereum/debug" "github.com/zeta-chain/zetacore/server/config" srvflags "github.com/zeta-chain/zetacore/server/flags" @@ -178,48 +172,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 +444,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/server/util.go b/server/util.go index 5b9e5d4e92..94b29cd769 100644 --- a/server/util.go +++ b/server/util.go @@ -20,19 +20,18 @@ import ( "net/http" "time" + tmcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" + tmlog "github.com/cometbft/cometbft/libs/log" + rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + sdkserver "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/version" "github.com/gorilla/mux" "github.com/improbable-eng/grpc-web/go/grpcweb" "github.com/spf13/cobra" - "github.com/zeta-chain/zetacore/server/config" "golang.org/x/net/netutil" - sdkserver "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/version" - - tmcmd "github.com/cometbft/cometbft/cmd/cometbft/commands" - tmlog "github.com/cometbft/cometbft/libs/log" - rpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + "github.com/zeta-chain/zetacore/server/config" ) // AddCommands adds server commands diff --git a/testutil/keeper/authority.go b/testutil/keeper/authority.go index 25ce0f7a67..3e7f98b506 100644 --- a/testutil/keeper/authority.go +++ b/testutil/keeper/authority.go @@ -10,6 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/keeper" "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/testutil/keeper/codec.go b/testutil/keeper/codec.go index 0b39933cb1..90d8ff6e7d 100644 --- a/testutil/keeper/codec.go +++ b/testutil/keeper/codec.go @@ -15,6 +15,7 @@ import ( upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" etherminttypes "github.com/evmos/ethermint/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/testutil/keeper/crosschain.go b/testutil/keeper/crosschain.go index 79a8ab6d96..0ff22a6250 100644 --- a/testutil/keeper/crosschain.go +++ b/testutil/keeper/crosschain.go @@ -13,6 +13,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" crosschainmocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/crosschain" @@ -266,7 +267,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 +282,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 +318,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 +341,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 +361,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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().ReceiverChainId, mock.Anything). Return().Once() @@ -391,7 +437,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/emissions.go b/testutil/keeper/emissions.go index a3a96f4696..594f46aca0 100644 --- a/testutil/keeper/emissions.go +++ b/testutil/keeper/emissions.go @@ -10,6 +10,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/require" + emissionsmocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/emissions" "github.com/zeta-chain/zetacore/x/emissions/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" diff --git a/testutil/keeper/fungible.go b/testutil/keeper/fungible.go index 1da1550925..9c25c80294 100644 --- a/testutil/keeper/fungible.go +++ b/testutil/keeper/fungible.go @@ -13,6 +13,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + fungiblemocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/fungible" "github.com/zeta-chain/zetacore/testutil/sample" fungiblemodule "github.com/zeta-chain/zetacore/x/fungible" @@ -67,7 +68,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/ibccrosschain.go b/testutil/keeper/ibccrosschain.go index ff941d9993..a13ca4fe00 100644 --- a/testutil/keeper/ibccrosschain.go +++ b/testutil/keeper/ibccrosschain.go @@ -10,6 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" "github.com/stretchr/testify/require" + ibccrosschainmocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/ibccrosschain" "github.com/zeta-chain/zetacore/x/ibccrosschain/keeper" "github.com/zeta-chain/zetacore/x/ibccrosschain/types" diff --git a/testutil/keeper/keeper.go b/testutil/keeper/keeper.go index f6f944bbb0..8b3a9d0dfb 100644 --- a/testutil/keeper/keeper.go +++ b/testutil/keeper/keeper.go @@ -47,6 +47,7 @@ import ( feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" authoritymodule "github.com/zeta-chain/zetacore/x/authority" authoritykeeper "github.com/zeta-chain/zetacore/x/authority/keeper" @@ -243,10 +244,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 +466,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..c9d907ec3d 100644 --- a/testutil/keeper/lightclient.go +++ b/testutil/keeper/lightclient.go @@ -9,6 +9,7 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + lightclientmocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/lightclient" "github.com/zeta-chain/zetacore/x/lightclient/keeper" "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -41,7 +42,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..f482fed0bc 100644 --- a/testutil/keeper/observer.go +++ b/testutil/keeper/observer.go @@ -15,6 +15,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + observermocks "github.com/zeta-chain/zetacore/testutil/keeper/mocks/observer" "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" @@ -65,7 +66,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 176ea65acb..18f464ccb7 100644 --- a/testutil/network/genesis_state.go +++ b/testutil/network/genesis_state.go @@ -6,22 +6,28 @@ import ( "strconv" "testing" - "github.com/zeta-chain/zetacore/pkg/chains" - "github.com/zeta-chain/zetacore/pkg/coin" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" + cmdcfg "github.com/zeta-chain/zetacore/cmd/zetacored/config" + "github.com/zeta-chain/zetacore/pkg/chains" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/nullify" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" 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 @@ -198,10 +219,23 @@ func AddCrosschainData(t *testing.T, n int, genesisState map[string]json.RawMess } 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..7fe4855de9 100644 --- a/testutil/network/network_setup.go +++ b/testutil/network/network_setup.go @@ -15,15 +15,10 @@ import ( "testing" "time" - "github.com/cometbft/cometbft/node" - tmclient "github.com/cometbft/cometbft/rpc/client" - "github.com/spf13/cobra" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" - "google.golang.org/grpc" - "cosmossdk.io/math" tmlog "github.com/cometbft/cometbft/libs/log" - + "github.com/cometbft/cometbft/node" + tmclient "github.com/cometbft/cometbft/rpc/client" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" @@ -45,6 +40,10 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/spf13/cobra" + "google.golang.org/grpc" + + "github.com/zeta-chain/zetacore/cmd/zetacored/config" ) // package-wide network lock to only allow one test network at a time @@ -362,7 +361,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..1fd2a8f7cd 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -6,6 +6,7 @@ import ( "path/filepath" "time" + tmos "github.com/cometbft/cometbft/libs/os" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" pvm "github.com/cometbft/cometbft/privval" @@ -13,8 +14,6 @@ import ( "github.com/cometbft/cometbft/rpc/client/local" tmtypes "github.com/cometbft/cometbft/types" tmtime "github.com/cometbft/cometbft/types/time" - - tmos "github.com/cometbft/cometbft/libs/os" "github.com/cosmos/cosmos-sdk/server/api" servergrpc "github.com/cosmos/cosmos-sdk/server/grpc" srvtypes "github.com/cosmos/cosmos-sdk/server/types" @@ -169,7 +168,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 56304f6994..5e9a1f952c 100644 --- a/testutil/sample/crosschain.go +++ b/testutil/sample/crosschain.go @@ -9,11 +9,11 @@ import ( "testing" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -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/crypto.go b/testutil/sample/crypto.go index 2f755df019..153f1a2a80 100644 --- a/testutil/sample/crypto.go +++ b/testutil/sample/crypto.go @@ -15,6 +15,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" ethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/cosmos" "github.com/zeta-chain/zetacore/pkg/crypto" ) diff --git a/testutil/sample/emissions.go b/testutil/sample/emissions.go index 491f16e501..c5501e4cfc 100644 --- a/testutil/sample/emissions.go +++ b/testutil/sample/emissions.go @@ -4,6 +4,7 @@ import ( "testing" "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/testutil/sample/lightclient.go b/testutil/sample/lightclient.go index ca24e92bbf..34271f2a42 100644 --- a/testutil/sample/lightclient.go +++ b/testutil/sample/lightclient.go @@ -7,6 +7,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" "github.com/zeta-chain/zetacore/pkg/proofs/ethereum" diff --git a/testutil/sample/observer.go b/testutil/sample/observer.go index b1223953f1..4e3096fc8b 100644 --- a/testutil/sample/observer.go +++ b/testutil/sample/observer.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/cosmos" zetacrypto "github.com/zeta-chain/zetacore/pkg/crypto" diff --git a/testutil/sample/sample.go b/testutil/sample/sample.go index d935352149..411c6dd7c9 100644 --- a/testutil/sample/sample.go +++ b/testutil/sample/sample.go @@ -8,18 +8,17 @@ import ( "strconv" "testing" - "github.com/zeta-chain/zetacore/pkg/chains" - sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/types" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - ethcrypto "github.com/ethereum/go-ethereum/crypto" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + ethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + + "github.com/zeta-chain/zetacore/cmd/zetacored/config" + "github.com/zeta-chain/zetacore/pkg/chains" ) var ErrSample = errors.New("sample error") @@ -111,7 +110,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.MsgVoteInbound\"\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.MsgVoteOutbound\"\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.MsgAddOutboundTracker\"\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.MsgVoteInbound\"\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.MsgVoteOutbound\"\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.MsgAddOutboundTracker\"\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 \"outboundTrackerList\": [],\n \"inboundHashToCctxList\": [],\n \"inbound_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.MsgVoteInbound\"\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.MsgVoteOutbound\"\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.MsgAddOutboundTracker\"\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.MsgVoteInbound\"\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.MsgVoteOutbound\"\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.MsgAddOutboundTracker\"\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 \"outboundTrackerList\": [],\n \"inboundHashToCctxList\": [],\n \"inbound_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..4bd0f3610b 100644 --- a/testutil/simapp/simapp.go +++ b/testutil/simapp/simapp.go @@ -5,25 +5,23 @@ import ( "testing" "time" + tmdb "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtypes "github.com/cometbft/cometbft/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" - types2 "github.com/zeta-chain/zetacore/x/emissions/types" - //"github.com/ignite-hq/cli/ignite/pkg/cosmoscmd" - tmdb "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" "github.com/zeta-chain/zetacore/app" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" + types2 "github.com/zeta-chain/zetacore/x/emissions/types" ) func Setup(isCheckTx bool) *app.App { @@ -52,14 +50,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 +104,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 +143,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 +189,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/client/cli/query.go b/x/authority/client/cli/query.go index 63ae30e227..02b056fa9e 100644 --- a/x/authority/client/cli/query.go +++ b/x/authority/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/client/cli/query_policies.go b/x/authority/client/cli/query_policies.go index 723dfcf71b..f1cf8a4811 100644 --- a/x/authority/client/cli/query_policies.go +++ b/x/authority/client/cli/query_policies.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/client/cli/tx.go b/x/authority/client/cli/tx.go index ae3d7efa6b..bd36f4d246 100644 --- a/x/authority/client/cli/tx.go +++ b/x/authority/client/cli/tx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/client/cli/tx_update_policies.go b/x/authority/client/cli/tx_update_policies.go index 0e0c822aa7..f1a4fac042 100644 --- a/x/authority/client/cli/tx_update_policies.go +++ b/x/authority/client/cli/tx_update_policies.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/genesis.go b/x/authority/genesis.go index b82983fab9..1391b5954d 100644 --- a/x/authority/genesis.go +++ b/x/authority/genesis.go @@ -2,6 +2,7 @@ package authority import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/authority/keeper" "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/genesis_test.go b/x/authority/genesis_test.go index bb6e0f7353..ac9c8d2e43 100644 --- a/x/authority/genesis_test.go +++ b/x/authority/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/authority/keeper/grpc_query_policies.go b/x/authority/keeper/grpc_query_policies.go index e799ce97ec..fcabed9bb7 100644 --- a/x/authority/keeper/grpc_query_policies.go +++ b/x/authority/keeper/grpc_query_policies.go @@ -4,13 +4,17 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/authority/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/authority/types" ) // 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/grpc_query_policies_test.go b/x/authority/keeper/grpc_query_policies_test.go index 40dc6a6124..fd8009f097 100644 --- a/x/authority/keeper/grpc_query_policies_test.go +++ b/x/authority/keeper/grpc_query_policies_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/authority/keeper/keeper.go b/x/authority/keeper/keeper.go index 003d91bee7..d75fd98960 100644 --- a/x/authority/keeper/keeper.go +++ b/x/authority/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/keeper/msg_server_update_policies.go b/x/authority/keeper/msg_server_update_policies.go index e228c8cdce..fb31a2cad5 100644 --- a/x/authority/keeper/msg_server_update_policies.go +++ b/x/authority/keeper/msg_server_update_policies.go @@ -6,11 +6,15 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/zeta-chain/zetacore/x/authority/types" ) // 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/keeper/msg_server_update_policies_test.go b/x/authority/keeper/msg_server_update_policies_test.go index 5a9a124a2a..a629ac1f33 100644 --- a/x/authority/keeper/msg_server_update_policies_test.go +++ b/x/authority/keeper/msg_server_update_policies_test.go @@ -3,10 +3,10 @@ package keeper_test import ( "testing" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/keeper" diff --git a/x/authority/keeper/policies.go b/x/authority/keeper/policies.go index 93f0086e7a..448f922749 100644 --- a/x/authority/keeper/policies.go +++ b/x/authority/keeper/policies.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/keeper/policies_test.go b/x/authority/keeper/policies_test.go index 13c0c4d80b..5e2347bd05 100644 --- a/x/authority/keeper/policies_test.go +++ b/x/authority/keeper/policies_test.go @@ -3,11 +3,11 @@ package keeper_test import ( "testing" - "github.com/zeta-chain/zetacore/x/authority/types" - "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" + "github.com/zeta-chain/zetacore/x/authority/types" ) func TestKeeper_SetPolicies(t *testing.T) { diff --git a/x/authority/module.go b/x/authority/module.go index b4c5b68e18..f92da86e37 100644 --- a/x/authority/module.go +++ b/x/authority/module.go @@ -14,6 +14,7 @@ import ( "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/authority/client/cli" "github.com/zeta-chain/zetacore/x/authority/keeper" "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/authority/types/genesis_test.go b/x/authority/types/genesis_test.go index 7b835c3ea4..46f4ad9bcb 100644 --- a/x/authority/types/genesis_test.go +++ b/x/authority/types/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/authority/types/message_update_policies_test.go b/x/authority/types/message_update_policies_test.go index def81cfad6..69c778c4dc 100644 --- a/x/authority/types/message_update_policies_test.go +++ b/x/authority/types/message_update_policies_test.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" - "github.com/zeta-chain/zetacore/testutil/sample" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/types" ) 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/authority/types/policies_test.go b/x/authority/types/policies_test.go index 8db173eb86..7f8d2ff52c 100644 --- a/x/authority/types/policies_test.go +++ b/x/authority/types/policies_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/crosschain/client/cli/cli_gas_price.go b/x/crosschain/client/cli/cli_gas_price.go index 9de219aefb..a588dced87 100644 --- a/x/crosschain/client/cli/cli_gas_price.go +++ b/x/crosschain/client/cli/cli_gas_price.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -99,7 +100,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/client/cli/cli_last_block_height.go b/x/crosschain/client/cli/cli_last_block_height.go index 3f1dfb54a9..e30722dee7 100644 --- a/x/crosschain/client/cli/cli_last_block_height.go +++ b/x/crosschain/client/cli/cli_last_block_height.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/cli_refund_aborted.go b/x/crosschain/client/cli/cli_refund_aborted.go index 12930dcbf0..46792b454f 100644 --- a/x/crosschain/client/cli/cli_refund_aborted.go +++ b/x/crosschain/client/cli/cli_refund_aborted.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/cli_tss.go b/x/crosschain/client/cli/cli_tss.go index 9b9d551ca8..c24733431f 100644 --- a/x/crosschain/client/cli/cli_tss.go +++ b/x/crosschain/client/cli/cli_tss.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cast" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/cli_whitelist_erc20.go b/x/crosschain/client/cli/cli_whitelist_erc20.go index 2f3af566d5..6941ece36d 100644 --- a/x/crosschain/client/cli/cli_whitelist_erc20.go +++ b/x/crosschain/client/cli/cli_whitelist_erc20.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/cli_zeta_height.go b/x/crosschain/client/cli/cli_zeta_height.go index 4287d561c0..a2b0f1ea51 100644 --- a/x/crosschain/client/cli/cli_zeta_height.go +++ b/x/crosschain/client/cli/cli_zeta_height.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query.go b/x/crosschain/client/cli/query.go index 37bbcb6407..63669896cf 100644 --- a/x/crosschain/client/cli/query.go +++ b/x/crosschain/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_cctx.go b/x/crosschain/client/cli/query_cctx.go index bb897c43d0..064d660830 100644 --- a/x/crosschain/client/cli/query_cctx.go +++ b/x/crosschain/client/cli/query_cctx.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_cctx_rate_limit.go b/x/crosschain/client/cli/query_cctx_rate_limit.go index 251a3897de..0abc092436 100644 --- a/x/crosschain/client/cli/query_cctx_rate_limit.go +++ b/x/crosschain/client/cli/query_cctx_rate_limit.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_inbound_hash_to_cctx.go b/x/crosschain/client/cli/query_inbound_hash_to_cctx.go index 22c1ae441c..2752f27836 100644 --- a/x/crosschain/client/cli/query_inbound_hash_to_cctx.go +++ b/x/crosschain/client/cli/query_inbound_hash_to_cctx.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_inbound_tracker.go b/x/crosschain/client/cli/query_inbound_tracker.go index c16138d2cd..e467386176 100644 --- a/x/crosschain/client/cli/query_inbound_tracker.go +++ b/x/crosschain/client/cli/query_inbound_tracker.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_outbound_tracker.go b/x/crosschain/client/cli/query_outbound_tracker.go index 3dd93d4989..8409786568 100644 --- a/x/crosschain/client/cli/query_outbound_tracker.go +++ b/x/crosschain/client/cli/query_outbound_tracker.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_rate_limiter_flags.go b/x/crosschain/client/cli/query_rate_limiter_flags.go index acb2cf4f91..ad4177295e 100644 --- a/x/crosschain/client/cli/query_rate_limiter_flags.go +++ b/x/crosschain/client/cli/query_rate_limiter_flags.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/query_zeta_accounting.go b/x/crosschain/client/cli/query_zeta_accounting.go index 29f35cdc4b..f823599190 100644 --- a/x/crosschain/client/cli/query_zeta_accounting.go +++ b/x/crosschain/client/cli/query_zeta_accounting.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx.go b/x/crosschain/client/cli/tx.go index 0a398e33ca..7ba75ff143 100644 --- a/x/crosschain/client/cli/tx.go +++ b/x/crosschain/client/cli/tx.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" - // "github.com/cosmos/cosmos-sdk/client/flags" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx_add_inbound_tracker.go b/x/crosschain/client/cli/tx_add_inbound_tracker.go index 13d9d32cc4..bcbe144592 100644 --- a/x/crosschain/client/cli/tx_add_inbound_tracker.go +++ b/x/crosschain/client/cli/tx_add_inbound_tracker.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx_add_outbound_tracker.go b/x/crosschain/client/cli/tx_add_outbound_tracker.go index f72bb1cb94..fe6075e6b2 100644 --- a/x/crosschain/client/cli/tx_add_outbound_tracker.go +++ b/x/crosschain/client/cli/tx_add_outbound_tracker.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx_remove_outbound_tracker.go b/x/crosschain/client/cli/tx_remove_outbound_tracker.go index c3a96761f7..25737fedef 100644 --- a/x/crosschain/client/cli/tx_remove_outbound_tracker.go +++ b/x/crosschain/client/cli/tx_remove_outbound_tracker.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx_vote_inbound.go b/x/crosschain/client/cli/tx_vote_inbound.go index d2b7ad9f92..3581b01e0c 100644 --- a/x/crosschain/client/cli/tx_vote_inbound.go +++ b/x/crosschain/client/cli/tx_vote_inbound.go @@ -5,11 +5,11 @@ import ( "strconv" "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/cli/tx_vote_outbound.go b/x/crosschain/client/cli/tx_vote_outbound.go index 21647bb54d..eec17f6020 100644 --- a/x/crosschain/client/cli/tx_vote_outbound.go +++ b/x/crosschain/client/cli/tx_vote_outbound.go @@ -6,11 +6,11 @@ import ( "strconv" "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/client/cli/tx_vote_stuck_cctx.go b/x/crosschain/client/cli/tx_vote_stuck_cctx.go index ad8735a90d..4ecd579395 100644 --- a/x/crosschain/client/cli/tx_vote_stuck_cctx.go +++ b/x/crosschain/client/cli/tx_vote_stuck_cctx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/client/querytests/cctx.go b/x/crosschain/client/querytests/cctx.go index 169d2ca10e..c9c9b37bac 100644 --- a/x/crosschain/client/querytests/cctx.go +++ b/x/crosschain/client/querytests/cctx.go @@ -6,10 +6,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/zeta-chain/zetacore/x/crosschain/client/cli" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/client/cli" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) func (s *CliTestSuite) TestListCCTX() { diff --git a/x/crosschain/client/querytests/cli_test.go b/x/crosschain/client/querytests/cli_test.go index ca7a115d8b..777fc81528 100644 --- a/x/crosschain/client/querytests/cli_test.go +++ b/x/crosschain/client/querytests/cli_test.go @@ -3,14 +3,14 @@ package querytests import ( "testing" + tmdb "github.com/cometbft/cometbft-db" "github.com/cosmos/cosmos-sdk/baseapp" servertypes "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/types/module/testutil" - - tmdb "github.com/cometbft/cometbft-db" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/testutil/network" ) diff --git a/x/crosschain/client/querytests/gas_price.go b/x/crosschain/client/querytests/gas_price.go index 3705e43c0a..de12a9d34b 100644 --- a/x/crosschain/client/querytests/gas_price.go +++ b/x/crosschain/client/querytests/gas_price.go @@ -6,10 +6,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/zeta-chain/zetacore/x/crosschain/client/cli" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/client/cli" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) func (s *CliTestSuite) TestShowGasPrice() { diff --git a/x/crosschain/client/querytests/inbound_hash.go b/x/crosschain/client/querytests/inbound_hash.go index 80af02814f..5c88f99141 100644 --- a/x/crosschain/client/querytests/inbound_hash.go +++ b/x/crosschain/client/querytests/inbound_hash.go @@ -2,18 +2,17 @@ package querytests import ( "fmt" + "strconv" + tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" - "strconv" - - tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/crosschain/client/cli" "github.com/zeta-chain/zetacore/x/crosschain/types" - "google.golang.org/grpc/status" ) func (s *CliTestSuite) TestShowInboundHashToCctx() { diff --git a/x/crosschain/client/querytests/inbound_tracker.go b/x/crosschain/client/querytests/inbound_tracker.go index 4bcc3954f0..d3c1b1a0de 100644 --- a/x/crosschain/client/querytests/inbound_tracker.go +++ b/x/crosschain/client/querytests/inbound_tracker.go @@ -6,6 +6,7 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/crosschain/client/cli" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/client/querytests/last_block_height.go b/x/crosschain/client/querytests/last_block_height.go index 518befe450..82ba19ff1f 100644 --- a/x/crosschain/client/querytests/last_block_height.go +++ b/x/crosschain/client/querytests/last_block_height.go @@ -6,10 +6,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/zeta-chain/zetacore/x/crosschain/client/cli" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/client/cli" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) func (s *CliTestSuite) TestShowLastBlockHeight() { diff --git a/x/crosschain/client/querytests/outbound_tracker.go b/x/crosschain/client/querytests/outbound_tracker.go index e23a42772a..0be4b74178 100644 --- a/x/crosschain/client/querytests/outbound_tracker.go +++ b/x/crosschain/client/querytests/outbound_tracker.go @@ -6,6 +6,7 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/crosschain/client/cli" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/client/querytests/suite.go b/x/crosschain/client/querytests/suite.go index 7fcc87f65e..ca42b9b4ec 100644 --- a/x/crosschain/client/querytests/suite.go +++ b/x/crosschain/client/querytests/suite.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcfg "github.com/evmos/ethermint/cmd/config" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/app" cmdcfg "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/testutil/network" diff --git a/x/crosschain/genesis.go b/x/crosschain/genesis.go index ee1acd8cbd..6a1fe1ed58 100644 --- a/x/crosschain/genesis.go +++ b/x/crosschain/genesis.go @@ -2,6 +2,7 @@ package crosschain import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/genesis_test.go b/x/crosschain/genesis_test.go index ffcccd3cf2..4a3cc7083f 100644 --- a/x/crosschain/genesis_test.go +++ b/x/crosschain/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/keeper/abci.go b/x/crosschain/keeper/abci.go index 850382dcd9..4897ae6f66 100644 --- a/x/crosschain/keeper/abci.go +++ b/x/crosschain/keeper/abci.go @@ -4,11 +4,11 @@ import ( "fmt" "time" - zetachains "github.com/zeta-chain/zetacore/pkg/chains" - cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + + zetachains "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/crosschain/keeper/abci_test.go b/x/crosschain/keeper/abci_test.go index 262fd2e7a9..d44e5d1ef1 100644 --- a/x/crosschain/keeper/abci_test.go +++ b/x/crosschain/keeper/abci_test.go @@ -6,9 +6,9 @@ import ( "time" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -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.GetCurrentOutboundParam().GetGasPriceUInt64() 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 323b441279..8c660fb99b 100644 --- a/x/crosschain/keeper/cctx.go +++ b/x/crosschain/keeper/cctx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -21,7 +22,8 @@ func (k Keeper) SetCctxAndNonceToCctxAndInboundHashToCctx(ctx sdk.Context, cctx 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.GetCurrentOutboundParam().ReceiverChainId, // #nosec G701 always in range diff --git a/x/crosschain/keeper/cctx_test.go b/x/crosschain/keeper/cctx_test.go index c231d2dace..647016849e 100644 --- a/x/crosschain/keeper/cctx_test.go +++ b/x/crosschain/keeper/cctx_test.go @@ -6,20 +6,25 @@ import ( "testing" "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/keeper" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" "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" @@ -118,11 +123,19 @@ func TestCCTXs(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 fe9fcf9612..f85b243c1c 100644 --- a/x/crosschain/keeper/cctx_utils.go +++ b/x/crosschain/keeper/cctx_utils.go @@ -6,10 +6,10 @@ import ( cosmoserrors "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" - "github.com/pkg/errors" - sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" @@ -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.GetCurrentOutboundParam().TssNonce = 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 ff79e8bbc3..d466c1f1c3 100644 --- a/x/crosschain/keeper/cctx_utils_test.go +++ b/x/crosschain/keeper/cctx_utils_test.go @@ -8,6 +8,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -216,7 +217,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 +303,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{ InboundParams: &types.InboundParams{ @@ -326,9 +332,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{ InboundParams: &types.InboundParams{ @@ -356,9 +363,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/events.go b/x/crosschain/keeper/events.go index 3419adb619..1bff85d750 100644 --- a/x/crosschain/keeper/events.go +++ b/x/crosschain/keeper/events.go @@ -3,9 +3,9 @@ package keeper import ( "strconv" - "github.com/zeta-chain/zetacore/pkg/chains" - sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/evm_deposit.go b/x/crosschain/keeper/evm_deposit.go index 7b452d5368..927e9f5eb1 100644 --- a/x/crosschain/keeper/evm_deposit.go +++ b/x/crosschain/keeper/evm_deposit.go @@ -11,6 +11,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/pkg/errors" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -51,7 +52,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 9dd8aec19a..7541c21aa6 100644 --- a/x/crosschain/keeper/evm_deposit_test.go +++ b/x/crosschain/keeper/evm_deposit_test.go @@ -11,6 +11,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -31,7 +32,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 +64,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.InboundParams.Sender = sender.String() cctx.GetCurrentOutboundParam().Receiver = receiver.String() @@ -122,125 +126,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.InboundParams.TxOrigin = "" - cctx.GetCurrentOutboundParam().Receiver = receiver.String() - cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundParams().Sender = sample.EthAddress().String() - cctx.GetInboundParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundParams().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.InboundParams.TxOrigin = "" + cctx.GetCurrentOutboundParam().Receiver = receiver.String() + cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundParams().Sender = sample.EthAddress().String() + cctx.GetInboundParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundParams().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.InboundParams.TxOrigin = "" - cctx.GetCurrentOutboundParam().Receiver = receiver.String() - cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundParams().Sender = sample.EthAddress().String() - cctx.GetInboundParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundParams().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.InboundParams.TxOrigin = "" + cctx.GetCurrentOutboundParam().Receiver = receiver.String() + cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundParams().Sender = sample.EthAddress().String() + cctx.GetInboundParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundParams().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 +452,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.GetCurrentOutboundParam().Receiver = receiver.String() - cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) - cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 - cctx.GetInboundParams().Sender = sample.EthAddress().String() - cctx.GetInboundParams().SenderChainId = senderChain - cctx.RelayedMessage = "" - cctx.GetInboundParams().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.GetCurrentOutboundParam().Receiver = receiver.String() + cctx.GetInboundParams().Amount = math.NewUintFromBigInt(amount) + cctx.GetInboundParams().CoinType = coin.CoinType_ERC20 + cctx.GetInboundParams().Sender = sample.EthAddress().String() + cctx.GetInboundParams().SenderChainId = senderChain + cctx.RelayedMessage = "" + cctx.GetInboundParams().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 4f1e7586b8..863bdd991b 100644 --- a/x/crosschain/keeper/evm_hooks.go +++ b/x/crosschain/keeper/evm_hooks.go @@ -16,6 +16,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" connectorzevm "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zetaconnectorzevm.sol" zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" @@ -61,7 +62,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 +85,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 +107,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 +135,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 +150,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 +206,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 +344,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 +361,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 75deb96f88..39ee88e63e 100644 --- a/x/crosschain/keeper/evm_hooks_test.go +++ b/x/crosschain/keeper/evm_hooks_test.go @@ -12,6 +12,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -25,7 +26,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 +70,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 +156,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 +175,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 +358,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 +475,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 +495,14 @@ 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].GetCurrentOutboundParam().Receiver), 0) + require.Equal( + t, + strings.Compare( + "0x60983881bdf302dcfa96603a58274d15d5966209", + cctxList[0].GetCurrentOutboundParam().Receiver, + ), + 0, + ) require.Equal(t, chains.EthChain.ChainId, cctxList[0].GetCurrentOutboundParam().ReceiverChainId) require.Equal(t, emittingContract.Hex(), cctxList[0].InboundParams.Sender) require.Equal(t, txOrigin.Hex(), cctxList[0].InboundParams.TxOrigin) @@ -480,7 +519,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 +543,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 +575,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 +606,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 +644,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 +704,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 +723,14 @@ 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].GetCurrentOutboundParam().Receiver), 0) + require.Equal( + t, + strings.Compare( + "0x60983881bdf302dcfa96603a58274d15d5966209", + cctxList[0].GetCurrentOutboundParam().Receiver, + ), + 0, + ) require.Equal(t, chains.EthChain.ChainId, cctxList[0].GetCurrentOutboundParam().ReceiverChainId) require.Equal(t, emittingContract.Hex(), cctxList[0].InboundParams.Sender) require.Equal(t, txOrigin.Hex(), cctxList[0].InboundParams.TxOrigin) @@ -687,25 +768,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.go b/x/crosschain/keeper/finalized_inbounds.go index 888d21dca3..dd2b2ab82a 100644 --- a/x/crosschain/keeper/finalized_inbounds.go +++ b/x/crosschain/keeper/finalized_inbounds.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/finalized_inbounds_test.go b/x/crosschain/keeper/finalized_inbounds_test.go index fe2ea6e4dc..8cc28c5aca 100644 --- a/x/crosschain/keeper/finalized_inbounds_test.go +++ b/x/crosschain/keeper/finalized_inbounds_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -77,6 +78,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/foreign_coins.go b/x/crosschain/keeper/foreign_coins.go index 15ecd54260..8920cb48b6 100644 --- a/x/crosschain/keeper/foreign_coins.go +++ b/x/crosschain/keeper/foreign_coins.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + fungibleModuleTypes "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/crosschain/keeper/foreign_coins_test.go b/x/crosschain/keeper/foreign_coins_test.go index aaa359cd72..4c19ac9f2b 100644 --- a/x/crosschain/keeper/foreign_coins_test.go +++ b/x/crosschain/keeper/foreign_coins_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/crosschain/keeper/gas_payment.go b/x/crosschain/keeper/gas_payment.go index 52963b887d..58bfe4ffbf 100644 --- a/x/crosschain/keeper/gas_payment.go +++ b/x/crosschain/keeper/gas_payment.go @@ -7,9 +7,9 @@ import ( cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -91,7 +91,11 @@ func (k Keeper) PayGasNativeAndUpdateCctx( ) error { // preliminary checks if cctx.InboundParams.CoinType != coin.CoinType_Gas { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in native gas with %s", cctx.InboundParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in native gas with %s", + cctx.InboundParams.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.InboundParams.CoinType != coin.CoinType_ERC20 { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in erc20 with %s", cctx.InboundParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in erc20 with %s", + cctx.InboundParams.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.InboundParams.Asset, chainID) if !found { - return cosmoserrors.Wrapf(types.ErrForeignCoinNotFound, "zrc20 from asset %s not found", cctx.InboundParams.Asset) + return cosmoserrors.Wrapf( + types.ErrForeignCoinNotFound, + "zrc20 from asset %s not found", + cctx.InboundParams.Asset, + ) } zrc20 := ethcommon.HexToAddress(fc.Zrc20ContractAddress) if zrc20 == (ethcommon.Address{}) { - return cosmoserrors.Wrapf(types.ErrForeignCoinNotFound, "zrc20 from asset %s invalid address", cctx.InboundParams.Asset) + return cosmoserrors.Wrapf( + types.ErrForeignCoinNotFound, + "zrc20 from asset %s invalid address", + cctx.InboundParams.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.InboundParams.CoinType != coin.CoinType_Zeta { - return cosmoserrors.Wrapf(types.ErrInvalidCoinType, "can't pay gas in zeta with %s", cctx.InboundParams.CoinType.String()) + return cosmoserrors.Wrapf( + types.ErrInvalidCoinType, + "can't pay gas in zeta with %s", + cctx.InboundParams.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 abebb1ba22..23d1888669 100644 --- a/x/crosschain/keeper/gas_payment_test.go +++ b/x/crosschain/keeper/gas_payment_test.go @@ -4,17 +4,16 @@ import ( "math/big" "testing" - "github.com/zeta-chain/zetacore/pkg/chains" - "github.com/zeta-chain/zetacore/pkg/coin" - "github.com/zeta-chain/zetacore/testutil/sample" - observertypes "github.com/zeta-chain/zetacore/x/observer/types" - "cosmossdk.io/math" - "github.com/stretchr/testify/require" + + "github.com/zeta-chain/zetacore/pkg/chains" + "github.com/zeta-chain/zetacore/pkg/coin" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) var ( @@ -442,7 +441,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 +482,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { ZetaFees: math.NewUint(100), } // gasLimit * gasPrice * 2 = 1000 * 2 * 2 = 4000 - expectedOutboundGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutboundGasFeeInZeta, 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 +496,13 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { require.NoError(t, err) require.Equal(t, "100000", cctx.GetCurrentOutboundParam().Amount.String()) require.Equal(t, "4", cctx.GetCurrentOutboundParam().GasPrice) // 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 +516,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { }, }, } - expectedOutboundGasFeeInZeta, err = zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutboundGasFeeInZeta, err = zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn( + ctx, + big.NewInt(4000), + zrc20, + ) require.NoError(t, err) expectedFeeInZeta = types.GetProtocolFee().Add(math.NewUintFromBigInt(expectedOutboundGasFeeInZeta)) inputAmount = expectedFeeInZeta.Add(math.NewUint(100000)) @@ -509,7 +528,13 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { require.NoError(t, err) require.Equal(t, "100000", cctx.GetCurrentOutboundParam().Amount.String()) require.Equal(t, "4", cctx.GetCurrentOutboundParam().GasPrice) // 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 +621,11 @@ func TestKeeper_PayGasInZetaAndUpdateCctx(t *testing.T) { }, ZetaFees: math.NewUint(100), } - expectedOutboundGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn(ctx, big.NewInt(4000), zrc20) + expectedOutboundGasFeeInZeta, err := zk.FungibleKeeper.QueryUniswapV2RouterGetZetaAmountsIn( + ctx, + big.NewInt(4000), + zrc20, + ) require.NoError(t, err) expectedFeeInZeta := types.GetProtocolFee().Add(math.NewUintFromBigInt(expectedOutboundGasFeeInZeta)) diff --git a/x/crosschain/keeper/gas_price.go b/x/crosschain/keeper/gas_price.go index 1d4159e4b9..84143cdc48 100644 --- a/x/crosschain/keeper/gas_price.go +++ b/x/crosschain/keeper/gas_price.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/gas_price_test.go b/x/crosschain/keeper/gas_price_test.go index bdd867081e..928f73b9f8 100644 --- a/x/crosschain/keeper/gas_price_test.go +++ b/x/crosschain/keeper/gas_price_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/keeper/grpc_query_cctx.go b/x/crosschain/keeper/grpc_query_cctx.go index 4014baf8f6..edfeaabc3d 100644 --- a/x/crosschain/keeper/grpc_query_cctx.go +++ b/x/crosschain/keeper/grpc_query_cctx.go @@ -7,10 +7,11 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/crosschain/types" - observertypes "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) const ( @@ -21,7 +22,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 +76,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 +99,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 +174,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 f6fb082eb4..e28f3e3677 100644 --- a/x/crosschain/keeper/grpc_query_cctx_rate_limit.go +++ b/x/crosschain/keeper/grpc_query_cctx_rate_limit.go @@ -6,14 +6,18 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/crosschain/types" - observertypes "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) // 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 +134,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 +177,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 +212,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 +326,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 +367,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 db16c45f49..07f2db200b 100644 --- a/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go +++ b/x/crosschain/keeper/grpc_query_cctx_rate_limit_test.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -102,13 +103,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 +176,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 +207,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 +251,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 +295,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 +339,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 @@ -391,13 +478,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 { @@ -452,9 +575,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{ @@ -477,8 +609,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{ @@ -504,8 +645,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{ @@ -531,8 +681,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{ @@ -552,15 +711,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{ @@ -577,17 +747,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{ @@ -607,7 +788,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 @@ -619,7 +802,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{ @@ -639,7 +831,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 @@ -678,7 +872,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_cctx_test.go b/x/crosschain/keeper/grpc_query_cctx_test.go index 90b397691c..77e9bbc175 100644 --- a/x/crosschain/keeper/grpc_query_cctx_test.go +++ b/x/crosschain/keeper/grpc_query_cctx_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/keeper" diff --git a/x/crosschain/keeper/grpc_query_gas_price.go b/x/crosschain/keeper/grpc_query_gas_price.go index 311bdc1d6b..56b95cff0c 100644 --- a/x/crosschain/keeper/grpc_query_gas_price.go +++ b/x/crosschain/keeper/grpc_query_gas_price.go @@ -7,12 +7,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -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 +44,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_gas_price_test.go b/x/crosschain/keeper/grpc_query_gas_price_test.go index bba8f9ae74..ac28dd7b95 100644 --- a/x/crosschain/keeper/grpc_query_gas_price_test.go +++ b/x/crosschain/keeper/grpc_query_gas_price_test.go @@ -7,10 +7,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" - keepertest "github.com/zeta-chain/zetacore/testutil/keeper" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) func TestGasPriceQuerySingle(t *testing.T) { diff --git a/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx.go b/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx.go index 8fa8fae114..fe11c1668b 100644 --- a/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx.go +++ b/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx.go @@ -6,12 +6,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -func (k Keeper) InboundHashToCctxAll(c context.Context, req *types.QueryAllInboundHashToCctxRequest) (*types.QueryAllInboundHashToCctxResponse, error) { +func (k Keeper) InboundHashToCctxAll( + c context.Context, + req *types.QueryAllInboundHashToCctxRequest, +) (*types.QueryAllInboundHashToCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -39,7 +43,10 @@ func (k Keeper) InboundHashToCctxAll(c context.Context, req *types.QueryAllInbou return &types.QueryAllInboundHashToCctxResponse{InboundHashToCctx: inTxHashToCctxs, Pagination: pageRes}, nil } -func (k Keeper) InboundHashToCctx(c context.Context, req *types.QueryGetInboundHashToCctxRequest) (*types.QueryGetInboundHashToCctxResponse, error) { +func (k Keeper) InboundHashToCctx( + c context.Context, + req *types.QueryGetInboundHashToCctxRequest, +) (*types.QueryGetInboundHashToCctxResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -61,7 +68,10 @@ func (k Keeper) InboundHashToCctxData( c context.Context, req *types.QueryInboundHashToCctxDataRequest, ) (*types.QueryInboundHashToCctxDataResponse, error) { - inTxHashToCctxRes, err := k.InboundHashToCctx(c, &types.QueryGetInboundHashToCctxRequest{InboundHash: req.InboundHash}) + inTxHashToCctxRes, err := k.InboundHashToCctx( + c, + &types.QueryGetInboundHashToCctxRequest{InboundHash: req.InboundHash}, + ) if err != nil { return nil, err } diff --git a/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx_test.go b/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx_test.go index 47ae437ed0..f1b2862520 100644 --- a/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx_test.go +++ b/x/crosschain/keeper/grpc_query_inbound_hash_to_cctx_test.go @@ -6,8 +6,6 @@ import ( "testing" "cosmossdk.io/math" - "github.com/zeta-chain/zetacore/testutil/sample" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" @@ -16,6 +14,7 @@ import ( keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" + "github.com/zeta-chain/zetacore/testutil/sample" crosschainkeeper "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/grpc_query_inbound_tracker.go b/x/crosschain/keeper/grpc_query_inbound_tracker.go index 431d1240bb..a076ffb677 100644 --- a/x/crosschain/keeper/grpc_query_inbound_tracker.go +++ b/x/crosschain/keeper/grpc_query_inbound_tracker.go @@ -4,13 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -func (k Keeper) InboundTrackerAllByChain(goCtx context.Context, request *types.QueryAllInboundTrackerByChainRequest) (*types.QueryAllInboundTrackerByChainResponse, error) { +func (k Keeper) InboundTrackerAllByChain( + goCtx context.Context, + request *types.QueryAllInboundTrackerByChainRequest, +) (*types.QueryAllInboundTrackerByChainResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) var inTxTrackers []types.InboundTracker inTxTrackers, pageRes, err := k.GetAllInboundTrackerForChainPaginated(ctx, request.ChainId, request.Pagination) @@ -20,7 +23,10 @@ func (k Keeper) InboundTrackerAllByChain(goCtx context.Context, request *types.Q return &types.QueryAllInboundTrackerByChainResponse{InboundTracker: inTxTrackers, Pagination: pageRes}, nil } -func (k Keeper) InboundTrackerAll(goCtx context.Context, req *types.QueryAllInboundTrackersRequest) (*types.QueryAllInboundTrackersResponse, error) { +func (k Keeper) InboundTrackerAll( + goCtx context.Context, + req *types.QueryAllInboundTrackersRequest, +) (*types.QueryAllInboundTrackersResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) var inTxTrackers []types.InboundTracker inTxTrackers, pageRes, err := k.GetAllInboundTrackerPaginated(ctx, req.Pagination) diff --git a/x/crosschain/keeper/grpc_query_inbound_tracker_test.go b/x/crosschain/keeper/grpc_query_inbound_tracker_test.go index b8c62ce703..3c17284faa 100644 --- a/x/crosschain/keeper/grpc_query_inbound_tracker_test.go +++ b/x/crosschain/keeper/grpc_query_inbound_tracker_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/keeper/grpc_query_last_block_height.go b/x/crosschain/keeper/grpc_query_last_block_height.go index 8fd59f7990..c5e691bf9c 100644 --- a/x/crosschain/keeper/grpc_query_last_block_height.go +++ b/x/crosschain/keeper/grpc_query_last_block_height.go @@ -7,12 +7,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -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 +44,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_block_height_test.go b/x/crosschain/keeper/grpc_query_last_block_height_test.go index 9ad97909e4..b06be8f975 100644 --- a/x/crosschain/keeper/grpc_query_last_block_height_test.go +++ b/x/crosschain/keeper/grpc_query_last_block_height_test.go @@ -7,10 +7,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" - keepertest "github.com/zeta-chain/zetacore/testutil/keeper" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) func TestLastBlockHeightQuerySingle(t *testing.T) { diff --git a/x/crosschain/keeper/grpc_query_last_zeta_height.go b/x/crosschain/keeper/grpc_query_last_zeta_height.go index ff1639d8dd..45fe776b96 100644 --- a/x/crosschain/keeper/grpc_query_last_zeta_height.go +++ b/x/crosschain/keeper/grpc_query_last_zeta_height.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -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_last_zeta_height_test.go b/x/crosschain/keeper/grpc_query_last_zeta_height_test.go index b34a96be20..22f82febf0 100644 --- a/x/crosschain/keeper/grpc_query_last_zeta_height_test.go +++ b/x/crosschain/keeper/grpc_query_last_zeta_height_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/grpc_query_legacy.go b/x/crosschain/keeper/grpc_query_legacy.go index cb72a5d157..1d52a0a603 100644 --- a/x/crosschain/keeper/grpc_query_legacy.go +++ b/x/crosschain/keeper/grpc_query_legacy.go @@ -8,48 +8,72 @@ import ( // OutTxTrackerAll // Deprecated(v17): use OutboundTrackerAll -func (k Keeper) OutTxTrackerAll(c context.Context, req *types.QueryAllOutboundTrackerRequest) (*types.QueryAllOutboundTrackerResponse, error) { +func (k Keeper) OutTxTrackerAll( + c context.Context, + req *types.QueryAllOutboundTrackerRequest, +) (*types.QueryAllOutboundTrackerResponse, error) { return k.OutboundTrackerAll(c, req) } // OutTxTrackerAllByChain // Deprecated(v17): use OutboundTrackerAllByChain -func (k Keeper) OutTxTrackerAllByChain(c context.Context, req *types.QueryAllOutboundTrackerByChainRequest) (*types.QueryAllOutboundTrackerByChainResponse, error) { +func (k Keeper) OutTxTrackerAllByChain( + c context.Context, + req *types.QueryAllOutboundTrackerByChainRequest, +) (*types.QueryAllOutboundTrackerByChainResponse, error) { return k.OutboundTrackerAllByChain(c, req) } // OutTxTracker // Deprecated(v17): use OutboundTracker -func (k Keeper) OutTxTracker(c context.Context, req *types.QueryGetOutboundTrackerRequest) (*types.QueryGetOutboundTrackerResponse, error) { +func (k Keeper) OutTxTracker( + c context.Context, + req *types.QueryGetOutboundTrackerRequest, +) (*types.QueryGetOutboundTrackerResponse, error) { return k.OutboundTracker(c, req) } // InTxTrackerAllByChain // Deprecated(v17): use InboundTrackerAllByChain -func (k Keeper) InTxTrackerAllByChain(c context.Context, req *types.QueryAllInboundTrackerByChainRequest) (*types.QueryAllInboundTrackerByChainResponse, error) { +func (k Keeper) InTxTrackerAllByChain( + c context.Context, + req *types.QueryAllInboundTrackerByChainRequest, +) (*types.QueryAllInboundTrackerByChainResponse, error) { return k.InboundTrackerAllByChain(c, req) } // InTxTrackerAll // Deprecated(v17): use InboundTrackerAll -func (k Keeper) InTxTrackerAll(c context.Context, req *types.QueryAllInboundTrackersRequest) (*types.QueryAllInboundTrackersResponse, error) { +func (k Keeper) InTxTrackerAll( + c context.Context, + req *types.QueryAllInboundTrackersRequest, +) (*types.QueryAllInboundTrackersResponse, error) { return k.InboundTrackerAll(c, req) } // InTxHashToCctxAll // Deprecated(v17): use InboundHashToCctxAll -func (k Keeper) InTxHashToCctxAll(c context.Context, req *types.QueryAllInboundHashToCctxRequest) (*types.QueryAllInboundHashToCctxResponse, error) { +func (k Keeper) InTxHashToCctxAll( + c context.Context, + req *types.QueryAllInboundHashToCctxRequest, +) (*types.QueryAllInboundHashToCctxResponse, error) { return k.InboundHashToCctxAll(c, req) } // InTxHashToCctx // Deprecated(v17): use InboundHashToCctx -func (k Keeper) InTxHashToCctx(c context.Context, req *types.QueryGetInboundHashToCctxRequest) (*types.QueryGetInboundHashToCctxResponse, error) { +func (k Keeper) InTxHashToCctx( + c context.Context, + req *types.QueryGetInboundHashToCctxRequest, +) (*types.QueryGetInboundHashToCctxResponse, error) { return k.InboundHashToCctx(c, req) } // InTxHashToCctxData // Deprecated(v17): use InboundHashToCctxData -func (k Keeper) InTxHashToCctxData(c context.Context, req *types.QueryInboundHashToCctxDataRequest) (*types.QueryInboundHashToCctxDataResponse, error) { +func (k Keeper) InTxHashToCctxData( + c context.Context, + req *types.QueryInboundHashToCctxDataRequest, +) (*types.QueryInboundHashToCctxDataResponse, error) { return k.InboundHashToCctxData(c, req) } diff --git a/x/crosschain/keeper/grpc_query_outbound_tracker.go b/x/crosschain/keeper/grpc_query_outbound_tracker.go index 356056559d..59919970dd 100644 --- a/x/crosschain/keeper/grpc_query_outbound_tracker.go +++ b/x/crosschain/keeper/grpc_query_outbound_tracker.go @@ -7,12 +7,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) -func (k Keeper) OutboundTrackerAll(c context.Context, req *types.QueryAllOutboundTrackerRequest) (*types.QueryAllOutboundTrackerResponse, error) { +func (k Keeper) OutboundTrackerAll( + c context.Context, + req *types.QueryAllOutboundTrackerRequest, +) (*types.QueryAllOutboundTrackerResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -38,7 +42,10 @@ func (k Keeper) OutboundTrackerAll(c context.Context, req *types.QueryAllOutboun return &types.QueryAllOutboundTrackerResponse{OutboundTracker: outboundTrackers, Pagination: pageRes}, nil } -func (k Keeper) OutboundTrackerAllByChain(c context.Context, req *types.QueryAllOutboundTrackerByChainRequest) (*types.QueryAllOutboundTrackerByChainResponse, error) { +func (k Keeper) OutboundTrackerAllByChain( + c context.Context, + req *types.QueryAllOutboundTrackerByChainRequest, +) (*types.QueryAllOutboundTrackerByChainResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } @@ -65,7 +72,10 @@ func (k Keeper) OutboundTrackerAllByChain(c context.Context, req *types.QueryAll return &types.QueryAllOutboundTrackerByChainResponse{OutboundTracker: outboundTrackers, Pagination: pageRes}, nil } -func (k Keeper) OutboundTracker(c context.Context, req *types.QueryGetOutboundTrackerRequest) (*types.QueryGetOutboundTrackerResponse, error) { +func (k Keeper) OutboundTracker( + c context.Context, + req *types.QueryGetOutboundTrackerRequest, +) (*types.QueryGetOutboundTrackerResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } diff --git a/x/crosschain/keeper/grpc_query_outbound_tracker_test.go b/x/crosschain/keeper/grpc_query_outbound_tracker_test.go index 650654e705..47cde5e33a 100644 --- a/x/crosschain/keeper/grpc_query_outbound_tracker_test.go +++ b/x/crosschain/keeper/grpc_query_outbound_tracker_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/grpc_query_rate_limiter_flags.go b/x/crosschain/keeper/grpc_query_rate_limiter_flags.go index 998b9cf0a2..066b86047f 100644 --- a/x/crosschain/keeper/grpc_query_rate_limiter_flags.go +++ b/x/crosschain/keeper/grpc_query_rate_limiter_flags.go @@ -4,13 +4,17 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/crosschain/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/crosschain/types" ) // 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_rate_limiter_flags_test.go b/x/crosschain/keeper/grpc_query_rate_limiter_flags_test.go index 66aaf2d751..6132c6fdbf 100644 --- a/x/crosschain/keeper/grpc_query_rate_limiter_flags_test.go +++ b/x/crosschain/keeper/grpc_query_rate_limiter_flags_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go b/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go index 5cb26ef831..184b398b66 100644 --- a/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go +++ b/x/crosschain/keeper/grpc_query_zeta_conversion_rate.go @@ -6,14 +6,18 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/codes" - "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 +46,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/grpc_query_zeta_conversion_rate_test.go b/x/crosschain/keeper/grpc_query_zeta_conversion_rate_test.go index f6baf0c625..275440cfed 100644 --- a/x/crosschain/keeper/grpc_query_zeta_conversion_rate_test.go +++ b/x/crosschain/keeper/grpc_query_zeta_conversion_rate_test.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/keeper/inbound_hash_to_cctx.go b/x/crosschain/keeper/inbound_hash_to_cctx.go index fcdcc41c80..7593ca4e3b 100644 --- a/x/crosschain/keeper/inbound_hash_to_cctx.go +++ b/x/crosschain/keeper/inbound_hash_to_cctx.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/inbound_hash_to_cctx_test.go b/x/crosschain/keeper/inbound_hash_to_cctx_test.go index 7bf1032fbb..6bdce68d82 100644 --- a/x/crosschain/keeper/inbound_hash_to_cctx_test.go +++ b/x/crosschain/keeper/inbound_hash_to_cctx_test.go @@ -4,12 +4,12 @@ import ( "strconv" "testing" - "github.com/zeta-chain/zetacore/x/crosschain/keeper" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" + "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/inbound_tracker.go b/x/crosschain/keeper/inbound_tracker.go index 92a4ac553c..9619f718c1 100644 --- a/x/crosschain/keeper/inbound_tracker.go +++ b/x/crosschain/keeper/inbound_tracker.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -22,7 +23,11 @@ func (k Keeper) SetInboundTracker(ctx sdk.Context, InboundTracker types.InboundT } // GetInboundTracker returns a InboundTracker from its index -func (k Keeper) GetInboundTracker(ctx sdk.Context, chainID int64, txHash string) (val types.InboundTracker, found bool) { +func (k Keeper) GetInboundTracker( + ctx sdk.Context, + chainID int64, + txHash string, +) (val types.InboundTracker, found bool) { key := getInboundTrackerKey(chainID, txHash) store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.InboundTrackerKeyPrefix)) b := store.Get(types.KeyPrefix(key)) @@ -40,7 +45,11 @@ func (k Keeper) RemoveInboundTrackerIfExists(ctx sdk.Context, chainID int64, txH store.Delete(types.KeyPrefix(key)) } } -func (k Keeper) GetAllInboundTrackerPaginated(ctx sdk.Context, pagination *query.PageRequest) (inTxTrackers []types.InboundTracker, pageRes *query.PageResponse, err error) { + +func (k Keeper) GetAllInboundTrackerPaginated( + ctx sdk.Context, + pagination *query.PageRequest, +) (inTxTrackers []types.InboundTracker, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.InboundTrackerKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer iterator.Close() @@ -79,7 +88,11 @@ func (k Keeper) GetAllInboundTrackerForChain(ctx sdk.Context, chainID int64) (li return list } -func (k Keeper) GetAllInboundTrackerForChainPaginated(ctx sdk.Context, chainID int64, pagination *query.PageRequest) (inTxTrackers []types.InboundTracker, pageRes *query.PageResponse, err error) { +func (k Keeper) GetAllInboundTrackerForChainPaginated( + ctx sdk.Context, + chainID int64, + pagination *query.PageRequest, +) (inTxTrackers []types.InboundTracker, pageRes *query.PageResponse, err error) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(fmt.Sprintf("%s", types.InboundTrackerKeyPrefix))) 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/inbound_tracker_test.go b/x/crosschain/keeper/inbound_tracker_test.go index f139d9002a..899824e074 100644 --- a/x/crosschain/keeper/inbound_tracker_test.go +++ b/x/crosschain/keeper/inbound_tracker_test.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" @@ -56,7 +57,11 @@ func TestKeeper_GetAllInboundTrackerForChain(t *testing.T) { t.Run("Get all InTx trackers for chain paginated by limit", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) inboundTrackers := createNInboundTracker(keeper, ctx, 100, 6) - rst, pageRes, err := keeper.GetAllInboundTrackerForChainPaginated(ctx, 6, &query.PageRequest{Limit: 10, CountTotal: true}) + rst, pageRes, err := keeper.GetAllInboundTrackerForChainPaginated( + ctx, + 6, + &query.PageRequest{Limit: 10, CountTotal: true}, + ) require.NoError(t, err) require.Subset(t, nullify.Fill(inboundTrackers), nullify.Fill(rst)) require.Equal(t, len(inboundTrackers), int(pageRes.Total)) @@ -64,14 +69,20 @@ func TestKeeper_GetAllInboundTrackerForChain(t *testing.T) { t.Run("Get all InTx trackers for chain paginated by offset", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) inboundTrackers := createNInboundTracker(keeper, ctx, 100, 6) - rst, pageRes, err := keeper.GetAllInboundTrackerForChainPaginated(ctx, 6, &query.PageRequest{Offset: 10, CountTotal: true}) + rst, pageRes, err := keeper.GetAllInboundTrackerForChainPaginated( + ctx, + 6, + &query.PageRequest{Offset: 10, CountTotal: true}, + ) require.NoError(t, err) require.Subset(t, nullify.Fill(inboundTrackers), nullify.Fill(rst)) require.Equal(t, len(inboundTrackers), int(pageRes.Total)) }) t.Run("Get all InTx trackers paginated by limit", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) - inboundTrackers := append(createNInboundTracker(keeper, ctx, 10, 6), createNInboundTracker(keeper, ctx, 10, 7)...) + inboundTrackers := append( + createNInboundTracker(keeper, ctx, 10, 6), + createNInboundTracker(keeper, ctx, 10, 7)...) rst, pageRes, err := keeper.GetAllInboundTrackerPaginated(ctx, &query.PageRequest{Limit: 20, CountTotal: true}) require.NoError(t, err) require.Subset(t, nullify.Fill(inboundTrackers), nullify.Fill(rst)) @@ -79,7 +90,9 @@ func TestKeeper_GetAllInboundTrackerForChain(t *testing.T) { }) t.Run("Get all InTx trackers paginated by offset", func(t *testing.T) { keeper, ctx, _, _ := keepertest.CrosschainKeeper(t) - inboundTrackers := append(createNInboundTracker(keeper, ctx, 100, 6), createNInboundTracker(keeper, ctx, 100, 7)...) + inboundTrackers := append( + createNInboundTracker(keeper, ctx, 100, 6), + createNInboundTracker(keeper, ctx, 100, 7)...) rst, pageRes, err := keeper.GetAllInboundTrackerPaginated(ctx, &query.PageRequest{Offset: 10, CountTotal: true}) require.NoError(t, err) require.Subset(t, nullify.Fill(inboundTrackers), nullify.Fill(rst)) diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 3d01e015b8..fc483689b3 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/last_block_height.go b/x/crosschain/keeper/last_block_height.go index bc4d5bb636..da4580153f 100644 --- a/x/crosschain/keeper/last_block_height.go +++ b/x/crosschain/keeper/last_block_height.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/last_block_height_test.go b/x/crosschain/keeper/last_block_height_test.go index 707b89ff02..d38cec8f99 100644 --- a/x/crosschain/keeper/last_block_height_test.go +++ b/x/crosschain/keeper/last_block_height_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/keeper/migrator.go b/x/crosschain/keeper/migrator.go index 4de64140c8..490592b4cb 100644 --- a/x/crosschain/keeper/migrator.go +++ b/x/crosschain/keeper/migrator.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + v2 "github.com/zeta-chain/zetacore/x/crosschain/migrations/v2" v3 "github.com/zeta-chain/zetacore/x/crosschain/migrations/v3" v4 "github.com/zeta-chain/zetacore/x/crosschain/migrations/v4" @@ -22,7 +23,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_abort_stuck_cctx.go b/x/crosschain/keeper/msg_server_abort_stuck_cctx.go index 972f6ccff6..ab6038d30a 100644 --- a/x/crosschain/keeper/msg_server_abort_stuck_cctx.go +++ b/x/crosschain/keeper/msg_server_abort_stuck_cctx.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/msg_server_abort_stuck_cctx_test.go b/x/crosschain/keeper/msg_server_abort_stuck_cctx_test.go index 3dc6e63459..aa1fc26786 100644 --- a/x/crosschain/keeper/msg_server_abort_stuck_cctx_test.go +++ b/x/crosschain/keeper/msg_server_abort_stuck_cctx_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/crosschain/keeper/msg_server_add_inbound_tracker.go b/x/crosschain/keeper/msg_server_add_inbound_tracker.go index 0ae7a0e227..5f2c85e96a 100644 --- a/x/crosschain/keeper/msg_server_add_inbound_tracker.go +++ b/x/crosschain/keeper/msg_server_add_inbound_tracker.go @@ -6,13 +6,17 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) // AddInboundTracker adds a new record to the inbound transaction tracker. -func (k msgServer) AddInboundTracker(goCtx context.Context, msg *types.MsgAddInboundTracker) (*types.MsgAddInboundTrackerResponse, error) { +func (k msgServer) AddInboundTracker( + goCtx context.Context, + msg *types.MsgAddInboundTracker, +) (*types.MsgAddInboundTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) chain := k.GetObserverKeeper().GetSupportedChainFromChainID(ctx, msg.ChainId) if chain == nil { diff --git a/x/crosschain/keeper/msg_server_add_inbound_tracker_test.go b/x/crosschain/keeper/msg_server_add_inbound_tracker_test.go index 17ccadacb6..ba91595689 100644 --- a/x/crosschain/keeper/msg_server_add_inbound_tracker_test.go +++ b/x/crosschain/keeper/msg_server_add_inbound_tracker_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/stretchr/testify/mock" - "github.com/zeta-chain/zetacore/pkg/chains" - "github.com/stretchr/testify/require" + + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -160,7 +160,8 @@ func TestMsgServer_AddToInboundTracker(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_AddToInboundTracker(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_AddToInboundTracker(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_AddToInboundTracker(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_AddToInboundTracker(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.AddInboundTracker(ctx, &types.MsgAddInboundTracker{ Creator: admin, diff --git a/x/crosschain/keeper/msg_server_add_outbound_tracker.go b/x/crosschain/keeper/msg_server_add_outbound_tracker.go index aefce2d929..977343265e 100644 --- a/x/crosschain/keeper/msg_server_add_outbound_tracker.go +++ b/x/crosschain/keeper/msg_server_add_outbound_tracker.go @@ -7,6 +7,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -19,7 +20,10 @@ const MaxOutboundTrackerHashes = 2 // AddOutboundTracker 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) AddOutboundTracker(goCtx context.Context, msg *types.MsgAddOutboundTracker) (*types.MsgAddOutboundTrackerResponse, error) { +func (k msgServer) AddOutboundTracker( + goCtx context.Context, + msg *types.MsgAddOutboundTracker, +) (*types.MsgAddOutboundTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // check the chain is supported @@ -37,7 +41,12 @@ func (k msgServer) AddOutboundTracker(goCtx context.Context, msg *types.MsgAddOu 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_outbound_tracker_test.go b/x/crosschain/keeper/msg_server_add_outbound_tracker_test.go index c075e681f9..070d97a30f 100644 --- a/x/crosschain/keeper/msg_server_add_outbound_tracker_test.go +++ b/x/crosschain/keeper/msg_server_add_outbound_tracker_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -345,7 +346,8 @@ func TestMsgServer_AddToOutboundTracker(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.AddOutboundTracker(ctx, &types.MsgAddOutboundTracker{ Creator: admin, @@ -387,7 +389,8 @@ func TestMsgServer_AddToOutboundTracker(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.SetOutboundTracker(ctx, types.OutboundTracker{ ChainId: chainID, @@ -442,7 +445,8 @@ func TestMsgServer_AddToOutboundTracker(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.AddOutboundTracker(ctx, &types.MsgAddOutboundTracker{ Creator: admin, @@ -477,7 +481,8 @@ func TestMsgServer_AddToOutboundTracker(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 +525,8 @@ func TestMsgServer_AddToOutboundTracker(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.AddOutboundTracker(ctx, &types.MsgAddOutboundTracker{ 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 97de2688e5..b651178312 100644 --- a/x/crosschain/keeper/msg_server_migrate_tss_funds.go +++ b/x/crosschain/keeper/msg_server_migrate_tss_funds.go @@ -11,24 +11,30 @@ import ( tmtypes "github.com/cometbft/cometbft/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/chains" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/constant" zetacrypto "github.com/zeta-chain/zetacore/pkg/crypto" "github.com/zeta-chain/zetacore/pkg/gas" - - "github.com/zeta-chain/zetacore/pkg/coin" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) // 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.GetCurrentOutboundParam().GasPrice = multipliedGasPrice.String() evmFee := sdkmath.NewUint(cctx.GetCurrentOutboundParam().GasLimit).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.GetCurrentOutboundParam().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 6dd77d8800..0d1207058e 100644 --- a/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go +++ b/x/crosschain/keeper/msg_server_migrate_tss_funds_test.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/gas" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -74,7 +75,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 +315,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 +480,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 3b3c9864f3..f33650ed96 100644 --- a/x/crosschain/keeper/msg_server_refund_aborted_tx.go +++ b/x/crosschain/keeper/msg_server_refund_aborted_tx.go @@ -6,10 +6,11 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "golang.org/x/net/context" + "github.com/zeta-chain/zetacore/pkg/coin" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" - "golang.org/x/net/context" ) // RefundAbortedCCTX refunds the aborted CCTX. @@ -17,7 +18,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 dd74dd1b52..2ac6b8c363 100644 --- a/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go +++ b/x/crosschain/keeper/msg_server_refund_aborted_tx_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -57,7 +58,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundParams.SenderChainId, "foobar", "foobar") + zrc20 := setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -95,7 +104,10 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.SenderChainId = chainID cctx.InboundParams.CoinType = coin.CoinType_Zeta k.SetCrossChainTx(ctx, *cctx) - k.SetZetaAccounting(ctx, crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}) + k.SetZetaAccounting( + ctx, + crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}, + ) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ @@ -135,7 +147,10 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Zeta cctx.OutboundParams = nil k.SetCrossChainTx(ctx, *cctx) - k.SetZetaAccounting(ctx, crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}) + k.SetZetaAccounting( + ctx, + crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}, + ) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ @@ -175,7 +190,10 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Zeta cctx.OutboundParams = nil k.SetCrossChainTx(ctx, *cctx) - k.SetZetaAccounting(ctx, crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}) + k.SetZetaAccounting( + ctx, + crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}, + ) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ @@ -207,7 +225,10 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Cmd cctx.OutboundParams = nil k.SetCrossChainTx(ctx, *cctx) - k.SetZetaAccounting(ctx, crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}) + k.SetZetaAccounting( + ctx, + crosschaintypes.ZetaAccounting{AbortedZetaAmount: cctx.GetCurrentOutboundParam().Amount}, + ) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ @@ -328,7 +349,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - zrc20 := setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundParams.SenderChainId, "foobar", "foobar") + zrc20 := setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -491,7 +520,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - _ = setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundParams.SenderChainId, "foobar", "foobar") + _ = setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, @@ -552,7 +589,15 @@ func TestMsgServer_RefundAbortedCCTX(t *testing.T) { cctx.InboundParams.CoinType = coin.CoinType_Gas k.SetCrossChainTx(ctx, *cctx) deploySystemContracts(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper) - _ = setupGasCoin(t, ctx, zk.FungibleKeeper, sdkk.EvmKeeper, cctx.InboundParams.SenderChainId, "foobar", "foobar") + _ = setupGasCoin( + t, + ctx, + zk.FungibleKeeper, + sdkk.EvmKeeper, + cctx.InboundParams.SenderChainId, + "foobar", + "foobar", + ) _, err := msgServer.RefundAbortedCCTX(ctx, &crosschaintypes.MsgRefundAbortedCCTX{ Creator: admin, diff --git a/x/crosschain/keeper/msg_server_remove_outbound_tracker.go b/x/crosschain/keeper/msg_server_remove_outbound_tracker.go index e614af1920..bd0b8d0465 100644 --- a/x/crosschain/keeper/msg_server_remove_outbound_tracker.go +++ b/x/crosschain/keeper/msg_server_remove_outbound_tracker.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -11,7 +12,10 @@ import ( // RemoveOutboundTracker removes a record from the outbound transaction tracker by chain ID and nonce. // // Authorized: admin policy group 1. -func (k msgServer) RemoveOutboundTracker(goCtx context.Context, msg *types.MsgRemoveOutboundTracker) (*types.MsgRemoveOutboundTrackerResponse, error) { +func (k msgServer) RemoveOutboundTracker( + goCtx context.Context, + msg *types.MsgRemoveOutboundTracker, +) (*types.MsgRemoveOutboundTrackerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if !k.GetAuthorityKeeper().IsAuthorized(ctx, msg.Creator, authoritytypes.PolicyType_groupEmergency) { return &types.MsgRemoveOutboundTrackerResponse{}, authoritytypes.ErrUnauthorized diff --git a/x/crosschain/keeper/msg_server_remove_outbound_tracker_test.go b/x/crosschain/keeper/msg_server_remove_outbound_tracker_test.go index ed6485eca8..6044a276c4 100644 --- a/x/crosschain/keeper/msg_server_remove_outbound_tracker_test.go +++ b/x/crosschain/keeper/msg_server_remove_outbound_tracker_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" 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..d312fd22f0 100644 --- a/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go +++ b/x/crosschain/keeper/msg_server_update_rate_limiter_flags.go @@ -6,13 +6,17 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" ) // 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_rate_limiter_flags_test.go b/x/crosschain/keeper/msg_server_update_rate_limiter_flags_test.go index 53b1d6772d..8a2ee87900 100644 --- a/x/crosschain/keeper/msg_server_update_rate_limiter_flags_test.go +++ b/x/crosschain/keeper/msg_server_update_rate_limiter_flags_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/crosschain/keeper/msg_server_update_tss.go b/x/crosschain/keeper/msg_server_update_tss.go index 29e8fe25db..c2a1a490e0 100644 --- a/x/crosschain/keeper/msg_server_update_tss.go +++ b/x/crosschain/keeper/msg_server_update_tss.go @@ -3,22 +3,28 @@ package keeper import ( "context" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/crosschain/types" ) // 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..f644982d3a 100644 --- a/x/crosschain/keeper/msg_server_update_tss_test.go +++ b/x/crosschain/keeper/msg_server_update_tss_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" @@ -74,7 +75,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 +116,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 +130,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 +160,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 +174,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 +252,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 +295,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..2fd84affc3 100644 --- a/x/crosschain/keeper/msg_server_vote_gas_price.go +++ b/x/crosschain/keeper/msg_server_vote_gas_price.go @@ -9,8 +9,8 @@ import ( cosmoserrors "cosmossdk.io/errors" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -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_gas_price_test.go b/x/crosschain/keeper/msg_server_vote_gas_price_test.go index 85b5b26c46..06400a3dbc 100644 --- a/x/crosschain/keeper/msg_server_vote_gas_price_test.go +++ b/x/crosschain/keeper/msg_server_vote_gas_price_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/keeper/msg_server_vote_inbound_tx.go b/x/crosschain/keeper/msg_server_vote_inbound_tx.go index 73d72b50bf..9b40097635 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx.go @@ -6,6 +6,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -52,7 +53,10 @@ import ( // ``` // // Only observer validators are authorized to broadcast this message. -func (k msgServer) VoteInbound(goCtx context.Context, msg *types.MsgVoteInbound) (*types.MsgVoteInboundResponse, error) { +func (k msgServer) VoteInbound( + goCtx context.Context, + msg *types.MsgVoteInbound, +) (*types.MsgVoteInboundResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) index := msg.Digest() @@ -79,7 +83,12 @@ func (k msgServer) VoteInbound(goCtx context.Context, msg *types.MsgVoteInbound) if k.IsFinalizedInbound(tmpCtx, msg.InboundHash, msg.SenderChainId, msg.EventIndex) { return nil, cosmoserrors.Wrap( types.ErrObservedTxAlreadyFinalized, - fmt.Sprintf("inboundHash:%s, SenderChainID:%d, EventIndex:%d", msg.InboundHash, msg.SenderChainId, msg.EventIndex), + fmt.Sprintf( + "inboundHash:%s, SenderChainID:%d, EventIndex:%d", + msg.InboundHash, + 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 e502981cb2..e2bf3c8c50 100644 --- a/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go +++ b/x/crosschain/keeper/msg_server_vote_inbound_tx_test.go @@ -14,12 +14,12 @@ import ( "github.com/evmos/ethermint/x/evm/statedb" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/keeper" - "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -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.InboundParams.TxFinalizationStatus) - require.True(t, k.IsFinalizedInbound(ctx, cctx.GetInboundParams().ObservedHash, cctx.GetInboundParams().SenderChainId, eventIndex)) + require.True( + t, + k.IsFinalizedInbound( + ctx, + cctx.GetInboundParams().ObservedHash, + cctx.GetInboundParams().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.InboundParams.TxFinalizationStatus) - require.True(t, k.IsFinalizedInbound(ctx, cctx.GetInboundParams().ObservedHash, cctx.GetInboundParams().SenderChainId, eventIndex)) + require.True( + t, + k.IsFinalizedInbound( + ctx, + cctx.GetInboundParams().ObservedHash, + cctx.GetInboundParams().SenderChainId, + eventIndex, + ), + ) _, found := k.GetCrossChainTx(ctx, cctx.Index) require.True(t, found) _, found = k.GetInboundTracker(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 aee69b7b4a..4c5d3b0d13 100644 --- a/x/crosschain/keeper/msg_server_vote_outbound_tx.go +++ b/x/crosschain/keeper/msg_server_vote_outbound_tx.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/x/crosschain/types" observerkeeper "github.com/zeta-chain/zetacore/x/observer/keeper" ) @@ -54,7 +55,10 @@ import ( // ``` // // Only observer validators are authorized to broadcast this message. -func (k msgServer) VoteOutbound(goCtx context.Context, msg *types.MsgVoteOutbound) (*types.MsgVoteOutboundResponse, error) { +func (k msgServer) VoteOutbound( + goCtx context.Context, + msg *types.MsgVoteOutbound, +) (*types.MsgVoteOutboundResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Validate the message params to verify it against an existing cctx @@ -107,12 +111,17 @@ func (k msgServer) VoteOutbound(goCtx context.Context, msg *types.MsgVoteOutboun 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.GetCurrentOutboundParam(), cctx.GetCurrentOutboundParam().ReceiverChainId); err != nil { - ctx.Logger().Error(fmt.Sprintf("VoteOutbound: CCTX: %s Can't fund the gas stability pool with remaining fees %s", cctx.Index, err.Error())) + ctx.Logger(). + Error(fmt.Sprintf("VoteOutbound: 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, OutboundParams types.OutboundParams, chainID int64) error { +func (k Keeper) FundGasStabilityPoolFromRemainingFees( + ctx sdk.Context, + OutboundParams types.OutboundParams, + chainID int64, +) error { gasUsed := OutboundParams.GasUsed gasLimit := OutboundParams.EffectiveGasLimit gasPrice := math.NewUintFromBigInt(OutboundParams.EffectiveGasPrice.BigInt()) @@ -189,7 +198,8 @@ 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.RemoveOutboundTrackerFromStore(ctx, receiverChain, outTxTssNonce) - ctx.Logger().Info(fmt.Sprintf("Remove tracker %s: , Block Height : %d ", getOutboundTrackerIndex(receiverChain, outTxTssNonce), ctx.BlockHeight())) + ctx.Logger(). + Info(fmt.Sprintf("Remove tracker %s: , Block Height : %d ", getOutboundTrackerIndex(receiverChain, outTxTssNonce), ctx.BlockHeight())) // This should set nonce to cctx only if a new revert is created. k.SetCctxAndNonceToCctxAndInboundHashToCctx(ctx, *cctx) } @@ -198,10 +208,20 @@ func (k Keeper) ValidateOutboundMessage(ctx sdk.Context, msg types.MsgVoteOutbou // 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.GetCurrentOutboundParam().TssNonce != msg.OutboundTssNonce { - return types.CrossChainTx{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutboundTssNonce %d does not match CCTX OutboundTssNonce %d", msg.OutboundTssNonce, cctx.GetCurrentOutboundParam().TssNonce)) + return types.CrossChainTx{}, cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "OutboundTssNonce %d does not match CCTX OutboundTssNonce %d", + msg.OutboundTssNonce, + cctx.GetCurrentOutboundParam().TssNonce, + ), + ) } // do not process an outbound vote if TSS is not found _, found = k.zetaObserverKeeper.GetTSS(ctx) @@ -209,7 +229,14 @@ func (k Keeper) ValidateOutboundMessage(ctx sdk.Context, msg types.MsgVoteOutbou return types.CrossChainTx{}, types.ErrCannotFindTSSKeys } if cctx.GetCurrentOutboundParam().ReceiverChainId != msg.OutboundChain { - return types.CrossChainTx{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("OutboundChain %d does not match CCTX OutboundChain %d", msg.OutboundChain, cctx.GetCurrentOutboundParam().ReceiverChainId)) + return types.CrossChainTx{}, cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "OutboundChain %d does not match CCTX OutboundChain %d", + msg.OutboundChain, + cctx.GetCurrentOutboundParam().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 c6cc37debe..427876d702 100644 --- a/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go +++ b/x/crosschain/keeper/msg_server_vote_outbound_tx_test.go @@ -11,6 +11,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -69,13 +70,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 +325,8 @@ func TestKeeper_VoteOutbound(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 +367,12 @@ func TestKeeper_VoteOutbound(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.GetCurrentOutboundParam().TssPubkey = tss.TssPubkey @@ -454,7 +463,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.GetOutboundTracker(ctx, cctx.GetCurrentOutboundParam().ReceiverChainId, cctx.GetCurrentOutboundParam().TssNonce) + _, found := k.GetOutboundTracker( + ctx, + cctx.GetCurrentOutboundParam().ReceiverChainId, + cctx.GetCurrentOutboundParam().TssNonce, + ) require.False(t, found) }) } @@ -472,7 +485,11 @@ func TestKeeper_SaveSuccessfulOutBound(t *testing.T) { cctx.CctxStatus.Status = types.CctxStatus_PendingOutbound k.SaveSuccessfulOutbound(ctx, cctx, sample.String()) require.Equal(t, cctx.GetCurrentOutboundParam().BallotIndex, sample.String()) - _, found := k.GetOutboundTracker(ctx, cctx.GetCurrentOutboundParam().ReceiverChainId, cctx.GetCurrentOutboundParam().TssNonce) + _, found := k.GetOutboundTracker( + ctx, + cctx.GetCurrentOutboundParam().ReceiverChainId, + cctx.GetCurrentOutboundParam().TssNonce, + ) require.False(t, found) }) } @@ -505,15 +522,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.GetCurrentOutboundParam().BallotIndex, ballotIndex) - _, found := k.GetOutboundTracker(ctx, cctx.GetCurrentOutboundParam().ReceiverChainId, cctx.GetCurrentOutboundParam().TssNonce) + _, found := k.GetOutboundTracker( + ctx, + cctx.GetCurrentOutboundParam().ReceiverChainId, + cctx.GetCurrentOutboundParam().TssNonce, + ) require.False(t, found) - pn, found := zk.ObserverKeeper.GetPendingNonces(ctx, cctx.GetCurrentOutboundParam().TssPubkey, cctx.GetCurrentOutboundParam().ReceiverChainId) + pn, found := zk.ObserverKeeper.GetPendingNonces( + ctx, + cctx.GetCurrentOutboundParam().TssPubkey, + cctx.GetCurrentOutboundParam().ReceiverChainId, + ) require.True(t, found) require.Equal(t, pn.NonceLow, int64(cctx.GetCurrentOutboundParam().TssNonce)+1) require.Equal(t, pn.NonceHigh, int64(cctx.GetCurrentOutboundParam().TssNonce)+1) _, found = k.GetInboundHashToCctx(ctx, cctx.InboundParams.ObservedHash) require.True(t, found) - _, found = zk.ObserverKeeper.GetNonceToCctx(ctx, cctx.GetCurrentOutboundParam().TssPubkey, cctx.GetCurrentOutboundParam().ReceiverChainId, int64(cctx.GetCurrentOutboundParam().TssNonce)) + _, found = zk.ObserverKeeper.GetNonceToCctx( + ctx, + cctx.GetCurrentOutboundParam().TssPubkey, + cctx.GetCurrentOutboundParam().ReceiverChainId, + int64(cctx.GetCurrentOutboundParam().TssNonce), + ) require.True(t, found) }) } @@ -553,7 +583,15 @@ func TestKeeper_ValidateOutboundMessage(t *testing.T) { } _, err := k.ValidateOutboundMessage(ctx, msg) require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("OutboundTssNonce %d does not match CCTX OutboundTssNonce %d", msg.OutboundTssNonce, cctx.GetCurrentOutboundParam().TssNonce)) + require.ErrorContains( + t, + err, + fmt.Sprintf( + "OutboundTssNonce %d does not match CCTX OutboundTssNonce %d", + msg.OutboundTssNonce, + cctx.GetCurrentOutboundParam().TssNonce, + ), + ) }) t.Run("failed to validate outbound message if tss not found", func(t *testing.T) { @@ -578,6 +616,14 @@ func TestKeeper_ValidateOutboundMessage(t *testing.T) { OutboundChain: 2, }) require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest) - require.ErrorContains(t, err, fmt.Sprintf("OutboundChain %d does not match CCTX OutboundChain %d", 2, cctx.GetCurrentOutboundParam().ReceiverChainId)) + require.ErrorContains( + t, + err, + fmt.Sprintf( + "OutboundChain %d does not match CCTX OutboundChain %d", + 2, + cctx.GetCurrentOutboundParam().ReceiverChainId, + ), + ) }) } diff --git a/x/crosschain/keeper/msg_server_whitelist_erc20.go b/x/crosschain/keeper/msg_server_whitelist_erc20.go index e518a1b22f..47f4007eb5 100644 --- a/x/crosschain/keeper/msg_server_whitelist_erc20.go +++ b/x/crosschain/keeper/msg_server_whitelist_erc20.go @@ -11,6 +11,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/constant" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" @@ -22,17 +23,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 +109,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/msg_server_whitelist_erc20_test.go b/x/crosschain/keeper/msg_server_whitelist_erc20_test.go index 6db8243405..ba0cfa2609 100644 --- a/x/crosschain/keeper/msg_server_whitelist_erc20_test.go +++ b/x/crosschain/keeper/msg_server_whitelist_erc20_test.go @@ -4,14 +4,14 @@ import ( "fmt" "testing" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/constant" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" crosschainkeeper "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/crosschain/keeper/outbound_tracker.go b/x/crosschain/keeper/outbound_tracker.go index 77df6d25c4..dbf8bf3bb5 100644 --- a/x/crosschain/keeper/outbound_tracker.go +++ b/x/crosschain/keeper/outbound_tracker.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/outbound_tracker_test.go b/x/crosschain/keeper/outbound_tracker_test.go index 5c62cf67fc..ce7cfe31f2 100644 --- a/x/crosschain/keeper/outbound_tracker_test.go +++ b/x/crosschain/keeper/outbound_tracker_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/crosschain/keeper" diff --git a/x/crosschain/keeper/process_inbound.go b/x/crosschain/keeper/process_inbound.go index 4c0ec0f9d0..2fe9bfb3c9 100644 --- a/x/crosschain/keeper/process_inbound.go +++ b/x/crosschain/keeper/process_inbound.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -21,9 +22,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 +96,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 00e8b52af1..c091b75ad1 100644 --- a/x/crosschain/keeper/process_inbound_test.go +++ b/x/crosschain/keeper/process_inbound_test.go @@ -8,6 +8,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -57,7 +58,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 +74,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.GetCurrentOutboundParam().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.InboundParams.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.GetCurrentOutboundParam().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.InboundParams.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 +141,100 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { cctx.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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 +315,46 @@ func TestKeeper_ProcessInboundZEVMDeposit(t *testing.T) { require.Equal(t, updatedNonce, cctx.GetCurrentOutboundParam().TssNonce) }) - 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.GetCurrentOutboundParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId - cctx.OutboundParams = append(cctx.OutboundParams, cctx.GetCurrentOutboundParam()) - 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.GetCurrentOutboundParam().ReceiverChainId = chains.ZetaPrivnetChain.ChainId + cctx.OutboundParams = append(cctx.OutboundParams, cctx.GetCurrentOutboundParam()) + 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 e14f0685c9..51c0f43afe 100644 --- a/x/crosschain/keeper/process_outbound.go +++ b/x/crosschain/keeper/process_outbound.go @@ -9,6 +9,7 @@ import ( tmtypes "github.com/cometbft/cometbft/types" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -18,7 +19,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 +132,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 6cdd588c90..a6f5dc81d7 100644 --- a/x/crosschain/keeper/process_outbound_test.go +++ b/x/crosschain/keeper/process_outbound_test.go @@ -10,6 +10,7 @@ import ( "github.com/evmos/ethermint/x/evm/statedb" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/contracts" @@ -74,7 +75,11 @@ func TestKeeper_ProcessFailedOutbound(t *testing.T) { receiver := sample.EthAddress() cctx := GetERC20Cctx(t, receiver, chains.GoerliChain, "", big.NewInt(42)) cctx.InboundParams.CoinType = coin.CoinType_Zeta - err := sdkk.EvmKeeper.SetAccount(ctx, ethcommon.HexToAddress(cctx.InboundParams.Sender), *statedb.NewEmptyAccount()) + err := sdkk.EvmKeeper.SetAccount( + ctx, + ethcommon.HexToAddress(cctx.InboundParams.Sender), + *statedb.NewEmptyAccount(), + ) require.NoError(t, err) cctx.InboundParams.SenderChainId = chains.ZetaChainMainnet.ChainId err = k.ProcessFailedOutbound(ctx, cctx, sample.String()) @@ -320,27 +325,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.GetCurrentOutboundParam().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.GetCurrentOutboundParam().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.InboundParams.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.GetCurrentOutboundParam().TxFinalizationStatus, types.TxFinalizationStatus_Executed) @@ -376,7 +399,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 +434,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 +469,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.OutboundParams, oldOutboundParamsLen+1) require.Equal(t, cctx.GetCurrentOutboundParam().TxFinalizationStatus, types.TxFinalizationStatus_NotFinalized) - require.Equal(t, cctx.OutboundParams[oldOutboundParamsLen-1].TxFinalizationStatus, types.TxFinalizationStatus_Executed) + require.Equal( + t, + cctx.OutboundParams[oldOutboundParamsLen-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..52a1b91f6b 100644 --- a/x/crosschain/keeper/rate_limiter_flags.go +++ b/x/crosschain/keeper/rate_limiter_flags.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -29,7 +30,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..cf7f829773 100644 --- a/x/crosschain/keeper/rate_limiter_flags_test.go +++ b/x/crosschain/keeper/rate_limiter_flags_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -93,15 +94,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 df36db70b5..e24a3f0158 100644 --- a/x/crosschain/keeper/refund.go +++ b/x/crosschain/keeper/refund.go @@ -7,12 +7,17 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "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.InboundParams.CoinType switch coinType { case coin.CoinType_Gas: @@ -27,7 +32,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 +61,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.InboundParams.SenderChainId @@ -73,7 +86,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: GetCurrentOutboundParam 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.InboundParams.CoinType != coin.CoinType_ERC20 { @@ -88,7 +105,11 @@ func (k Keeper) RefundAmountOnZetaChainERC20(ctx sdk.Context, cctx types.CrossCh } // get address of the zrc20 - fc, found := k.fungibleKeeper.GetForeignCoinFromAsset(ctx, cctx.InboundParams.Asset, cctx.InboundParams.SenderChainId) + fc, found := k.fungibleKeeper.GetForeignCoinFromAsset( + ctx, + cctx.InboundParams.Asset, + cctx.InboundParams.SenderChainId, + ) if !found { return fmt.Errorf("asset %s zrc not found", cctx.InboundParams.Asset) } diff --git a/x/crosschain/keeper/refund_test.go b/x/crosschain/keeper/refund_test.go index 728e1c219c..1b1a22e100 100644 --- a/x/crosschain/keeper/refund_test.go +++ b/x/crosschain/keeper/refund_test.go @@ -10,6 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -90,7 +91,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{ InboundParams: &types.InboundParams{ @@ -370,9 +372,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 +408,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{ InboundParams: &types.InboundParams{ diff --git a/x/crosschain/keeper/utils_test.go b/x/crosschain/keeper/utils_test.go index a8d63f17d1..48a1078ec6 100644 --- a/x/crosschain/keeper/utils_test.go +++ b/x/crosschain/keeper/utils_test.go @@ -5,18 +5,18 @@ import ( "math/big" "testing" - "github.com/zeta-chain/zetacore/pkg/chains" - "github.com/zeta-chain/zetacore/testutil/sample" - "github.com/zeta-chain/zetacore/x/crosschain/types" - sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/ethereum/go-ethereum/common" evmkeeper "github.com/evmos/ethermint/x/evm/keeper" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" + "github.com/zeta-chain/zetacore/pkg/chains" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/testutil/sample" + "github.com/zeta-chain/zetacore/x/crosschain/types" fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/crosschain/keeper/zeta_accounting.go b/x/crosschain/keeper/zeta_accounting.go index 2f9a849666..275d7801bf 100644 --- a/x/crosschain/keeper/zeta_accounting.go +++ b/x/crosschain/keeper/zeta_accounting.go @@ -3,6 +3,7 @@ package keeper import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/keeper/zeta_accounting_test.go b/x/crosschain/keeper/zeta_accounting_test.go index 7a3eee1223..1e31cd1b4b 100644 --- a/x/crosschain/keeper/zeta_accounting_test.go +++ b/x/crosschain/keeper/zeta_accounting_test.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/migrations/v2/migrate.go b/x/crosschain/migrations/v2/migrate.go index 308872726c..67f6ae709e 100644 --- a/x/crosschain/migrations/v2/migrate.go +++ b/x/crosschain/migrations/v2/migrate.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/crosschain/migrations/v3/migrate.go b/x/crosschain/migrations/v3/migrate.go index 37b04ed324..cbe11eef98 100644 --- a/x/crosschain/migrations/v3/migrate.go +++ b/x/crosschain/migrations/v3/migrate.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/crosschain/migrations/v4/migrate.go b/x/crosschain/migrations/v4/migrate.go index 55db3e85e4..0be2ca2f08 100644 --- a/x/crosschain/migrations/v4/migrate.go +++ b/x/crosschain/migrations/v4/migrate.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/migrations/v4/migrate_test.go b/x/crosschain/migrations/v4/migrate_test.go index e6fecc9249..00eaf9c51f 100644 --- a/x/crosschain/migrations/v4/migrate_test.go +++ b/x/crosschain/migrations/v4/migrate_test.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -71,7 +72,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 be70e65d1f..79990aa96e 100644 --- a/x/crosschain/migrations/v5/migrate.go +++ b/x/crosschain/migrations/v5/migrate.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -97,9 +98,13 @@ func SetZetaAccounting( switch cctx.InboundParams.CoinType { case coin.CoinType_ERC20: { - receiverChain := observerKeeper.GetSupportedChainFromChainID(ctx, cctx.GetCurrentOutboundParam().ReceiverChainId) + receiverChain := observerKeeper.GetSupportedChainFromChainID( + ctx, + cctx.GetCurrentOutboundParam().ReceiverChainId, + ) if receiverChain == nil { - ctx.Logger().Error(fmt.Sprintf("Error getting chain from chain id: %d , cctx index", cctx.GetCurrentOutboundParam().ReceiverChainId), cctx.Index) + ctx.Logger(). + Error(fmt.Sprintf("Error getting chain from chain id: %d , cctx index", cctx.GetCurrentOutboundParam().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 e2af9b62cc..577dc160d0 100644 --- a/x/crosschain/migrations/v5/migrate_test.go +++ b/x/crosschain/migrations/v5/migrate_test.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/math" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -25,7 +26,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.InboundParams.CoinType != coin.CoinType_Zeta { + if cctx.CctxStatus.Status != crosschaintypes.CctxStatus_Aborted || + cctx.InboundParams.CoinType != coin.CoinType_Zeta { continue } v5ZetaAccountingAmount = v5ZetaAccountingAmount.Add(crosschainkeeper.GetAbortedAmount(cctx)) @@ -47,7 +49,10 @@ func TestMigrateStore(t *testing.T) { for _, cctx := range cctxListUpdated { switch cctx.InboundParams.CoinType { case coin.CoinType_ERC20: - receiverChain := zk.ObserverKeeper.GetSupportedChainFromChainID(ctx, cctx.GetCurrentOutboundParam().ReceiverChainId) + receiverChain := zk.ObserverKeeper.GetSupportedChainFromChainID( + ctx, + cctx.GetCurrentOutboundParam().ReceiverChainId, + ) require.NotNil(t, receiverChain) if receiverChain.IsZetaChain() { require.True(t, cctx.CctxStatus.IsAbortRefunded) @@ -67,7 +72,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/module.go b/x/crosschain/module.go index 12e4b2ca4c..01bb84fc82 100644 --- a/x/crosschain/module.go +++ b/x/crosschain/module.go @@ -6,17 +6,17 @@ import ( "fmt" abci "github.com/cometbft/cometbft/abci/types" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - "github.com/zeta-chain/zetacore/x/crosschain/keeper" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/crosschain/client/cli" + "github.com/zeta-chain/zetacore/x/crosschain/keeper" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/module_simulation.go b/x/crosschain/module_simulation.go index ea4a98ef52..11cfe46d64 100644 --- a/x/crosschain/module_simulation.go +++ b/x/crosschain/module_simulation.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/authz.go b/x/crosschain/types/authz.go index 5d734d8135..8750b41fb3 100644 --- a/x/crosschain/types/authz.go +++ b/x/crosschain/types/authz.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/crosschain/types/authz_test.go b/x/crosschain/types/authz_test.go index 0315c401c5..615b2a775c 100644 --- a/x/crosschain/types/authz_test.go +++ b/x/crosschain/types/authz_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/cctx.go b/x/crosschain/types/cctx.go index df3d01c106..7feece0e1a 100644 --- a/x/crosschain/types/cctx.go +++ b/x/crosschain/types/cctx.go @@ -8,6 +8,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -101,13 +102,24 @@ func (m *CrossChainTx) AddRevertOutbound(gasLimit uint64) error { } // AddOutbound adds a new outbound tx to the CCTX. -func (m *CrossChainTx) AddOutbound(ctx sdk.Context, msg MsgVoteOutbound, ballotStatus observertypes.BallotStatus) error { +func (m *CrossChainTx) AddOutbound( + ctx sdk.Context, + msg MsgVoteOutbound, + ballotStatus observertypes.BallotStatus, +) error { if ballotStatus != observertypes.BallotStatus_BallotFinalized_FailureObservation { if !msg.ValueReceived.Equal(m.GetCurrentOutboundParam().Amount) { ctx.Logger().Error(fmt.Sprintf("VoteOutbound: Mint mismatch: %s value received vs %s cctx amount", msg.ValueReceived, m.GetCurrentOutboundParam().Amount)) - return cosmoserrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("ValueReceived %s does not match sent value %s", msg.ValueReceived, m.GetCurrentOutboundParam().Amount)) + return cosmoserrors.Wrap( + sdkerrors.ErrInvalidRequest, + fmt.Sprintf( + "ValueReceived %s does not match sent value %s", + msg.ValueReceived, + m.GetCurrentOutboundParam().Amount, + ), + ) } } // Update CCTX values diff --git a/x/crosschain/types/cctx_test.go b/x/crosschain/types/cctx_test.go index 8d9c8aa86e..8cfa773428 100644 --- a/x/crosschain/types/cctx_test.go +++ b/x/crosschain/types/cctx_test.go @@ -7,6 +7,7 @@ import ( sdkmath "cosmossdk.io/math" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" 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 f8f3f3ea19..7b564fc78a 100644 --- a/x/crosschain/types/expected_keepers.go +++ b/x/crosschain/types/expected_keepers.go @@ -9,6 +9,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ethcommon "github.com/ethereum/go-ethereum/common" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -45,17 +46,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 +118,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 +165,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/genesis_test.go b/x/crosschain/types/genesis_test.go index e3bdccde9c..9b71922821 100644 --- a/x/crosschain/types/genesis_test.go +++ b/x/crosschain/types/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/inbound_params.go b/x/crosschain/types/inbound_params.go index 5ea6fc56af..782c57013c 100644 --- a/x/crosschain/types/inbound_params.go +++ b/x/crosschain/types/inbound_params.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/crosschain/types/inbound_params_test.go b/x/crosschain/types/inbound_params_test.go index 5ef3b081ae..4387e440b8 100644 --- a/x/crosschain/types/inbound_params_test.go +++ b/x/crosschain/types/inbound_params_test.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/crosschain/types/keys.go b/x/crosschain/types/keys.go index 2ffd892cde..f47912f66c 100644 --- a/x/crosschain/types/keys.go +++ b/x/crosschain/types/keys.go @@ -81,7 +81,13 @@ func (m CrossChainTx) LogIdentifierForCCTX() string { } i := len(m.OutboundParams) - 1 outTx := m.OutboundParams[i] - return fmt.Sprintf("%s-%d-%d-%d", m.InboundParams.Sender, m.InboundParams.SenderChainId, outTx.ReceiverChainId, outTx.TssNonce) + return fmt.Sprintf( + "%s-%d-%d-%d", + m.InboundParams.Sender, + m.InboundParams.SenderChainId, + outTx.ReceiverChainId, + outTx.TssNonce, + ) } func FinalizedInboundKey(inboundHash string, chainID int64, eventIndex uint64) string { diff --git a/x/crosschain/types/message_abort_stuck_cctx_test.go b/x/crosschain/types/message_abort_stuck_cctx_test.go index 5b0d539c0f..f3bfb6617d 100644 --- a/x/crosschain/types/message_abort_stuck_cctx_test.go +++ b/x/crosschain/types/message_abort_stuck_cctx_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/message_add_inbound_tracker.go b/x/crosschain/types/message_add_inbound_tracker.go index c22bf19dd6..0734033569 100644 --- a/x/crosschain/types/message_add_inbound_tracker.go +++ b/x/crosschain/types/message_add_inbound_tracker.go @@ -4,6 +4,7 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" ) @@ -52,7 +53,11 @@ func (msg *MsgAddInboundTracker) 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_inbound_tracker_test.go b/x/crosschain/types/message_add_inbound_tracker_test.go index 10bb97c576..0c81de17a7 100644 --- a/x/crosschain/types/message_add_inbound_tracker_test.go +++ b/x/crosschain/types/message_add_inbound_tracker_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -48,7 +49,11 @@ func TestMsgAddInboundTracker_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_add_outbound_tracker.go b/x/crosschain/types/message_add_outbound_tracker.go index 1910bd0478..a569cc6719 100644 --- a/x/crosschain/types/message_add_outbound_tracker.go +++ b/x/crosschain/types/message_add_outbound_tracker.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/proofs" ) diff --git a/x/crosschain/types/message_add_outbound_tracker_test.go b/x/crosschain/types/message_add_outbound_tracker_test.go index e007c22d8a..753c13af1c 100644 --- a/x/crosschain/types/message_add_outbound_tracker_test.go +++ b/x/crosschain/types/message_add_outbound_tracker_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/message_migrate_tss_funds.go b/x/crosschain/types/message_migrate_tss_funds.go index cb78371d43..2de565c72d 100644 --- a/x/crosschain/types/message_migrate_tss_funds.go +++ b/x/crosschain/types/message_migrate_tss_funds.go @@ -5,6 +5,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/crosschain/types/message_migrate_tss_funds_test.go b/x/crosschain/types/message_migrate_tss_funds_test.go index f882cf90fa..f07943bf59 100644 --- a/x/crosschain/types/message_migrate_tss_funds_test.go +++ b/x/crosschain/types/message_migrate_tss_funds_test.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/types/message_refund_aborted_test.go b/x/crosschain/types/message_refund_aborted_test.go index 2884b8b7c1..e7c1bdffec 100644 --- a/x/crosschain/types/message_refund_aborted_test.go +++ b/x/crosschain/types/message_refund_aborted_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -31,7 +32,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/message_remove_outbound_tracker_test.go b/x/crosschain/types/message_remove_outbound_tracker_test.go index c7bc8ead85..4ef8b7fe1e 100644 --- a/x/crosschain/types/message_remove_outbound_tracker_test.go +++ b/x/crosschain/types/message_remove_outbound_tracker_test.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" - "github.com/zeta-chain/zetacore/testutil/sample" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/message_update_rate_limiter_flags_test.go b/x/crosschain/types/message_update_rate_limiter_flags_test.go index 9a6f933a8b..a0ead6ed22 100644 --- a/x/crosschain/types/message_update_rate_limiter_flags_test.go +++ b/x/crosschain/types/message_update_rate_limiter_flags_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/x/crosschain/types/message_update_tss_address.go b/x/crosschain/types/message_update_tss_address.go index 163e232780..7e18ba27f6 100644 --- a/x/crosschain/types/message_update_tss_address.go +++ b/x/crosschain/types/message_update_tss_address.go @@ -4,6 +4,7 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/cosmos" ) diff --git a/x/crosschain/types/message_update_tss_address_test.go b/x/crosschain/types/message_update_tss_address_test.go index 1d92774717..cfcdea94f2 100644 --- a/x/crosschain/types/message_update_tss_address_test.go +++ b/x/crosschain/types/message_update_tss_address_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/types/message_vote_gas_price.go b/x/crosschain/types/message_vote_gas_price.go index 31ae0479ea..d1d3dceb7a 100644 --- a/x/crosschain/types/message_vote_gas_price.go +++ b/x/crosschain/types/message_vote_gas_price.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/authz" ) diff --git a/x/crosschain/types/message_vote_gas_price_test.go b/x/crosschain/types/message_vote_gas_price_test.go index 295d8b6342..936d694417 100644 --- a/x/crosschain/types/message_vote_gas_price_test.go +++ b/x/crosschain/types/message_vote_gas_price_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/types/message_vote_inbound.go b/x/crosschain/types/message_vote_inbound.go index 84173d2ff7..b2ee24ce2d 100644 --- a/x/crosschain/types/message_vote_inbound.go +++ b/x/crosschain/types/message_vote_inbound.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/coin" ) diff --git a/x/crosschain/types/message_vote_inbound_test.go b/x/crosschain/types/message_vote_inbound_test.go index 9d6b3dfc18..749f94f946 100644 --- a/x/crosschain/types/message_vote_inbound_test.go +++ b/x/crosschain/types/message_vote_inbound_test.go @@ -1,14 +1,14 @@ package types_test import ( - "testing" - "math/rand" + "testing" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/types/message_vote_outbound.go b/x/crosschain/types/message_vote_outbound.go index ed232b22a1..b853ec4b0b 100644 --- a/x/crosschain/types/message_vote_outbound.go +++ b/x/crosschain/types/message_vote_outbound.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" diff --git a/x/crosschain/types/message_vote_outbound_test.go b/x/crosschain/types/message_vote_outbound_test.go index f6439f80fc..31d44e8f81 100644 --- a/x/crosschain/types/message_vote_outbound_test.go +++ b/x/crosschain/types/message_vote_outbound_test.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" diff --git a/x/crosschain/types/message_whitelist_erc20.go b/x/crosschain/types/message_whitelist_erc20.go index 48987df470..a9a396e05f 100644 --- a/x/crosschain/types/message_whitelist_erc20.go +++ b/x/crosschain/types/message_whitelist_erc20.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/crosschain/types/message_whitelist_erc20_test.go b/x/crosschain/types/message_whitelist_erc20_test.go index d13016aef3..f881915ae8 100644 --- a/x/crosschain/types/message_whitelist_erc20_test.go +++ b/x/crosschain/types/message_whitelist_erc20_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" diff --git a/x/crosschain/types/outbound_params.go b/x/crosschain/types/outbound_params.go index 8ddf623337..466ef45756 100644 --- a/x/crosschain/types/outbound_params.go +++ b/x/crosschain/types/outbound_params.go @@ -5,6 +5,7 @@ import ( "strconv" "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/crosschain/types/outbound_params_test.go b/x/crosschain/types/outbound_params_test.go index 42c076dd6d..396a80ddcc 100644 --- a/x/crosschain/types/outbound_params_test.go +++ b/x/crosschain/types/outbound_params_test.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/crosschain/types/rate_limiter_flags.go b/x/crosschain/types/rate_limiter_flags.go index e5305bf8af..0d4310ddc8 100644 --- a/x/crosschain/types/rate_limiter_flags.go +++ b/x/crosschain/types/rate_limiter_flags.go @@ -7,6 +7,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + coin "github.com/zeta-chain/zetacore/pkg/coin" ) diff --git a/x/crosschain/types/rate_limiter_flags_test.go b/x/crosschain/types/rate_limiter_flags_test.go index 299489df19..5ed627be6b 100644 --- a/x/crosschain/types/rate_limiter_flags_test.go +++ b/x/crosschain/types/rate_limiter_flags_test.go @@ -9,6 +9,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/types/status.go b/x/crosschain/types/status.go index 33314b4f09..ded81edeec 100644 --- a/x/crosschain/types/status.go +++ b/x/crosschain/types/status.go @@ -21,7 +21,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..247cc19f50 100644 --- a/x/crosschain/types/status_test.go +++ b/x/crosschain/types/status_test.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/crosschain/types" ) @@ -33,33 +34,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 +161,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/tx_body_verification.go b/x/crosschain/types/tx_body_verification.go index c10e626e19..fbb8d4c6ea 100644 --- a/x/crosschain/types/tx_body_verification.go +++ b/x/crosschain/types/tx_body_verification.go @@ -8,6 +8,7 @@ import ( "github.com/btcsuite/btcutil" eth "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" observertypes "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/crosschain/types/tx_body_verification_test.go b/x/crosschain/types/tx_body_verification_test.go index 0b28183ae5..a51d56b8bc 100644 --- a/x/crosschain/types/tx_body_verification_test.go +++ b/x/crosschain/types/tx_body_verification_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/crosschain/types/validate.go b/x/crosschain/types/validate.go index fb83c0d1d6..46f36615f2 100644 --- a/x/crosschain/types/validate.go +++ b/x/crosschain/types/validate.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/crosschain/types/validate_test.go b/x/crosschain/types/validate_test.go index 3daf789442..d146d67817 100644 --- a/x/crosschain/types/validate_test.go +++ b/x/crosschain/types/validate_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -14,20 +15,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 +69,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..e063212471 100644 --- a/x/emissions/abci.go +++ b/x/emissions/abci.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/x/emissions/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" @@ -15,7 +16,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 +59,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 +84,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 +111,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..849174642a 100644 --- a/x/emissions/abci_test.go +++ b/x/emissions/abci_test.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -55,7 +56,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 +73,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 +195,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 +221,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 +245,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 +262,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 +291,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 +312,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 +333,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 +354,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 +377,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 +463,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/client/cli/query.go b/x/emissions/client/cli/query.go index bd2ed2b0bb..9ce7692962 100644 --- a/x/emissions/client/cli/query.go +++ b/x/emissions/client/cli/query.go @@ -2,14 +2,11 @@ package cli import ( "fmt" - // "strings" + "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" - "github.com/zeta-chain/zetacore/x/emissions/types" - "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/emissions/client/cli/query_get_emmisons_factors.go b/x/emissions/client/cli/query_get_emmisons_factors.go index 304f7760dc..c98ec7c6af 100644 --- a/x/emissions/client/cli/query_get_emmisons_factors.go +++ b/x/emissions/client/cli/query_get_emmisons_factors.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/client/cli/query_list_balances.go b/x/emissions/client/cli/query_list_balances.go index 83e4609fa2..3e40965d87 100644 --- a/x/emissions/client/cli/query_list_balances.go +++ b/x/emissions/client/cli/query_list_balances.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/client/cli/query_params.go b/x/emissions/client/cli/query_params.go index 82d3ef153a..b65f31c127 100644 --- a/x/emissions/client/cli/query_params.go +++ b/x/emissions/client/cli/query_params.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/client/cli/query_show_available_emissions.go b/x/emissions/client/cli/query_show_available_emissions.go index 6014656bcf..c7e17fe78e 100644 --- a/x/emissions/client/cli/query_show_available_emissions.go +++ b/x/emissions/client/cli/query_show_available_emissions.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/client/cli/tx.go b/x/emissions/client/cli/tx.go index 888a192327..46cf05a1f7 100644 --- a/x/emissions/client/cli/tx.go +++ b/x/emissions/client/cli/tx.go @@ -3,10 +3,10 @@ package cli import ( "fmt" + "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" - "github.com/zeta-chain/zetacore/x/emissions/types" - "github.com/cosmos/cosmos-sdk/client" + "github.com/zeta-chain/zetacore/x/emissions/types" ) // GetTxCmd returns the transaction commands for this module diff --git a/x/emissions/client/cli/tx_withdraw_emissions..go b/x/emissions/client/cli/tx_withdraw_emissions..go index fff24330dd..67295b71d0 100644 --- a/x/emissions/client/cli/tx_withdraw_emissions..go +++ b/x/emissions/client/cli/tx_withdraw_emissions..go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/genesis.go b/x/emissions/genesis.go index 81939d55bb..b477c24ee8 100644 --- a/x/emissions/genesis.go +++ b/x/emissions/genesis.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/genesis_test.go b/x/emissions/genesis_test.go index 1b14a60315..75f7c24038 100644 --- a/x/emissions/genesis_test.go +++ b/x/emissions/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/emissions/keeper/block_rewards_components.go b/x/emissions/keeper/block_rewards_components.go index e9786876a7..207fb73c90 100644 --- a/x/emissions/keeper/block_rewards_components.go +++ b/x/emissions/keeper/block_rewards_components.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/emissions/types" diff --git a/x/emissions/keeper/block_rewards_components_test.go b/x/emissions/keeper/block_rewards_components_test.go index 6f4acf004a..e256a8bb84 100644 --- a/x/emissions/keeper/block_rewards_components_test.go +++ b/x/emissions/keeper/block_rewards_components_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" emissionskeeper "github.com/zeta-chain/zetacore/x/emissions/keeper" diff --git a/x/emissions/keeper/grpc_query_get_emmisons_factors.go b/x/emissions/keeper/grpc_query_get_emmisons_factors.go index 5b265de52a..1959131a21 100644 --- a/x/emissions/keeper/grpc_query_get_emmisons_factors.go +++ b/x/emissions/keeper/grpc_query_get_emmisons_factors.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/emissions/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/emissions/types" ) -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..b0e832083e 100644 --- a/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go +++ b/x/emissions/keeper/grpc_query_get_emmisons_factors_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" ) @@ -27,7 +28,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..f1d9c42aaf 100644 --- a/x/emissions/keeper/grpc_query_list_balances.go +++ b/x/emissions/keeper/grpc_query_list_balances.go @@ -3,17 +3,23 @@ package keeper import ( "context" - "github.com/zeta-chain/zetacore/x/emissions/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/emissions/types" ) -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_list_balances_test.go b/x/emissions/keeper/grpc_query_list_balances_test.go index 40b24af023..5ec24f7c5e 100644 --- a/x/emissions/keeper/grpc_query_list_balances_test.go +++ b/x/emissions/keeper/grpc_query_list_balances_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/keeper/grpc_query_params.go b/x/emissions/keeper/grpc_query_params.go index 97f4a9077f..70c6de7f03 100644 --- a/x/emissions/keeper/grpc_query_params.go +++ b/x/emissions/keeper/grpc_query_params.go @@ -4,9 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/emissions/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/emissions/types" ) func (k Keeper) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { diff --git a/x/emissions/keeper/grpc_query_show_available_emissions.go b/x/emissions/keeper/grpc_query_show_available_emissions.go index 50b9d14dae..63b4c6a4eb 100644 --- a/x/emissions/keeper/grpc_query_show_available_emissions.go +++ b/x/emissions/keeper/grpc_query_show_available_emissions.go @@ -3,15 +3,18 @@ package keeper import ( "context" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" - "github.com/zeta-chain/zetacore/x/emissions/types" + sdk "github.com/cosmos/cosmos-sdk/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" + "github.com/zeta-chain/zetacore/x/emissions/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/grpc_query_show_available_emissions_test.go b/x/emissions/keeper/grpc_query_show_available_emissions_test.go index e5c900a61c..9d78079108 100644 --- a/x/emissions/keeper/grpc_query_show_available_emissions_test.go +++ b/x/emissions/keeper/grpc_query_show_available_emissions_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/emissions/keeper/keeper.go b/x/emissions/keeper/keeper.go index 14ffc42f6a..c066d47c78 100644 --- a/x/emissions/keeper/keeper.go +++ b/x/emissions/keeper/keeper.go @@ -4,12 +4,11 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - "github.com/zeta-chain/zetacore/x/emissions/types" - "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/zeta-chain/zetacore/x/emissions/types" ) type ( diff --git a/x/emissions/keeper/migrator.go b/x/emissions/keeper/migrator.go index bf40f54e31..b31327f54d 100644 --- a/x/emissions/keeper/migrator.go +++ b/x/emissions/keeper/migrator.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/exported" v3 "github.com/zeta-chain/zetacore/x/emissions/migrations/v3" ) diff --git a/x/emissions/keeper/msg_server_update_params.go b/x/emissions/keeper/msg_server_update_params.go index 9581a1b19f..8652e4bb20 100644 --- a/x/emissions/keeper/msg_server_update_params.go +++ b/x/emissions/keeper/msg_server_update_params.go @@ -6,14 +6,23 @@ import ( "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/zeta-chain/zetacore/x/emissions/types" ) // 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_update_params_test.go b/x/emissions/keeper/msg_server_update_params_test.go index ecf4376742..4500ceac90 100644 --- a/x/emissions/keeper/msg_server_update_params_test.go +++ b/x/emissions/keeper/msg_server_update_params_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/emissions/keeper" diff --git a/x/emissions/keeper/msg_server_withdraw_emissions.go b/x/emissions/keeper/msg_server_withdraw_emissions.go index 3bf40e1428..3b570ea81b 100644 --- a/x/emissions/keeper/msg_server_withdraw_emissions.go +++ b/x/emissions/keeper/msg_server_withdraw_emissions.go @@ -6,6 +6,7 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/x/emissions/types" ) @@ -14,7 +15,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 +29,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..44834b8700 100644 --- a/x/emissions/keeper/msg_server_withdraw_emissions_test.go +++ b/x/emissions/keeper/msg_server_withdraw_emissions_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -21,9 +22,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 +42,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 +58,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 +79,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 +117,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 +150,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 +165,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/keeper/params.go b/x/emissions/keeper/params.go index 2ba5a542a7..760f34cfba 100644 --- a/x/emissions/keeper/params.go +++ b/x/emissions/keeper/params.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/keeper/params_test.go b/x/emissions/keeper/params_test.go index 21e8b4c2df..6e4bf4cb6e 100644 --- a/x/emissions/keeper/params_test.go +++ b/x/emissions/keeper/params_test.go @@ -5,6 +5,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/keeper/withdrawable_emissions.go b/x/emissions/keeper/withdrawable_emissions.go index 40b627f654..e4edf60298 100644 --- a/x/emissions/keeper/withdrawable_emissions.go +++ b/x/emissions/keeper/withdrawable_emissions.go @@ -4,6 +4,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/keeper/withdrawable_emissions_test.go b/x/emissions/keeper/withdrawable_emissions_test.go index c7ab7667f9..a9b7d3d5dd 100644 --- a/x/emissions/keeper/withdrawable_emissions_test.go +++ b/x/emissions/keeper/withdrawable_emissions_test.go @@ -5,6 +5,7 @@ import ( sdkmath "cosmossdk.io/math" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" diff --git a/x/emissions/migrations/v3/migrate.go b/x/emissions/migrations/v3/migrate.go index 4ba1da387d..17061abfed 100644 --- a/x/emissions/migrations/v3/migrate.go +++ b/x/emissions/migrations/v3/migrate.go @@ -2,6 +2,7 @@ package v3 import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/emissions/exported" "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/migrations/v3/migrate_test.go b/x/emissions/migrations/v3/migrate_test.go index e074928997..50c1ecd5d9 100644 --- a/x/emissions/migrations/v3/migrate_test.go +++ b/x/emissions/migrations/v3/migrate_test.go @@ -3,10 +3,10 @@ package v3_test import ( "testing" - "github.com/stretchr/testify/require" - sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/emissions/exported" v3 "github.com/zeta-chain/zetacore/x/emissions/migrations/v3" diff --git a/x/emissions/module.go b/x/emissions/module.go index 6d8375f7ec..48a7a70749 100644 --- a/x/emissions/module.go +++ b/x/emissions/module.go @@ -5,21 +5,20 @@ import ( "encoding/json" "fmt" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/emissions/client/cli" "github.com/zeta-chain/zetacore/x/emissions/exported" "github.com/zeta-chain/zetacore/x/emissions/keeper" "github.com/zeta-chain/zetacore/x/emissions/types" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" ) var ( diff --git a/x/emissions/types/distributions_test.go b/x/emissions/types/distributions_test.go index 76d2534583..5039d35082 100644 --- a/x/emissions/types/distributions_test.go +++ b/x/emissions/types/distributions_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/emissions/types" ) 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..7639bec2fc 100644 --- a/x/emissions/types/expected_keepers.go +++ b/x/emissions/types/expected_keepers.go @@ -3,6 +3,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -20,7 +21,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/genesis_test.go b/x/emissions/types/genesis_test.go index 8a3ecd6795..42cfd14a06 100644 --- a/x/emissions/types/genesis_test.go +++ b/x/emissions/types/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/types/message_update_params_test.go b/x/emissions/types/message_update_params_test.go index 734cd14039..65a594b61a 100644 --- a/x/emissions/types/message_update_params_test.go +++ b/x/emissions/types/message_update_params_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/types/message_withdraw_emissons_test.go b/x/emissions/types/message_withdraw_emissons_test.go index d375d6fe94..f5e529e694 100644 --- a/x/emissions/types/message_withdraw_emissons_test.go +++ b/x/emissions/types/message_withdraw_emissons_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" emissionstypes "github.com/zeta-chain/zetacore/x/emissions/types" ) diff --git a/x/emissions/types/params_legacy.go b/x/emissions/types/params_legacy.go index a98cab6047..09565233a5 100644 --- a/x/emissions/types/params_legacy.go +++ b/x/emissions/types/params_legacy.go @@ -21,9 +21,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.go b/x/fungible/client/cli/query.go index e5f0033532..eeb4104d52 100644 --- a/x/fungible/client/cli/query.go +++ b/x/fungible/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/query_code_hash.go b/x/fungible/client/cli/query_code_hash.go index 460fd7a414..94d3cd61c7 100644 --- a/x/fungible/client/cli/query_code_hash.go +++ b/x/fungible/client/cli/query_code_hash.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/query_foreign_coins.go b/x/fungible/client/cli/query_foreign_coins.go index e115fbd65b..ba57fa58b0 100644 --- a/x/fungible/client/cli/query_foreign_coins.go +++ b/x/fungible/client/cli/query_foreign_coins.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/query_gas_stability_pool.go b/x/fungible/client/cli/query_gas_stability_pool.go index 516353daae..6d037da809 100644 --- a/x/fungible/client/cli/query_gas_stability_pool.go +++ b/x/fungible/client/cli/query_gas_stability_pool.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -20,7 +21,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 +83,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/client/cli/query_system_contract.go b/x/fungible/client/cli/query_system_contract.go index f4fe29cc59..b4e8f69023 100644 --- a/x/fungible/client/cli/query_system_contract.go +++ b/x/fungible/client/cli/query_system_contract.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx.go b/x/fungible/client/cli/tx.go index e321ea4866..5830233c37 100644 --- a/x/fungible/client/cli/tx.go +++ b/x/fungible/client/cli/tx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go b/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go index 703b57fd1e..9274d2c537 100644 --- a/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go +++ b/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go @@ -3,12 +3,12 @@ package cli import ( "strconv" - "github.com/zeta-chain/zetacore/pkg/coin" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_deploy_system_contracts.go b/x/fungible/client/cli/tx_deploy_system_contracts.go index c57e68f65e..c31a19c888 100644 --- a/x/fungible/client/cli/tx_deploy_system_contracts.go +++ b/x/fungible/client/cli/tx_deploy_system_contracts.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_remove_foreign_coin.go b/x/fungible/client/cli/tx_remove_foreign_coin.go index 29fdc3612e..c2b20e3947 100644 --- a/x/fungible/client/cli/tx_remove_foreign_coin.go +++ b/x/fungible/client/cli/tx_remove_foreign_coin.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_update_contract_bytecode.go b/x/fungible/client/cli/tx_update_contract_bytecode.go index a03116dc5a..334cd12a68 100644 --- a/x/fungible/client/cli/tx_update_contract_bytecode.go +++ b/x/fungible/client/cli/tx_update_contract_bytecode.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_update_system_contract.go b/x/fungible/client/cli/tx_update_system_contract.go index 63f367c402..4e4e9ea4f1 100644 --- a/x/fungible/client/cli/tx_update_system_contract.go +++ b/x/fungible/client/cli/tx_update_system_contract.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_update_zrc20_liquidity_cap.go b/x/fungible/client/cli/tx_update_zrc20_liquidity_cap.go index 4c84c38527..1524dbd0be 100644 --- a/x/fungible/client/cli/tx_update_zrc20_liquidity_cap.go +++ b/x/fungible/client/cli/tx_update_zrc20_liquidity_cap.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_update_zrc20_paused_status.go b/x/fungible/client/cli/tx_update_zrc20_paused_status.go index cb29f3cdcf..3c0b498d5a 100644 --- a/x/fungible/client/cli/tx_update_zrc20_paused_status.go +++ b/x/fungible/client/cli/tx_update_zrc20_paused_status.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/client/cli/tx_update_zrc20_withdraw_fee.go b/x/fungible/client/cli/tx_update_zrc20_withdraw_fee.go index 647ff6419e..693eafc3ca 100644 --- a/x/fungible/client/cli/tx_update_zrc20_withdraw_fee.go +++ b/x/fungible/client/cli/tx_update_zrc20_withdraw_fee.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/genesis.go b/x/fungible/genesis.go index 4f19c7cebd..ba8a3d0153 100644 --- a/x/fungible/genesis.go +++ b/x/fungible/genesis.go @@ -2,6 +2,7 @@ package fungible import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/genesis_test.go b/x/fungible/genesis_test.go index ba57014f6b..5fd1dfc408 100644 --- a/x/fungible/genesis_test.go +++ b/x/fungible/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/fungible/keeper/deposits.go b/x/fungible/keeper/deposits.go index 695386fd01..4af00de688 100644 --- a/x/fungible/keeper/deposits.go +++ b/x/fungible/keeper/deposits.go @@ -7,6 +7,7 @@ import ( eth "github.com/ethereum/go-ethereum/common" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/keeper/deposits_test.go b/x/fungible/keeper/deposits_test.go index 0e6f245173..e394053edd 100644 --- a/x/fungible/keeper/deposits_test.go +++ b/x/fungible/keeper/deposits_test.go @@ -9,6 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index c4ab0d81de..bb7a037c07 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -26,6 +26,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-core/contracts/uniswapv2factory.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/server/config" @@ -42,7 +43,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 +57,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 +70,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 +135,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 +156,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 +188,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 +659,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_hooks.go b/x/fungible/keeper/evm_hooks.go index 4e3894290c..a171adb3e4 100644 --- a/x/fungible/keeper/evm_hooks.go +++ b/x/fungible/keeper/evm_hooks.go @@ -7,6 +7,7 @@ import ( "github.com/ethereum/go-ethereum/core" ethtypes "github.com/ethereum/go-ethereum/core/types" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/evm_hooks_test.go b/x/fungible/keeper/evm_hooks_test.go index 70bc486c0d..83e96d9aea 100644 --- a/x/fungible/keeper/evm_hooks_test.go +++ b/x/fungible/keeper/evm_hooks_test.go @@ -5,6 +5,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/keeper/evm_test.go b/x/fungible/keeper/evm_test.go index 8e2bc2f005..a175943247 100644 --- a/x/fungible/keeper/evm_test.go +++ b/x/fungible/keeper/evm_test.go @@ -15,6 +15,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/wzeta.sol" zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/server/config" @@ -301,7 +302,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 +394,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 +1353,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 +1438,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/foreign_coins.go b/x/fungible/keeper/foreign_coins.go index 5c52eb543e..b86d6d4841 100644 --- a/x/fungible/keeper/foreign_coins.go +++ b/x/fungible/keeper/foreign_coins.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/foreign_coins_test.go b/x/fungible/keeper/foreign_coins_test.go index f3a6f6dacd..5b5ef5caed 100644 --- a/x/fungible/keeper/foreign_coins_test.go +++ b/x/fungible/keeper/foreign_coins_test.go @@ -6,12 +6,12 @@ import ( "testing" "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" - - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/gas_coin_and_pool.go b/x/fungible/keeper/gas_coin_and_pool.go index 60cc436965..1ee7ece40c 100644 --- a/x/fungible/keeper/gas_coin_and_pool.go +++ b/x/fungible/keeper/gas_coin_and_pool.go @@ -10,6 +10,7 @@ import ( systemcontract "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" uniswapv2router02 "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -49,7 +50,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 +81,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 +136,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 +166,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_coin_and_pool_test.go b/x/fungible/keeper/gas_coin_and_pool_test.go index 9ee6a9d17f..0d76945c0f 100644 --- a/x/fungible/keeper/gas_coin_and_pool_test.go +++ b/x/fungible/keeper/gas_coin_and_pool_test.go @@ -6,15 +6,15 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/ethereum/go-ethereum/common" evmkeeper "github.com/evmos/ethermint/x/evm/keeper" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" uniswapv2router02 "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/fungible/keeper/gas_price.go b/x/fungible/keeper/gas_price.go index 636cffeec9..bc28f777f8 100644 --- a/x/fungible/keeper/gas_price.go +++ b/x/fungible/keeper/gas_price.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" systemcontract "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" + "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -27,7 +28,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 +64,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 +100,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..ae79e105e7 100644 --- a/x/fungible/keeper/gas_price_test.go +++ b/x/fungible/keeper/gas_price_test.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/keeper" @@ -22,7 +23,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 +148,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/gas_stability_pool.go b/x/fungible/keeper/gas_stability_pool.go index 5bbdfc4e9e..3e2a341d8b 100644 --- a/x/fungible/keeper/gas_stability_pool.go +++ b/x/fungible/keeper/gas_stability_pool.go @@ -4,6 +4,7 @@ import ( "math/big" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/gas_stability_pool_test.go b/x/fungible/keeper/gas_stability_pool_test.go index d05e9aee19..f72a344343 100644 --- a/x/fungible/keeper/gas_stability_pool_test.go +++ b/x/fungible/keeper/gas_stability_pool_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/grpc_query_code_hash.go b/x/fungible/keeper/grpc_query_code_hash.go index 78fa60e3be..cd80e49e79 100644 --- a/x/fungible/keeper/grpc_query_code_hash.go +++ b/x/fungible/keeper/grpc_query_code_hash.go @@ -5,10 +5,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcommon "github.com/ethereum/go-ethereum/common" - - "github.com/zeta-chain/zetacore/x/fungible/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/fungible/types" ) // CodeHash returns the code hash of an account if it exists diff --git a/x/fungible/keeper/grpc_query_code_hash_test.go b/x/fungible/keeper/grpc_query_code_hash_test.go index 5a31f5c736..7ef7ceaa25 100644 --- a/x/fungible/keeper/grpc_query_code_hash_test.go +++ b/x/fungible/keeper/grpc_query_code_hash_test.go @@ -5,6 +5,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/keeper/grpc_query_foreign_coins.go b/x/fungible/keeper/grpc_query_foreign_coins.go index 20c661d7d1..827ff5a9be 100644 --- a/x/fungible/keeper/grpc_query_foreign_coins.go +++ b/x/fungible/keeper/grpc_query_foreign_coins.go @@ -6,12 +6,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/fungible/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/fungible/types" ) -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 +43,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_gas_stability_pool.go b/x/fungible/keeper/grpc_query_gas_stability_pool.go index 770c58a10e..321fdb7e5b 100644 --- a/x/fungible/keeper/grpc_query_gas_stability_pool.go +++ b/x/fungible/keeper/grpc_query_gas_stability_pool.go @@ -4,9 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/fungible/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/fungible/types" ) func (k Keeper) GasStabilityPoolAddress( diff --git a/x/fungible/keeper/grpc_query_gas_stability_pool_test.go b/x/fungible/keeper/grpc_query_gas_stability_pool_test.go index 7dfe91d530..f503c76698 100644 --- a/x/fungible/keeper/grpc_query_gas_stability_pool_test.go +++ b/x/fungible/keeper/grpc_query_gas_stability_pool_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/keeper/grpc_query_system_contract.go b/x/fungible/keeper/grpc_query_system_contract.go index f753a57ed4..03a548d7d4 100644 --- a/x/fungible/keeper/grpc_query_system_contract.go +++ b/x/fungible/keeper/grpc_query_system_contract.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/fungible/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/fungible/types" ) -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/grpc_query_system_contract_test.go b/x/fungible/keeper/grpc_query_system_contract_test.go index 849e2c87de..78411a9584 100644 --- a/x/fungible/keeper/grpc_query_system_contract_test.go +++ b/x/fungible/keeper/grpc_query_system_contract_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/keeper/keeper.go b/x/fungible/keeper/keeper.go index b441e16971..15d0575ead 100644 --- a/x/fungible/keeper/keeper.go +++ b/x/fungible/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/fungible/types" ) 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..8792817fb7 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go @@ -7,6 +7,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/coin" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -30,7 +31,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 +45,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_fungible_coin_zrc20_test.go b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20_test.go index 7f599895a8..2bc23b7c32 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20_test.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20_test.go @@ -7,6 +7,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/fungible/keeper/msg_server_deploy_system_contract.go b/x/fungible/keeper/msg_server_deploy_system_contract.go index 2b504ee524..68814a4c6b 100644 --- a/x/fungible/keeper/msg_server_deploy_system_contract.go +++ b/x/fungible/keeper/msg_server_deploy_system_contract.go @@ -5,6 +5,7 @@ import ( cosmoserror "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -12,11 +13,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_deploy_system_contract_test.go b/x/fungible/keeper/msg_server_deploy_system_contract_test.go index 06cb2d29cd..6b11c46592 100644 --- a/x/fungible/keeper/msg_server_deploy_system_contract_test.go +++ b/x/fungible/keeper/msg_server_deploy_system_contract_test.go @@ -9,6 +9,7 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/fungible/keeper/msg_server_remove_foreign_coin.go b/x/fungible/keeper/msg_server_remove_foreign_coin.go index 5cf4617110..3f46997e3d 100644 --- a/x/fungible/keeper/msg_server_remove_foreign_coin.go +++ b/x/fungible/keeper/msg_server_remove_foreign_coin.go @@ -6,6 +6,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -14,10 +15,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_remove_foreign_coin_test.go b/x/fungible/keeper/msg_server_remove_foreign_coin_test.go index 60abc77647..fafb01b597 100644 --- a/x/fungible/keeper/msg_server_remove_foreign_coin_test.go +++ b/x/fungible/keeper/msg_server_remove_foreign_coin_test.go @@ -5,6 +5,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" 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..e519ea509b 100644 --- a/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go +++ b/x/fungible/keeper/msg_server_udpate_zrc20_liquidity_cap.go @@ -5,6 +5,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -12,12 +13,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..416ba3115e 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 @@ -3,12 +3,12 @@ package keeper_test import ( "testing" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - "cosmossdk.io/math" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -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..2bbb24e7f3 100644 --- a/x/fungible/keeper/msg_server_update_contract_bytecode.go +++ b/x/fungible/keeper/msg_server_update_contract_bytecode.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -18,12 +19,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 +53,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_contract_bytecode_test.go b/x/fungible/keeper/msg_server_update_contract_bytecode_test.go index f2ae02c435..18d095493a 100644 --- a/x/fungible/keeper/msg_server_update_contract_bytecode_test.go +++ b/x/fungible/keeper/msg_server_update_contract_bytecode_test.go @@ -11,6 +11,7 @@ import ( "github.com/evmos/ethermint/x/evm/statedb" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" diff --git a/x/fungible/keeper/msg_server_update_system_contract.go b/x/fungible/keeper/msg_server_update_system_contract.go index 1d8344125c..411a2c07a0 100644 --- a/x/fungible/keeper/msg_server_update_system_contract.go +++ b/x/fungible/keeper/msg_server_update_system_contract.go @@ -10,20 +10,31 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "github.com/zeta-chain/zetacore/pkg/coin" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) // 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 +54,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..9849ae6523 100644 --- a/x/fungible/keeper/msg_server_update_system_contract_test.go +++ b/x/fungible/keeper/msg_server_update_system_contract_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/systemcontract.sol" zrc20 "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -34,7 +35,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..a8a17fe585 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_paused_status.go +++ b/x/fungible/keeper/msg_server_update_zrc20_paused_status.go @@ -3,11 +3,10 @@ package keeper import ( "context" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - cosmoserrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -33,7 +32,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..588361ce5a 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 @@ -5,6 +5,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" @@ -34,7 +35,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..67d4821836 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee.go @@ -7,27 +7,42 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/fungible/types" ) // 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 +60,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/msg_server_update_zrc20_withdraw_fee_test.go b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go index bef609a10e..2d6c9a95a3 100644 --- a/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go +++ b/x/fungible/keeper/msg_server_update_zrc20_withdraw_fee_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index 822bccf766..656593238d 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -12,6 +12,7 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/wzeta.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/zevm/zrc20.sol" "github.com/zeta-chain/protocol-contracts/pkg/uniswap/v2-periphery/contracts/uniswapv2router02.sol" + "github.com/zeta-chain/zetacore/x/fungible/types" ) @@ -48,7 +49,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 +62,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 +85,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 +113,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 +136,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 +167,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 +190,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 +289,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 +313,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 +325,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 +385,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 +447,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 +503,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 +558,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 +574,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 +609,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 +624,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 +669,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..4bbb957562 100644 --- a/x/fungible/keeper/system_contract_test.go +++ b/x/fungible/keeper/system_contract_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" @@ -114,14 +115,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 +405,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 +515,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 +839,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 +874,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 +992,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 +1011,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 +1030,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 +1067,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 +1090,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/zeta.go b/x/fungible/keeper/zeta.go index 33f3d81486..7dfde65ca7 100644 --- a/x/fungible/keeper/zeta.go +++ b/x/fungible/keeper/zeta.go @@ -4,6 +4,7 @@ import ( "math/big" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/keeper/zeta_test.go b/x/fungible/keeper/zeta_test.go index cec34d06ea..d315690df9 100644 --- a/x/fungible/keeper/zeta_test.go +++ b/x/fungible/keeper/zeta_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" testkeeper "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/fungible/keeper/zevm_message_passing_test.go b/x/fungible/keeper/zevm_message_passing_test.go index fe03808e81..5a450968be 100644 --- a/x/fungible/keeper/zevm_message_passing_test.go +++ b/x/fungible/keeper/zevm_message_passing_test.go @@ -10,6 +10,7 @@ import ( "github.com/evmos/ethermint/x/evm/statedb" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/testutil/contracts" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -34,7 +35,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 +87,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 +112,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 +148,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 +179,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 +233,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 +260,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 +298,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 +327,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/module.go b/x/fungible/module.go index 7b3d846092..b79481a9a2 100644 --- a/x/fungible/module.go +++ b/x/fungible/module.go @@ -5,17 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/fungible/client/cli" "github.com/zeta-chain/zetacore/x/fungible/keeper" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/module_simulation.go b/x/fungible/module_simulation.go index 30228431f1..a55870a742 100644 --- a/x/fungible/module_simulation.go +++ b/x/fungible/module_simulation.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/evm_test.go b/x/fungible/types/evm_test.go index 0be4d916da..aa4a402900 100644 --- a/x/fungible/types/evm_test.go +++ b/x/fungible/types/evm_test.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/core/vm" evmtypes "github.com/evmos/ethermint/x/evm/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/expected_keepers.go b/x/fungible/types/expected_keepers.go index f1064b0476..514e7867f3 100644 --- a/x/fungible/types/expected_keepers.go +++ b/x/fungible/types/expected_keepers.go @@ -11,6 +11,7 @@ import ( "github.com/ethereum/go-ethereum/core/vm" "github.com/evmos/ethermint/x/evm/statedb" evmtypes "github.com/evmos/ethermint/x/evm/types" + "github.com/zeta-chain/zetacore/pkg/chains" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" ) @@ -26,7 +27,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/gas_stablity_pool_test.go b/x/fungible/types/gas_stablity_pool_test.go index c0ec0000f5..6b3e0dcdac 100644 --- a/x/fungible/types/gas_stablity_pool_test.go +++ b/x/fungible/types/gas_stablity_pool_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/genesis_test.go b/x/fungible/types/genesis_test.go index 57927528af..9113eb1a6b 100644 --- a/x/fungible/types/genesis_test.go +++ b/x/fungible/types/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/message_deploy_fungible_coin_zrc20.go b/x/fungible/types/message_deploy_fungible_coin_zrc20.go index 6103b6ef35..6d7b06a8fa 100644 --- a/x/fungible/types/message_deploy_fungible_coin_zrc20.go +++ b/x/fungible/types/message_deploy_fungible_coin_zrc20.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/coin" ) @@ -11,7 +12,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_deploy_fungible_coin_zrc20_test.go b/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go index 99b7ea9886..8b69f28b98 100644 --- a/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go +++ b/x/fungible/types/message_deploy_fungible_coin_zrc20_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" diff --git a/x/fungible/types/message_deploy_system_contracts_test.go b/x/fungible/types/message_deploy_system_contracts_test.go index 5040db4345..3bf1b44dcc 100644 --- a/x/fungible/types/message_deploy_system_contracts_test.go +++ b/x/fungible/types/message_deploy_system_contracts_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/message_remove_foreign_coin_test.go b/x/fungible/types/message_remove_foreign_coin_test.go index ae5c811c21..5c26ecf519 100644 --- a/x/fungible/types/message_remove_foreign_coin_test.go +++ b/x/fungible/types/message_remove_foreign_coin_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/message_update_contract_bytecode.go b/x/fungible/types/message_update_contract_bytecode.go index 212526b558..6ec0c1592a 100644 --- a/x/fungible/types/message_update_contract_bytecode.go +++ b/x/fungible/types/message_update_contract_bytecode.go @@ -2,7 +2,6 @@ package types import ( cosmoserror "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" diff --git a/x/fungible/types/message_update_contract_bytecode_test.go b/x/fungible/types/message_update_contract_bytecode_test.go index cb8f3ab65e..4555d20a5e 100644 --- a/x/fungible/types/message_update_contract_bytecode_test.go +++ b/x/fungible/types/message_update_contract_bytecode_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) 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_system_contract_test.go b/x/fungible/types/message_update_system_contract_test.go index 7ffe048f47..b8d6e089e2 100644 --- a/x/fungible/types/message_update_system_contract_test.go +++ b/x/fungible/types/message_update_system_contract_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/message_update_zrc20_liquidity_cap_test.go b/x/fungible/types/message_update_zrc20_liquidity_cap_test.go index f509fa65f9..c072a96472 100644 --- a/x/fungible/types/message_update_zrc20_liquidity_cap_test.go +++ b/x/fungible/types/message_update_zrc20_liquidity_cap_test.go @@ -4,10 +4,10 @@ import ( "testing" "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) 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_paused_status_test.go b/x/fungible/types/message_update_zrc20_paused_status_test.go index f70d0d81d2..691585711f 100644 --- a/x/fungible/types/message_update_zrc20_paused_status_test.go +++ b/x/fungible/types/message_update_zrc20_paused_status_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/message_update_zrc20_withdraw_fee.go b/x/fungible/types/message_update_zrc20_withdraw_fee.go index fb2b98955c..c3d163f753 100644 --- a/x/fungible/types/message_update_zrc20_withdraw_fee.go +++ b/x/fungible/types/message_update_zrc20_withdraw_fee.go @@ -3,7 +3,6 @@ package types import ( cosmoserror "cosmossdk.io/errors" math "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethcommon "github.com/ethereum/go-ethereum/common" @@ -13,7 +12,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/fungible/types/message_update_zrc20_withdraw_fee_test.go b/x/fungible/types/message_update_zrc20_withdraw_fee_test.go index 21e6fb7fcd..b9b660df1f 100644 --- a/x/fungible/types/message_update_zrc20_withdraw_fee_test.go +++ b/x/fungible/types/message_update_zrc20_withdraw_fee_test.go @@ -4,10 +4,10 @@ import ( "testing" math "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/fungible/types/zrc20_test.go b/x/fungible/types/zrc20_test.go index fcb248753f..ca74e8c6ad 100644 --- a/x/fungible/types/zrc20_test.go +++ b/x/fungible/types/zrc20_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/fungible/types" ) diff --git a/x/ibccrosschain/client/cli/query.go b/x/ibccrosschain/client/cli/query.go index 9d4b18dacb..1c8e81aec9 100644 --- a/x/ibccrosschain/client/cli/query.go +++ b/x/ibccrosschain/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/ibccrosschain/types" ) diff --git a/x/ibccrosschain/client/cli/tx.go b/x/ibccrosschain/client/cli/tx.go index a5c78a32be..cc92e0ea95 100644 --- a/x/ibccrosschain/client/cli/tx.go +++ b/x/ibccrosschain/client/cli/tx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/ibccrosschain/types" ) diff --git a/x/ibccrosschain/genesis.go b/x/ibccrosschain/genesis.go index 71f979b90a..9f32a2e2de 100644 --- a/x/ibccrosschain/genesis.go +++ b/x/ibccrosschain/genesis.go @@ -2,6 +2,7 @@ package ibccrosschain import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/ibccrosschain/keeper" "github.com/zeta-chain/zetacore/x/ibccrosschain/types" ) diff --git a/x/ibccrosschain/ibc_module.go b/x/ibccrosschain/ibc_module.go index e78d7d61ae..b745e2910f 100644 --- a/x/ibccrosschain/ibc_module.go +++ b/x/ibccrosschain/ibc_module.go @@ -6,6 +6,7 @@ import ( channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + "github.com/zeta-chain/zetacore/x/ibccrosschain/keeper" ) diff --git a/x/ibccrosschain/keeper/keeper.go b/x/ibccrosschain/keeper/keeper.go index f800792634..1e7f567b49 100644 --- a/x/ibccrosschain/keeper/keeper.go +++ b/x/ibccrosschain/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/ibccrosschain/types" ) diff --git a/x/ibccrosschain/module.go b/x/ibccrosschain/module.go index a6803e3c94..acc7be0423 100644 --- a/x/ibccrosschain/module.go +++ b/x/ibccrosschain/module.go @@ -13,6 +13,7 @@ import ( "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/ibccrosschain/client/cli" "github.com/zeta-chain/zetacore/x/ibccrosschain/keeper" "github.com/zeta-chain/zetacore/x/ibccrosschain/types" diff --git a/x/lightclient/client/cli/query.go b/x/lightclient/client/cli/query.go index 70fb5ff65a..b0fe0e7f38 100644 --- a/x/lightclient/client/cli/query.go +++ b/x/lightclient/client/cli/query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/query_block_header.go b/x/lightclient/client/cli/query_block_header.go index 99b54fbdfc..16281c4d05 100644 --- a/x/lightclient/client/cli/query_block_header.go +++ b/x/lightclient/client/cli/query_block_header.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/query_chain_state.go b/x/lightclient/client/cli/query_chain_state.go index 672152c737..283b699fe2 100644 --- a/x/lightclient/client/cli/query_chain_state.go +++ b/x/lightclient/client/cli/query_chain_state.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/query_verification_flags.go b/x/lightclient/client/cli/query_verification_flags.go index 168ba4acbb..112aac151e 100644 --- a/x/lightclient/client/cli/query_verification_flags.go +++ b/x/lightclient/client/cli/query_verification_flags.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/tx.go b/x/lightclient/client/cli/tx.go index 5d73dfa500..41dbb09c56 100644 --- a/x/lightclient/client/cli/tx.go +++ b/x/lightclient/client/cli/tx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/tx_disable_verification_flags.go b/x/lightclient/client/cli/tx_disable_verification_flags.go index 3d3a92dcba..4d86dee552 100644 --- a/x/lightclient/client/cli/tx_disable_verification_flags.go +++ b/x/lightclient/client/cli/tx_disable_verification_flags.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/client/cli/tx_enable_verification_flags.go b/x/lightclient/client/cli/tx_enable_verification_flags.go index 518b9030f2..cf896fd2be 100644 --- a/x/lightclient/client/cli/tx_enable_verification_flags.go +++ b/x/lightclient/client/cli/tx_enable_verification_flags.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/genesis.go b/x/lightclient/genesis.go index 6df4bc8ae6..13742d9281 100644 --- a/x/lightclient/genesis.go +++ b/x/lightclient/genesis.go @@ -2,6 +2,7 @@ package lightclient import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/lightclient/keeper" "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/genesis_test.go b/x/lightclient/genesis_test.go index 0c7a08c97a..6613701a8d 100644 --- a/x/lightclient/genesis_test.go +++ b/x/lightclient/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -54,6 +55,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.go b/x/lightclient/keeper/block_header.go index be8c6fabff..4e4cc6089e 100644 --- a/x/lightclient/keeper/block_header.go +++ b/x/lightclient/keeper/block_header.go @@ -6,6 +6,7 @@ import ( cosmoserrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/proofs" "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/keeper/block_header_test.go b/x/lightclient/keeper/block_header_test.go index 8d610e621f..756e4a4514 100644 --- a/x/lightclient/keeper/block_header_test.go +++ b/x/lightclient/keeper/block_header_test.go @@ -8,6 +8,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -325,43 +326,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.go b/x/lightclient/keeper/block_header_verification.go index 5455b672b8..c06609a0d0 100644 --- a/x/lightclient/keeper/block_header_verification.go +++ b/x/lightclient/keeper/block_header_verification.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/keeper/block_header_verification_test.go b/x/lightclient/keeper/block_header_verification_test.go index 0a5e29eb6a..6bdc608540 100644 --- a/x/lightclient/keeper/block_header_verification_test.go +++ b/x/lightclient/keeper/block_header_verification_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" @@ -52,7 +53,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 +77,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 +112,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/chain_state.go b/x/lightclient/keeper/chain_state.go index 9803f1d927..2e439a0657 100644 --- a/x/lightclient/keeper/chain_state.go +++ b/x/lightclient/keeper/chain_state.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/keeper/chain_state_test.go b/x/lightclient/keeper/chain_state_test.go index 73c1b2f098..4ad91e167a 100644 --- a/x/lightclient/keeper/chain_state_test.go +++ b/x/lightclient/keeper/chain_state_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/lightclient/keeper/grpc_query_block_header.go b/x/lightclient/keeper/grpc_query_block_header.go index a17b4ef9d7..2f4a1945ef 100644 --- a/x/lightclient/keeper/grpc_query_block_header.go +++ b/x/lightclient/keeper/grpc_query_block_header.go @@ -4,15 +4,19 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/pkg/proofs" - "github.com/zeta-chain/zetacore/x/lightclient/types" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/pkg/proofs" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) // 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 +41,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_block_header_test.go b/x/lightclient/keeper/grpc_query_block_header_test.go index 8be62d2d75..0ccc6b81ce 100644 --- a/x/lightclient/keeper/grpc_query_block_header_test.go +++ b/x/lightclient/keeper/grpc_query_block_header_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" diff --git a/x/lightclient/keeper/grpc_query_chain_state.go b/x/lightclient/keeper/grpc_query_chain_state.go index bc428bd91c..1c648a5b2a 100644 --- a/x/lightclient/keeper/grpc_query_chain_state.go +++ b/x/lightclient/keeper/grpc_query_chain_state.go @@ -7,13 +7,17 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/lightclient/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/lightclient/types" ) // 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 +42,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_chain_state_test.go b/x/lightclient/keeper/grpc_query_chain_state_test.go index e8e9fe175e..542cf0d8aa 100644 --- a/x/lightclient/keeper/grpc_query_chain_state_test.go +++ b/x/lightclient/keeper/grpc_query_chain_state_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/lightclient/keeper/grpc_query_header_enabled_chains.go b/x/lightclient/keeper/grpc_query_header_enabled_chains.go index 39d5886b4c..8a9700cc03 100644 --- a/x/lightclient/keeper/grpc_query_header_enabled_chains.go +++ b/x/lightclient/keeper/grpc_query_header_enabled_chains.go @@ -4,15 +4,19 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/lightclient/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/lightclient/types" ) // 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 +24,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 +34,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 +45,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_header_enabled_chains_test.go b/x/lightclient/keeper/grpc_query_header_enabled_chains_test.go index 3f9f0e30a0..6747510fb3 100644 --- a/x/lightclient/keeper/grpc_query_header_enabled_chains_test.go +++ b/x/lightclient/keeper/grpc_query_header_enabled_chains_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/lightclient/types" diff --git a/x/lightclient/keeper/grpc_query_prove.go b/x/lightclient/keeper/grpc_query_prove.go index 7fbbc8bf3c..4a2017c65b 100644 --- a/x/lightclient/keeper/grpc_query_prove.go +++ b/x/lightclient/keeper/grpc_query_prove.go @@ -7,11 +7,12 @@ import ( "github.com/btcsuite/btcutil" sdk "github.com/cosmos/cosmos-sdk/types" ethtypes "github.com/ethereum/go-ethereum/core/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" "github.com/zeta-chain/zetacore/x/lightclient/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) // Prove checks two things: @@ -46,7 +47,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/grpc_query_prove_test.go b/x/lightclient/keeper/grpc_query_prove_test.go index 34ca1b7f28..5cbc78befd 100644 --- a/x/lightclient/keeper/grpc_query_prove_test.go +++ b/x/lightclient/keeper/grpc_query_prove_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/lightclient/keeper/keeper.go b/x/lightclient/keeper/keeper.go index df55f61157..c37b0be358 100644 --- a/x/lightclient/keeper/keeper.go +++ b/x/lightclient/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/keeper/msg_server_disable_block_header_verification._test.go b/x/lightclient/keeper/msg_server_disable_block_header_verification._test.go index 122de250f2..d4aca8a708 100644 --- a/x/lightclient/keeper/msg_server_disable_block_header_verification._test.go +++ b/x/lightclient/keeper/msg_server_disable_block_header_verification._test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" 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..023bc17515 100644 --- a/x/lightclient/keeper/msg_server_disable_block_header_verification.go +++ b/x/lightclient/keeper/msg_server_disable_block_header_verification.go @@ -4,13 +4,17 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/lightclient/types" ) // 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/msg_server_enable_block_header_verification.go b/x/lightclient/keeper/msg_server_enable_block_header_verification.go index a4653cd4b5..84b3ff3a69 100644 --- a/x/lightclient/keeper/msg_server_enable_block_header_verification.go +++ b/x/lightclient/keeper/msg_server_enable_block_header_verification.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/keeper/msg_server_enable_block_header_verification_test.go b/x/lightclient/keeper/msg_server_enable_block_header_verification_test.go index 87d21cf211..90cd4d0974 100644 --- a/x/lightclient/keeper/msg_server_enable_block_header_verification_test.go +++ b/x/lightclient/keeper/msg_server_enable_block_header_verification_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/lightclient/keeper/proof.go b/x/lightclient/keeper/proof.go index 8b84cd7977..7067ab3ac1 100644 --- a/x/lightclient/keeper/proof.go +++ b/x/lightclient/keeper/proof.go @@ -3,6 +3,7 @@ package keeper import ( cosmoserror "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -10,7 +11,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 +26,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 +41,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..c637a29827 100644 --- a/x/lightclient/keeper/proof_test.go +++ b/x/lightclient/keeper/proof_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" @@ -68,7 +69,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/module.go b/x/lightclient/module.go index 66696ac1e5..c5bb382236 100644 --- a/x/lightclient/module.go +++ b/x/lightclient/module.go @@ -14,6 +14,7 @@ import ( "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/lightclient/client/cli" "github.com/zeta-chain/zetacore/x/lightclient/keeper" "github.com/zeta-chain/zetacore/x/lightclient/types" diff --git a/x/lightclient/types/block_header_verification_test.go b/x/lightclient/types/block_header_verification_test.go index ec5d7cd4cc..2bc71a92ef 100644 --- a/x/lightclient/types/block_header_verification_test.go +++ b/x/lightclient/types/block_header_verification_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -12,13 +13,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 +38,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 +55,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 +92,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 +118,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 +150,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/expected_keepers.go b/x/lightclient/types/expected_keepers.go index 4361fa112a..57dec2bd11 100644 --- a/x/lightclient/types/expected_keepers.go +++ b/x/lightclient/types/expected_keepers.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" ) diff --git a/x/lightclient/types/genesis_test.go b/x/lightclient/types/genesis_test.go index 0ccb3a11fe..bf3067a570 100644 --- a/x/lightclient/types/genesis_test.go +++ b/x/lightclient/types/genesis_test.go @@ -3,10 +3,10 @@ package types_test import ( "testing" + "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" - - "github.com/stretchr/testify/require" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/lightclient/types" ) diff --git a/x/lightclient/types/message_disable_verification_flags.go b/x/lightclient/types/message_disable_verification_flags.go index 90779b53dd..e051a7d4b7 100644 --- a/x/lightclient/types/message_disable_verification_flags.go +++ b/x/lightclient/types/message_disable_verification_flags.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) @@ -55,7 +56,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..8559d1d14a 100644 --- a/x/lightclient/types/message_disable_verification_flags_test.go +++ b/x/lightclient/types/message_disable_verification_flags_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -57,7 +58,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..a77706699a 100644 --- a/x/lightclient/types/message_enable_verification_flags.go +++ b/x/lightclient/types/message_enable_verification_flags.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) @@ -54,7 +55,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..b598bfa440 100644 --- a/x/lightclient/types/message_enable_verification_flags_test.go +++ b/x/lightclient/types/message_enable_verification_flags_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -57,7 +58,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/lightclient/types/verification_flags_test.go b/x/lightclient/types/verification_flags_test.go index 0fedb960c8..9db0aa4951 100644 --- a/x/lightclient/types/verification_flags_test.go +++ b/x/lightclient/types/verification_flags_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/observer/abci.go b/x/observer/abci.go index 41121ced19..1cc55eeb5d 100644 --- a/x/observer/abci.go +++ b/x/observer/abci.go @@ -4,6 +4,7 @@ import ( "math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -25,7 +26,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 +36,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/abci_test.go b/x/observer/abci_test.go index 02a161d6b6..8885d436b6 100644 --- a/x/observer/abci_test.go +++ b/x/observer/abci_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer" diff --git a/x/observer/client/cli/query.go b/x/observer/client/cli/query.go index 61e82af1fa..84b9c6c6e6 100644 --- a/x/observer/client/cli/query.go +++ b/x/observer/client/cli/query.go @@ -2,13 +2,9 @@ package cli import ( "fmt" - // "strings" - - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_ballot.go b/x/observer/client/cli/query_ballot.go index a686736b61..55f2ebdab5 100644 --- a/x/observer/client/cli/query_ballot.go +++ b/x/observer/client/cli/query_ballot.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_blame.go b/x/observer/client/cli/query_blame.go index efe7945a73..ded997d35c 100644 --- a/x/observer/client/cli/query_blame.go +++ b/x/observer/client/cli/query_blame.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_chain_nonce.go b/x/observer/client/cli/query_chain_nonce.go index a5a1ec1cb6..f0aa6a7ad1 100644 --- a/x/observer/client/cli/query_chain_nonce.go +++ b/x/observer/client/cli/query_chain_nonce.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_chain_params.go b/x/observer/client/cli/query_chain_params.go index 68433ef75e..b4126b5c76 100644 --- a/x/observer/client/cli/query_chain_params.go +++ b/x/observer/client/cli/query_chain_params.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_get_tss_address.go b/x/observer/client/cli/query_get_tss_address.go index d37fb95f0c..f663ca43df 100644 --- a/x/observer/client/cli/query_get_tss_address.go +++ b/x/observer/client/cli/query_get_tss_address.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_keygen.go b/x/observer/client/cli/query_keygen.go index 85ec112bbe..5140bc82cf 100644 --- a/x/observer/client/cli/query_keygen.go +++ b/x/observer/client/cli/query_keygen.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_node_account.go b/x/observer/client/cli/query_node_account.go index 51113aaac4..dd811dbe66 100644 --- a/x/observer/client/cli/query_node_account.go +++ b/x/observer/client/cli/query_node_account.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_observers.go b/x/observer/client/cli/query_observers.go index 688b32c6da..6bdc34616c 100644 --- a/x/observer/client/cli/query_observers.go +++ b/x/observer/client/cli/query_observers.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_pending_nonces.go b/x/observer/client/cli/query_pending_nonces.go index e15abbb893..5cf9493d3d 100644 --- a/x/observer/client/cli/query_pending_nonces.go +++ b/x/observer/client/cli/query_pending_nonces.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_permission_flags.go b/x/observer/client/cli/query_permission_flags.go index fbd3f3adb5..588fa70067 100644 --- a/x/observer/client/cli/query_permission_flags.go +++ b/x/observer/client/cli/query_permission_flags.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_show_observer_count.go b/x/observer/client/cli/query_show_observer_count.go index 47240e7a74..43c7feb7a6 100644 --- a/x/observer/client/cli/query_show_observer_count.go +++ b/x/observer/client/cli/query_show_observer_count.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_supported_chains.go b/x/observer/client/cli/query_supported_chains.go index 913a2869ec..93a1294015 100644 --- a/x/observer/client/cli/query_supported_chains.go +++ b/x/observer/client/cli/query_supported_chains.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/query_tss.go b/x/observer/client/cli/query_tss.go index aa917125c0..28e29ea7ca 100644 --- a/x/observer/client/cli/query_tss.go +++ b/x/observer/client/cli/query_tss.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx.go b/x/observer/client/cli/tx.go index 9d65f09b70..b66dd7a058 100644 --- a/x/observer/client/cli/tx.go +++ b/x/observer/client/cli/tx.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" - // "github.com/cosmos/cosmos-sdk/client/flags" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_add_blame_vote.go b/x/observer/client/cli/tx_add_blame_vote.go index ea2272332a..d15b056875 100644 --- a/x/observer/client/cli/tx_add_blame_vote.go +++ b/x/observer/client/cli/tx_add_blame_vote.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" "github.com/zeta-chain/go-tss/blame" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_add_observer.go b/x/observer/client/cli/tx_add_observer.go index 1e35552725..3c18fbcca5 100644 --- a/x/observer/client/cli/tx_add_observer.go +++ b/x/observer/client/cli/tx_add_observer.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_permission_flags.go b/x/observer/client/cli/tx_permission_flags.go index 71c6304e51..1aa219ac98 100644 --- a/x/observer/client/cli/tx_permission_flags.go +++ b/x/observer/client/cli/tx_permission_flags.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -29,7 +30,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/client/cli/tx_remove_chain_params.go b/x/observer/client/cli/tx_remove_chain_params.go index 35e4d07655..49f4fb6f47 100644 --- a/x/observer/client/cli/tx_remove_chain_params.go +++ b/x/observer/client/cli/tx_remove_chain_params.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_reset_chain_nonces.go b/x/observer/client/cli/tx_reset_chain_nonces.go index 01a992bd9e..3363eead31 100644 --- a/x/observer/client/cli/tx_reset_chain_nonces.go +++ b/x/observer/client/cli/tx_reset_chain_nonces.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_update_chain_params.go b/x/observer/client/cli/tx_update_chain_params.go index 3417fa6b50..81e5cac7a1 100644 --- a/x/observer/client/cli/tx_update_chain_params.go +++ b/x/observer/client/cli/tx_update_chain_params.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_update_keygen.go b/x/observer/client/cli/tx_update_keygen.go index ac98e03046..c826d23f87 100644 --- a/x/observer/client/cli/tx_update_keygen.go +++ b/x/observer/client/cli/tx_update_keygen.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_update_observer.go b/x/observer/client/cli/tx_update_observer.go index f052106136..abc8c72e51 100644 --- a/x/observer/client/cli/tx_update_observer.go +++ b/x/observer/client/cli/tx_update_observer.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/cli/tx_vote_tss.go b/x/observer/client/cli/tx_vote_tss.go index 2c2b837513..088ec36fcf 100644 --- a/x/observer/client/cli/tx_vote_tss.go +++ b/x/observer/client/cli/tx_vote_tss.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cast" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/client/querytests/chain_nonces.go b/x/observer/client/querytests/chain_nonces.go index ebe99b8f01..1cee363051 100644 --- a/x/observer/client/querytests/chain_nonces.go +++ b/x/observer/client/querytests/chain_nonces.go @@ -6,10 +6,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/zeta-chain/zetacore/x/observer/client/cli" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/client/cli" + "github.com/zeta-chain/zetacore/x/observer/types" ) func (s *CliTestSuite) TestShowChainNonces() { diff --git a/x/observer/client/querytests/cli_test.go b/x/observer/client/querytests/cli_test.go index ca7a115d8b..777fc81528 100644 --- a/x/observer/client/querytests/cli_test.go +++ b/x/observer/client/querytests/cli_test.go @@ -3,14 +3,14 @@ package querytests import ( "testing" + tmdb "github.com/cometbft/cometbft-db" "github.com/cosmos/cosmos-sdk/baseapp" servertypes "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/types/module/testutil" - - tmdb "github.com/cometbft/cometbft-db" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/testutil/network" ) diff --git a/x/observer/client/querytests/crosschain_flags.go b/x/observer/client/querytests/crosschain_flags.go index d351ea248b..e9756e750f 100644 --- a/x/observer/client/querytests/crosschain_flags.go +++ b/x/observer/client/querytests/crosschain_flags.go @@ -5,10 +5,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/observer/client/cli" "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/status" ) func (s *CliTestSuite) TestShowCrosschainFlags() { diff --git a/x/observer/client/querytests/keygen.go b/x/observer/client/querytests/keygen.go index b738c04144..904f254a15 100644 --- a/x/observer/client/querytests/keygen.go +++ b/x/observer/client/querytests/keygen.go @@ -5,9 +5,10 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/x/observer/client/cli" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/status" ) func (s *CliTestSuite) TestShowKeygen() { diff --git a/x/observer/client/querytests/node_account.go b/x/observer/client/querytests/node_account.go index 4d6185e16d..1e72d561b0 100644 --- a/x/observer/client/querytests/node_account.go +++ b/x/observer/client/querytests/node_account.go @@ -5,10 +5,11 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/zeta-chain/zetacore/x/observer/client/cli" - zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/client/cli" + zetaObserverTypes "github.com/zeta-chain/zetacore/x/observer/types" ) func (s *CliTestSuite) TestShowNodeAccount() { diff --git a/x/observer/client/querytests/suite.go b/x/observer/client/querytests/suite.go index 344819c890..8fc7063676 100644 --- a/x/observer/client/querytests/suite.go +++ b/x/observer/client/querytests/suite.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ethcfg "github.com/evmos/ethermint/cmd/config" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/app" cmdcfg "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/testutil/network" diff --git a/x/observer/client/querytests/tss.go b/x/observer/client/querytests/tss.go index 1f0b6366b2..72d15d1452 100644 --- a/x/observer/client/querytests/tss.go +++ b/x/observer/client/querytests/tss.go @@ -5,9 +5,10 @@ import ( tmcli "github.com/cometbft/cometbft/libs/cli" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/x/observer/client/cli" "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/status" ) func (s *CliTestSuite) TestShowTSS() { diff --git a/x/observer/genesis.go b/x/observer/genesis.go index ea63b10a24..9a8a3bcee1 100644 --- a/x/observer/genesis.go +++ b/x/observer/genesis.go @@ -2,6 +2,7 @@ package observer import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" @@ -66,7 +67,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/genesis_test.go b/x/observer/genesis_test.go index 086a5cddc4..73edbc1946 100644 --- a/x/observer/genesis_test.go +++ b/x/observer/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/ballot.go b/x/observer/keeper/ballot.go index 5a05a5e76b..7a42532ab3 100644 --- a/x/observer/keeper/ballot.go +++ b/x/observer/keeper/ballot.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/ballot_test.go b/x/observer/keeper/ballot_test.go index 1f06f4bb91..95ec24363e 100644 --- a/x/observer/keeper/ballot_test.go +++ b/x/observer/keeper/ballot_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/blame.go b/x/observer/keeper/blame.go index 63e4c84809..20b8170bf0 100644 --- a/x/observer/keeper/blame.go +++ b/x/observer/keeper/blame.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -35,7 +36,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 +52,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/blame_test.go b/x/observer/keeper/blame_test.go index 420e6f7d8f..94e7a1edf8 100644 --- a/x/observer/keeper/blame_test.go +++ b/x/observer/keeper/blame_test.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/chain_nonces.go b/x/observer/keeper/chain_nonces.go index 7a9a6ab53c..95260804f1 100644 --- a/x/observer/keeper/chain_nonces.go +++ b/x/observer/keeper/chain_nonces.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/chain_nonces_test.go b/x/observer/keeper/chain_nonces_test.go index e0b12aedec..0199f8d103 100644 --- a/x/observer/keeper/chain_nonces_test.go +++ b/x/observer/keeper/chain_nonces_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/observer/keeper/chain_params.go b/x/observer/keeper/chain_params.go index 8c4d7301fb..a2354f9b2c 100644 --- a/x/observer/keeper/chain_params.go +++ b/x/observer/keeper/chain_params.go @@ -4,6 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/chain_params_test.go b/x/observer/keeper/chain_params_test.go index 84f28e5cff..4d608f0462 100644 --- a/x/observer/keeper/chain_params_test.go +++ b/x/observer/keeper/chain_params_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/crosschain_flags.go b/x/observer/keeper/crosschain_flags.go index 2a58604627..f23a9fd843 100644 --- a/x/observer/keeper/crosschain_flags.go +++ b/x/observer/keeper/crosschain_flags.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/crosschain_flags_test.go b/x/observer/keeper/crosschain_flags_test.go index 4d3f003b92..630e893a1c 100644 --- a/x/observer/keeper/crosschain_flags_test.go +++ b/x/observer/keeper/crosschain_flags_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/observer/types" ) 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..85463af55a 100644 --- a/x/observer/keeper/grpc_query_ballot.go +++ b/x/observer/keeper/grpc_query_ballot.go @@ -4,9 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) func (k Keeper) HasVoted(goCtx context.Context, req *types.QueryHasVotedRequest) (*types.QueryHasVotedResponse, error) { @@ -27,7 +28,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_ballot_test.go b/x/observer/keeper/grpc_query_ballot_test.go index 32bbe6265d..2282723f38 100644 --- a/x/observer/keeper/grpc_query_ballot_test.go +++ b/x/observer/keeper/grpc_query_ballot_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/grpc_query_blame.go b/x/observer/keeper/grpc_query_blame.go index e0cb709772..8a73d839d2 100644 --- a/x/observer/keeper/grpc_query_blame.go +++ b/x/observer/keeper/grpc_query_blame.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) -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 +28,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 +47,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_blame_test.go b/x/observer/keeper/grpc_query_blame_test.go index 728d1748d0..1d5ed6900f 100644 --- a/x/observer/keeper/grpc_query_blame_test.go +++ b/x/observer/keeper/grpc_query_blame_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/grpc_query_chain_params.go b/x/observer/keeper/grpc_query_chain_params.go index e35d4087a4..5985fd5516 100644 --- a/x/observer/keeper/grpc_query_chain_params.go +++ b/x/observer/keeper/grpc_query_chain_params.go @@ -4,9 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) func (k Keeper) GetChainParamsForChain( diff --git a/x/observer/keeper/grpc_query_chain_params_test.go b/x/observer/keeper/grpc_query_chain_params_test.go index decebbd59b..c1ca70a9d3 100644 --- a/x/observer/keeper/grpc_query_chain_params_test.go +++ b/x/observer/keeper/grpc_query_chain_params_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/grpc_query_crosschain_flags.go b/x/observer/keeper/grpc_query_crosschain_flags.go index 9444ec6a3f..4051666d35 100644 --- a/x/observer/keeper/grpc_query_crosschain_flags.go +++ b/x/observer/keeper/grpc_query_crosschain_flags.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) -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_crosschain_flags_test.go b/x/observer/keeper/grpc_query_crosschain_flags_test.go index 172df715d9..3e15548687 100644 --- a/x/observer/keeper/grpc_query_crosschain_flags_test.go +++ b/x/observer/keeper/grpc_query_crosschain_flags_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/grpc_query_keygen.go b/x/observer/keeper/grpc_query_keygen.go index f479991759..cf33d949b6 100644 --- a/x/observer/keeper/grpc_query_keygen.go +++ b/x/observer/keeper/grpc_query_keygen.go @@ -4,9 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) func (k Keeper) Keygen(c context.Context, _ *types.QueryGetKeygenRequest) (*types.QueryGetKeygenResponse, error) { diff --git a/x/observer/keeper/grpc_query_keygen_test.go b/x/observer/keeper/grpc_query_keygen_test.go index f081382452..0c68bce737 100644 --- a/x/observer/keeper/grpc_query_keygen_test.go +++ b/x/observer/keeper/grpc_query_keygen_test.go @@ -1,11 +1,11 @@ package keeper_test import ( - "github.com/stretchr/testify/require" - "testing" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/grpc_query_node_account.go b/x/observer/keeper/grpc_query_node_account.go index 44aa499757..49222a8b1f 100644 --- a/x/observer/keeper/grpc_query_node_account.go +++ b/x/observer/keeper/grpc_query_node_account.go @@ -6,12 +6,16 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) -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 +43,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_node_account_test.go b/x/observer/keeper/grpc_query_node_account_test.go index 8645357a0c..de2fe756c2 100644 --- a/x/observer/keeper/grpc_query_node_account_test.go +++ b/x/observer/keeper/grpc_query_node_account_test.go @@ -6,10 +6,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" - keepertest "github.com/zeta-chain/zetacore/testutil/keeper" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" + "github.com/zeta-chain/zetacore/x/observer/types" ) func TestNodeAccountQuerySingle(t *testing.T) { diff --git a/x/observer/keeper/grpc_query_nonces.go b/x/observer/keeper/grpc_query_nonces.go index 80ff3a23b2..1ae62ffdc2 100644 --- a/x/observer/keeper/grpc_query_nonces.go +++ b/x/observer/keeper/grpc_query_nonces.go @@ -7,14 +7,18 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) // 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 +46,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 +65,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 +84,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_nonces_test.go b/x/observer/keeper/grpc_query_nonces_test.go index 5a66eebfbf..60fdbca97a 100644 --- a/x/observer/keeper/grpc_query_nonces_test.go +++ b/x/observer/keeper/grpc_query_nonces_test.go @@ -6,11 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestChainNoncesQuerySingle(t *testing.T) { diff --git a/x/observer/keeper/grpc_query_observer.go b/x/observer/keeper/grpc_query_observer.go index d588aae96e..181ba163f8 100644 --- a/x/observer/keeper/grpc_query_observer.go +++ b/x/observer/keeper/grpc_query_observer.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/zeta-chain/zetacore/x/observer/types" ) -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 +30,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_observer_test.go b/x/observer/keeper/grpc_query_observer_test.go index 73675fae0d..ca29b47940 100644 --- a/x/observer/keeper/grpc_query_observer_test.go +++ b/x/observer/keeper/grpc_query_observer_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/grpc_query_supported_chain.go b/x/observer/keeper/grpc_query_supported_chain.go index dbd985d53c..f9f8b2f688 100644 --- a/x/observer/keeper/grpc_query_supported_chain.go +++ b/x/observer/keeper/grpc_query_supported_chain.go @@ -4,10 +4,14 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + "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_supported_chain_test.go b/x/observer/keeper/grpc_query_supported_chain_test.go index 50acd5703a..1b73c53394 100644 --- a/x/observer/keeper/grpc_query_supported_chain_test.go +++ b/x/observer/keeper/grpc_query_supported_chain_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" ) diff --git a/x/observer/keeper/grpc_query_tss.go b/x/observer/keeper/grpc_query_tss.go index 0b6f4a7614..6223d7c425 100644 --- a/x/observer/keeper/grpc_query_tss.go +++ b/x/observer/keeper/grpc_query_tss.go @@ -5,11 +5,12 @@ import ( "sort" sdk "github.com/cosmos/cosmos-sdk/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/crypto" "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) // TSS returns the tss address for the current tss only @@ -37,7 +38,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 +72,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/grpc_query_tss_test.go b/x/observer/keeper/grpc_query_tss_test.go index 601945c22f..8565ff9349 100644 --- a/x/observer/keeper/grpc_query_tss_test.go +++ b/x/observer/keeper/grpc_query_tss_test.go @@ -6,13 +6,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/crypto" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestTSSQuerySingle(t *testing.T) { diff --git a/x/observer/keeper/hooks.go b/x/observer/keeper/hooks.go index b6955df0ce..7e11cae282 100644 --- a/x/observer/keeper/hooks.go +++ b/x/observer/keeper/hooks.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -122,7 +123,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/hooks_test.go b/x/observer/keeper/hooks_test.go index 0727b17c71..a00549f05b 100644 --- a/x/observer/keeper/hooks_test.go +++ b/x/observer/keeper/hooks_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/keeper.go b/x/observer/keeper/keeper.go index 61cc3a8f56..1019fc1002 100644 --- a/x/observer/keeper/keeper.go +++ b/x/observer/keeper/keeper.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/keygen.go b/x/observer/keeper/keygen.go index a8860c9c9f..8ff3d8b4e2 100644 --- a/x/observer/keeper/keygen.go +++ b/x/observer/keeper/keygen.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/last_observer_count.go b/x/observer/keeper/last_observer_count.go index 7ae211acd1..53c1f1419e 100644 --- a/x/observer/keeper/last_observer_count.go +++ b/x/observer/keeper/last_observer_count.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/msg_server_add_blame_vote.go b/x/observer/keeper/msg_server_add_blame_vote.go index 452a15c56a..fec760dda8 100644 --- a/x/observer/keeper/msg_server_add_blame_vote.go +++ b/x/observer/keeper/msg_server_add_blame_vote.go @@ -6,18 +6,25 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + crosschainTypes "github.com/zeta-chain/zetacore/x/crosschain/types" "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_blame_vote_test.go b/x/observer/keeper/msg_server_add_blame_vote_test.go index 28ada869b0..8150e57517 100644 --- a/x/observer/keeper/msg_server_add_blame_vote_test.go +++ b/x/observer/keeper/msg_server_add_blame_vote_test.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/keeper" diff --git a/x/observer/keeper/msg_server_add_observer.go b/x/observer/keeper/msg_server_add_observer.go index c725516ccd..034cd5e22e 100644 --- a/x/observer/keeper/msg_server_add_observer.go +++ b/x/observer/keeper/msg_server_add_observer.go @@ -4,17 +4,20 @@ import ( "context" "math" - "github.com/zeta-chain/zetacore/pkg/crypto" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/zeta-chain/zetacore/pkg/crypto" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) // 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_add_observer_test.go b/x/observer/keeper/msg_server_add_observer_test.go index f3e0aab028..e8006f4e42 100644 --- a/x/observer/keeper/msg_server_add_observer_test.go +++ b/x/observer/keeper/msg_server_add_observer_test.go @@ -7,6 +7,7 @@ import ( "github.com/cometbft/cometbft/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/observer/keeper/msg_server_remove_chain_params.go b/x/observer/keeper/msg_server_remove_chain_params.go index 8124f534c7..30f7a3e91b 100644 --- a/x/observer/keeper/msg_server_remove_chain_params.go +++ b/x/observer/keeper/msg_server_remove_chain_params.go @@ -4,12 +4,16 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) // 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_remove_chain_params_test.go b/x/observer/keeper/msg_server_remove_chain_params_test.go index 21b68f7f8e..e4d5b457ee 100644 --- a/x/observer/keeper/msg_server_remove_chain_params_test.go +++ b/x/observer/keeper/msg_server_remove_chain_params_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/msg_server_reset_chain_nonces.go b/x/observer/keeper/msg_server_reset_chain_nonces.go index 853ef1ad16..3c03ea6f82 100644 --- a/x/observer/keeper/msg_server_reset_chain_nonces.go +++ b/x/observer/keeper/msg_server_reset_chain_nonces.go @@ -4,13 +4,17 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) // 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_reset_chain_nonces_test.go b/x/observer/keeper/msg_server_reset_chain_nonces_test.go index ca64406828..adf11439e2 100644 --- a/x/observer/keeper/msg_server_reset_chain_nonces_test.go +++ b/x/observer/keeper/msg_server_reset_chain_nonces_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/msg_server_update_chain_params.go b/x/observer/keeper/msg_server_update_chain_params.go index 011f5d0786..c7895016fc 100644 --- a/x/observer/keeper/msg_server_update_chain_params.go +++ b/x/observer/keeper/msg_server_update_chain_params.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -12,7 +13,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_chain_params_test.go b/x/observer/keeper/msg_server_update_chain_params_test.go index 2f20605519..d842ab9ac7 100644 --- a/x/observer/keeper/msg_server_update_chain_params_test.go +++ b/x/observer/keeper/msg_server_update_chain_params_test.go @@ -3,13 +3,13 @@ package keeper_test import ( "testing" - "github.com/zeta-chain/zetacore/pkg/chains" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/msg_server_update_crosschain_flags.go b/x/observer/keeper/msg_server_update_crosschain_flags.go index cbdc2b29ac..045b21dd7d 100644 --- a/x/observer/keeper/msg_server_update_crosschain_flags.go +++ b/x/observer/keeper/msg_server_update_crosschain_flags.go @@ -3,9 +3,9 @@ package keeper import ( "context" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - sdk "github.com/cosmos/cosmos-sdk/types" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -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..b4a5f1f516 100644 --- a/x/observer/keeper/msg_server_update_crosschain_flags_test.go +++ b/x/observer/keeper/msg_server_update_crosschain_flags_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" @@ -126,7 +127,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..6ee1faca62 100644 --- a/x/observer/keeper/msg_server_update_keygen.go +++ b/x/observer/keeper/msg_server_update_keygen.go @@ -3,9 +3,9 @@ package keeper import ( "context" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - sdk "github.com/cosmos/cosmos-sdk/types" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -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_keygen_test.go b/x/observer/keeper/msg_server_update_keygen_test.go index 8b3201c5ed..4cf6237ce3 100644 --- a/x/observer/keeper/msg_server_update_keygen_test.go +++ b/x/observer/keeper/msg_server_update_keygen_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/observer/keeper/msg_server_update_observer.go b/x/observer/keeper/msg_server_update_observer.go index b3046b1d9f..81e76ac2e2 100644 --- a/x/observer/keeper/msg_server_update_observer.go +++ b/x/observer/keeper/msg_server_update_observer.go @@ -4,17 +4,20 @@ import ( "context" "fmt" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" ) // 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_update_observer_test.go b/x/observer/keeper/msg_server_update_observer_test.go index 1d6123dab9..afdb4d4907 100644 --- a/x/observer/keeper/msg_server_update_observer_test.go +++ b/x/observer/keeper/msg_server_update_observer_test.go @@ -9,6 +9,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" diff --git a/x/observer/keeper/msg_server_vote_block_header.go b/x/observer/keeper/msg_server_vote_block_header.go index a9050e7ebc..bbcdc05719 100644 --- a/x/observer/keeper/msg_server_vote_block_header.go +++ b/x/observer/keeper/msg_server_vote_block_header.go @@ -5,12 +5,16 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" "github.com/zeta-chain/zetacore/x/observer/types" ) // 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_block_header_test.go b/x/observer/keeper/msg_server_vote_block_header_test.go index f58ed14299..8e51043ae2 100644 --- a/x/observer/keeper/msg_server_vote_block_header_test.go +++ b/x/observer/keeper/msg_server_vote_block_header_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" diff --git a/x/observer/keeper/msg_server_vote_tss.go b/x/observer/keeper/msg_server_vote_tss.go index 402a84a3db..065bfe68f2 100644 --- a/x/observer/keeper/msg_server_vote_tss.go +++ b/x/observer/keeper/msg_server_vote_tss.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/common/math" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -28,7 +29,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/msg_server_vote_tss_test.go b/x/observer/keeper/msg_server_vote_tss_test.go index e92f59cb7e..f44ceaa07d 100644 --- a/x/observer/keeper/msg_server_vote_tss_test.go +++ b/x/observer/keeper/msg_server_vote_tss_test.go @@ -6,6 +6,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/node_account.go b/x/observer/keeper/node_account.go index 3f6a14be66..988a9a4a70 100644 --- a/x/observer/keeper/node_account.go +++ b/x/observer/keeper/node_account.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/node_account_test.go b/x/observer/keeper/node_account_test.go index c20501f8b2..e81b4552fe 100644 --- a/x/observer/keeper/node_account_test.go +++ b/x/observer/keeper/node_account_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/nonce_to_cctx.go b/x/observer/keeper/nonce_to_cctx.go index 6ecedd22ea..057f4b1b4b 100644 --- a/x/observer/keeper/nonce_to_cctx.go +++ b/x/observer/keeper/nonce_to_cctx.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -22,7 +23,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..510030a00c 100644 --- a/x/observer/keeper/nonce_to_cctx_test.go +++ b/x/observer/keeper/nonce_to_cctx_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" @@ -38,7 +39,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/nonces_test.go b/x/observer/keeper/nonces_test.go index 5ccd7909f6..0509ad63c1 100644 --- a/x/observer/keeper/nonces_test.go +++ b/x/observer/keeper/nonces_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/observer/keeper/observer_set.go b/x/observer/keeper/observer_set.go index b8c45bfd30..deeae5395b 100644 --- a/x/observer/keeper/observer_set.go +++ b/x/observer/keeper/observer_set.go @@ -3,6 +3,7 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/observer_set_test.go b/x/observer/keeper/observer_set_test.go index 0feec7c1b2..3ae4a99cf2 100644 --- a/x/observer/keeper/observer_set_test.go +++ b/x/observer/keeper/observer_set_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/observer/keeper/pending_nonces.go b/x/observer/keeper/pending_nonces.go index 34f241a10e..6eb8dd2ae1 100644 --- a/x/observer/keeper/pending_nonces.go +++ b/x/observer/keeper/pending_nonces.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -30,7 +31,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..6eaaa3abf3 100644 --- a/x/observer/keeper/pending_nonces_test.go +++ b/x/observer/keeper/pending_nonces_test.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) @@ -38,7 +39,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..55915d55d2 100644 --- a/x/observer/keeper/tss.go +++ b/x/observer/keeper/tss.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -79,7 +80,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/tss_funds_migrator.go b/x/observer/keeper/tss_funds_migrator.go index 8ff91e4e16..72c34397aa 100644 --- a/x/observer/keeper/tss_funds_migrator.go +++ b/x/observer/keeper/tss_funds_migrator.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/tss_funds_migrator_test.go b/x/observer/keeper/tss_funds_migrator_test.go index 620fa2ca06..ec7ad852da 100644 --- a/x/observer/keeper/tss_funds_migrator_test.go +++ b/x/observer/keeper/tss_funds_migrator_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" ) diff --git a/x/observer/keeper/tss_test.go b/x/observer/keeper/tss_test.go index a1f1ca6ddc..2340c6e6dc 100644 --- a/x/observer/keeper/tss_test.go +++ b/x/observer/keeper/tss_test.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/query" "github.com/stretchr/testify/require" + keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/keeper/utils.go b/x/observer/keeper/utils.go index ca3fc00f55..8d37e82d57 100644 --- a/x/observer/keeper/utils.go +++ b/x/observer/keeper/utils.go @@ -4,11 +4,17 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" "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/keeper/utils_test.go b/x/observer/keeper/utils_test.go index 3a04c739a3..9e334cb9bf 100644 --- a/x/observer/keeper/utils_test.go +++ b/x/observer/keeper/utils_test.go @@ -9,6 +9,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/keeper/vote_inbound.go b/x/observer/keeper/vote_inbound.go index dff4515098..e0189d7dac 100644 --- a/x/observer/keeper/vote_inbound.go +++ b/x/observer/keeper/vote_inbound.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/vote_inbound_test.go b/x/observer/keeper/vote_inbound_test.go index b271bbfebe..7db8619205 100644 --- a/x/observer/keeper/vote_inbound_test.go +++ b/x/observer/keeper/vote_inbound_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" diff --git a/x/observer/keeper/vote_outbound.go b/x/observer/keeper/vote_outbound.go index edc5d5cdcf..b502badc57 100644 --- a/x/observer/keeper/vote_outbound.go +++ b/x/observer/keeper/vote_outbound.go @@ -2,6 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/keeper/vote_outbound_test.go b/x/observer/keeper/vote_outbound_test.go index 72f498d413..209841b1fc 100644 --- a/x/observer/keeper/vote_outbound_test.go +++ b/x/observer/keeper/vote_outbound_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" keepertest "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" diff --git a/x/observer/module.go b/x/observer/module.go index f110323948..ec0dbdaea8 100644 --- a/x/observer/module.go +++ b/x/observer/module.go @@ -5,17 +5,16 @@ import ( "encoding/json" "fmt" - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/client/cli" "github.com/zeta-chain/zetacore/x/observer/keeper" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/module_simulation.go b/x/observer/module_simulation.go index 05d61243a4..0ae96a3186 100644 --- a/x/observer/module_simulation.go +++ b/x/observer/module_simulation.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/zeta-chain/zetacore/x/observer/types" ) 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 511fbb621b..3ce11dbbc5 100644 --- a/x/observer/types/chain_params.go +++ b/x/observer/types/chain_params.go @@ -4,11 +4,11 @@ import ( "fmt" "strings" - sdk "github.com/cosmos/cosmos-sdk/types" - errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ethchains "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/chains" ) @@ -76,27 +76,51 @@ func ValidateChainParams(params *ChainParams) error { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutboundTicker %d out of range", params.OutboundTicker) } if params.OutboundScheduleInterval == 0 || params.OutboundScheduleInterval > 100 { // 600 secs - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutboundScheduleInterval %d out of range", params.OutboundScheduleInterval) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "OutboundScheduleInterval %d out of range", + params.OutboundScheduleInterval, + ) } if params.OutboundScheduleLookahead == 0 || params.OutboundScheduleLookahead > 500 { // 500 cctxs - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "OutboundScheduleLookahead %d out of range", params.OutboundScheduleLookahead) + return errorsmod.Wrapf( + sdkerrors.ErrInvalidRequest, + "OutboundScheduleLookahead %d out of range", + params.OutboundScheduleLookahead, + ) } // 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/chain_params_test.go b/x/observer/types/chain_params_test.go index ba9aad64e5..9aab9dc9ff 100644 --- a/x/observer/types/chain_params_test.go +++ b/x/observer/types/chain_params_test.go @@ -6,8 +6,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/zeta-chain/zetacore/x/observer/types" . "gopkg.in/check.v1" + + "github.com/zeta-chain/zetacore/x/observer/types" ) func TestChainParamsList_Validate(t *testing.T) { diff --git a/x/observer/types/crosschain_flags_test.go b/x/observer/types/crosschain_flags_test.go index ed80bf652f..967a6ada27 100644 --- a/x/observer/types/crosschain_flags_test.go +++ b/x/observer/types/crosschain_flags_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/x/observer/types" ) 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..63abdd7887 100644 --- a/x/observer/types/expected_keepers.go +++ b/x/observer/types/expected_keepers.go @@ -4,13 +4,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/zeta-chain/zetacore/pkg/proofs" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" ) 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/genesis_test.go b/x/observer/types/genesis_test.go index 676bca7d62..ec61b97b99 100644 --- a/x/observer/types/genesis_test.go +++ b/x/observer/types/genesis_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/types/message_add_blame_vote.go b/x/observer/types/message_add_blame_vote.go index 5a93f0cafe..cbbc922291 100644 --- a/x/observer/types/message_add_blame_vote.go +++ b/x/observer/types/message_add_blame_vote.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/observer/types/message_add_blame_vote_test.go b/x/observer/types/message_add_blame_vote_test.go index 810cdad433..e7d3178090 100644 --- a/x/observer/types/message_add_blame_vote_test.go +++ b/x/observer/types/message_add_blame_vote_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/keeper" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/message_add_observer.go b/x/observer/types/message_add_observer.go index 087636b10a..19a58eef0a 100644 --- a/x/observer/types/message_add_observer.go +++ b/x/observer/types/message_add_observer.go @@ -4,6 +4,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/crypto" ) @@ -11,7 +12,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_add_observer_test.go b/x/observer/types/message_add_observer_test.go index 455868d49f..32645d9371 100644 --- a/x/observer/types/message_add_observer_test.go +++ b/x/observer/types/message_add_observer_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/types/message_remove_chain_params.go b/x/observer/types/message_remove_chain_params.go index 5b333c4bc1..b34574e4de 100644 --- a/x/observer/types/message_remove_chain_params.go +++ b/x/observer/types/message_remove_chain_params.go @@ -2,10 +2,10 @@ package types import ( cosmoserrors "cosmossdk.io/errors" - "github.com/zeta-chain/zetacore/pkg/chains" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/zeta-chain/zetacore/pkg/chains" ) const TypeMsgRemoveChainParams = "remove_chain_params" diff --git a/x/observer/types/message_remove_chain_params_test.go b/x/observer/types/message_remove_chain_params_test.go index bd46dfe692..b81f29ff77 100644 --- a/x/observer/types/message_remove_chain_params_test.go +++ b/x/observer/types/message_remove_chain_params_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/message_reset_chain_nonces.go b/x/observer/types/message_reset_chain_nonces.go index c7bb615040..ac14463af5 100644 --- a/x/observer/types/message_reset_chain_nonces.go +++ b/x/observer/types/message_reset_chain_nonces.go @@ -4,17 +4,22 @@ import ( "errors" cosmoserrors "cosmossdk.io/errors" - "github.com/zeta-chain/zetacore/pkg/chains" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/zeta-chain/zetacore/pkg/chains" ) 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_reset_chain_nonces_test.go b/x/observer/types/message_reset_chain_nonces_test.go index 4f37b359bb..d131d32ed6 100644 --- a/x/observer/types/message_reset_chain_nonces_test.go +++ b/x/observer/types/message_reset_chain_nonces_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/message_update_chain_params.go b/x/observer/types/message_update_chain_params.go index 7682a684f3..52bd399f02 100644 --- a/x/observer/types/message_update_chain_params.go +++ b/x/observer/types/message_update_chain_params.go @@ -2,7 +2,6 @@ package types import ( cosmoserrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) diff --git a/x/observer/types/message_update_chain_params_test.go b/x/observer/types/message_update_chain_params_test.go index 1e909ea783..fe2d526631 100644 --- a/x/observer/types/message_update_chain_params_test.go +++ b/x/observer/types/message_update_chain_params_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/message_update_crosschain_flags.go b/x/observer/types/message_update_crosschain_flags.go index 27881e0994..472d9ffdf6 100644 --- a/x/observer/types/message_update_crosschain_flags.go +++ b/x/observer/types/message_update_crosschain_flags.go @@ -3,12 +3,11 @@ package types import ( "errors" - authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" - cosmoserrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" ) const ( diff --git a/x/observer/types/message_update_crosschain_flags_test.go b/x/observer/types/message_update_crosschain_flags_test.go index bb1a40544b..ae529d7d02 100644 --- a/x/observer/types/message_update_crosschain_flags_test.go +++ b/x/observer/types/message_update_crosschain_flags_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" authoritytypes "github.com/zeta-chain/zetacore/x/authority/types" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/message_update_keygen_test.go b/x/observer/types/message_update_keygen_test.go index 2e494d6dc4..08476bb0e8 100644 --- a/x/observer/types/message_update_keygen_test.go +++ b/x/observer/types/message_update_keygen_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" ) 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_update_observer_test.go b/x/observer/types/message_update_observer_test.go index 041142c0a9..d27cf0e19a 100644 --- a/x/observer/types/message_update_observer_test.go +++ b/x/observer/types/message_update_observer_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/x/observer/types/message_vote_block_header.go b/x/observer/types/message_vote_block_header.go index 0cc70776da..004b2ce199 100644 --- a/x/observer/types/message_vote_block_header.go +++ b/x/observer/types/message_vote_block_header.go @@ -2,10 +2,10 @@ package types import ( cosmoserrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" ) @@ -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/x/observer/types/message_vote_block_header_test.go b/x/observer/types/message_vote_block_header_test.go index f398617cbf..5b03a99041 100644 --- a/x/observer/types/message_vote_block_header_test.go +++ b/x/observer/types/message_vote_block_header_test.go @@ -9,6 +9,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" "github.com/zeta-chain/zetacore/testutil/keeper" diff --git a/x/observer/types/message_vote_tss.go b/x/observer/types/message_vote_tss.go index ccb3c8b960..fa10c4ad37 100644 --- a/x/observer/types/message_vote_tss.go +++ b/x/observer/types/message_vote_tss.go @@ -6,6 +6,7 @@ import ( cosmoserrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/observer/types/message_vote_tss_test.go b/x/observer/types/message_vote_tss_test.go index 4026ccb018..232d945190 100644 --- a/x/observer/types/message_vote_tss_test.go +++ b/x/observer/types/message_vote_tss_test.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/observer_set.go b/x/observer/types/observer_set.go index a5ca5661d0..ffa2d1c05a 100644 --- a/x/observer/types/observer_set.go +++ b/x/observer/types/observer_set.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/observer/types/observer_set_test.go b/x/observer/types/observer_set_test.go index 391ecc57b6..69a9a19f96 100644 --- a/x/observer/types/observer_set_test.go +++ b/x/observer/types/observer_set_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/parsers.go b/x/observer/types/parsers.go index b202c06c2c..27cd73df74 100644 --- a/x/observer/types/parsers.go +++ b/x/observer/types/parsers.go @@ -2,6 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/chains" ) diff --git a/x/observer/types/parsers_test.go b/x/observer/types/parsers_test.go index 50053758a3..326f2c094e 100644 --- a/x/observer/types/parsers_test.go +++ b/x/observer/types/parsers_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/x/observer/types/utils_test.go b/x/observer/types/utils_test.go index ac42ea127c..d68c3de792 100644 --- a/x/observer/types/utils_test.go +++ b/x/observer/types/utils_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/require" "github.com/zeta-chain/go-tss/blame" + "github.com/zeta-chain/zetacore/x/observer/types" ) diff --git a/zetaclient/authz/authz_signer.go b/zetaclient/authz/authz_signer.go index 42f9cea92a..5f1221f9a9 100644 --- a/zetaclient/authz/authz_signer.go +++ b/zetaclient/authz/authz_signer.go @@ -2,6 +2,7 @@ package authz import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/zeta-chain/zetacore/pkg/authz" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/chains/bitcoin/fee.go b/zetaclient/chains/bitcoin/fee.go index 955a43a8aa..27b3037145 100644 --- a/zetaclient/chains/bitcoin/fee.go +++ b/zetaclient/chains/bitcoin/fee.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/btcutil" "github.com/pkg/errors" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" ) @@ -211,7 +212,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 81125ae134..cc2ab07386 100644 --- a/zetaclient/chains/bitcoin/fee_test.go +++ b/zetaclient/chains/bitcoin/fee_test.go @@ -12,6 +12,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" ) @@ -242,7 +243,9 @@ func TestOutboundSizeXIn3Out(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 := EstimateOutboundSize(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 ee38bb0b94..e9b4c20d60 100644 --- a/zetaclient/chains/bitcoin/observer/inbound.go +++ b/zetaclient/chains/bitcoin/observer/inbound.go @@ -12,6 +12,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -40,7 +41,8 @@ func (ob *Observer) WatchInbound() { select { case <-ticker.C(): if !context.IsInboundObservationEnabled(ob.coreContext, ob.GetChainParams()) { - sampledLogger.Info().Msgf("WatchInbound: inbound observation is disabled for chain %d", ob.chain.ChainId) + sampledLogger.Info(). + Msgf("WatchInbound: inbound observation is disabled for chain %d", ob.chain.ChainId) continue } err := ob.ObserveInbound() @@ -65,7 +67,11 @@ func (ob *Observer) ObserveInbound() error { return fmt.Errorf("observeInboundBTC: block number is negative: %d", cnt) } if cnt < ob.GetLastBlockHeight() { - return fmt.Errorf("observeInboundBTC: block number should not decrease: current %d last %d", cnt, ob.GetLastBlockHeight()) + return fmt.Errorf( + "observeInboundBTC: block number should not decrease: current %d last %d", + cnt, + ob.GetLastBlockHeight(), + ) } ob.SetLastBlockHeight(cnt) @@ -123,7 +129,9 @@ func (ob *Observer) ObserveInbound() error { depositorFee, ) if err != nil { - ob.logger.Inbound.Error().Err(err).Msgf("observeInboundBTC: error filtering incoming txs for block %d", blockNumber) + ob.logger.Inbound.Error(). + Err(err). + Msgf("observeInboundBTC: error filtering incoming txs for block %d", blockNumber) return err // we have to re-scan this block next time } @@ -131,9 +139,15 @@ func (ob *Observer) ObserveInbound() error { for _, inbound := range inbounds { msg := ob.GetInboundVoteMessageFromBtcEvent(inbound) 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.Inbound.Error().Err(err).Msgf("observeInboundBTC: error posting to zetacore for tx %s", inbound.TxHash) + ob.logger.Inbound.Error(). + Err(err). + Msgf("observeInboundBTC: error posting to zetacore for tx %s", inbound.TxHash) return err // we have to re-scan this block next time } else if zetaHash != "" { ob.logger.Inbound.Info().Msgf("observeInboundBTC: PostVoteInbound zeta tx hash: %s inbound %s ballot %s fee %v", @@ -148,7 +162,9 @@ func (ob *Observer) ObserveInbound() error { // #nosec G701 always positive if err := ob.db.Save(types.ToLastBlockSQLType(uint64(blockNumber))).Error; err != nil { - ob.logger.Inbound.Error().Err(err).Msgf("observeInboundBTC: error writing last scanned block %d to db", blockNumber) + ob.logger.Inbound.Error(). + Err(err). + Msgf("observeInboundBTC: error writing last scanned block %d to db", blockNumber) } return nil @@ -171,7 +187,9 @@ func (ob *Observer) WatchInboundTracker() { } err := ob.ProcessInboundTrackers() if err != nil { - ob.logger.Inbound.Error().Err(err).Msgf("error observing inbound tracker for chain %d", ob.chain.ChainId) + ob.logger.Inbound.Error(). + Err(err). + Msgf("error observing inbound tracker for chain %d", ob.chain.ChainId) } ticker.UpdateInterval(ob.GetChainParams().InboundTicker, ob.logger.Inbound) case <-ob.stop: @@ -189,12 +207,14 @@ func (ob *Observer) ProcessInboundTrackers() error { } for _, tracker := range trackers { - ob.logger.Inbound.Info().Msgf("checking tracker with hash :%s and coin-type :%s ", tracker.TxHash, tracker.CoinType) + ob.logger.Inbound.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.Inbound.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.Inbound.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 @@ -233,7 +253,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.Inbound, ob.netParams, depositorFee) + event, err := GetBtcEvent( + ob.rpcClient, + *tx, + tss, + uint64(blockVb.Height), + ob.logger.Inbound, + ob.netParams, + depositorFee, + ) if err != nil { return "", err } @@ -251,7 +279,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.Inbound.Error().Err(err).Msg("error posting to zetacore") return "", err @@ -374,7 +406,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 ea4778a043..de27d6e1f3 100644 --- a/zetaclient/chains/bitcoin/observer/inbound_test.go +++ b/zetaclient/chains/bitcoin/observer/inbound_test.go @@ -15,6 +15,7 @@ import ( "github.com/btcsuite/btcutil" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin" clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" @@ -41,11 +42,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 +64,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 +154,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 @@ -237,7 +254,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 8a1a000e88..f35637d7cc 100644 --- a/zetaclient/chains/bitcoin/observer/live_test.go +++ b/zetaclient/chains/bitcoin/observer/live_test.go @@ -18,6 +18,7 @@ import ( "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin" clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" @@ -110,7 +111,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 +254,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 +282,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 226ef675ee..22be51fef1 100644 --- a/zetaclient/chains/bitcoin/observer/observer.go +++ b/zetaclient/chains/bitcoin/observer/observer.go @@ -21,6 +21,10 @@ import ( lru "github.com/hashicorp/golang-lru" "github.com/pkg/errors" "github.com/rs/zerolog" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" observertypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -32,9 +36,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/metrics" clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" "github.com/zeta-chain/zetacore/zetaclient/zetacore" - "gorm.io/driver/sqlite" - "gorm.io/gorm" - "gorm.io/gorm/logger" ) const ( @@ -320,16 +321,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 @@ -606,13 +612,18 @@ func (ob *Observer) SaveBroadcastedTx(txHash string, nonce uint64) { broadcastEntry := clienttypes.ToOutboundHashSQLType(txHash, outboundID) if err := ob.db.Save(&broadcastEntry).Error; err != nil { - ob.logger.Outbound.Error().Err(err).Msgf("SaveBroadcastedTx: error saving broadcasted txHash %s for outbound %s", txHash, outboundID) + ob.logger.Outbound.Error(). + Err(err). + Msgf("SaveBroadcastedTx: error saving broadcasted txHash %s for outbound %s", txHash, outboundID) } ob.logger.Outbound.Info().Msgf("SaveBroadcastedTx: saved broadcasted txHash %s for outbound %s", txHash, outboundID) } // 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) @@ -627,11 +638,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/observer_test.go b/zetaclient/chains/bitcoin/observer/observer_test.go index 1bf3dafa98..ba2f417968 100644 --- a/zetaclient/chains/bitcoin/observer/observer_test.go +++ b/zetaclient/chains/bitcoin/observer/observer_test.go @@ -8,6 +8,9 @@ import ( "github.com/btcsuite/btcd/btcjson" "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" observertypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -17,8 +20,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" - "gorm.io/driver/sqlite" - "gorm.io/gorm" ) const ( diff --git a/zetaclient/chains/bitcoin/observer/outbound.go b/zetaclient/chains/bitcoin/observer/outbound.go index 6890069a28..74459e5b9d 100644 --- a/zetaclient/chains/bitcoin/observer/outbound.go +++ b/zetaclient/chains/bitcoin/observer/outbound.go @@ -8,6 +8,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/pkg/errors" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -40,12 +41,15 @@ func (ob *Observer) WatchOutbound() { select { case <-ticker.C(): if !context.IsOutboundObservationEnabled(ob.coreContext, ob.GetChainParams()) { - sampledLogger.Info().Msgf("WatchOutbound: outbound observation is disabled for chain %d", ob.chain.ChainId) + sampledLogger.Info(). + Msgf("WatchOutbound: outbound observation is disabled for chain %d", ob.chain.ChainId) continue } trackers, err := ob.zetacoreClient.GetAllOutboundTrackerByChain(ob.chain.ChainId, interfaces.Ascending) if err != nil { - ob.logger.Outbound.Error().Err(err).Msgf("WatchOutbound: error GetAllOutboundTrackerByChain for chain %d", ob.chain.ChainId) + ob.logger.Outbound.Error(). + Err(err). + Msgf("WatchOutbound: error GetAllOutboundTrackerByChain for chain %d", ob.chain.ChainId) continue } for _, tracker := range trackers { @@ -53,18 +57,22 @@ func (ob *Observer) WatchOutbound() { outboundID := ob.GetTxID(tracker.Nonce) cctx, err := ob.zetacoreClient.GetCctxByNonce(ob.chain.ChainId, tracker.Nonce) if err != nil { - ob.logger.Outbound.Info().Err(err).Msgf("WatchOutbound: can't find cctx for chain %d nonce %d", ob.chain.ChainId, tracker.Nonce) + ob.logger.Outbound.Info(). + Err(err). + Msgf("WatchOutbound: can't find cctx for chain %d nonce %d", ob.chain.ChainId, tracker.Nonce) break } nonce := cctx.GetCurrentOutboundParam().TssNonce if tracker.Nonce != nonce { // Tanmay: it doesn't hurt to check - ob.logger.Outbound.Error().Msgf("WatchOutbound: tracker nonce %d not match cctx nonce %d", tracker.Nonce, nonce) + ob.logger.Outbound.Error(). + Msgf("WatchOutbound: tracker nonce %d not match cctx nonce %d", tracker.Nonce, nonce) break } if len(tracker.HashList) > 1 { - ob.logger.Outbound.Warn().Msgf("WatchOutbound: oops, outboundID %s got multiple (%d) outbound hashes", outboundID, len(tracker.HashList)) + ob.logger.Outbound.Warn(). + Msgf("WatchOutbound: oops, outboundID %s got multiple (%d) outbound hashes", outboundID, len(tracker.HashList)) } // iterate over all txHashes to find the truly included one. @@ -76,7 +84,8 @@ func (ob *Observer) WatchOutbound() { if result != nil && !inMempool { // included txCount++ txResult = result - ob.logger.Outbound.Info().Msgf("WatchOutbound: included outbound %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, tracker.Nonce) + ob.logger.Outbound.Info(). + Msgf("WatchOutbound: included outbound %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, tracker.Nonce) if txCount > 1 { ob.logger.Outbound.Error().Msgf( "WatchOutbound: checkIncludedTx passed, txCount %d chain %d nonce %d result %v", txCount, ob.chain.ChainId, tracker.Nonce, result) @@ -168,7 +177,9 @@ func (ob *Observer) IsOutboundProcessed(cctx *crosschaintypes.CrossChainTx, logg coin.CoinType_Gas, ) if err != nil { - logger.Error().Err(err).Msgf("IsOutboundProcessed: error confirming bitcoin outbound %s, nonce %d ballot %s", res.TxID, nonce, ballot) + logger.Error(). + Err(err). + Msgf("IsOutboundProcessed: error confirming bitcoin outbound %s, nonce %d ballot %s", res.TxID, nonce, ballot) } else if zetaHash != "" { logger.Info().Msgf("IsOutboundProcessed: confirmed Bitcoin outbound %s, zeta tx hash %s nonce %d ballot %s", res.TxID, zetaHash, nonce, ballot) } @@ -246,7 +257,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 +312,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 +337,12 @@ func (ob *Observer) getOutboundIDByNonce(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, "getOutboundIDByNonce: error getting outbound result for nonce %d hash %s", nonce, txid) + return "", errors.Wrapf( + err, + "getOutboundIDByNonce: error getting outbound result for nonce %d hash %s", + nonce, + txid, + ) } if getTxResult.Confirmations <= 0 { // just a double check return "", fmt.Errorf("getOutboundIDByNonce: outbound txid %s for nonce %d is not included", txid, nonce) @@ -340,7 +361,8 @@ func (ob *Observer) findNonceMarkUTXO(nonce uint64, txid string) (int, error) { ob.logger.Outbound.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.Outbound.Info().Msgf("findNonceMarkUTXO: found nonce-mark utxo with txid %s, amount %d satoshi", utxo.TxID, sats) + ob.logger.Outbound.Info(). + Msgf("findNonceMarkUTXO: found nonce-mark utxo with txid %s, amount %d satoshi", utxo.TxID, sats) return i, nil } } @@ -349,7 +371,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) { outboundID := ob.GetTxID(cctx.GetCurrentOutboundParam().TssNonce) hash, getTxResult, err := GetTxResultByHash(ob.rpcClient, txHash) if err != nil { @@ -358,14 +383,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.Outbound.Error().Msgf("checkIncludedTx: inconsistent txHash %s and getTxResult.TxID %s", txHash, getTxResult.TxID) + ob.logger.Outbound.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.checkTssOutboundResult(cctx, hash, getTxResult) if err != nil { - ob.logger.Outbound.Error().Err(err).Msgf("checkIncludedTx: error verify bitcoin outbound %s outboundID %s", txHash, outboundID) + ob.logger.Outbound.Error(). + Err(err). + Msgf("checkIncludedTx: error verify bitcoin outbound %s outboundID %s", txHash, outboundID) return nil, false } return getTxResult, false // included @@ -388,7 +416,8 @@ func (ob *Observer) setIncludedTx(nonce uint64, getTxResult *btcjson.GetTransact if nonce >= ob.pendingNonce { // try increasing pending nonce on every newly included outbound ob.pendingNonce = nonce + 1 } - ob.logger.Outbound.Info().Msgf("setIncludedTx: included new bitcoin outbound %s outboundID %s pending nonce %d", txHash, outboundID, ob.pendingNonce) + ob.logger.Outbound.Info(). + Msgf("setIncludedTx: included new bitcoin outbound %s outboundID %s pending nonce %d", txHash, outboundID, ob.pendingNonce) } else if txHash == res.TxID { // found same hash. ob.includedTxResults[outboundID] = getTxResult // update tx result as confirmations may increase if getTxResult.Confirmations > res.Confirmations { @@ -424,7 +453,11 @@ func (ob *Observer) removeIncludedTx(nonce uint64) { // - check if all inputs are segwit && TSS inputs // // Returns: true if outbound passes basic checks. -func (ob *Observer) checkTssOutboundResult(cctx *crosschaintypes.CrossChainTx, hash *chainhash.Hash, res *btcjson.GetTransactionResult) error { +func (ob *Observer) checkTssOutboundResult( + cctx *crosschaintypes.CrossChainTx, + hash *chainhash.Hash, + res *btcjson.GetTransactionResult, +) error { params := cctx.GetCurrentOutboundParam() nonce := params.TssNonce rawResult, err := GetRawTxResult(ob.rpcClient, hash, res) @@ -440,7 +473,12 @@ func (ob *Observer) checkTssOutboundResult(cctx *crosschaintypes.CrossChainTx, h if compliance.IsCctxRestricted(cctx) { err = ob.checkTSSVoutCancelled(params, rawResult.Vout) if err != nil { - return errors.Wrapf(err, "checkTssOutboundResult: invalid TSS Vout in cancelled outbound %s nonce %d", hash, nonce) + return errors.Wrapf( + err, + "checkTssOutboundResult: invalid TSS Vout in cancelled outbound %s nonce %d", + hash, + nonce, + ) } } else { err = ob.checkTSSVout(params, rawResult.Vout) @@ -476,7 +514,12 @@ func (ob *Observer) checkTSSVin(vins []btcjson.Vin, nonce uint64) error { } // nonce-mark MUST the 1st output that comes from prior TSS outbound 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 +552,26 @@ func (ob *Observer) checkTSSVout(params *crosschaintypes.OutboundParams, 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 +606,26 @@ func (ob *Observer) checkTSSVoutCancelled(params *crosschaintypes.OutboundParams 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 1e291d1803..726d12a2a0 100644 --- a/zetaclient/chains/bitcoin/observer/outbound_test.go +++ b/zetaclient/chains/bitcoin/observer/outbound_test.go @@ -9,6 +9,7 @@ import ( "github.com/btcsuite/btcd/btcjson" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/context" @@ -65,7 +66,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 +319,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 +397,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 +420,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 6cef73a211..0c51fc7204 100644 --- a/zetaclient/chains/bitcoin/signer/signer.go +++ b/zetaclient/chains/bitcoin/signer/signer.go @@ -16,6 +16,7 @@ import ( "github.com/btcsuite/btcutil" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -185,7 +186,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 +216,17 @@ func (signer *Signer) SignWithdrawTx( return nil, err } if sizeLimit < bitcoin.BtcOutboundBytesWithdrawer { // ZRC20 'withdraw' charged less fee from end user - signer.logger.Info().Msgf("sizeLimit %d is less than BtcOutboundBytesWithdrawer %d for nonce %d", sizeLimit, txSize, nonce) + signer.logger.Info(). + Msgf("sizeLimit %d is less than BtcOutboundBytesWithdrawer %d for nonce %d", sizeLimit, txSize, nonce) } if txSize < bitcoin.OutboundBytesMin { // outbound shouldn't be blocked a low sizeLimit - signer.logger.Warn().Msgf("txSize %d is less than outboundBytesMin %d; use outboundBytesMin", txSize, bitcoin.OutboundBytesMin) + signer.logger.Warn(). + Msgf("txSize %d is less than outboundBytesMin %d; use outboundBytesMin", txSize, bitcoin.OutboundBytesMin) txSize = bitcoin.OutboundBytesMin } if txSize > bitcoin.OutboundBytesMax { // in case of accident - signer.logger.Warn().Msgf("txSize %d is greater than outboundBytesMax %d; use outboundBytesMax", txSize, bitcoin.OutboundBytesMax) + signer.logger.Warn(). + Msgf("txSize %d is greater than outboundBytesMax %d; use outboundBytesMax", txSize, bitcoin.OutboundBytesMax) txSize = bitcoin.OutboundBytesMax } @@ -324,7 +334,8 @@ func (signer *Signer) TryProcessOutbound( return } - logger.Info().Msgf("BTC TryProcessOutbound: %s, value %d to %s", cctx.Index, params.Amount.BigInt(), params.Receiver) + logger.Info(). + Msgf("BTC TryProcessOutbound: %s, value %d to %s", cctx.Index, params.Amount.BigInt(), params.Receiver) btcObserver, ok := chainObserver.(*observer.Observer) if !ok { logger.Error().Msgf("chain observer is not a bitcoin observer") @@ -397,16 +408,20 @@ func (signer *Signer) TryProcessOutbound( logger.Warn().Err(err).Msgf("SignOutbound error: nonce %d chain %d", outboundTssNonce, params.ReceiverChainId) return } - logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundParams.SenderChainId, chain.ChainName, outboundTssNonce) + logger.Info(). + Msgf("Key-sign success: %d => %s, nonce %d", cctx.InboundParams.SenderChainId, chain.ChainName, outboundTssNonce) // FIXME: add prometheus metrics _, err = zetacoreClient.GetObserverList() if err != nil { - logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", outboundTssNonce, observertypes.ObservationType_OutBoundTx.String()) + logger.Warn(). + Err(err). + Msgf("unable to get observer list: chain %d observation %s", outboundTssNonce, observertypes.ObservationType_OutBoundTx.String()) } if tx != nil { outboundHash := tx.TxHash().String() - logger.Info().Msgf("on chain %s nonce %d, outboundHash %s signer %s", chain.ChainName, outboundTssNonce, outboundHash, signerAddress) + logger.Info(). + Msgf("on chain %s nonce %d, outboundHash %s signer %s", chain.ChainName, outboundTssNonce, outboundHash, signerAddress) // TODO: pick a few broadcasters. //if len(signers) == 0 || myid == signers[send.OutboundParams.Broadcaster] || myid == signers[int(send.OutboundParams.Broadcaster+1)%len(signers)] { // retry loop: 1s, 2s, 4s, 8s, 16s in case of RPC error @@ -415,13 +430,24 @@ func (signer *Signer) TryProcessOutbound( 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", outboundHash, chain.ChainName, outboundTssNonce, i) + logger.Warn(). + Err(err). + Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outboundHash, chain.ChainName, outboundTssNonce, i) continue } - logger.Info().Msgf("Broadcast success: nonce %d to chain %s outboundHash %s", outboundTssNonce, chain.String(), outboundHash) - zetaHash, err := zetacoreClient.AddOutboundTracker(chain.ChainId, outboundTssNonce, outboundHash, nil, "", -1) + logger.Info(). + Msgf("Broadcast success: nonce %d to chain %s outboundHash %s", outboundTssNonce, chain.String(), outboundHash) + zetaHash, err := zetacoreClient.AddOutboundTracker( + chain.ChainId, + outboundTssNonce, + outboundHash, + nil, + "", + -1, + ) if err != nil { - logger.Err(err).Msgf("Unable to add to tracker on zetacore: nonce %d chain %s outboundHash %s", outboundTssNonce, chain.ChainName, outboundHash) + logger.Err(err). + Msgf("Unable to add to tracker on zetacore: nonce %d chain %s outboundHash %s", outboundTssNonce, chain.ChainName, outboundHash) } 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..8cc90cf3eb 100644 --- a/zetaclient/chains/bitcoin/signer/signer_keysign_test.go +++ b/zetaclient/chains/bitcoin/signer/signer_keysign_test.go @@ -14,6 +14,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" "github.com/stretchr/testify/suite" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin" "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" @@ -107,7 +108,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 +133,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..ef4ea522d3 100644 --- a/zetaclient/chains/bitcoin/signer/signer_test.go +++ b/zetaclient/chains/bitcoin/signer/signer_test.go @@ -15,6 +15,8 @@ import ( "github.com/btcsuite/btcutil" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" + . "gopkg.in/check.v1" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin" clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" @@ -22,7 +24,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/context" "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" - . "gopkg.in/check.v1" ) type BTCSignerSuite struct { @@ -173,7 +174,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 +200,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 +230,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/bitcoin/tx_script.go b/zetaclient/chains/bitcoin/tx_script.go index f68fc0e224..2259e8c555 100644 --- a/zetaclient/chains/bitcoin/tx_script.go +++ b/zetaclient/chains/bitcoin/tx_script.go @@ -12,9 +12,10 @@ import ( "github.com/btcsuite/btcutil" "github.com/cosmos/btcutil/base58" "github.com/pkg/errors" + "golang.org/x/crypto/ripemd160" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/constant" - "golang.org/x/crypto/ripemd160" ) const ( diff --git a/zetaclient/chains/bitcoin/tx_script_test.go b/zetaclient/chains/bitcoin/tx_script_test.go index 6e638e8b2f..26df8aa1f0 100644 --- a/zetaclient/chains/bitcoin/tx_script_test.go +++ b/zetaclient/chains/bitcoin/tx_script_test.go @@ -9,6 +9,7 @@ import ( "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/constant" "github.com/zeta-chain/zetacore/zetaclient/testutils" diff --git a/zetaclient/chains/evm/observer/inbound.go b/zetaclient/chains/evm/observer/inbound.go index 2670c1708a..373536fe6d 100644 --- a/zetaclient/chains/evm/observer/inbound.go +++ b/zetaclient/chains/evm/observer/inbound.go @@ -19,6 +19,7 @@ import ( "github.com/rs/zerolog" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/constant" @@ -34,7 +35,10 @@ import ( // WatchInbound watches evm chain for incoming txs and post votes to zetacore func (ob *Observer) WatchInbound() { - ticker, err := clienttypes.NewDynamicTicker(fmt.Sprintf("EVM_WatchInbound_%d", ob.chain.ChainId), ob.GetChainParams().InboundTicker) + ticker, err := clienttypes.NewDynamicTicker( + fmt.Sprintf("EVM_WatchInbound_%d", ob.chain.ChainId), + ob.GetChainParams().InboundTicker, + ) if err != nil { ob.logger.Inbound.Error().Err(err).Msg("error creating ticker") return @@ -48,7 +52,8 @@ func (ob *Observer) WatchInbound() { select { case <-ticker.C(): if !clientcontext.IsInboundObservationEnabled(ob.coreContext, ob.GetChainParams()) { - sampledLogger.Info().Msgf("WatchInbound: inbound observation is disabled for chain %d", ob.chain.ChainId) + sampledLogger.Info(). + Msgf("WatchInbound: inbound observation is disabled for chain %d", ob.chain.ChainId) continue } err := ob.ObserveInbound(sampledLogger) @@ -105,7 +110,12 @@ func (ob *Observer) ProcessInboundTrackers() error { // query tx and receipt tx, _, err := ob.TransactionByHash(tracker.TxHash) if err != nil { - return errors.Wrapf(err, "error getting transaction for inbound %s chain %d", tracker.TxHash, ob.chain.ChainId) + return errors.Wrapf( + err, + "error getting transaction for inbound %s chain %d", + tracker.TxHash, + ob.chain.ChainId, + ) } receipt, err := ob.evmClient.TransactionReceipt(context.Background(), ethcommon.HexToHash(tracker.TxHash)) @@ -123,7 +133,12 @@ func (ob *Observer) ProcessInboundTrackers() error { case coin.CoinType_Gas: _, err = ob.CheckAndVoteInboundTokenGas(tx, receipt, true) default: - return fmt.Errorf("unknown coin type %s for inbound %s chain %d", tracker.CoinType, tx.Hash, ob.chain.ChainId) + return fmt.Errorf( + "unknown coin type %s for inbound %s chain %d", + tracker.CoinType, + tx.Hash, + ob.chain.ChainId, + ) } if err != nil { return errors.Wrapf(err, "error checking and voting for inbound %s chain %d", tx.Hash, ob.chain.ChainId) @@ -139,7 +154,11 @@ func (ob *Observer) ObserveInbound(sampledLogger zerolog.Logger) error { return err } if blockNumber < ob.GetLastBlockHeight() { - return fmt.Errorf("observeInbound: block number should not decrease: current %d last %d", blockNumber, ob.GetLastBlockHeight()) + return fmt.Errorf( + "observeInbound: block number should not decrease: current %d last %d", + blockNumber, + ob.GetLastBlockHeight(), + ) } ob.SetLastBlockHeight(blockNumber) @@ -155,7 +174,8 @@ func (ob *Observer) ObserveInbound(sampledLogger zerolog.Logger) error { // skip if no new block is confirmed lastScanned := ob.GetLastBlockHeightScanned() if lastScanned >= confirmedBlockNum { - sampledLogger.Debug().Msgf("observeInbound: skipping observer, no new block is produced for chain %d", ob.chain.ChainId) + sampledLogger.Debug(). + Msgf("observeInbound: skipping observer, no new block is produced for chain %d", ob.chain.ChainId) return nil } @@ -183,11 +203,14 @@ func (ob *Observer) ObserveInbound(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("observeInbound: lasstScanned heights for chain %d ZetaSent %d ERC20Deposited %d TssRecvd %d", - ob.chain.ChainId, lastScannedZetaSent, lastScannedDeposited, lastScannedTssRecvd) + sampledLogger.Info(). + Msgf("observeInbound: 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.Inbound.Error().Err(err).Msgf("observeInbound: error writing lastScannedLowest %d to db", lastScannedLowest) + ob.logger.Inbound.Error(). + Err(err). + Msgf("observeInbound: error writing lastScannedLowest %d to db", lastScannedLowest) } } return nil @@ -222,8 +245,10 @@ func (ob *Observer) ObserveZetaSent(startBlock, toBlock uint64) uint64 { events = append(events, iter.Event) continue } - ob.logger.Inbound.Warn().Err(err).Msgf("ObserveZetaSent: invalid ZetaSent event in tx %s on chain %d at height %d", - iter.Event.Raw.TxHash.Hex(), ob.chain.ChainId, iter.Event.Raw.BlockNumber) + ob.logger.Inbound.Warn(). + Err(err). + Msgf("ObserveZetaSent: invalid ZetaSent 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 { @@ -248,14 +273,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.Inbound.Warn().Msgf("ObserveZetaSent: multiple remote call events detected in tx %s", event.Raw.TxHash) + ob.logger.Inbound.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 +325,10 @@ func (ob *Observer) ObserveERC20Deposited(startBlock, toBlock uint64) uint64 { events = append(events, iter.Event) continue } - ob.logger.Inbound.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.Inbound.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 +361,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.Inbound.Warn().Msgf("ObserveERC20Deposited: multiple remote call events detected in tx %s", event.Raw.TxHash) + ob.logger.Inbound.Warn(). + Msgf("ObserveERC20Deposited: multiple remote call events detected in tx %s", event.Raw.TxHash) continue } guard[event.Raw.TxHash.Hex()] = true @@ -368,7 +401,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.Inbound.Error().Err(err).Msgf("ObserverTSSReceive: error observing TSS received token in block %d for chain %d", bn, ob.chain.ChainId) + ob.logger.Inbound.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 +412,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("inbound %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "inbound %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // get zeta connector contract @@ -418,10 +461,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("inbound %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "inbound %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // get erc20 custody contract @@ -460,10 +511,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("inbound %s has not been confirmed yet: receipt block %d", tx.Hash, receipt.BlockNumber.Uint64()) + return "", fmt.Errorf( + "inbound %s has not been confirmed yet: receipt block %d", + tx.Hash, + receipt.BlockNumber.Uint64(), + ) } // checks receiver and tx status @@ -490,12 +549,17 @@ func (ob *Observer) CheckAndVoteInboundTokenGas(tx *ethrpc.Transaction, receipt } // PostVoteInbound posts a vote for the given vote message -func (ob *Observer) PostVoteInbound(msg *types.MsgVoteInbound, coinType coin.CoinType, retryGasLimit uint64) (string, error) { +func (ob *Observer) PostVoteInbound( + msg *types.MsgVoteInbound, + coinType coin.CoinType, + retryGasLimit uint64, +) (string, error) { txHash := msg.InboundHash chainID := ob.chain.ChainId zetaHash, ballot, err := ob.zetacoreClient.PostVoteInbound(zetacore.PostVoteInboundGasLimit, retryGasLimit, msg) if err != nil { - ob.logger.Inbound.Err(err).Msgf("inbound detected: error posting vote for chain %d token %s inbound %s", chainID, coinType, txHash) + ob.logger.Inbound.Err(err). + Msgf("inbound detected: error posting vote for chain %d token %s inbound %s", chainID, coinType, txHash) return "", err } else if zetaHash != "" { ob.logger.Inbound.Info().Msgf("inbound detected: chain %d token %s inbound %s vote %s ballot %s", chainID, coinType, txHash, zetaHash, ballot) @@ -513,7 +577,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.MsgVoteInbound { +func (ob *Observer) BuildInboundVoteMsgForDepositedEvent( + event *erc20custody.ERC20CustodyDeposited, + sender ethcommon.Address, +) *types.MsgVoteInbound { // compliance check maybeReceiver := "" parsedAddress, _, err := chains.ParseAddressAndData(hex.EncodeToString(event.Message)) @@ -521,19 +588,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.Inbound, ob.logger.Compliance, - false, ob.chain.ChainId, event.Raw.TxHash.Hex(), sender.Hex(), clienttypes.BytesToEthHex(event.Recipient), "ERC20") + compliance.PrintComplianceLog( + ob.logger.Inbound, + 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.Inbound.Info().Msgf("thank you rich folk for your donation! tx %s chain %d", event.Raw.TxHash.Hex(), ob.chain.ChainId) + ob.logger.Inbound.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.Inbound.Info().Msgf("ERC20CustodyDeposited inbound 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.Inbound.Info(). + Msgf("ERC20CustodyDeposited inbound 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 +631,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.MsgVoteInbound { +func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent( + event *zetaconnector.ZetaConnectorNonEthZetaSent, +) *types.MsgVoteInbound { destChain := chains.GetChainFromChainID(event.DestinationChainId.Int64()) if destChain == nil { ob.logger.Inbound.Warn().Msgf("chain id not supported %d", event.DestinationChainId.Int64()) @@ -573,12 +652,14 @@ func (ob *Observer) BuildInboundVoteMsgForZetaSentEvent(event *zetaconnector.Zet if !destChain.IsZetaChain() { paramsDest, found := ob.coreContext.GetEVMChainParams(destChain.ChainId) if !found { - ob.logger.Inbound.Warn().Msgf("chain id not present in EVMChainParams %d", event.DestinationChainId.Int64()) + ob.logger.Inbound.Warn(). + Msgf("chain id not present in EVMChainParams %d", event.DestinationChainId.Int64()) return nil } if strings.EqualFold(destAddr, paramsDest.ZetaTokenContractAddress) { - ob.logger.Inbound.Warn().Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr) + ob.logger.Inbound.Warn(). + Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr) return nil } } @@ -605,7 +686,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.MsgVoteInbound { +func (ob *Observer) BuildInboundVoteMsgForTokenSentToTSS( + tx *ethrpc.Transaction, + sender ethcommon.Address, + blockNumber uint64, +) *types.MsgVoteInbound { message := tx.Input // compliance check @@ -624,7 +709,8 @@ func (ob *Observer) BuildInboundVoteMsgForTokenSentToTSS(tx *ethrpc.Transaction, // #nosec G703 err is already checked data, _ := hex.DecodeString(message) if bytes.Equal(data, []byte(constant.DonationMessage)) { - ob.logger.Inbound.Info().Msgf("thank you rich folk for your donation! tx %s chain %d", tx.Hash, ob.chain.ChainId) + ob.logger.Inbound.Info(). + Msgf("thank you rich folk for your donation! tx %s chain %d", tx.Hash, ob.chain.ChainId) return nil } ob.logger.Inbound.Info().Msgf("TSS inbound detected on chain %d tx %s block %d from %s value %s message %s", @@ -665,7 +751,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 inbound %s chain %d", tx.Hash, ob.chain.ChainId) + return errors.Wrapf( + err, + "error checking and voting inbound gas asset for inbound %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 308b89efd9..21d372a4ce 100644 --- a/zetaclient/chains/evm/observer/inbound_test.go +++ b/zetaclient/chains/evm/observer/inbound_test.go @@ -8,6 +8,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/onrik/ethrpc" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/constant" @@ -29,7 +30,13 @@ func Test_CheckAndVoteInboundTokenZeta(t *testing.T) { inboundHash := "0xf3935200c80f98502d5edc7e871ffc40ca898e134525c42c2ae3cbc5725f9d76" t.Run("should pass for archived inbound, receipt and cctx", func(t *testing.T) { - tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_Zeta) + tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_Zeta, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -39,7 +46,13 @@ func Test_CheckAndVoteInboundTokenZeta(t *testing.T) { require.Equal(t, cctx.InboundParams.BallotIndex, ballot) }) t.Run("should fail on unconfirmed inbound", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_Zeta) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_Zeta, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation - 1 @@ -48,7 +61,13 @@ func Test_CheckAndVoteInboundTokenZeta(t *testing.T) { require.ErrorContains(t, err, "not been confirmed") }) t.Run("should not act if no ZetaSent event", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_Zeta) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_Zeta, + ) receipt.Logs = receipt.Logs[:2] // remove ZetaSent event require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -59,7 +78,13 @@ func Test_CheckAndVoteInboundTokenZeta(t *testing.T) { require.Equal(t, "", ballot) }) t.Run("should not act if emitter is not ZetaConnector", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_Zeta) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_Zeta, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -80,7 +105,13 @@ func Test_CheckAndVoteInboundTokenERC20(t *testing.T) { inboundHash := "0x4ea69a0e2ff36f7548ab75791c3b990e076e2a4bffeb616035b239b7d33843da" t.Run("should pass for archived inbound, receipt and cctx", func(t *testing.T) { - tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_ERC20) + tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_ERC20, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -90,7 +121,13 @@ func Test_CheckAndVoteInboundTokenERC20(t *testing.T) { require.Equal(t, cctx.InboundParams.BallotIndex, ballot) }) t.Run("should fail on unconfirmed inbound", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_ERC20) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_ERC20, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation - 1 @@ -99,7 +136,13 @@ func Test_CheckAndVoteInboundTokenERC20(t *testing.T) { require.ErrorContains(t, err, "not been confirmed") }) t.Run("should not act if no Deposit event", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_ERC20) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_ERC20, + ) receipt.Logs = receipt.Logs[:1] // remove Deposit event require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -110,7 +153,13 @@ func Test_CheckAndVoteInboundTokenERC20(t *testing.T) { require.Equal(t, "", ballot) }) t.Run("should not act if emitter is not ERC20 Custody", func(t *testing.T) { - tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_ERC20) + tx, receipt, _ := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_ERC20, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -131,7 +180,13 @@ func Test_CheckAndVoteInboundTokenGas(t *testing.T) { inboundHash := "0xeaec67d5dd5d85f27b21bef83e01cbdf59154fd793ea7a22c297f7c3a722c532" t.Run("should pass for archived inbound, receipt and cctx", func(t *testing.T) { - tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx(t, TestDataDir, chainID, inboundHash, coin.CoinType_Gas) + tx, receipt, cctx := testutils.LoadEVMInboundNReceiptNCctx( + t, + TestDataDir, + chainID, + inboundHash, + coin.CoinType_Gas, + ) require.NoError(t, evm.ValidateEvmTransaction(tx)) lastBlock := receipt.BlockNumber.Uint64() + confirmation @@ -289,7 +344,13 @@ func Test_BuildInboundVoteMsgForTokenSentToTSS(t *testing.T) { // load archived gas token donation to TSS // https://etherscan.io/tx/0x52f214cf7b10be71f4d274193287d47bc9632b976e69b9d2cdeb527c2ba32155 inboundHashDonation := "0x52f214cf7b10be71f4d274193287d47bc9632b976e69b9d2cdeb527c2ba32155" - txDonation, receiptDonation := testutils.LoadEVMInboundNReceiptDonation(t, TestDataDir, chainID, inboundHashDonation, coin.CoinType_Gas) + txDonation, receiptDonation := testutils.LoadEVMInboundNReceiptDonation( + t, + TestDataDir, + chainID, + inboundHashDonation, + coin.CoinType_Gas, + ) require.NoError(t, evm.ValidateEvmTransaction(txDonation)) // create test compliance config @@ -299,14 +360,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.InboundParams.BallotIndex, 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) { @@ -316,7 +385,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 8b20374415..e584c0a414 100644 --- a/zetaclient/chains/evm/observer/observer.go +++ b/zetaclient/chains/evm/observer/observer.go @@ -24,6 +24,9 @@ import ( "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zeta.non-eth.sol" zetaconnectoreth "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.eth.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" observertypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -34,8 +37,6 @@ import ( clientcontext "github.com/zeta-chain/zetacore/zetaclient/context" "github.com/zeta-chain/zetacore/zetaclient/metrics" clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" - "gorm.io/driver/sqlite" - "gorm.io/gorm" ) // Logger is the logger for evm chains @@ -250,19 +251,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 +326,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 +391,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.outboundConfirmedReceipts[ob.GetTxID(nonce)] != nil && ob.outboundConfirmedTransactions[ob.GetTxID(nonce)] != nil + return ob.outboundConfirmedReceipts[ob.GetTxID(nonce)] != nil && + ob.outboundConfirmedTransactions[ob.GetTxID(nonce)] != nil } // CheckTxInclusion returns nil only if tx is included at the position indicated by the receipt ([block, index]) @@ -434,7 +450,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 @@ -601,7 +620,9 @@ func (ob *Observer) LoadDB(dbPath string, chain chains.Chain) error { path := fmt.Sprintf("%s/%s", dbPath, chain.ChainName.String()) //Use "file::memory:?cache=shared" for temp db db, err := gorm.Open(sqlite.Open(path), &gorm.Config{}) if err != nil { - ob.logger.Chain.Error().Err(err).Msgf("failed to open observer database for %s", ob.chain.ChainName.String()) + ob.logger.Chain.Error(). + Err(err). + Msgf("failed to open observer database for %s", ob.chain.ChainName.String()) return err } diff --git a/zetaclient/chains/evm/observer/observer_db_test.go b/zetaclient/chains/evm/observer/observer_db_test.go index d9d1cda1c1..524bdb5cf5 100644 --- a/zetaclient/chains/evm/observer/observer_db_test.go +++ b/zetaclient/chains/evm/observer/observer_db_test.go @@ -9,9 +9,10 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/suite" - clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" "gorm.io/driver/sqlite" "gorm.io/gorm" + + clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" ) const TempSQLiteDbPath = "file::memory:?cache=shared" diff --git a/zetaclient/chains/evm/observer/observer_test.go b/zetaclient/chains/evm/observer/observer_test.go index bb9b3d848b..bfc85e15e1 100644 --- a/zetaclient/chains/evm/observer/observer_test.go +++ b/zetaclient/chains/evm/observer/observer_test.go @@ -5,11 +5,11 @@ import ( "testing" "cosmossdk.io/math" - lru "github.com/hashicorp/golang-lru" "github.com/onrik/ethrpc" "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" @@ -29,7 +29,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 8e144f6a3d..8dda7ac034 100644 --- a/zetaclient/chains/evm/observer/outbound.go +++ b/zetaclient/chains/evm/observer/outbound.go @@ -16,6 +16,7 @@ import ( "github.com/rs/zerolog/log" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -34,7 +35,10 @@ func (ob *Observer) GetTxID(nonce uint64) string { // WatchOutbound watches evm chain for outgoing txs status func (ob *Observer) WatchOutbound() { - ticker, err := clienttypes.NewDynamicTicker(fmt.Sprintf("EVM_WatchOutbound_%d", ob.chain.ChainId), ob.GetChainParams().OutboundTicker) + ticker, err := clienttypes.NewDynamicTicker( + fmt.Sprintf("EVM_WatchOutbound_%d", ob.chain.ChainId), + ob.GetChainParams().OutboundTicker, + ) if err != nil { ob.logger.Outbound.Error().Err(err).Msg("error creating ticker") return @@ -47,7 +51,8 @@ func (ob *Observer) WatchOutbound() { select { case <-ticker.C(): if !clientcontext.IsOutboundObservationEnabled(ob.coreContext, ob.GetChainParams()) { - sampledLogger.Info().Msgf("WatchOutbound: outbound observation is disabled for chain %d", ob.chain.ChainId) + sampledLogger.Info(). + Msgf("WatchOutbound: outbound observation is disabled for chain %d", ob.chain.ChainId) continue } trackers, err := ob.zetacoreClient.GetAllOutboundTrackerByChain(ob.chain.ChainId, interfaces.Ascending) @@ -67,7 +72,8 @@ func (ob *Observer) WatchOutbound() { txCount++ outboundReceipt = receipt outbound = tx - ob.logger.Outbound.Info().Msgf("WatchOutbound: confirmed outbound %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, nonceInt) + ob.logger.Outbound.Info(). + Msgf("WatchOutbound: confirmed outbound %s for chain %d nonce %d", txHash.TxHash, ob.chain.ChainId, nonceInt) if txCount > 1 { ob.logger.Outbound.Error().Msgf( "WatchOutbound: checkConfirmedTx passed, txCount %d chain %d nonce %d receipt %v transaction %v", txCount, ob.chain.ChainId, nonceInt, outboundReceipt, outbound) @@ -114,7 +120,9 @@ func (ob *Observer) PostVoteOutbound( cointype, ) if err != nil { - logger.Error().Err(err).Msgf("PostVoteOutbound: error posting vote for chain %d nonce %d outbound %s ", chainID, nonce, receipt.TxHash) + logger.Error(). + Err(err). + Msgf("PostVoteOutbound: error posting vote for chain %d nonce %d outbound %s ", chainID, nonce, receipt.TxHash) } else if zetaTxHash != "" { logger.Info().Msgf("PostVoteOutbound: posted vote for chain %d nonce %d outbound %s vote %s ballot %s", chainID, nonce, receipt.TxHash, zetaTxHash, ballot) } @@ -160,9 +168,20 @@ func (ob *Observer) IsOutboundProcessed(cctx *crosschaintypes.CrossChainTx, logg } // parse the received value from the outbound receipt - receiveValue, receiveStatus, err = ParseOutboundReceivedValue(cctx, receipt, transaction, cointype, connectorAddr, connector, custodyAddr, custody) + receiveValue, receiveStatus, err = ParseOutboundReceivedValue( + cctx, + receipt, + transaction, + cointype, + connectorAddr, + connector, + custodyAddr, + custody, + ) if err != nil { - logger.Error().Err(err).Msgf("IsOutboundProcessed: error parsing outbound event for chain %d txhash %s", ob.chain.ChainId, receipt.TxHash) + logger.Error(). + Err(err). + Msgf("IsOutboundProcessed: error parsing outbound event for chain %d txhash %s", ob.chain.ChainId, receipt.TxHash) return false, false, err } @@ -209,7 +228,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.InboundParams.Sender) { + if !strings.EqualFold( + ethcommon.BytesToAddress(reverted.DestinationAddress[:]).Hex(), + cctx.InboundParams.Sender, + ) { return nil, nil, fmt.Errorf("receiver address mismatch in ZetaReverted event, want %s got %s", cctx.InboundParams.Sender, ethcommon.BytesToAddress(reverted.DestinationAddress[:]).Hex()) } @@ -322,7 +344,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 outbound %s chain %d", txHash, ob.chain.ChainId) + log.Error(). + Err(err). + Msgf("confirmTxByHash: error getting transaction for outbound %s chain %d", txHash, ob.chain.ChainId) return nil, nil, false } if transaction == nil { // should not happen @@ -334,7 +358,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 outbound %s chain %d", transaction.Hash().Hex(), ob.chain.ChainId) + log.Error(). + Err(err). + Msgf("confirmTxByHash: local recovery of sender address failed for outbound %s chain %d", transaction.Hash().Hex(), ob.chain.ChainId) return nil, nil, false } if from != ob.Tss.EVMAddress() { // must be TSS address @@ -343,7 +369,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: outbound %s nonce mismatch: wanted %d, got tx nonce %d", txHash, nonce, transaction.Nonce()) + log.Error(). + Msgf("confirmTxByHash: outbound %s nonce mismatch: wanted %d, got tx nonce %d", txHash, nonce, transaction.Nonce()) return nil, nil, false } @@ -368,8 +395,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 da4525e624..d757938c46 100644 --- a/zetaclient/chains/evm/observer/outbound_test.go +++ b/zetaclient/chains/evm/observer/outbound_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" @@ -19,7 +20,10 @@ import ( ) // getContractsByChainID is a helper func to get contracts and addresses by chainID -func getContractsByChainID(t *testing.T, chainID int64) (*zetaconnector.ZetaConnectorNonEth, ethcommon.Address, *erc20custody.ERC20Custody, ethcommon.Address) { +func getContractsByChainID( + t *testing.T, + chainID int64, +) (*zetaconnector.ZetaConnectorNonEth, ethcommon.Address, *erc20custody.ERC20Custody, ethcommon.Address) { connector := mocks.MockConnectorNonEth(t, chainID) connectorAddress := testutils.ConnectorAddresses[chainID] custody := mocks.MockERC20Custody(t, chainID) @@ -36,8 +40,21 @@ func Test_IsOutboundProcessed(t *testing.T) { chainParam := mocks.MockChainParams(chain.ChainId, 1) outboundHash := "0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f" cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_Zeta, testutils.EventZetaReceived) - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) t.Run("should post vote and return true if outbound is processed", func(t *testing.T) { // create evm client and set outbound and receipt @@ -113,8 +130,21 @@ func Test_IsOutboundProcessed_ContractError(t *testing.T) { chainParam := mocks.MockChainParams(chain.ChainId, 1) outboundHash := "0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f" cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_Zeta, testutils.EventZetaReceived) - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + 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 outbound and receipt @@ -148,7 +178,13 @@ func Test_PostVoteOutbound(t *testing.T) { chain := chains.EthChain nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chain.ChainId, nonce, testutils.EventZetaReceived) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + 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 +194,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, outbound, receiveValue, receiveStatus, nonce, coinType, zerolog.Logger{}) + client.PostVoteOutbound( + cctx.Index, + receipt, + outbound, + receiveValue, + receiveStatus, + nonce, + coinType, + zerolog.Logger{}, + ) // pause the mock zetacore client to simulate error posting vote zetacoreClient.Pause() - client.PostVoteOutbound(cctx.Index, receipt, outbound, receiveValue, receiveStatus, nonce, coinType, zerolog.Logger{}) + client.PostVoteOutbound( + cctx.Index, + receipt, + outbound, + receiveValue, + receiveStatus, + nonce, + coinType, + zerolog.Logger{}, + ) }) } @@ -175,7 +229,14 @@ func Test_ParseZetaReceived(t *testing.T) { connector := mocks.MockConnectorNonEth(t, chainID) connectorAddress := testutils.ConnectorAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_Zeta, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + coin.CoinType_Zeta, + testutils.EventZetaReceived, + ) t.Run("should parse ZetaReceived event from archived outbound receipt", func(t *testing.T) { receivedLog, revertedLog, err := observer.ParseAndCheckZetaEvent(cctx, receipt, connectorAddress, connector) @@ -219,7 +280,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.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_Zeta, testutils.EventZetaReceived) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + 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 +304,14 @@ func Test_ParseZetaReverted(t *testing.T) { connector := mocks.MockConnectorNonEth(t, chainID) connectorAddress := testutils.ConnectorAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_Zeta, testutils.EventZetaReverted) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + coin.CoinType_Zeta, + testutils.EventZetaReverted, + ) t.Run("should parse ZetaReverted event from archived outbound receipt", func(t *testing.T) { receivedLog, revertedLog, err := observer.ParseAndCheckZetaEvent(cctx, receipt, connectorAddress, connector) @@ -288,7 +363,14 @@ func Test_ParseERC20WithdrawnEvent(t *testing.T) { custody := mocks.MockERC20Custody(t, chainID) custodyAddress := testutils.CustodyAddresses[chainID] cctx := testutils.LoadCctxByNonce(t, chainID, nonce) - receipt := testutils.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_ERC20, testutils.EventERC20Withdraw) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + coin.CoinType_ERC20, + testutils.EventERC20Withdraw, + ) t.Run("should parse ERC20 Withdrawn event from archived outbound receipt", func(t *testing.T) { withdrawn, err := observer.ParseAndCheckWithdrawnEvent(cctx, receipt, custodyAddress, custody) @@ -329,7 +411,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.LoadEVMOutboundReceipt(t, TestDataDir, chainID, outboundHash, coin.CoinType_ERC20, testutils.EventERC20Withdraw) + receipt := testutils.LoadEVMOutboundReceipt( + t, + TestDataDir, + chainID, + outboundHash, + 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 +435,24 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) params := cctx.GetCurrentOutboundParam() - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + 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 +464,13 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { nonce := uint64(14) coinType := coin.CoinType_Zeta connectorLocal, connectorAddrLocal, custodyLocal, custodyAddrLocal := getContractsByChainID(t, localChainID) - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, localChainID, nonce, testutils.EventZetaReverted) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + localChainID, + nonce, + testutils.EventZetaReverted, + ) params := cctx.GetCurrentOutboundParam() value, status, err := observer.ParseOutboundReceivedValue( cctx, receipt, outbound, coinType, connectorAddrLocal, connectorLocal, custodyAddrLocal, custodyLocal) @@ -373,9 +483,24 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { // https://etherscan.io/tx/0xd2eba7ac3da1b62800165414ea4bcaf69a3b0fb9b13a0fc32f4be11bfef79146 nonce := uint64(8014) coinType := coin.CoinType_ERC20 - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventERC20Withdraw) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventERC20Withdraw, + ) params := cctx.GetCurrentOutboundParam() - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + 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 +512,16 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { coinType := coin.CoinType_Gas cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, "") params := cctx.GetCurrentOutboundParam() - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, connectorAddr, connector, custodyAddr, custody) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + 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 +531,23 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType(5) // unknown coin type - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, connectorAddr, connector, custodyAddr, custody) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + 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 +557,26 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { // https://etherscan.io/tx/0x81342051b8a85072d3e3771c1a57c7bdb5318e8caf37f5a687b7a91e50a7257f nonce := uint64(9718) coinType := coin.CoinType_Zeta - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventZetaReceived) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventZetaReceived, + ) // use an arbitrary address to make event parsing fail fakeConnectorAddress := sample.EthAddress() - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, fakeConnectorAddress, connector, custodyAddr, custody) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + coinType, + fakeConnectorAddress, + connector, + custodyAddr, + custody, + ) require.Error(t, err) require.Nil(t, value) require.Equal(t, chains.ReceiveStatus_failed, status) @@ -422,11 +586,26 @@ func Test_ParseOutboundReceivedValue(t *testing.T) { // https://etherscan.io/tx/0xd2eba7ac3da1b62800165414ea4bcaf69a3b0fb9b13a0fc32f4be11bfef79146 nonce := uint64(8014) coinType := coin.CoinType_ERC20 - cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt(t, TestDataDir, chainID, nonce, testutils.EventERC20Withdraw) + cctx, outbound, receipt := testutils.LoadEVMCctxNOutboundNReceipt( + t, + TestDataDir, + chainID, + nonce, + testutils.EventERC20Withdraw, + ) // use an arbitrary address to make event parsing fail fakeCustodyAddress := sample.EthAddress() - value, status, err := observer.ParseOutboundReceivedValue(cctx, receipt, outbound, coinType, connectorAddr, connector, fakeCustodyAddress, custody) + value, status, err := observer.ParseOutboundReceivedValue( + cctx, + receipt, + outbound, + 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_data.go b/zetaclient/chains/evm/signer/outbound_data.go index 3dfb81677b..d12ecb118c 100644 --- a/zetaclient/chains/evm/signer/outbound_data.go +++ b/zetaclient/chains/evm/signer/outbound_data.go @@ -10,6 +10,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -74,11 +75,13 @@ func (txData *OutboundData) SetupGas( txData.gasLimit = cctx.GetCurrentOutboundParam().GasLimit if txData.gasLimit < MinGasLimit { txData.gasLimit = MinGasLimit - logger.Warn().Msgf("gasLimit %d is too low; set to %d", cctx.GetCurrentOutboundParam().GasLimit, txData.gasLimit) + logger.Warn(). + Msgf("gasLimit %d is too low; set to %d", cctx.GetCurrentOutboundParam().GasLimit, txData.gasLimit) } if txData.gasLimit > MaxGasLimit { txData.gasLimit = MaxGasLimit - logger.Warn().Msgf("gasLimit %d is too high; set to %d", cctx.GetCurrentOutboundParam().GasLimit, txData.gasLimit) + logger.Warn(). + Msgf("gasLimit %d is too high; set to %d", cctx.GetCurrentOutboundParam().GasLimit, txData.gasLimit) } // use dynamic gas price for ethereum chains. @@ -153,7 +156,8 @@ func NewOutboundData( } // Get sendHash - logger.Info().Msgf("chain %s minting %d to %s, nonce %d, finalized zeta bn %d", toChain, cctx.InboundParams.Amount, txData.to.Hex(), nonce, cctx.InboundParams.FinalizedZetaHeight) + logger.Info(). + Msgf("chain %s minting %d to %s, nonce %d, finalized zeta bn %d", toChain, cctx.InboundParams.Amount, txData.to.Hex(), nonce, cctx.InboundParams.FinalizedZetaHeight) cctxIndex, err := hex.DecodeString(cctx.Index[2:]) // remove the leading 0x if err != nil || len(cctxIndex) != 32 { return nil, true, fmt.Errorf("decode CCTX %s error", cctx.Index) @@ -164,7 +168,8 @@ func NewOutboundData( pendingTx := evmObserver.GetPendingTx(nonce) if pendingTx != nil { if txData.gasPrice.Cmp(pendingTx.GasPrice()) > 0 { - logger.Info().Msgf("replace pending outbound %s nonce %d using gas price %d", pendingTx.Hash().Hex(), nonce, txData.gasPrice) + logger.Info(). + Msgf("replace pending outbound %s nonce %d using gas price %d", pendingTx.Hash().Hex(), nonce, txData.gasPrice) } else { logger.Info().Msgf("please wait for pending outbound %s nonce %d to be included", pendingTx.Hash().Hex(), nonce) return nil, true, nil diff --git a/zetaclient/chains/evm/signer/outbound_data_test.go b/zetaclient/chains/evm/signer/outbound_data_test.go index 23b13d8168..f3b5cd5ce5 100644 --- a/zetaclient/chains/evm/signer/outbound_data_test.go +++ b/zetaclient/chains/evm/signer/outbound_data_test.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/chains/evm/signer/signer.go b/zetaclient/chains/evm/signer/signer.go index 374aaf7813..e4fb93bbda 100644 --- a/zetaclient/chains/evm/signer/signer.go +++ b/zetaclient/chains/evm/signer/signer.go @@ -20,6 +20,7 @@ import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/constant" @@ -541,18 +542,25 @@ func (signer *Signer) BroadcastOutbound( // Try to broadcast transaction if tx != nil { outboundHash := tx.Hash().Hex() - logger.Info().Msgf("on chain %s nonce %d, outboundHash %s signer %s", signer.chain, cctx.GetCurrentOutboundParam().TssNonce, outboundHash, myID) + logger.Info(). + Msgf("on chain %s nonce %d, outboundHash %s signer %s", signer.chain, cctx.GetCurrentOutboundParam().TssNonce, outboundHash, myID) //if len(signers) == 0 || myid == signers[send.OutboundParams.Broadcaster] || myid == signers[int(send.OutboundParams.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", outboundHash, toChain, cctx.GetCurrentOutboundParam().TssNonce, i) + logger.Info(). + Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outboundHash, toChain, cctx.GetCurrentOutboundParam().TssNonce, 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("Outbound Broadcast error") - retry, report := zetacore.HandleBroadcastError(err, strconv.FormatUint(cctx.GetCurrentOutboundParam().TssNonce, 10), toChain.String(), outboundHash) + retry, report := zetacore.HandleBroadcastError( + err, + strconv.FormatUint(cctx.GetCurrentOutboundParam().TssNonce, 10), + toChain.String(), + outboundHash, + ) if report { signer.reportToOutboundTracker(zetacoreClient, toChain.ChainId, tx.Nonce(), outboundHash, logger) } @@ -562,7 +570,8 @@ func (signer *Signer) BroadcastOutbound( backOff *= 2 continue } - logger.Info().Msgf("Broadcast success: nonce %d to chain %s outboundHash %s", cctx.GetCurrentOutboundParam().TssNonce, toChain, outboundHash) + logger.Info(). + Msgf("Broadcast success: nonce %d to chain %s outboundHash %s", cctx.GetCurrentOutboundParam().TssNonce, toChain, outboundHash) signer.reportToOutboundTracker(zetacoreClient, toChain.ChainId, tx.Nonce(), outboundHash, logger) break // successful broadcast; no need to retry } @@ -583,7 +592,14 @@ func (signer *Signer) SignERC20WithdrawTx(txData *OutboundData) (*ethtypes.Trans 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) } @@ -641,13 +657,21 @@ 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.InboundParams.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.GetCurrentOutboundParam().TssNonce, cctx.GetCurrentOutboundParam().ReceiverChainId) + return fmt.Sprintf( + "signer SignOutbound error: nonce %d chain %d", + cctx.GetCurrentOutboundParam().TssNonce, + cctx.GetCurrentOutboundParam().ReceiverChainId, + ) } func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundData, params string) (*ethtypes.Transaction, error) { @@ -664,7 +688,14 @@ func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundData, params string) if err != nil { return nil, err } - tx, _, _, err := signer.Sign(data, txData.to, txData.gasLimit, txData.gasPrice, outboundParams.TssNonce, txData.height) + tx, _, _, err := signer.Sign( + data, + txData.to, + txData.gasLimit, + txData.gasPrice, + outboundParams.TssNonce, + txData.height, + ) if err != nil { return nil, fmt.Errorf("sign error: %w", err) } @@ -673,7 +704,14 @@ func (signer *Signer) SignWhitelistERC20Cmd(txData *OutboundData, params string) func (signer *Signer) SignMigrateTssFundsCmd(txData *OutboundData) (*ethtypes.Transaction, error) { outboundParams := txData.outboundParams - tx, _, _, err := signer.Sign(nil, txData.to, txData.gasLimit, txData.gasPrice, outboundParams.TssNonce, txData.height) + tx, _, _, err := signer.Sign( + nil, + txData.to, + txData.gasLimit, + txData.gasPrice, + outboundParams.TssNonce, + txData.height, + ) if err != nil { return nil, err } @@ -692,7 +730,8 @@ func (signer *Signer) reportToOutboundTracker( signer.mu.Lock() defer signer.mu.Unlock() if _, found := signer.outboundHashBeingReported[outboundHash]; found { - logger.Info().Msgf("reportToOutboundTracker: outboundHash %s for chain %d nonce %d is being reported", outboundHash, chainID, nonce) + logger.Info(). + Msgf("reportToOutboundTracker: outboundHash %s for chain %d nonce %d is being reported", outboundHash, chainID, nonce) return } signer.outboundHashBeingReported[outboundHash] = true // mark as being reported @@ -720,13 +759,16 @@ func (signer *Signer) reportToOutboundTracker( if isPending { report = true // probably will be included later } - logger.Info().Msgf("reportToOutboundTracker: timeout waiting tx inclusion for chain %d nonce %d outboundHash %s report %v", chainID, nonce, outboundHash, report) + logger.Info(). + Msgf("reportToOutboundTracker: timeout waiting tx inclusion for chain %d nonce %d outboundHash %s report %v", chainID, nonce, outboundHash, report) break } // try getting the tx _, isPending, err = signer.client.TransactionByHash(context.TODO(), ethcommon.HexToHash(outboundHash)) if err != nil { - logger.Info().Err(err).Msgf("reportToOutboundTracker: error getting tx for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) + logger.Info(). + Err(err). + Msgf("reportToOutboundTracker: error getting tx for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) continue } // if tx is include in a block, try getting receipt @@ -734,7 +776,9 @@ func (signer *Signer) reportToOutboundTracker( report = true // included receipt, err := signer.client.TransactionReceipt(context.TODO(), ethcommon.HexToHash(outboundHash)) if err != nil { - logger.Info().Err(err).Msgf("reportToOutboundTracker: error getting receipt for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) + logger.Info(). + Err(err). + Msgf("reportToOutboundTracker: error getting receipt for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) } if receipt != nil { blockNumber = receipt.BlockNumber.Uint64() @@ -742,7 +786,8 @@ func (signer *Signer) reportToOutboundTracker( break } // keep monitoring pending tx - logger.Info().Msgf("reportToOutboundTracker: tx has not been included yet for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) + logger.Info(). + Msgf("reportToOutboundTracker: tx has not been included yet for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) } // try adding to outbound tracker for 10 minutes @@ -751,13 +796,15 @@ func (signer *Signer) reportToOutboundTracker( for { // give up after 10 minutes of retrying if time.Since(tStart) > evm.OutboundTrackerReportTimeout { - logger.Info().Msgf("reportToOutboundTracker: timeout adding outbound tracker for chain %d nonce %d outboundHash %s, please add manually", chainID, nonce, outboundHash) + logger.Info(). + Msgf("reportToOutboundTracker: timeout adding outbound tracker for chain %d nonce %d outboundHash %s, please add manually", chainID, nonce, outboundHash) break } // stop if the cctx is already finalized cctx, err := zetacoreClient.GetCctxByNonce(chainID, nonce) if err != nil { - logger.Err(err).Msgf("reportToOutboundTracker: error getting cctx for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) + logger.Err(err). + Msgf("reportToOutboundTracker: error getting cctx for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) } else if !crosschainkeeper.IsPending(cctx) { logger.Info().Msgf("reportToOutboundTracker: cctx already finalized for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) break @@ -765,7 +812,8 @@ func (signer *Signer) reportToOutboundTracker( // report to outbound tracker zetaHash, err := zetacoreClient.AddOutboundTracker(chainID, nonce, outboundHash, nil, "", -1) if err != nil { - logger.Err(err).Msgf("reportToOutboundTracker: error adding to outbound tracker for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) + logger.Err(err). + Msgf("reportToOutboundTracker: error adding to outbound tracker for chain %d nonce %d outboundHash %s", chainID, nonce, outboundHash) } else if zetaHash != "" { logger.Info().Msgf("reportToOutboundTracker: added outboundHash to core successful %s, chain %d nonce %d outboundHash %s block %d", zetaHash, chainID, nonce, outboundHash, blockNumber) diff --git a/zetaclient/chains/evm/signer/signer_test.go b/zetaclient/chains/evm/signer/signer_test.go index 24a209e710..06998c61a8 100644 --- a/zetaclient/chains/evm/signer/signer_test.go +++ b/zetaclient/chains/evm/signer/signer_test.go @@ -7,6 +7,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/constant" "github.com/zeta-chain/zetacore/testutil/sample" @@ -300,7 +301,14 @@ func TestSigner_BroadcastOutbound(t *testing.T) { tx, err := evmSigner.SignERC20WithdrawTx(txData) require.NoError(t, err) - evmSigner.BroadcastOutbound(tx, cctx, zerolog.Logger{}, sdktypes.AccAddress{}, mocks.NewMockZetacoreClient(), txData) + evmSigner.BroadcastOutbound( + tx, + cctx, + zerolog.Logger{}, + sdktypes.AccAddress{}, + mocks.NewMockZetacoreClient(), + txData, + ) //Check if cctx was signed and broadcasted list := evmSigner.GetReportedTxList() diff --git a/zetaclient/chains/evm/validation_test.go b/zetaclient/chains/evm/validation_test.go index 263da97cf9..330d15f8f8 100644 --- a/zetaclient/chains/evm/validation_test.go +++ b/zetaclient/chains/evm/validation_test.go @@ -9,6 +9,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/onrik/ethrpc" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/zetaclient/chains/evm" "github.com/zeta-chain/zetacore/zetaclient/testutils" diff --git a/zetaclient/chains/interfaces/interfaces.go b/zetaclient/chains/interfaces/interfaces.go index 786905ebb3..1d901d4f53 100644 --- a/zetaclient/chains/interfaces/interfaces.go +++ b/zetaclient/chains/interfaces/interfaces.go @@ -16,6 +16,7 @@ import ( "github.com/onrik/ethrpc" "github.com/rs/zerolog" "github.com/zeta-chain/go-tss/blame" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -144,7 +145,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 3f3204e2e4..e085b6954b 100644 --- a/zetaclient/compliance/compliance.go +++ b/zetaclient/compliance/compliance.go @@ -2,6 +2,7 @@ package compliance import ( "github.com/rs/zerolog" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/zetaclient/config" ) @@ -29,8 +30,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 inbound for inbound tx logMsg = "Restricted address detected in inbound" diff --git a/zetaclient/compliance/compliance_test.go b/zetaclient/compliance/compliance_test.go index 41ee39836d..036ca3a7e1 100644 --- a/zetaclient/compliance/compliance_test.go +++ b/zetaclient/compliance/compliance_test.go @@ -5,6 +5,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/testutils" 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.go b/zetaclient/context/zetacore_context.go index e9f9d44bf3..73ad83ff29 100644 --- a/zetaclient/context/zetacore_context.go +++ b/zetaclient/context/zetacore_context.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" diff --git a/zetaclient/context/zetacore_context_test.go b/zetaclient/context/zetacore_context_test.go index 409af6154a..7e2b162e5f 100644 --- a/zetaclient/context/zetacore_context_test.go +++ b/zetaclient/context/zetacore_context_test.go @@ -5,6 +5,7 @@ import ( "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/testutil/sample" lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" @@ -225,110 +226,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/hsm/hsm_signer_test.go b/zetaclient/hsm/hsm_signer_test.go index 5c7ba38099..2cb6970732 100644 --- a/zetaclient/hsm/hsm_signer_test.go +++ b/zetaclient/hsm/hsm_signer_test.go @@ -8,10 +8,9 @@ import ( "log" "testing" - "github.com/frumioj/crypto11" - btcsecp256k1 "github.com/btcsuite/btcd/btcec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/frumioj/crypto11" "github.com/stretchr/testify/require" keystone "github.com/zeta-chain/keystone/keys" ) diff --git a/zetaclient/keys/keys.go b/zetaclient/keys/keys.go index 5bee8af8b2..3532c12233 100644 --- a/zetaclient/keys/keys.go +++ b/zetaclient/keys/keys.go @@ -15,6 +15,7 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/rs/zerolog/log" + "github.com/zeta-chain/zetacore/pkg/cosmos" zetacrypto "github.com/zeta-chain/zetacore/pkg/crypto" "github.com/zeta-chain/zetacore/zetaclient/config" @@ -37,7 +38,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, @@ -79,7 +85,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 81b46cd896..6f47c673d0 100644 --- a/zetaclient/keys/keys_test.go +++ b/zetaclient/keys/keys_test.go @@ -17,10 +17,11 @@ import ( cKeys "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + . "gopkg.in/check.v1" + "github.com/zeta-chain/zetacore/cmd" "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" - . "gopkg.in/check.v1" ) type KeysSuite struct{} @@ -68,7 +69,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/metrics/metrics.go b/zetaclient/metrics/metrics.go index d466524970..1170d16f68 100644 --- a/zetaclient/metrics/metrics.go +++ b/zetaclient/metrics/metrics.go @@ -7,7 +7,6 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/rs/zerolog/log" ) diff --git a/zetaclient/orchestrator/orchestrator.go b/zetaclient/orchestrator/orchestrator.go index 83caf9cf99..f9678301ff 100644 --- a/zetaclient/orchestrator/orchestrator.go +++ b/zetaclient/orchestrator/orchestrator.go @@ -8,6 +8,7 @@ import ( sdkmath "cosmossdk.io/math" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" zetamath "github.com/zeta-chain/zetacore/pkg/math" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -119,7 +120,10 @@ func (oc *Orchestrator) MonitorCore(appContext *context.AppContext) error { } // 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) @@ -147,7 +151,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) @@ -174,7 +181,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 { @@ -286,12 +295,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()) { @@ -348,7 +361,8 @@ func (oc *Orchestrator) ScheduleCctxEVM( outboundID := outboundprocessor.ToOutboundID(cctx.Index, params.ReceiverChainId, nonce) if params.ReceiverChainId != chainID { - oc.logger.Std.Error().Msgf("ScheduleCctxEVM: outbound %s chainid mismatch: want %d, got %d", outboundID, chainID, params.ReceiverChainId) + oc.logger.Std.Error(). + Msgf("ScheduleCctxEVM: outbound %s chainid mismatch: want %d, got %d", outboundID, chainID, params.ReceiverChainId) continue } if params.TssNonce > cctxList[0].GetCurrentOutboundParam().TssNonce+outboundScheduleLookback { @@ -360,11 +374,14 @@ func (oc *Orchestrator) ScheduleCctxEVM( // try confirming the outbound 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 { - oc.logger.Std.Info().Msgf("ScheduleCctxEVM: outbound %s already included; do not schedule keysign", outboundID) + oc.logger.Std.Info(). + Msgf("ScheduleCctxEVM: outbound %s already included; do not schedule keysign", outboundID) continue } @@ -390,9 +407,11 @@ func (oc *Orchestrator) ScheduleCctxEVM( } // otherwise, the normal interval is used - if nonce%outboundScheduleInterval == zetaHeight%outboundScheduleInterval && !oc.outboundProc.IsOutboundActive(outboundID) { + if nonce%outboundScheduleInterval == zetaHeight%outboundScheduleInterval && + !oc.outboundProc.IsOutboundActive(outboundID) { oc.outboundProc.StartTryProcess(outboundID) - oc.logger.Std.Debug().Msgf("ScheduleCctxEVM: sign outbound %s with value %d\n", outboundID, cctx.GetCurrentOutboundParam().Amount) + oc.logger.Std.Debug(). + Msgf("ScheduleCctxEVM: sign outbound %s with value %d\n", outboundID, cctx.GetCurrentOutboundParam().Amount) go signer.TryProcessOutbound(cctx, oc.outboundProc, outboundID, observer, oc.zetacoreClient, zetaHeight) } @@ -430,17 +449,21 @@ func (oc *Orchestrator) ScheduleCctxBTC( outboundID := outboundprocessor.ToOutboundID(cctx.Index, params.ReceiverChainId, nonce) if params.ReceiverChainId != chainID { - oc.logger.Std.Error().Msgf("ScheduleCctxBTC: outbound %s chainid mismatch: want %d, got %d", outboundID, chainID, params.ReceiverChainId) + oc.logger.Std.Error(). + Msgf("ScheduleCctxBTC: outbound %s chainid mismatch: want %d, got %d", outboundID, chainID, params.ReceiverChainId) continue } // try confirming the outbound 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 { - oc.logger.Std.Info().Msgf("ScheduleCctxBTC: outbound %s already included; do not schedule keysign", outboundID) + oc.logger.Std.Info(). + Msgf("ScheduleCctxBTC: outbound %s already included; do not schedule keysign", outboundID) continue } @@ -449,8 +472,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].GetCurrentOutboundParam().TssNonce) + 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].GetCurrentOutboundParam().TssNonce) break } // try confirming the outbound or scheduling a keysign diff --git a/zetaclient/orchestrator/orchestrator_test.go b/zetaclient/orchestrator/orchestrator_test.go index fa3fd2476b..f4dcf1ffd0 100644 --- a/zetaclient/orchestrator/orchestrator_test.go +++ b/zetaclient/orchestrator/orchestrator_test.go @@ -7,6 +7,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" @@ -52,7 +53,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 +218,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/outboundprocessor/outbound_processor_manager.go b/zetaclient/outboundprocessor/outbound_processor_manager.go index 4be70c5ee3..8499252ede 100644 --- a/zetaclient/outboundprocessor/outbound_processor_manager.go +++ b/zetaclient/outboundprocessor/outbound_processor_manager.go @@ -43,7 +43,8 @@ func (p *Processor) EndTryProcess(outboundID string) { p.outboundEndTime[outboundID] = time.Now() delete(p.outboundActive, outboundID) p.numActiveProcessor-- - p.Logger.Info().Msgf("EndTryProcess %s, numActiveProcessor %d, time elapsed %s", outboundID, p.numActiveProcessor, time.Since(p.outboundStartTime[outboundID])) + p.Logger.Info(). + Msgf("EndTryProcess %s, numActiveProcessor %d, time elapsed %s", outboundID, p.numActiveProcessor, time.Since(p.outboundStartTime[outboundID])) } func (p *Processor) IsOutboundActive(outboundID string) bool { diff --git a/zetaclient/ratelimiter/rate_limiter.go b/zetaclient/ratelimiter/rate_limiter.go index 0598b5eff4..0ddb3b378b 100644 --- a/zetaclient/ratelimiter/rate_limiter.go +++ b/zetaclient/ratelimiter/rate_limiter.go @@ -3,6 +3,7 @@ package ratelimiter import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/ratelimiter/rate_limiter_test.go b/zetaclient/ratelimiter/rate_limiter_test.go index 0f6c3a0e73..c028b3c526 100644 --- a/zetaclient/ratelimiter/rate_limiter_test.go +++ b/zetaclient/ratelimiter/rate_limiter_test.go @@ -6,6 +6,7 @@ import ( sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/testutil/sample" @@ -117,14 +118,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 +239,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 +263,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 +288,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/logger.go b/zetaclient/supplychecker/logger.go index 87fe8b1d83..223e43eab8 100644 --- a/zetaclient/supplychecker/logger.go +++ b/zetaclient/supplychecker/logger.go @@ -3,6 +3,7 @@ package supplychecker import ( sdkmath "cosmossdk.io/math" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin" ) 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 6db00def4a..f975c7eb88 100644 --- a/zetaclient/supplychecker/zeta_supply_checker.go +++ b/zetaclient/supplychecker/zeta_supply_checker.go @@ -8,6 +8,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/pkg/errors" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/x/crosschain/types" @@ -85,7 +86,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 +149,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 } @@ -176,7 +181,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 48daed4557..ed984de2d8 100644 --- a/zetaclient/supplychecker/zeta_supply_checker_test.go +++ b/zetaclient/supplychecker/zeta_supply_checker_test.go @@ -44,7 +44,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/testdata/cctx/chain_1337_cctx_14.go b/zetaclient/testdata/cctx/chain_1337_cctx_14.go index b0b8257507..3822c07f22 100644 --- a/zetaclient/testdata/cctx/chain_1337_cctx_14.go +++ b/zetaclient/testdata/cctx/chain_1337_cctx_14.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_6270.go b/zetaclient/testdata/cctx/chain_1_cctx_6270.go index fc0fe6e680..1b6948d085 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_6270.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_6270.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_7260.go b/zetaclient/testdata/cctx/chain_1_cctx_7260.go index 29a2634ed7..239a510fd5 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_7260.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_7260.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_8014.go b/zetaclient/testdata/cctx/chain_1_cctx_8014.go index 067192609d..eaa4067cc2 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_8014.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_8014.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_9718.go b/zetaclient/testdata/cctx/chain_1_cctx_9718.go index 413559297a..af337f12a6 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_9718.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_9718.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_inbound_ERC20_0x4ea69a0e2ff36f7548ab75791c3b990e076e2a4bffeb616035b239b7d33843da.go b/zetaclient/testdata/cctx/chain_1_cctx_inbound_ERC20_0x4ea69a0e2ff36f7548ab75791c3b990e076e2a4bffeb616035b239b7d33843da.go index ed3852158e..f629b000e9 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_inbound_ERC20_0x4ea69a0e2ff36f7548ab75791c3b990e076e2a4bffeb616035b239b7d33843da.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_inbound_ERC20_0x4ea69a0e2ff36f7548ab75791c3b990e076e2a4bffeb616035b239b7d33843da.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_inbound_Gas_0xeaec67d5dd5d85f27b21bef83e01cbdf59154fd793ea7a22c297f7c3a722c532.go b/zetaclient/testdata/cctx/chain_1_cctx_inbound_Gas_0xeaec67d5dd5d85f27b21bef83e01cbdf59154fd793ea7a22c297f7c3a722c532.go index 7b01206acd..91fc0beaf8 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_inbound_Gas_0xeaec67d5dd5d85f27b21bef83e01cbdf59154fd793ea7a22c297f7c3a722c532.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_inbound_Gas_0xeaec67d5dd5d85f27b21bef83e01cbdf59154fd793ea7a22c297f7c3a722c532.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_1_cctx_inbound_Zeta_0xf3935200c80f98502d5edc7e871ffc40ca898e134525c42c2ae3cbc5725f9d76.go b/zetaclient/testdata/cctx/chain_1_cctx_inbound_Zeta_0xf3935200c80f98502d5edc7e871ffc40ca898e134525c42c2ae3cbc5725f9d76.go index d63ad8143d..6e3f5d855d 100644 --- a/zetaclient/testdata/cctx/chain_1_cctx_inbound_Zeta_0xf3935200c80f98502d5edc7e871ffc40ca898e134525c42c2ae3cbc5725f9d76.go +++ b/zetaclient/testdata/cctx/chain_1_cctx_inbound_Zeta_0xf3935200c80f98502d5edc7e871ffc40ca898e134525c42c2ae3cbc5725f9d76.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_56_cctx_68270.go b/zetaclient/testdata/cctx/chain_56_cctx_68270.go index 6d9d9de064..e492de434e 100644 --- a/zetaclient/testdata/cctx/chain_56_cctx_68270.go +++ b/zetaclient/testdata/cctx/chain_56_cctx_68270.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) diff --git a/zetaclient/testdata/cctx/chain_8332_cctx_148.go b/zetaclient/testdata/cctx/chain_8332_cctx_148.go index 1bbfbdc1b2..258eea5a3c 100644 --- a/zetaclient/testdata/cctx/chain_8332_cctx_148.go +++ b/zetaclient/testdata/cctx/chain_8332_cctx_148.go @@ -2,6 +2,7 @@ package cctx import ( sdkmath "cosmossdk.io/math" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" ) 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..cfd63ef87b 100644 --- a/zetaclient/testutils/mocks/btc_rpc.go +++ b/zetaclient/testutils/mocks/btc_rpc.go @@ -8,6 +8,7 @@ import ( "github.com/btcsuite/btcd/rpcclient" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" + "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" ) @@ -59,11 +60,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/chain_clients.go b/zetaclient/testutils/mocks/chain_clients.go index da648c7665..44f1a9ea71 100644 --- a/zetaclient/testutils/mocks/chain_clients.go +++ b/zetaclient/testutils/mocks/chain_clients.go @@ -2,6 +2,7 @@ package mocks import ( "github.com/rs/zerolog" + crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" diff --git a/zetaclient/testutils/mocks/chain_params.go b/zetaclient/testutils/mocks/chain_params.go index e785007e61..45c5df2497 100644 --- a/zetaclient/testutils/mocks/chain_params.go +++ b/zetaclient/testutils/mocks/chain_params.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/erc20custody.sol" "github.com/zeta-chain/protocol-contracts/pkg/contracts/evm/zetaconnector.non-eth.sol" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/testutils" ) diff --git a/zetaclient/testutils/mocks/chain_signer.go b/zetaclient/testutils/mocks/chain_signer.go index 55e8d3953d..73135b387f 100644 --- a/zetaclient/testutils/mocks/chain_signer.go +++ b/zetaclient/testutils/mocks/chain_signer.go @@ -2,6 +2,7 @@ package mocks import ( ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/zeta-chain/zetacore/pkg/chains" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" diff --git a/zetaclient/testutils/mocks/evm_json_rpc.go b/zetaclient/testutils/mocks/evm_json_rpc.go index 5eeaaa24a3..f3e3676e25 100644 --- a/zetaclient/testutils/mocks/evm_json_rpc.go +++ b/zetaclient/testutils/mocks/evm_json_rpc.go @@ -4,6 +4,7 @@ import ( "errors" "github.com/onrik/ethrpc" + "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" ) diff --git a/zetaclient/testutils/mocks/evm_rpc.go b/zetaclient/testutils/mocks/evm_rpc.go index 054f43461c..926be6ec28 100644 --- a/zetaclient/testutils/mocks/evm_rpc.go +++ b/zetaclient/testutils/mocks/evm_rpc.go @@ -7,8 +7,9 @@ import ( "github.com/ethereum/go-ethereum" ethcommon "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" "golang.org/x/net/context" + + "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" ) const EVMRPCEnabled = "MockEVMRPCEnabled" @@ -38,7 +39,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 +97,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 +114,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 b4265a86ae..fe0af87429 100644 --- a/zetaclient/testutils/mocks/keyring.go +++ b/zetaclient/testutils/mocks/keyring.go @@ -59,7 +59,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..ebe07d84bc 100644 --- a/zetaclient/testutils/mocks/tss_signer.go +++ b/zetaclient/testutils/mocks/tss_signer.go @@ -9,6 +9,7 @@ import ( "github.com/btcsuite/btcutil" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" "github.com/zeta-chain/zetacore/zetaclient/testutils" @@ -112,7 +113,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 aaea360b8b..953d8ce287 100644 --- a/zetaclient/testutils/mocks/zetacore_client.go +++ b/zetaclient/testutils/mocks/zetacore_client.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/math" "github.com/rs/zerolog" "github.com/zeta-chain/go-tss/blame" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -57,7 +58,19 @@ func (m *MockZetacoreClient) PostVoteInbound(_, _ uint64, _ *crosschaintypes.Msg return "", "", nil } -func (m *MockZetacoreClient) PostVoteOutbound(_ string, _ string, _ uint64, _ uint64, _ *big.Int, _ uint64, _ *big.Int, _ chains.ReceiveStatus, _ chains.Chain, _ uint64, _ coin.CoinType) (string, string, error) { +func (m *MockZetacoreClient) PostVoteOutbound( + _ string, + _ string, + _ uint64, + _ uint64, + _ *big.Int, + _ uint64, + _ *big.Int, + _ chains.ReceiveStatus, + _ chains.Chain, + _ uint64, + _ coin.CoinType, +) (string, string, error) { if m.paused { return "", "", errors.New(ErrMsgPaused) } @@ -92,7 +105,14 @@ func (m *MockZetacoreClient) PostBlameData(_ *blame.Blame, _ int64, _ string) (s return "", nil } -func (m *MockZetacoreClient) AddOutboundTracker(_ int64, _ uint64, _ string, _ *proofs.Proof, _ string, _ int64) (string, error) { +func (m *MockZetacoreClient) AddOutboundTracker( + _ int64, + _ uint64, + _ string, + _ *proofs.Proof, + _ string, + _ int64, +) (string, error) { if m.paused { return "", errors.New(ErrMsgPaused) } @@ -177,7 +197,10 @@ func (m *MockZetacoreClient) GetOutboundTracker(_ chains.Chain, _ uint64) (*cros return &crosschaintypes.OutboundTracker{}, nil } -func (m *MockZetacoreClient) GetAllOutboundTrackerByChain(_ int64, _ chaininterfaces.Order) ([]crosschaintypes.OutboundTracker, error) { +func (m *MockZetacoreClient) GetAllOutboundTrackerByChain( + _ int64, + _ chaininterfaces.Order, +) ([]crosschaintypes.OutboundTracker, error) { if m.paused { return nil, errors.New(ErrMsgPaused) } @@ -256,7 +279,9 @@ func (m *MockZetacoreClient) WithRateLimiterFlags(flags *crosschaintypes.RateLim return m } -func (m *MockZetacoreClient) WithRateLimiterInput(input *crosschaintypes.QueryRateLimiterInputResponse) *MockZetacoreClient { +func (m *MockZetacoreClient) WithRateLimiterInput( + input *crosschaintypes.QueryRateLimiterInputResponse, +) *MockZetacoreClient { m.input = input return m } diff --git a/zetaclient/testutils/testdata.go b/zetaclient/testutils/testdata.go index ed28c687ed..fc028bf0ec 100644 --- a/zetaclient/testutils/testdata.go +++ b/zetaclient/testutils/testdata.go @@ -11,6 +11,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/onrik/ethrpc" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/pkg/coin" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/zetaclient/config" @@ -101,7 +102,13 @@ func LoadBTCTxRawResult(t *testing.T, dir string, chainID int64, txType string, } // LoadBTCInboundRawResult loads archived Bitcoin inbound raw result from file -func LoadBTCInboundRawResult(t *testing.T, dir string, chainID int64, txHash string, donation bool) *btcjson.TxRawResult { +func LoadBTCInboundRawResult( + t *testing.T, + dir string, + chainID int64, + txHash string, + donation bool, +) *btcjson.TxRawResult { name := path.Join(dir, TestDataPathBTC, FileNameBTCInbound(chainID, txHash, donation)) rawResult := &btcjson.TxRawResult{} LoadObjectFromJSONFile(t, rawResult, name) @@ -109,7 +116,12 @@ func LoadBTCInboundRawResult(t *testing.T, dir string, chainID int64, txHash str } // LoadBTCTxRawResultNCctx loads archived Bitcoin outbound 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, FileNameBTCOutbound(chainID, nonce)) rawResult := &btcjson.TxRawResult{} LoadObjectFromJSONFile(t, rawResult, nameTx) diff --git a/zetaclient/tss/concurrent_keysigns_tracker.go b/zetaclient/tss/concurrent_keysigns_tracker.go index 72ab4780f2..42b6cb8413 100644 --- a/zetaclient/tss/concurrent_keysigns_tracker.go +++ b/zetaclient/tss/concurrent_keysigns_tracker.go @@ -4,6 +4,7 @@ import ( "sync" "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/zetaclient/metrics" ) diff --git a/zetaclient/tss/tss_signer.go b/zetaclient/tss/tss_signer.go index 610b93faf5..2915dd6d0a 100644 --- a/zetaclient/tss/tss_signer.go +++ b/zetaclient/tss/tss_signer.go @@ -25,6 +25,7 @@ import ( "github.com/zeta-chain/go-tss/keysign" "github.com/zeta-chain/go-tss/p2p" "github.com/zeta-chain/go-tss/tss" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/cosmos" observertypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -213,7 +214,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 +230,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 +346,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 +389,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 +564,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/tss/tss_signer_test.go b/zetaclient/tss/tss_signer_test.go index d19e2effcc..5e214cf7b1 100644 --- a/zetaclient/tss/tss_signer_test.go +++ b/zetaclient/tss/tss_signer_test.go @@ -9,6 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/rs/zerolog" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/cmd" "github.com/zeta-chain/zetacore/pkg/cosmos" "github.com/zeta-chain/zetacore/pkg/crypto" diff --git a/zetaclient/zetacore/broadcast.go b/zetaclient/zetacore/broadcast.go index 7991f7edc6..82a011c6ba 100644 --- a/zetaclient/zetacore/broadcast.go +++ b/zetaclient/zetacore/broadcast.go @@ -15,6 +15,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/rs/zerolog/log" flag "github.com/spf13/pflag" + "github.com/zeta-chain/zetacore/app/ante" "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/zetaclient/authz" @@ -40,7 +41,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 +144,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,17 +230,23 @@ func (c *Client) QueryTxResult(hash string) (*sdktypes.TxResponse, error) { // returns (bool retry, bool report) func HandleBroadcastError(err error, nonce, toChain, outboundHash 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 outbound confirmation") + log.Warn(). + Err(err). + Msgf("nonce too low! this might be a unnecessary key-sign. increase re-try interval and awaits outbound confirmation") return false, false } if strings.Contains(err.Error(), "replacement transaction underpriced") { - log.Warn().Err(err).Msgf("Broadcast replacement: nonce %s chain %s outboundHash %s", nonce, toChain, outboundHash) + log.Warn(). + Err(err). + Msgf("Broadcast replacement: nonce %s chain %s outboundHash %s", nonce, toChain, outboundHash) return false, false } else if strings.Contains(err.Error(), "already known") { // this is error code from QuickNode log.Warn().Err(err).Msgf("Broadcast duplicates: nonce %s chain %s outboundHash %s", nonce, toChain, outboundHash) return false, true // report to tracker, because there's possibilities a successful broadcast gets this error code } - log.Error().Err(err).Msgf("Broadcast error: nonce %s chain %s outboundHash %s; retrying...", nonce, toChain, outboundHash) + log.Error(). + Err(err). + Msgf("Broadcast error: nonce %s chain %s outboundHash %s; retrying...", nonce, toChain, outboundHash) return true, false } diff --git a/zetaclient/zetacore/broadcast_test.go b/zetaclient/zetacore/broadcast_test.go index b0aaaa8ca7..1449fc87e6 100644 --- a/zetaclient/zetacore/broadcast_test.go +++ b/zetaclient/zetacore/broadcast_test.go @@ -10,13 +10,14 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/require" + "go.nhat.io/grpcmock" + "go.nhat.io/grpcmock/planner" + "github.com/zeta-chain/zetacore/pkg/chains" crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/keys" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" - "go.nhat.io/grpcmock" - "go.nhat.io/grpcmock/planner" ) func TestHandleBroadcastError(t *testing.T) { @@ -79,7 +80,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 +94,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 05a54a4a38..84ea0194d7 100644 --- a/zetaclient/zetacore/client.go +++ b/zetaclient/zetacore/client.go @@ -10,6 +10,8 @@ import ( "github.com/pkg/errors" "github.com/rs/zerolog" "github.com/rs/zerolog/log" + "google.golang.org/grpc" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/pkg/authz" "github.com/zeta-chain/zetacore/pkg/chains" @@ -19,7 +21,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/context" keyinterfaces "github.com/zeta-chain/zetacore/zetaclient/keys/interfaces" "github.com/zeta-chain/zetacore/zetaclient/metrics" - "google.golang.org/grpc" ) var _ interfaces.ZetacoreClient = &Client{} @@ -192,7 +193,11 @@ func (c *Client) WaitForZetacoreToCreateBlocks() error { // 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) @@ -203,8 +208,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 d813c3768b..b68ea37f8b 100644 --- a/zetaclient/zetacore/query.go +++ b/zetaclient/zetacore/query.go @@ -14,6 +14,8 @@ import ( genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" + "google.golang.org/grpc" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -21,7 +23,6 @@ import ( lightclienttypes "github.com/zeta-chain/zetacore/x/lightclient/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/chains/interfaces" - "google.golang.org/grpc" ) func (c *Client) GetCrosschainFlags() (observertypes.CrosschainFlags, error) { @@ -53,7 +54,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 +256,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 +296,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 +343,10 @@ func (c *Client) GetBallot(ballotIdentifier string) (*observertypes.QueryBallotB func (c *Client) GetInboundTrackersForChain(chainID int64) ([]crosschaintypes.InboundTracker, error) { client := crosschaintypes.NewQueryClient(c.grpcConn) - resp, err := client.InboundTrackerAllByChain(context.Background(), &crosschaintypes.QueryAllInboundTrackerByChainRequest{ChainId: chainID}) + resp, err := client.InboundTrackerAllByChain( + context.Background(), + &crosschaintypes.QueryAllInboundTrackerByChainRequest{ChainId: chainID}, + ) if err != nil { return nil, err } @@ -390,18 +403,24 @@ func (c *Client) GetOutboundTracker(chain chains.Chain, nonce uint64) (*crosscha return &resp.OutboundTracker, nil } -func (c *Client) GetAllOutboundTrackerByChain(chainID int64, order interfaces.Order) ([]crosschaintypes.OutboundTracker, error) { +func (c *Client) GetAllOutboundTrackerByChain( + chainID int64, + order interfaces.Order, +) ([]crosschaintypes.OutboundTracker, error) { client := crosschaintypes.NewQueryClient(c.grpcConn) - resp, err := client.OutboundTrackerAllByChain(context.Background(), &crosschaintypes.QueryAllOutboundTrackerByChainRequest{ - Chain: chainID, - Pagination: &query.PageRequest{ - Key: nil, - Offset: 0, - Limit: 2000, - CountTotal: false, - Reverse: false, + resp, err := client.OutboundTrackerAllByChain( + context.Background(), + &crosschaintypes.QueryAllOutboundTrackerByChainRequest{ + Chain: chainID, + Pagination: &query.PageRequest{ + Key: nil, + Offset: 0, + Limit: 2000, + CountTotal: false, + Reverse: false, + }, }, - }) + ) if err != nil { return nil, err } @@ -420,7 +439,10 @@ func (c *Client) GetAllOutboundTrackerByChain(chainID int64, order interfaces.Or 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 +476,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 b1b2aedd2b..c98e5560c2 100644 --- a/zetaclient/zetacore/query_test.go +++ b/zetaclient/zetacore/query_test.go @@ -12,6 +12,9 @@ import ( upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" "github.com/stretchr/testify/require" + "go.nhat.io/grpcmock" + "go.nhat.io/grpcmock/planner" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" @@ -23,8 +26,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/keys" "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" - "go.nhat.io/grpcmock" - "go.nhat.io/grpcmock/planner" ) func setupMockServer(t *testing.T, serviceFunc any, method string, input any, expectedOutput any) *grpcmock.Server { @@ -126,16 +127,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 +245,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 de90ba4c3c..dbf144e9ab 100644 --- a/zetaclient/zetacore/tx.go +++ b/zetaclient/zetacore/tx.go @@ -12,6 +12,7 @@ import ( "github.com/pkg/errors" "github.com/rs/zerolog" "github.com/zeta-chain/go-tss/blame" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -211,7 +212,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) @@ -246,7 +252,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 @@ -361,7 +372,10 @@ func (c *Client) PostVoteOutbound( } // PostVoteOutboundFromMsg posts a vote on an observed outbound tx from a MsgVoteOutbound -func (c *Client) PostVoteOutboundFromMsg(gasLimit, retryGasLimit uint64, msg *types.MsgVoteOutbound) (string, string, error) { +func (c *Client) PostVoteOutboundFromMsg( + gasLimit, retryGasLimit uint64, + msg *types.MsgVoteOutbound, +) (string, string, error) { authzMsg, authzSigner, err := c.WrapMessageWithAuthz(msg) if err != nil { return "", "", err @@ -371,7 +385,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 diff --git a/zetaclient/zetacore/tx_test.go b/zetaclient/zetacore/tx_test.go index 335769a82f..02a3b17ab8 100644 --- a/zetaclient/zetacore/tx_test.go +++ b/zetaclient/zetacore/tx_test.go @@ -16,6 +16,9 @@ import ( "github.com/rs/zerolog" "github.com/stretchr/testify/require" "github.com/zeta-chain/go-tss/blame" + "go.nhat.io/grpcmock" + "go.nhat.io/grpcmock/planner" + "github.com/zeta-chain/zetacore/pkg/chains" "github.com/zeta-chain/zetacore/pkg/coin" "github.com/zeta-chain/zetacore/pkg/proofs" @@ -27,8 +30,6 @@ import ( "github.com/zeta-chain/zetacore/zetaclient/context" "github.com/zeta-chain/zetacore/zetaclient/keys" "github.com/zeta-chain/zetacore/zetaclient/testutils/mocks" - "go.nhat.io/grpcmock" - "go.nhat.io/grpcmock/planner" ) const ( From 6fab9e2aefbc7eebc8dca8d5f33ea40ce6ec78de Mon Sep 17 00:00:00 2001 From: Charlie Chen <34498985+ws4charlie@users.noreply.github.com> Date: Wed, 22 May 2024 06:41:57 -0500 Subject: [PATCH 2/2] fix: removed maxHeightDiff to let observer scan Bitcoin block from where it left off (#2222) * removed maxHeightDiff to let observer scan Bitcoin block from where it left off * added changelog entry * renamed LoadLastBlock -> LoadLastScannedBlock; added more comments * run format --------- Co-authored-by: Lucas Bertrand --- changelog.md | 1 + .../chains/bitcoin/observer/observer.go | 27 +++++++---------- zetaclient/chains/evm/observer/observer.go | 29 ++++++++++++------- 3 files changed, 31 insertions(+), 26 deletions(-) diff --git a/changelog.md b/changelog.md index 5f165d0d2a..d03a2aa6da 100644 --- a/changelog.md +++ b/changelog.md @@ -40,6 +40,7 @@ * [1484](https://github.com/zeta-chain/node/issues/1484) - replaced hard-coded `MaxLookaheadNonce` with a default lookback factor * [2125](https://github.com/zeta-chain/node/pull/2125) - fix develop upgrade test +* [2222](https://github.com/zeta-chain/node/pull/2222) - removed `maxHeightDiff` to let observer scan from Bitcoin height where it left off ### CI diff --git a/zetaclient/chains/bitcoin/observer/observer.go b/zetaclient/chains/bitcoin/observer/observer.go index 22be51fef1..9b823e1b6d 100644 --- a/zetaclient/chains/bitcoin/observer/observer.go +++ b/zetaclient/chains/bitcoin/observer/observer.go @@ -39,9 +39,6 @@ import ( ) const ( - // maxHeightDiff contains the max height diff in case the last block is too old when the observer starts - maxHeightDiff = 10000 - // btcBlocksPerDay represents Bitcoin blocks per days for LRU block cache size btcBlocksPerDay = 144 @@ -684,37 +681,35 @@ func (ob *Observer) BuildBroadcastedTxMap() error { return nil } -func (ob *Observer) LoadLastBlock() error { +// LoadLastScannedBlock loads last scanned block from database +// The last scanned block is the height from which the observer should continue scanning for inbound transactions +func (ob *Observer) LoadLastScannedBlock() error { // Get the latest block number from node bn, err := ob.rpcClient.GetBlockCount() if err != nil { return err } if bn < 0 { - return fmt.Errorf("LoadLastBlock: negative block number %d", bn) + return fmt.Errorf("LoadLastScannedBlock: negative block number %d", bn) } //Load persisted block number var lastBlockNum clienttypes.LastBlockSQLType if err := ob.db.First(&lastBlockNum, clienttypes.LastBlockNumID).Error; err != nil { - ob.logger.Chain.Info().Msg("LastBlockNum not found in DB, scan from latest") + ob.logger.Chain.Info().Msg("LoadLastScannedBlock: last scanned block not found in DB, scan from latest") ob.SetLastBlockHeightScanned(bn) } else { // #nosec G701 always in range lastBN := int64(lastBlockNum.Num) ob.SetLastBlockHeightScanned(lastBN) - - //If persisted block number is too low, use the latest height - if (bn - lastBN) > maxHeightDiff { - ob.logger.Chain.Info().Msgf("LastBlockNum too low: %d, scan from latest", lastBlockNum.Num) - ob.SetLastBlockHeightScanned(bn) - } } - if ob.chain.ChainId == 18444 { // bitcoin regtest: start from block 100 + // bitcoin regtest starts from block 100 + if chains.IsBitcoinRegnet(ob.chain.ChainId) { ob.SetLastBlockHeightScanned(100) } - ob.logger.Chain.Info().Msgf("%s: start scanning from block %d", ob.chain.String(), ob.GetLastBlockHeightScanned()) + ob.logger.Chain.Info(). + Msgf("LoadLastScannedBlock: chain %d starts scanning from block %d", ob.chain.ChainId, ob.GetLastBlockHeightScanned()) return nil } @@ -812,8 +807,8 @@ func (ob *Observer) loadDB(dbpath string) error { return err } - //Load last block - err = ob.LoadLastBlock() + // Load last scanned block + err = ob.LoadLastScannedBlock() if err != nil { return err } diff --git a/zetaclient/chains/evm/observer/observer.go b/zetaclient/chains/evm/observer/observer.go index e584c0a414..4a38a62d12 100644 --- a/zetaclient/chains/evm/observer/observer.go +++ b/zetaclient/chains/evm/observer/observer.go @@ -570,12 +570,17 @@ func (ob *Observer) BlockByNumber(blockNumber int) (*ethrpc.Block, error) { return block, nil } -func (ob *Observer) BuildLastBlock() error { - logger := ob.logger.Chain.With().Str("module", "BuildBlockIndex").Logger() +// LoadLastScannedBlock loads last scanned block from specified height or from database +// The last scanned block is the height from which the observer should continue scanning for inbound transactions +func (ob *Observer) LoadLastScannedBlock() error { + // get environment variable envvar := ob.chain.ChainName.String() + "_SCAN_FROM" scanFromBlock := os.Getenv(envvar) + + // load from environment variable if set if scanFromBlock != "" { - logger.Info().Msgf("BuildLastBlock: envvar %s is set; scan from block %s", envvar, scanFromBlock) + ob.logger.Chain.Info(). + Msgf("LoadLastScannedBlock: envvar %s is set; scan from block %s", envvar, scanFromBlock) if scanFromBlock == clienttypes.EnvVarLatest { header, err := ob.evmClient.HeaderByNumber(context.Background(), nil) if err != nil { @@ -589,22 +594,26 @@ func (ob *Observer) BuildLastBlock() error { } ob.SetLastBlockHeightScanned(scanFromBlockInt) } - } else { // last observed block - var lastBlockNum clienttypes.LastBlockSQLType - if err := ob.db.First(&lastBlockNum, clienttypes.LastBlockNumID).Error; err != nil { - logger.Info().Msgf("BuildLastBlock: db PosKey does not exist; read from external chain %s", ob.chain.String()) + } else { + // load from DB otherwise + var lastBlock clienttypes.LastBlockSQLType + if err := ob.db.First(&lastBlock, clienttypes.LastBlockNumID).Error; err != nil { + ob.logger.Chain.Info().Msg("LoadLastScannedBlock: last scanned block not found in DB, scan from latest") header, err := ob.evmClient.HeaderByNumber(context.Background(), nil) if err != nil { return err } ob.SetLastBlockHeightScanned(header.Number.Uint64()) if dbc := ob.db.Save(clienttypes.ToLastBlockSQLType(ob.GetLastBlockHeightScanned())); dbc.Error != nil { - logger.Error().Err(dbc.Error).Msgf("BuildLastBlock: error writing lastBlockScanned %d to db", ob.GetLastBlockHeightScanned()) + ob.logger.Chain.Error().Err(dbc.Error).Msgf("LoadLastScannedBlock: error writing last scanned block %d to DB", ob.GetLastBlockHeightScanned()) } } else { - ob.SetLastBlockHeightScanned(lastBlockNum.Num) + ob.SetLastBlockHeightScanned(lastBlock.Num) } } + ob.logger.Chain.Info(). + Msgf("LoadLastScannedBlock: chain %d starts scanning from block %d", ob.chain.ChainId, ob.GetLastBlockHeightScanned()) + return nil } @@ -635,7 +644,7 @@ func (ob *Observer) LoadDB(dbPath string, chain chains.Chain) error { } ob.db = db - err = ob.BuildLastBlock() + err = ob.LoadLastScannedBlock() if err != nil { return err }