2

I have written code in Rust to do Uniswap V2 swap via the ethers-rs library. This code is not part of a contract but rather a standalone application.

I understand it's possible to test this locally. Can anyone guide me on how to:

  1. Start and connect to a local Foundry(i.e. Anvil)/Hardhat node that is a fork of the live network that I want to simulat the transaction against?
  2. Simulate the transaction against the local node impersonating a specified account/address?
4
  • Everything you asked is very well explained in either foundry or hardhat documentation. And if you use the search bar there are also many answers to that on stack overflow.
    – Torof
    Aug 22, 2023 at 8:11
  • Believe that before asking here i've searched in lot place but did not found the answer for it. I'm still blocked on this since yesterday... I've found answer for Solidity contract test but not code test Aug 22, 2023 at 8:13
  • In ethers.js there is a static call functionality to simulate a transaction using the eth_call json rpc method, ethers-rs seems to have this functionality as well: contract.function().call().await?; as shown here with the get_reserves() call gakonst.com/ethers-rs/providers/http.html#basic-usage Alternatively you can start up a local hardhat/foundry node with network forking enabled, however static calls would probably be better for your use case.
    – MShakeG
    Aug 22, 2023 at 10:52
  • Also, can you provide some of your actual code?
    – MShakeG
    Aug 22, 2023 at 11:22

1 Answer 1

1

I think what you are looking for is creating a local fork of mainnet or testnet. I would personally recommend using foundry for this, but other tools are capable of forking too. Foundry ships with a command called anvil that creates a local node. It forks EVM-compatible networks (more here)

  1. Run anvil and specify an RPC endpoint. It fetches blockchain state over instead of starting from an empty state. anvil --fork-url https://ethereum.publicnode.com
  2. Copy and use the local RPC endpoint in your script that is presented once Anvil is running. It's usually listening on 127.0.0.1:8545.
  3. Test your script, ensuring it's pointed to the right RPC and uses the correct account.

All changes you make on this endpoint are local to you. You can use the same contract address and accounts if you'd like. However, I do recommend using one of the generated accounts that was presented to you by anvil. This is to avoid scenarios of running the script on the mainnet by mistake. It's just a good practice to have different RPC endpoints and accounts for testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.