### Simulate IBC Path Setup and Packet Relay Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Demonstrates setting up an IBC path, relaying packets between chains, and acknowledging packet receipts. This example covers client, connection, and channel setup, packet sending, receiving, and acknowledgment. ```go path := ibctesting.NewPath(suite.chainA, suite.chainB) // clientID, connectionID, channelID empty suite.coordinator.Setup(path) // clientID, connectionID, channelID filled suite.Require().Equal("07-tendermint-0", path.EndpointA.ClientID) suite.Require().Equal("connection-0", path.EndpointA.ClientID) suite.Require().Equal("channel-0", path.EndpointA.ClientID) // send on endpointA sequence, err := path.EndpointA.SendPacket(timeoutHeight1, timeoutTimestamp1, packet1Data) // create packet 1 packet1 := NewPacket() // NewPacket would construct your packet // receive on endpointB path.EndpointB.RecvPacket(packet1) // acknowledge the receipt of the packet path.EndpointA.AcknowledgePacket(packet1, ack) // we can also relay sequence, err := path.EndpointA.SendPacket(timeoutHeight2, timeoutTimestamp2, packet2Data) packet2 := NewPacket() path.RelayPacket(packet2) // if needed we can update our clients path.EndpointB.UpdateClient() ``` -------------------------------- ### Usage Example Source: https://github.com/cosmos/evm/blob/main/precompiles/erc20/README.md Example of how to interact with the ERC20 precompile from a Solidity smart contract. ```APIDOC ```solidity // Assuming the precompile is deployed at a specific address for a native token IERC20 token = IERC20(0x...); // Precompile address for the native token // Check balance uint256 balance = token.balanceOf(msg.sender); // Transfer tokens token.transfer(recipient, 1000000); // Transfer 1 token (assuming 6 decimals) // Approve and transferFrom token.approve(spender, 5000000); // Spender can now call: token.transferFrom(owner, recipient, 3000000); ``` ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/viem/README.md Run this command to install project dependencies. ```shell npm install ``` -------------------------------- ### Build and Install EVM Source: https://github.com/cosmos/evm/blob/main/AGENTS.md Commands to build the EVM executable and install it to the Go binary path. Use `build-linux` for cross-compiling for Linux. ```bash make build # builds ./build/evmd make install # installs evmd to $GOPATH/bin make build-linux # cross-compile linux/amd64 ``` -------------------------------- ### Install Dependencies Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/web3.js/README.md Install the necessary npm packages for the project, including web3.js and chai. ```shell npm install npm i chai@4 ``` -------------------------------- ### Start Geth Node for Comparison Source: https://github.com/cosmos/evm/blob/main/tests/jsonrpc/README.md Start a Geth node to serve as a comparison point for JSON-RPC compatibility testing. ```bash # Start geth for comparison ./tests/jsonrpc/scripts/geth/start-geth.sh ``` -------------------------------- ### Create Environment File Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/foundry-uniswap-v3/README.md Copies the example environment file to be customized for local settings. Remember not to commit this file. ```bash cp .env.example .env # modify .env ``` -------------------------------- ### Run Compatibility Tests (Quick Start) Source: https://github.com/cosmos/evm/blob/main/tests/jsonrpc/README.md Execute the comprehensive JSON-RPC compatibility tests from the project root. ```bash # From project root make test-rpc-compat ``` -------------------------------- ### Basic Deposit and Transfer Example Source: https://github.com/cosmos/evm/blob/main/precompiles/werc20/README.md Example demonstrating how to deposit native tokens and then use the WERC20 token for transfers. ```APIDOC ## Usage Examples ### Basic Deposit and Transfer ```solidity // Assume WERC20 is deployed at a specific address IWERC20 wrappedToken = IWERC20(0x...); // WERC20 precompile address // Deposit native tokens (sent value is returned to sender as wrapped tokens) wrappedToken.deposit{value: 1 ether}(); // Now you can use it as an ERC20 token wrappedToken.transfer(recipient, 0.5 ether); // Check balance uint256 balance = wrappedToken.balanceOf(msg.sender); ``` ``` -------------------------------- ### Integration with DeFi Protocols Example Source: https://github.com/cosmos/evm/blob/main/precompiles/werc20/README.md Example showing how a DeFi protocol can integrate with the WERC20 precompile for collateral or swaps. ```APIDOC ## Integration with DeFi Protocols ```solidity contract DeFiProtocol { IWERC20 public wrappedNative; constructor(address _wrappedNative) { wrappedNative = IWERC20(_wrappedNative); } function depositCollateral() external payable { // Automatically wraps native tokens wrappedNative.deposit{value: msg.value}(); // Now treat it as ERC20 collateral // The protocol can use standard ERC20 operations } function swapTokens(IERC20 tokenIn, uint256 amountIn) external { // Works seamlessly with wrapped native tokens tokenIn.transferFrom(msg.sender, address(this), amountIn); // Perform swap logic... } } ``` ``` -------------------------------- ### Install Foundry Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/foundry-uniswap-v3/README.md Installs Foundry, a suite of tools for smart contract development, using a provided script. ```bash curl -L https://foundry.paradigm.xyz | bash foundryup ``` -------------------------------- ### Governance Precompile Usage Example Source: https://github.com/cosmos/evm/blob/main/precompiles/gov/README.md Example of how to use the governance precompile from a Solidity smart contract. ```APIDOC ## Usage Example ```solidity IGov gov = IGov(GOV_PRECOMPILE_ADDRESS); // Submit a proposal with initial deposit Coin[] memory initialDeposit = new Coin[](1); initialDeposit[0] = Coin({denom: "aevmos", amount: 1000000000000000000}); // 1 token bytes memory proposalJSON = '{"messages":[...],"metadata":"...","title":"...","summary":"..."}'; uint64 proposalId = gov.submitProposal(msg.sender, proposalJSON, initialDeposit); // Vote on the proposal gov.vote(msg.sender, proposalId, VoteOption.Yes, "Supporting this proposal"); // Add additional deposit Coin[] memory additionalDeposit = new Coin[](1); additionalDeposit[0] = Coin({denom: "aevmos", amount: 500000000000000000}); // 0.5 token gov.deposit(msg.sender, proposalId, additionalDeposit); // Query proposal status ProposalData memory proposal = gov.getProposal(proposalId); ``` ``` -------------------------------- ### Setup Block Mempool Configuration Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.6.x_to_v0.7.0.md This code sets up the necessary components for the EVM mempool configuration in v0.7.0. Ensure `app.SetAnteHandler(...)` is called before this setup to avoid runtime panics. ```go mpConfig := server.ResolveMempoolConfig(app.GetAnteHandler(), appOpts, logger) txEncoder := evmmempool.NewTxEncoder(app.txConfig) evMRechecker := evmmempool.NewTxRechecker(mpConfig.AnteHandler, txEncoder) cosmosRechecker := evmmempool.NewTxRechecker(mpConfig.AnteHandler, txEncoder) cosmosPoolMaxTx := server.GetCosmosPoolMaxTx(appOpts, logger) checkTxTimeout := server.GetMempoolCheckTxTimeout(appOpts, logger) ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/foundry/README.md Clones the compatibility test repository and installs necessary Foundry dependencies. ```bash git clone https://github.com/b-harvest/evm-tools-compatibility.git cd evm-tools-compatibility/foundry forge install forge install OpenZeppelin/openzeppelin-contracts@5.3.0 ``` -------------------------------- ### ERC20 Precompile Usage Example Source: https://github.com/cosmos/evm/blob/main/precompiles/erc20/README.md Example of interacting with the ERC20 precompile to check balances, transfer tokens, and manage allowances. ```solidity // Assuming the precompile is deployed at a specific address for a native token IERC20 token = IERC20(0x...); // Precompile address for the native token // Check balance uint256 balance = token.balanceOf(msg.sender); // Transfer tokens token.transfer(recipient, 1000000); // Transfer 1 token (assuming 6 decimals) // Approve and transferFrom token.approve(spender, 5000000); // Spender can now call: token.transferFrom(owner, recipient, 3000000); ``` -------------------------------- ### Run Local Cosmos EVM Chain Source: https://github.com/cosmos/evm/blob/main/evmd/README.md Execute this script to run the example Cosmos EVM chain locally. Flags can be used to control database overwriting, installation, and debugging. ```bash ./local_node.sh [FLAGS] ``` -------------------------------- ### Complete ERC20 Precompile Migration Handler Example Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_erc20_precompiles_migration.md This is a complete example of an upgrade handler function for v0.4.0, including standard module migrations and the specific ERC20 precompile migration logic. ```go // app/upgrades/v040/handler.go package v040 import ( "context" storetypes "cosmossdk.io/store/types" upgradetypes "cosmossdk.io/x/upgrade/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" erc20keeper "github.com/cosmos/evm/x/erc20/keeper" erc20types "github.com/cosmos/evm/x/erc20/types" "github.com/ethereum/go-ethereum/common" ) const UpgradeName = "v0.4.0" func CreateUpgradeHandler( mm *module.Manager, configurator module.Configurator, keepers *UpgradeKeepers, storeKeys map[string]*storetypes.KVStoreKey, ) upgradetypes.UpgradeHandler { return func(c context.Context, plan upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { ctx := sdk.UnwrapSDKContext(c) ctx.Logger().Info("Starting v0.4.0 upgrade...") // Run standard module migrations vm, err := mm.RunMigrations(ctx, configurator, vm) if err != nil { return vm, err } // Migrate ERC20 precompiles if err := migrateERC20Precompiles(ctx, storeKeys[erc20types.StoreKey], keepers.Erc20Keeper); err != nil { return vm, err } ctx.Logger().Info("v0.4.0 upgrade complete") return vm, nil } } ``` -------------------------------- ### Start Both EVMD and Geth Nodes Source: https://github.com/cosmos/evm/blob/main/tests/jsonrpc/README.md Convenience script to start both EVMD and Geth nodes simultaneously for testing. ```bash # Or start both at once ./tests/jsonrpc/scripts/start-networks.sh ``` -------------------------------- ### Metamask RPC URL for Example Chain Source: https://github.com/cosmos/evm/blob/main/evmd/README.md Configure Metamask to connect to the running example Cosmos EVM chain by adding this RPC URL. Ensure the chain is accessible at http://localhost:8545. ```text http://localhost:8545 ``` -------------------------------- ### Basic WERC20 Deposit and Transfer Example Source: https://github.com/cosmos/evm/blob/main/precompiles/werc20/README.md Demonstrates how to deposit native tokens into the WERC20 precompile and then use the wrapped tokens for a transfer. Ensure the WERC20 precompile address is correctly set. ```solidity IWERC20 wrappedToken = IWERC20(0x...); // WERC20 precompile address // Deposit native tokens (sent value is returned to sender as wrapped tokens) wrappedToken.deposit{value: 1 ether}(); // Now you can use it as an ERC20 token wrappedToken.transfer(recipient, 0.5 ether); // Check balance uint256 balance = wrappedToken.balanceOf(msg.sender); ``` -------------------------------- ### Refactor Mempool Configuration Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_to_v0.5.0.md The mempool configuration can now be handled by a helper function. This example shows the 'before' state with manual configuration. ```go mempoolConfig := &evmmempool.EVMMempoolConfig{ AnteHandler: app.GetAnteHandler(), BlockGasLimit: blockGasLimit, MinTip: minTip, } evmMempool := evmmempool.NewExperimentalEVMMempool( app.CreateQueryContext, logger, app.EVMKeeper, app.FeeMarketKeeper, app.txConfig, app.clientCtx, mempoolConfig, ) ``` -------------------------------- ### Create Validator Example Source: https://github.com/cosmos/evm/blob/main/precompiles/staking/README.md Demonstrates how to create a new validator using the staking precompile. Ensure correct Description and CommissionRates are set, and amounts are in the bond denomination precision. ```solidity StakingI staking = StakingI(STAKING_PRECOMPILE_ADDRESS); Description memory desc = Description({ moniker: "My Validator", identity: "keybase-identity", website: "https://validator.example.com", securityContact: "security@example.com", details: "Professional validator service" }); CommissionRates memory rates = CommissionRates({ rate: 100, // 1% (100 / 10000) maxRate: 2000, // 20% max maxChangeRate: 100 // 1% max daily change }); // Create validator with 1000 tokens self-delegation bool success = staking.createValidator( desc, rates, 1000e18, // Min self delegation msg.sender, // Validator address "validator_pubkey", // Consensus public key 1000e18 // Initial self delegation ); ``` -------------------------------- ### Run Local EVM Node Source: https://github.com/cosmos/evm/blob/main/README.md Execute this script from the repository root to run the example `evmd` chain. ```bash ./local_node.sh ``` -------------------------------- ### Start EVMD Node for Testing Source: https://github.com/cosmos/evm/blob/main/tests/jsonrpc/README.md Initialize and start a single-node EVMD instance with JSON-RPC enabled for testing purposes. ```bash # Start evmd with JSON-RPC enabled ./tests/jsonrpc/scripts/evmd/start-evmd.sh ``` -------------------------------- ### Wire EVM Tx Runner (Sequential) Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.6.x_to_v0.7.0.md Install the baseapp tx runner wrapped with EVM module's PatchTxResponses for sequential execution. ```diff + vmrunner.SetRunner(bApp, txnrunner.NewDefaultRunner(txDecoder)) ``` -------------------------------- ### Get Help for Foundry Tools Source: https://github.com/cosmos/evm/blob/main/tests/systemtests/Counter/README.md Displays help information for Forge, Anvil, and Cast commands. ```shell forge --help ``` ```shell anvil --help ``` ```shell cast --help ``` -------------------------------- ### Solidity Usage Example for Slashing Precompile Source: https://github.com/cosmos/evm/blob/main/precompiles/slashing/README.md Demonstrates how to interact with the Slashing precompile to query validator signing information, check jail status, unjail a validator, and retrieve slashing parameters. ```solidity ISlashing slashing = ISlashing(SLASHING_PRECOMPILE_ADDRESS); // Query validator signing info address consAddress = 0x...; // Validator consensus address SigningInfo memory info = slashing.getSigningInfo(consAddress); // Check if validator is jailed if (info.jailedUntil > int64(block.timestamp)) { // Validator is currently jailed // If jail period has expired and caller is the validator if (block.timestamp >= uint64(info.jailedUntil)) { // Unjail the validator bool success = slashing.unjail(msg.sender); require(success, "Failed to unjail"); } } // Query slashing parameters Params memory params = slashing.getParams(); // Access parameters like params.signedBlocksWindow ``` -------------------------------- ### Implement TestingApp Interface for SimApp Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Example implementation of the TestingApp interface for a SimApp, providing access to its core components like BaseApp, StakingKeeper, IBCKeeper, and TxConfig. ```go // TestingApp functions // Example using SimApp to implement TestingApp // GetBaseApp implements the TestingApp interface. func (app *SimApp) GetBaseApp() *baseapp.BaseApp { return app.BaseApp } // GetStakingKeeper implements the TestingApp interface. func (app *SimApp) GetStakingKeeper() ibctestingtypes.Keeper { return app.StakingKeeper } // GetIBCKeeper implements the TestingApp interface. func (app *SimApp) GetIBCKeeper() *ibckeeper.Keeper { return app.IBCKeeper } // GetTxConfig implements the TestingApp interface. func (app *SimApp) GetTxConfig() client.TxConfig { return app.txConfig } ``` -------------------------------- ### Delegate to Validator Example Source: https://github.com/cosmos/evm/blob/main/precompiles/staking/README.md Shows how to delegate tokens to an existing validator and query the delegation details. Amounts should use the bond denomination precision. ```solidity StakingI staking = StakingI(STAKING_PRECOMPILE_ADDRESS); // Delegate 100 tokens to a validator string memory validatorAddr = "evmosvaloper1..."; // Bech32 validator address bool success = staking.delegate(msg.sender, validatorAddr, 100e18); // Query delegation (uint256 shares, Coin memory balance) = staking.delegation(msg.sender, validatorAddr); ``` -------------------------------- ### ICS20 Usage Example Source: https://github.com/cosmos/evm/blob/main/precompiles/ics20/README.md Demonstrates how to use the ICS20 precompile from a Solidity smart contract to perform an IBC transfer and query denomination information. ```APIDOC ## Usage Example ```solidity ICS20I ics20 = ICS20I(ICS20_PRECOMPILE_ADDRESS); // Prepare transfer parameters string memory sourcePort = "transfer"; string memory sourceChannel = "channel-0"; string memory denom = "uatom"; uint256 amount = 1000000; // 1 ATOM (6 decimals) string memory receiver = "cosmos1..."; // Bech32 address on destination chain // Set timeout (e.g., 1 hour from now) Height memory timeoutHeight = Height({ revisionNumber: 0, revisionHeight: 0 // Disabled }); uint64 timeoutTimestamp = uint64(block.timestamp + 3600) * 1e9; // Convert to nanoseconds // Execute IBC transfer uint64 sequence = ics20.transfer( sourcePort, sourceChannel, denom, amount, msg.sender, receiver, timeoutHeight, timeoutTimestamp, "Transfer from EVM" ); // Query denomination information Denom memory denomInfo = ics20.denom("ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2"); ``` ``` -------------------------------- ### Start Local Node with Anvil Source: https://github.com/cosmos/evm/blob/main/tests/systemtests/Counter/README.md Launches a local Ethereum node using Anvil. This provides a local environment for testing and development. ```shell anvil ``` -------------------------------- ### KeeperTestSuite Setup Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Defines a testing suite for keeper functions, initializing a coordinator with two test chains (chainA and chainB) for convenience and readability. ```go // KeeperTestSuite is a testing suite to test keeper functions. type KeeperTestSuite struct { testifysuite.Suite coordinator *ibctesting.Coordinator // testing chains used for convenience and readability chainA *ibctesting.TestChain chainB *ibctesting.TestChain } // TestKeeperTestSuite runs all the tests within this package. func TestKeeperTestSuite(t *testing.T) { testifysuite.Run(t, new(KeeperTestSuite)) } // SetupTest creates a coordinator with 2 test chains. func (suite *KeeperTestSuite) SetupTest() { suite.coordinator = ibctesting.NewCoordinator(suite.T(), 2) // initializes 2 test chains suite.chainA = suite.coordinator.GetChain(ibctesting.GetChainID(1)) // convenience and readability suite.chainB = suite.coordinator.GetChain(ibctesting.GetChainID(2)) // convenience and readability } ``` -------------------------------- ### Compile Uniswap v3-core Submodule Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/hardhat/README.md Prepare the v3-core submodule for compilation by initializing and updating git submodules, installing dependencies, and compiling the contract. ```shell cd external/v3-core git submodule init git submodule update npm install npx hardhat compile ``` -------------------------------- ### Cosmos EVM Governance Precompile Usage Example Source: https://github.com/cosmos/evm/blob/main/precompiles/gov/README.md Demonstrates how to interact with the governance precompile to submit proposals, vote, deposit funds, and query proposal status. Ensure proposal JSON is correctly formatted and vote weights sum to '1.0'. ```solidity IGov gov = IGov(GOV_PRECOMPILE_ADDRESS); // Submit a proposal with initial deposit Coin[] memory initialDeposit = new Coin[](1); initialDeposit[0] = Coin({denom: "aevmos", amount: 1000000000000000000}); // 1 token bytes memory proposalJSON = '{"messages":[...],"metadata":"...","title":"...","summary":"..."}'; uint64 proposalId = gov.submitProposal(msg.sender, proposalJSON, initialDeposit); // Vote on the proposal gov.vote(msg.sender, proposalId, VoteOption.Yes, "Supporting this proposal"); // Add additional deposit Coin[] memory additionalDeposit = new Coin[](1); additionalDeposit[0] = Coin({denom: "aevmos", amount: 500000000000000000}); // 0.5 token gov.deposit(msg.sender, proposalId, additionalDeposit); // Query proposal status ProposalData memory proposal = gov.getProposal(proposalId); ``` -------------------------------- ### Manage Delegations Example Source: https://github.com/cosmos/evm/blob/main/precompiles/staking/README.md Illustrates how to undelegate tokens, redelegate to a different validator, and cancel an unbonding delegation. Note that canceling requires the creation height. ```solidity // Undelegate 50 tokens (starts unbonding period) int64 completionTime = staking.undelegate(msg.sender, validatorAddr, 50e18); // Redelegate to another validator (no unbonding period) string memory newValidator = "evmosvaloper2..."; int64 redelegationTime = staking.redelegate( msg.sender, validatorAddr, newValidator, 25e18 ); // Cancel unbonding (must specify the creation height) uint256 creationHeight = 12345; staking.cancelUnbondingDelegation( msg.sender, validatorAddr, 50e18, creationHeight ); ``` -------------------------------- ### Compile Smart Contracts Source: https://github.com/cosmos/evm/blob/main/scripts/compile_smart_contracts/README.md Run this command to compile all smart contracts and generate JSON files. It uses a Hardhat setup to process contracts found in the repository. ```bash make contracts-compile ``` -------------------------------- ### ICS20 Precompile Usage Example (Solidity) Source: https://github.com/cosmos/evm/blob/main/precompiles/ics20/README.md Demonstrates how to use the ICS20 precompile to perform a cross-chain token transfer and query denomination information. Ensure receiver addresses are valid Bech32 addresses. ```solidity ICS20I ics20 = ICS20I(ICS20_PRECOMPILE_ADDRESS); // Prepare transfer parameters string memory sourcePort = "transfer"; string memory sourceChannel = "channel-0"; string memory denom = "uatom"; uint256 amount = 1000000; // 1 ATOM (6 decimals) string memory receiver = "cosmos1..."; // Bech32 address on destination chain // Set timeout (e.g., 1 hour from now) Height memory timeoutHeight = Height({ revisionNumber: 0, revisionHeight: 0 // Disabled }); uint64 timeoutTimestamp = uint64(block.timestamp + 3600) * 1e9; // Convert to nanoseconds // Execute IBC transfer uint64 sequence = ics20.transfer( sourcePort, sourceChannel, denom, amount, msg.sender, receiver, timeoutHeight, timeoutTimestamp, "Transfer from EVM" ); // Query denomination information Denom memory denomInfo = ics20.denom("ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2"); ``` -------------------------------- ### Setup Transfer Testing App Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Configures a testing application for IBC transfer module tests. This function initializes a new SimApp with necessary configurations and returns the app and its default genesis state. ```go package transfertesting import ( "encoding/json" "github.com/cometbft/cometbft/libs/log" dbm "github.com/cometbft/cometbft-db" "github.com/cosmos/ibc-go/v11/modules/apps/transfer/simapp" ibctesting "github.com/cosmos/ibc-go/v11/testing" ) func SetupTransferTestingApp() (ibctesting.TestingApp, map[string]json.RawMessage) { db := dbm.NewMemDB() encCdc := simapp.MakeTestEncodingConfig() app := simapp.NewSimApp( log.NewNopLogger(), db, nil, true, map[int64]bool{}, simapp.DefaultNodeHome, 5, encCdc, simapp.EmptyAppOptions{}, ) return app, simapp.NewDefaultGenesisState(encCdc.Marshaler) } func init() { ibctesting.DefaultTestingAppInit = SetupTransferTestingApp } ``` -------------------------------- ### Initialize EVM Interpreter with Configuration Source: https://github.com/cosmos/evm/blob/main/eips/README.md Details the initialization of the EVM interpreter, including setting up the default jump table and enabling extra EIPs. ```go func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { // If jump table was not initialised we set the default one. if cfg.JumpTable == nil { cfg.JumpTable = DefaultJumpTable(evm.chainRules) for i, eip := range cfg.ExtraEips { // Deep-copy jumptable to prevent modification of opcodes in other tables copy := CopyJumpTable(cfg.JumpTable) if err := EnableEIP(eip, copy); err != nil { // Disable it, so caller can check if it's activated or not cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) log.Error("EIP activation failed", "eip", eip, "error", err) } cfg.JumpTable = copy } } return &EVMInterpreter{ evm: evm, cfg: cfg, } } ``` -------------------------------- ### Run Bank Precompile Test Suite Source: https://github.com/cosmos/evm/blob/main/tests/integration/README.md This Go code demonstrates how to set up and run the Bank Precompile integration test suite. It requires implementing the `EvmApp` interface and providing a `CreateApp` function. ```go package integration import ( t"testing" "github.com/stretchr/testify/suite" "github.com/cosmos/cosmos-sdk/baseapp" ev "github.com/cosmos/evm" testapp "github.com/cosmos/evm/testutil/app" "github.com/cosmos/evm/tests/integration/precompiles/bank" ) func TestBankPrecompileTestSuite(t *testing.T) { create := testapp.ToEvmAppCreator[evm.BankPrecompileApp](CreateEvmd, "evm.BankPrecompileApp") s := bank.NewPrecompileTestSuite(create) suite.Run(t, s) } func TestBankPrecompileIntegrationTestSuite(t *testing.T) { create := testapp.ToEvmAppCreator[evm.BankPrecompileApp](CreateEvmd, "evm.BankPrecompileApp") bank.TestIntegrationSuite(t, create) } ``` -------------------------------- ### Build Speedtest Tool Source: https://github.com/cosmos/evm/blob/main/tests/speedtest/README.md Navigate to the speedtest directory and build the executable. This prepares the tool for execution. ```bash cd tests/speedtest go build . ``` -------------------------------- ### Install Forge Dependencies Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/foundry-uniswap-v3/README.md Installs project dependencies required by Forge, the smart contract build tool. ```bash forge install ``` -------------------------------- ### Build and Test Cosmos EVM Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.6.x_to_v0.7.0.md Use these Go commands to build the project and run tests. Ensure all dependencies are met before execution. ```bash go build ./... ``` ```bash go test ./... ``` -------------------------------- ### Initialize and Configure EVMConfigurator Source: https://github.com/cosmos/evm/blob/main/eips/README.md Demonstrates the builder pattern usage for initializing and configuring the EVMConfigurator. This should be done in the init() function. ```go configurator := evmconfig.NewEVMConfigurator(). WithExtendedEips(customActivators). WithExtendedDefaultExtraEIPs(defaultEnabledEIPs...). Configure() err := configurator.Configure() ``` -------------------------------- ### Run Speedtest with Default Configuration Source: https://github.com/cosmos/evm/blob/main/tests/speedtest/README.md Execute the speedtest tool with its default settings. This runs a simulation with 10k accounts, 4k transactions per block, for 100 blocks. ```bash ./speedtest ``` -------------------------------- ### Build Project Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_to_v0.5.0.md Compile the project using the go build command. This command builds all packages in the specified directory. ```bash go build ./... ``` -------------------------------- ### Run Solidity Tests Source: https://github.com/cosmos/evm/blob/main/README.md Execute Solidity tests using the `make test-solidity` command. ```bash make test-solidity ``` -------------------------------- ### Metamask Seed Phrase for Example Chain Source: https://github.com/cosmos/evm/blob/main/evmd/README.md Use this seed phrase to import a wallet into Metamask for connecting to the example chain. Ensure the chain is running and configured with the correct RPC URL. ```text gesture inject test cycle original hollow east ridge hen combine junk child bacon zero hope comfort vacuum milk pitch cage oppose unhappy lunar seat ``` -------------------------------- ### Create New EVM Instance Source: https://github.com/cosmos/evm/blob/main/eips/README.md Shows the creation of a new EVM instance using the retrieved configuration and other necessary parameters. ```go evm := k.NewEVM(ctx, msg, cfg, tracer, stateDB) ``` -------------------------------- ### Build and Test Commands Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.5.x_to_v0.6.0.md Standard commands to build the project and run tests. ```bash go build ./... go test ./... ``` -------------------------------- ### Get Signing Infos (Paginated) Source: https://github.com/cosmos/evm/blob/main/precompiles/slashing/README.md Retrieves a paginated list of signing information for multiple validators. ```APIDOC ## getSigningInfos ### Description Retrieves a paginated list of `SigningInfo` for multiple validators. This is useful for querying multiple validators' signing statuses at once. ### Method `external view` ### Parameters - **pagination** (PageRequest) - Calldata for pagination, specifying how many results to return and where to start. ### Returns - **signingInfos** (SigningInfo[]) - An array of `SigningInfo` structs for the validators. - **pageResponse** (PageResponse) - Information about the pagination response, such as next key and total count. ### Usage Example ```solidity PageRequest memory req = PageRequest({ key: bytes(''), offset: 0, limit: 10, reverse: false }); (SigningInfo[] memory infos, PageResponse memory resp) = slashing.getSigningInfos(req); ``` ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/foundry-uniswap-v3/README.md Clones the compatibility tools repository and navigates into the specific Foundry Uniswap V3 directory. ```bash git clone https://github.com/b-harvest/evm-tools-compatibility.git cd evm-tools-compatibility/foundry-uniswap-v3 ``` -------------------------------- ### Update NewExampleApp Constructor Signature Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.6.x_to_v0.7.0.md The `traceStore io.Writer` parameter has been removed from the `NewExampleApp` constructor. Ensure all call sites, including CLI commands, test fixtures, and integration tests, are updated to reflect this change. Sites passing `nil` for this argument must also drop the argument. ```diff func NewExampleApp( logger log.Logger, db dbm.DB, - traceStore io.Writer, loadLatest bool, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *EVMD { ``` -------------------------------- ### Get Slashing Parameters Source: https://github.com/cosmos/evm/blob/main/precompiles/slashing/README.md Retrieves the current slashing module parameters, which define rules for validator penalties and behavior. ```APIDOC ## getParams ### Description Retrieves the current parameters configured for the Cosmos SDK slashing module. These parameters govern validator behavior, penalties, and jail durations. ### Method `external view` ### Returns - **params** (Params) - A struct containing the slashing module parameters. - `signedBlocksWindow` (int64) - `minSignedPerWindow` (Dec) - `downtimeJailDuration` (int64) - `slashFractionDoubleSign` (Dec) - `slashFractionDowntime` (Dec) ### Usage Example ```solidity Params memory params = slashing.getParams(); int64 window = params.signedBlocksWindow; ``` ``` -------------------------------- ### Create SDK app creator wrapper Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.3.0_to_v0.4.0.md Provide a wrapper function for commands that expect the older SDK application type, ensuring compatibility with `pruning.Cmd` and `snapshot.Cmd`. ```go sdkAppCreatorWrapper := func(l log.Logger, d dbm.DB, w io.Writer, ao servertypes.AppOptions) servertypes.Application { return ac.newApp(l, d, w, ao) } ``` -------------------------------- ### Get Signing Info Source: https://github.com/cosmos/evm/blob/main/precompiles/slashing/README.md Retrieves the signing information for a specific validator, including their jail status and missed block count. ```APIDOC ## getSigningInfo ### Description Retrieves the `SigningInfo` for a given validator consensus address. This includes details about missed blocks, jail status, and tombstone status. ### Method `external view` ### Parameters - **consAddress** (address) - The consensus address of the validator. ### Returns - **signingInfo** (SigningInfo) - A struct containing the validator's signing information. - `validatorAddress` (address) - `startHeight` (int64) - `indexOffset` (int64) - `jailedUntil` (int64) - `tombstoned` (bool) - `missedBlocksCounter` (int64) ### Usage Example ```solidity address consAddress = 0x...; SigningInfo memory info = slashing.getSigningInfo(consAddress); ``` ``` -------------------------------- ### Run JSON-RPC Compatibility Simulator Source: https://github.com/cosmos/evm/blob/main/tests/jsonrpc/README.md Build and run the simulator tool, which is the primary method for comprehensive compatibility testing. ```bash cd tests/jsonrpc/simulator go build . ./simulator ``` -------------------------------- ### Compile Uniswap v3-periphery Submodule Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/hardhat/README.md Prepare the v3-periphery submodule for compilation by initializing and updating git submodules, installing dependencies, and compiling the contract. ```shell cd external/v3-periphery git submodule init git submodule update npm install npx hardhat compile ``` -------------------------------- ### Initialize TestingApp with SimApp Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Provides a function to initialize the TestingApp using the SimApp implementation. This function returns the TestingApp and its default genesis state. ```go func SetupTestingApp() (TestingApp, map[string]json.RawMessage) { db := dbm.NewMemDB() app := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, simtestutil.EmptyAppOptions{}) return app, app.DefaultGenesis() } ``` -------------------------------- ### Handle EVM Configuration Errors Source: https://github.com/cosmos/evm/blob/main/eips/README.md Shows how to handle errors during EVM configuration, suggesting to panic as this configuration happens before node startup. ```go if err != nil { panic(err) } ``` -------------------------------- ### Generate Protobufs and Mocks for EVM Source: https://github.com/cosmos/evm/blob/main/AGENTS.md Commands to generate protobuf definitions and mocks, requiring Docker and Go tooling. `proto-all` includes formatting and linting. ```bash make proto-all # format + lint + gen make proto-gen make mocks ``` -------------------------------- ### Initialize EVM Address Codec Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_to_v0.5.0.md Use `evmaddress.NewEvmCodec()` for address codec initialization, as address-related functions have moved to the new `github.com/cosmos/evm/encoding/address` package. ```go app.AccountKeeper = authkeeper.NewAccountKeeper( appCodec, runtime.NewKVStoreService(keys[authtypes.StoreKey]), authtypes.ProtoBaseAccount, evmconfig.GetMaccPerms(), evmaddress.NewEvmCodec(sdk.GetConfig().GetBech32AccountAddrPrefix()), sdk.GetConfig().GetBech32AccountAddrPrefix(), authAddr, ) ``` -------------------------------- ### Set DefaultTestingAppInit Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Sets the DefaultTestingAppInit to use a custom setup function. This is typically called within an init function to configure the testing environment. ```go func init() { ibctesting.DefaultTestingAppInit = SetupTestingApp } ``` -------------------------------- ### Clean Smart Contract Artifacts Source: https://github.com/cosmos/evm/blob/main/scripts/compile_smart_contracts/README.md Use this command to remove generated artifacts, installed dependencies, and cached files related to smart contract compilation. ```bash make contracts-clean ``` -------------------------------- ### Run Benchmark Tests Source: https://github.com/cosmos/evm/blob/main/README.md Execute benchmark tests using the `make benchmark` command. ```bash make benchmark ``` -------------------------------- ### Calling EVM from Non-Precompile Contexts Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.5.x_to_v0.6.0.md When calling EVM functions from outside a precompile, create a new stateDB and pass false for callFromPrecompile. This example shows the before and after for CallEVM. ```go import ( "github.com/cosmos/evm/x/vm/statedb" ) // Before (v0.5.x) res, err := k.evmKeeper.CallEVM( ctx, abi, from, contract, false, // commit nil, // gasCap "balanceOf", account, ) ``` ```go // After (v0.6.0) stateDB := statedb.New(ctx, k.evmKeeper, statedb.NewEmptyTxConfig()) res, err := k.evmKeeper.CallEVM( ctx, stateDB, abi, from, contract, false, // commit false, // callFromPrecompile nil, // gasCap "balanceOf", account, ) ``` -------------------------------- ### Start and Stop EVM Localnet Source: https://github.com/cosmos/evm/blob/main/AGENTS.md Commands to manage a local 4-node Docker testnet for the EVM. Also includes a command to run a single-node development chain. ```bash make localnet-start # 4-node testnet make localnet-stop ./local_node.sh # single-node dev chain ``` -------------------------------- ### Configure EVM Mempool with Helper Function Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_to_v0.5.0.md This is the 'after' state, demonstrating the optional use of a helper function to configure the EVM mempool. The helper function reads configuration from `appOpts` or applies defaults. ```go if err := app.configureEVMMempool(appOpts, logger); err != nil { panic(fmt.Sprintf("failed to configure EVM mempool: %s", err.Error())) } ``` -------------------------------- ### Solidity Query Methods for Slashing Information Source: https://github.com/cosmos/evm/blob/main/precompiles/slashing/README.md Defines the view functions to retrieve signing information for a specific validator or all validators, and to get the slashing module parameters. ```solidity // Get signing info for a specific validator function getSigningInfo( address consAddress ) external view returns (SigningInfo memory signingInfo); // Get signing info for all validators with pagination function getSigningInfos( PageRequest calldata pagination ) external view returns ( SigningInfo[] memory signingInfos, PageResponse memory pageResponse ); // Get slashing module parameters function getParams() external view returns (Params memory params); ``` -------------------------------- ### Configure Precompile Options in Go Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.3.0_to_v0.4.0.md Set up options for precompiles, such as overriding default address codecs if non-standard prefixes or codecs are used. This is necessary when initializing `NewAvailableStaticPrecompiles`. ```go opts := []Option{ // override defaults only if you use non-standard prefixes/codecs WithAddressCodec(myAcctCodec), WithValidatorAddrCodec(myValCodec), WithConsensusAddrCodec(myConsCodec), } pcs := NewAvailableStaticPrecompiles(ctx, /* ... keepers ... */, opts...) ``` -------------------------------- ### Get Transfer Sim App Instance Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Retrieves the SimApp instance from a test chain, asserting that it is indeed a transfer application. Panics if the chain's app is not a *simapp.SimApp. ```go func GetTransferSimApp(chain *ibctesting.TestChain) *simapp.SimApp { app, ok := chain.App.(*simapp.SimApp) if !ok { panic("not transfer app") } return app } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cosmos/evm/blob/main/README.md Execute unit tests using the `make test-unit` command. ```bash make test-unit ``` -------------------------------- ### Query Validator Slashing Events Source: https://github.com/cosmos/evm/blob/main/precompiles/distribution/README.md Retrieve slashing events for a validator within a specified height range. Requires validator address, start and end heights, and pagination parameters. ```solidity function validatorSlashes( string memory validator, uint64 startingHeight, uint64 endingHeight, PageRequest memory pageRequest ) external view returns ( ValidatorSlashEvent[] memory, PageResponse memory ); ``` -------------------------------- ### Update Node Configuration in System Tests Source: https://github.com/cosmos/evm/blob/main/tests/systemtests/README.md Demonstrates how to update the `config.toml` of nodes during system test setup, specifically setting the commit timeout. This feature was introduced in systemtests v1.4.0. ```go s := systemtest.Sut s.ResetChain(t) s.SetupChain("--config-changes=consensus.timeout_commit=10s") ``` -------------------------------- ### Mock ICA Auth OnChanOpenInit Callback Source: https://github.com/cosmos/evm/blob/main/testutil/ibc/README.md Mocks the OnChanOpenInit callback for an ICA (Interchain Accounts) authentication module. This example demonstrates how to set a custom error to verify that the mock is being invoked. ```go suite.chainA.GetSimApp().ICAAuthModule.IBCApp.OnChanOpenInit = func( ctx sdk.Context, order channeltypes.Order, connectionHops []string, portID, channelID string, counterparty channeltypes.Counterparty, version string, ) error { return fmt.Errorf("mock ica auth fails") } ``` -------------------------------- ### Run Basic Test Environment Source: https://github.com/cosmos/evm/blob/main/tests/evm-tools-compatibility/hardhat/README.md Execute the basic test suite for the project using the default Hardhat environment. ```shell npx hardhat test ``` -------------------------------- ### Modify CREATE Opcode Constant Gas Source: https://github.com/cosmos/evm/blob/main/eips/README.md Example of an EIP that modifies the constant gas cost for the CREATE opcode. This is done by calling the SetConstantGas method on the specific opcode entry in the JumpTable. ```go // Enable a custom EIP-0000 func Enable0000(jt *vm.JumpTable) { jt[vm.CREATE].SetConstantGas(1) } ``` -------------------------------- ### Build and Run System Tests Source: https://github.com/cosmos/evm/blob/main/tests/systemtests/README.md Builds the system tests and runs them. Alternatively, manually build the evmd binary and copy it to the specified directory. ```shell make test-system ``` ```shell make build mkdir -p ./tests/systemtests/binaries cp ./build/evmd ./tests/systemtests/binaries cp ./build/evmd ./tests/systemtests/binaries/v0.4 ``` -------------------------------- ### Simple Mempool Config Migration Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.4.0_to_v0.5.0.md This snippet shows a simplified mempool configuration, illustrating default values for `BlockGasLimit` and `BroadCastTxFn` if not explicitly set. ```go mempoolConfig := &evmmempool.EVMMempoolConfig{ AnteHandler: app.GetAnteHandler(), BlockGasLimit: 100_000_000, // or 0 to use default } evmMempool := evmmempool.NewExperimentalEVMMempool( app.CreateQueryContext, logger, app.EVMKeeper, app.FeeMarketKeeper, app.txConfig, app.clientCtx, mempoolConfig ) ``` -------------------------------- ### Retrieve EVM Configuration Source: https://github.com/cosmos/evm/blob/main/eips/README.md Illustrates how the EVM configuration is created within the EthereumTx method by querying x/evm parameters. ```go cfg, err := k.EVMConfig(ctx, sdk.ConsAddress(ctx.BlockHeader().ProposerAddress), k.eip155ChainID) ``` -------------------------------- ### Calling EVM from Precompile Contexts Source: https://github.com/cosmos/evm/blob/main/docs/migrations/v0.5.x_to_v0.6.0.md When calling EVM functions from within a precompile, reuse the existing stateDB and pass true for callFromPrecompile. This example demonstrates usage within a precompile's Run method. ```go // In your precompile's Run() method, you'll have access to stateDB func (p *MyPrecompile) Run( evm *vm.EVM, contract *vm.Contract, readOnly bool, ) ([]byte, error) { stateDB := evm.StateDB.(*statedb.StateDB) // Use the existing stateDB and set callFromPrecompile=true res, err := p.evmKeeper.CallEVM( ctx, stateDB, // reuse existing stateDB abi, from, contract, true, // commit (will flush to cache context) true, // callFromPrecompile nil, // gasCap "transfer", recipient, amount, ) } ``` -------------------------------- ### Solidity: WebAuthn Signature Verification with P256 Source: https://github.com/cosmos/evm/blob/main/precompiles/p256/README.md An example Solidity contract showing how to integrate WebAuthn signature verification using the P256 precompile. It maps user addresses to their public keys and verifies challenge signatures. ```solidity contract WebAuthnWallet { address constant P256_PRECOMPILE = 0x0000000000000000000000000000000000000100; struct PublicKey { bytes32 x; bytes32 y; } mapping(address => PublicKey) public userKeys; function verifyWebAuthnSignature( address user, bytes32 challenge, bytes32 r, bytes32 s ) public view returns (bool) { PublicKey memory pubKey = userKeys[user]; bytes memory input = abi.encodePacked( challenge, // WebAuthn challenge hash r, // Signature r s, // Signature s pubKey.x, // Public key x pubKey.y // Public key y ); (bool success, bytes memory result) = P256_PRECOMPILE.staticcall(input); return success && result.length == 32 && uint256(bytes32(result)) == 1; } } ```