Last active
May 5, 2024 11:59
-
-
Save elyase/339de6d8955361b0ad6522b905a278f2 to your computer and use it in GitHub Desktop.
Swap simulation with pyrevm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from eth_abi import decode, encode | |
from eth_utils import function_signature_to_4byte_selector | |
from pyrevm import EVM | |
# https://etherscan.io/tx/0x652bae3b1c11fbcf64309c2dfec5537b9bd1d3f2b521176f71ba1115a313ecbd" | |
# Swap 0.031485012992133186 ETH for 1,110.686711078457978839 CSWAP on Uniswap v2 | |
block_number = 19726294 | |
caller = "0xc0170e050355408e53800d093f3f13c3a53b29c8" | |
router = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D" | |
token = "0xae41b275aaAF484b541A5881a2dDED9515184CCA" | |
value = 31485012992133186 | |
tx_input = bytes.fromhex( | |
"b6f9de9500000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000080000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000ae41b275aaaf484b541a5881a2dded9515184cca" | |
) | |
def balance_of(erc20, address): | |
selector = function_signature_to_4byte_selector("balanceOf(address)") | |
encoded_address = encode(["address"], [address]) | |
calldata = selector + encoded_address | |
balance = evm.message_call( | |
caller=caller, | |
to=erc20, | |
calldata=calldata, | |
) | |
return decode(["uint256"], balance)[0] | |
fork_url = "https://eth.llamarpc.com" | |
evm = EVM( | |
fork_url=fork_url, | |
fork_block=str(block_number - 1), | |
) | |
amount_before = balance_of(token, caller) | |
print("Amount before:", amount_before) | |
# simulate swap | |
evm.set_balance(caller, value) | |
output = evm.message_call( | |
caller=caller, | |
to=router, | |
calldata=tx_input, | |
value=value, | |
) | |
amount_after = balance_of(token, caller) | |
print("Amount after :", amount_after) | |
amount = amount_after - amount_before | |
expected = 1055152375524535079898 | |
assert amount == expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment