=============== LIBRARY RULES =============== From library maintainers: - Use degenbot patterns for MEV bot development - Reference specific post numbers for implementation details - Follow AnvilFork testing patterns before mainnet deployment - Prioritize gas optimization for competitive MEV execution - Use event-driven state management with auto_update - Implement proper error handling and recovery mechanisms ### Project Setup and Configuration (Brownie) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md This section details the initial setup for the project, including defining contract addresses and configuring the Brownie environment. These global variables and objects are accessible throughout the project. ```python BROWNIE_NETWORK = "moralis-avax-main-websocket" BROWNIE_ACCOUNT = "degenbot" # Contract addresses SNOWSIGHT_CONTRACT_ADDRESS = "0xD9B1ee4AE46d4fe51Eeaf644107f53A37F93352f" CRA_CONTRACT_ADDRESS = "0xA32608e873F9DdEF944B24798db69d80Bbb4d1ed" WAVAX_CONTRACT_ADDRESS = "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7" TRADERJOE_LP_CRA_WAVAX_ADDRESS = "0x140cac5f0e05cbec857e65353839fddd0d8482c1" ``` -------------------------------- ### Python Virtual Environment Setup and Editable Install Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md Demonstrates setting up a Python virtual environment and performing an editable installation of the degenbot package from a local repository using pip. ```bash python3 -m venv .venv source .venv/bin/activate pip install -e ~/code/degenbot/ ``` -------------------------------- ### Python Configuration and Setup Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md Sets up environment variables, defines contract addresses, and initializes Brownie network connections and accounts. It also loads contract ABIs from the explorer. ```python SNOWTRACE_API_KEY = "[redacted]" ROUTERS = { "0x60aE616a2155Ee3d9A68541Ba4544862310933d4".lower(): { "name": "TraderJoe", "abi": [], }, } os.environ["SNOWTRACE_TOKEN"] = SNOWTRACE_API_KEY try: network.connect(BROWNIE_NETWORK) except: sys.exit( "Could not connect! Verify your Brownie network settings using 'brownie networks list'" ) try: degenbot = accounts.load(BROWNIE_ACCOUNT) except: sys.exit( "Could not load account! Verify your Brownie account settings using 'brownie accounts list'" ) print("\nContracts loaded:") cra = Erc20Token(address=CRA_CONTRACT_ADDRESS) wavax = Erc20Token(address=WAVAX_CONTRACT_ADDRESS) for address in ROUTERS.keys(): ROUTERS[address]["abi"] = brownie.Contract.from_explorer(address).abi traderjoe_lp_cra_wavax = LiquidityPool( address=TRADERJOE_LP_CRA_WAVAX_ADDRESS, name="TraderJoe", tokens=[cra, wavax], ) lps = [ traderjoe_lp_cra_wavax, ] asyncio.run(main()) ``` -------------------------------- ### Ape Framework Setup and Basic Operations Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/056_start-here.md Covers the setup of Ape Framework, a modern alternative to Brownie, and provides examples of generating/importing accounts, connecting to networks, sending transactions, creating forks, and debugging. ```bash # Install Ape Framework and necessary plugins pip install "ape[ganache,web3,eth]" ``` ```python from ape import accounts, networks # Connect to a network (e.g., Sepolia testnet) networks.ethereum.sepolia.connect() # Generate a new account (or use an existing one from accounts.load()) account = accounts.generate_account() print(f"New account: {account.address}") # Send a transaction (example: sending ETH) # recipient = '0x...' # Replace with a recipient address # tx = account.transfer(recipient, '0.1 ether') # tx.wait_to_be_ Mined() ``` -------------------------------- ### Install Python Packages with Pip Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md Installs or upgrades specified Python packages within the active virtual environment. This example installs 'eth-brownie', 'scipy', and 'requests', and then upgrades 'websockets'. ```bash pip install eth-brownie scipy requests pip install --upgrade websockets ``` -------------------------------- ### Installing Development Packages with apt Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md Installs Python development headers and the pip package installer using the apt package manager. These are necessary for many Python development tasks. ```bash apt install python3-dev apt install python3-pip ``` -------------------------------- ### Reth Container Log Output Example Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/120_running-a-reth-archive-node.md An example of the log output from a Reth container, showing the version, commit hash, configuration loading, database opening, and pre-merge hard fork information. This helps in verifying the node's status and version. ```log 2023-10-21T18:10:57.552028Z INFO reth::cli: reth 0.1.0-alpha.10 (3a8fe5a7) starting 2023-10-21T18:10:57.552271Z INFO reth::cli: Configuration loaded path="/data/reth.toml" 2023-10-21T18:10:57.552284Z INFO reth::cli: Opening database path="/data/db" 2023-10-21T18:10:57.555982Z INFO reth::cli: Database opened 2023-10-21T18:10:57.557220Z INFO reth::cli: Pre-merge hard forks (block based): - Frontier @0 - Homestead @1150000 - Dao @1920000 - Tangerine @2463000 ``` -------------------------------- ### Setup Development Environment with Linux, Python, and Brownie Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/056_start-here.md This section covers the initial setup of a development environment, including installing Linux, Python, and the Brownie framework. Brownie is a Python-based development and testing framework for smart contracts. ```bash # Example commands for setting up the environment sudo apt update sudo apt install python3 python3-pip pip install --upgrade pip pip install eth-brownie ``` -------------------------------- ### Pip Install Output - Editable Install Process Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md Shows the output from pip during an editable installation, including dependency resolution and package metadata preparation for degenbot. ```text Obtaining file:///home/btd/code/degenbot Installing build dependencies ... done Checking if build backend supports build_editable ... done Getting requirements to build editable ... done Installing backend dependencies ... done Preparing editable metadata (pyproject.toml) ... done Collecting eth-abi<5,>=4.2.0 Downloading eth_abi-4.2.1-py3-none-any.whl (28 kB) Collecting eth-typing<4,>=3.4.0 Downloading eth_typing-3.5.1-py3-none-any.whl (14 kB) [...] Collecting urllib3<3,>=1.21.1 Downloading urllib3-2.0.7-py3-none-any.whl (124 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 124.2/124.2 kB 54.9 MB/s eta 0:00:00 Collecting certifi>=2017.4.17 Downloading certifi-2023.7.22-py3-none-any.whl (158 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 158.3/158.3 kB 82.0 MB/s eta 0:00:00 Installing collected packages: lru-dict, bitarray, websockets, urllib3, ujson, typing-extensions, toolz, rpds-py, regex, pyunormalize, pycryptodome, protobuf, pluggy, packaging, numpy, multidict, iniconfig, idna, hexbytes, frozenlist, eth-hash, charset-normalizer, certifi, attrs, async-timeout, yarl, scipy, requests, referencing, pytest, parsimonious, eth-typing, cytoolz, aiosignal, jsonschema-specifications, eth-utils, aiohttp, rlp, jsonschema, eth-keys, eth-abi, eth-rlp, eth-keyfile, eth-account, web3, degenbot DEPRECATION: pyunormalize is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559 Running setup.py install for pyunormalize ... done DEPRECATION: parsimonious is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559 Running setup.py install for parsimonious ... done ``` -------------------------------- ### Install Websockets Package Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/038_asynchronous-websocket-listeners.md This command installs the 'websockets' Python package, which is necessary for establishing WebSocket connections. It's a prerequisite for the subsequent code examples. ```bash (.venv) devil@hades:~/bots$ pip install websockets ``` -------------------------------- ### Load Base Staking Rate (Python) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md Attempts to load the base staking rate from a file named `STAKING_RATE_FILENAME`. If the file is not found, the script exits with an error message guiding the user to run a setup script. ```python try: with open(STAKING_RATE_FILENAME, "r") as file: base_staking_rate = float(file.read().strip()) print(f"\nEthereum L1 Staking Rate: {base_staking_rate}") except FileNotFoundError: sys.exit( "Cannot load the base Abracadabra SPELL/sSPELL staking rate. Run `python3 abra_rate.py` and try again." ) ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md These commands create a new directory for bot scripts, navigate into it, create a Python virtual environment named '.venv', and then activate it. Activating the environment ensures that subsequent Python package installations are isolated to this project. ```bash mkdir bots cd bots python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Build Silverback Bot Container Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/177_silverback-part-i-introduction-setup-local-testing-cloud-dep.md Builds a Docker image for a Silverback bot. This process involves using a Dockerfile, copying necessary files (like `ape-config.yaml` and `block_watcher.py`), and installing Ape plugins. The output includes the image tag. ```shell (silverback_bots) btd@dev:~/code/silverback_bots$ silverback build STEP 1/8: FROM ghcr.io/apeworx/silverback:stable STEP 2/8: USER root --> Using cache 9f686772e7813183b7c9493e4887606503fd45daf49f77e2fcb4c1b4cb4b647e --> 9f686772e781 STEP 3/8: WORKDIR /app --> Using cache e04650456a1e3ceb1d354373453cf6ee651983bc22606b3a71e506224983e899 --> e04650456a1e STEP 4/8: RUN chown harambe:harambe /app --> Using cache 08a721aa01a589f0ef9e151fc5e150334d7dc85b14eedf849ecb09b3461045fb --> 08a721aa01a5 STEP 5/8: USER harambe --> Using cache 9f624e10de0c8beb9379b242734585e9fe8e61bafd241a99fb2c6ec1f9127f69 --> 9f624e10de0c STEP 6/8: COPY ape-config.yaml /app --> Using cache 6ed97d42a6a3dd4993b0f5a2109a160822146853a9817a33aff2e6223ad926cd --> 6ed97d42a6a3 STEP 7/8: RUN ape plugins install -U . --> Using cache c998bc4770537999c67dc0d48b007c342d7e58bc9ca3ab54deb65804bca741a2 --> c998bc477053 STEP 8/8: COPY block_watcher.py /app/bot.py --> Using cache 52e96a28d7ad1cec355659ed42bd67462e61b9afb72ca772cb6aacf3facd6869 --> 52e96a28d7ad 52e96a28d7ad1cec355659ed42bd67462e61b9afb72ca772cb6aacf3facd6869 This will create a Dockerfile in the .silverback-images folder and build an image with the shown tag on the last line. Here mine is 52e96a28d7ad, yours may differ. ``` -------------------------------- ### Price Watcher Setup with Degenbot and Web3 (Python) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/131_conditional-actions-part-i-proof-of-concept.md Initializes the Degenbot library and sets up a Web3 connection for a price watcher example. It specifies the provider URL for the local Ethereum node and imports necessary modules like functools, time, degenbot, and web3. ```python import functools import time import degenbot import web3 from degenbot.actions.conditional_action import ConditionalAction degenbot.set_web3(web3.Web3(web3.HTTPProvider("http://localhost:8545"))) ``` -------------------------------- ### Installing a specific version of Degenbot Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md This command installs a specific version of the degenbot library from PyPI, allowing users to match the version used in historical examples. ```bash pip install degenbot==0.0.1 ``` -------------------------------- ### Install Ape Framework and Recommended Plugins Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Installs the Ape Framework along with a set of recommended plugins using pip. Ensures you have the necessary Python development packages installed if build issues arise. ```bash pip install eth-ape'[recommended-plugins]' ``` -------------------------------- ### Initialize Ape Project Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Command to initialize a new Ape project, creating standard directories and configuration. ```bash ape init ``` -------------------------------- ### Installing Degenbot from PyPI Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md This command installs the degenbot library from the Python Package Index (PyPI). It automatically handles dependencies. ```bash pip install degenbot ``` -------------------------------- ### Install Fantom Ape Plugin Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Command to install the Fantom ecosystem plugin for Ape. ```bash ape plugins install fantom ``` -------------------------------- ### Create Virtual Environment with uv Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/177_silverback-part-i-introduction-setup-local-testing-cloud-dep.md This command sequence demonstrates how to create a new directory for Silverback bots and then create a Python virtual environment within that directory using the 'uv' tool. This isolates project dependencies. ```shell mkdir ~/code/silverback_bots cd ~/code/silverback_bots/ uv venv ``` -------------------------------- ### Get Hex Signature of Signed Message Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md Retrieves the hexadecimal representation of a signature from a signed message object. This is used for EIP-191 compatible signed messages. ```python signed_msg.signature.hex() ``` -------------------------------- ### List Available Ape Network Providers Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Displays the default and available network configurations for Ape, including ecosystems, networks, and their associated provider plugins. ```bash (.venv) [btd@main ape_sandbox]$ ape networks list ``` -------------------------------- ### Brownie Console Setup and Testing (Shell) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/uniswap/v3/080_uniswap-v3-lp-helper-part-ii.md Demonstrates setting up a local fork of the Ethereum mainnet using Brownie and interacting with Uniswap V3 contracts. It shows how to instantiate liquidity pools and the Quoter contract, and perform swap calculations. ```shell (.venv) [devil@dev bots]$ brownie console --network mainnet-fork Brownie v1.19.2 - Python development framework for Ethereum BotsProject is the active project. Launching 'ganache-cli --chain.vmErrorsOnRPCResponse true --wallet.totalAccounts 10 --hardfork istanbul --fork.url https://rpc.ankr.com/eth --miner.blockGasLimit 12000000 --wallet.mnemonic brownie --server.port 6969 --chain.chainId 1'... Brownie environment is ready. >>> import degenbot as bot >>> lp = bot.uniswap.v3.V3LiquidityPool( '0xCBCdF9626bC03E24f779434178A73a0B4bad62eD' ) >>> quoter = Contract.from_explorer( '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6' ) Fetching source of 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6 from api.etherscan.io... >>> weth = Contract.from_explorer('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2') Fetching source of 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 from api.etherscan.io... >>> wbtc = Contract.from_explorer('0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599') Fetching source of 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 from api.etherscan.io... >>> quoter.quoteExactInputSingle.call( weth.address, wbtc.address, 3000, 10*10**18, 0 ) 71105812 >>> lp.calculate_tokens_out_from_tokens_in(weth,10*10**18) 71105812 Testing the same swap in the opposite direction: >>> lp.calculate_tokens_out_from_tokens_in(wbtc.address,71105812) 9939825250263624635 >>> quoter.quoteExactInputSingle.call( wbtc.address, weth.address, 3000, 71105812, 0 ) 9939825250263624635 ``` -------------------------------- ### Install Python 3 Virtual Environment Package Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md Installs the 'python3-venv' package, which is necessary for creating isolated Python environments. This ensures project dependencies do not conflict. ```bash sudo apt install python3-venv ``` -------------------------------- ### Reth Client Initialization and Hard Forks Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/120_running-a-reth-archive-node.md This section shows the initialization logs for the Reth Ethereum client. It includes the client version, configuration loading, database opening, and a comprehensive list of pre-merge and post-merge hard forks with their corresponding block numbers or timestamps. ```log reth | 2023-10-21T17:55:46.260587Z INFO reth::cli: reth 0.1.0-alpha.10 (1b16d80) starting reth | 2023-10-21T17:55:46.260766Z INFO reth::cli: Configuration loaded path="/data/reth.toml" reth | 2023-10-21T17:55:46.260778Z INFO reth::cli: Opening database path="/data/db" reth | 2023-10-21T17:55:46.270082Z INFO reth::cli: Database opened reth | 2023-10-21T17:55:46.270158Z INFO reth::cli: Pre-merge hard forks (block based): reth | - Frontier @0 reth | - Homestead @1150000 reth | - Dao @1920000 reth | - Tangerine @2463000 reth | - SpuriousDragon @2675000 reth | - Byzantium @4370000 reth | - Constantinople @7280000 reth | - Petersburg @7280000 reth | - Istanbul @9069000 reth | - MuirGlacier @9200000 reth | - Berlin @12244000 reth | - London @12965000 reth | - ArrowGlacier @13773000 reth | - GrayGlacier @15050000 reth | Merge hard forks: reth | - Paris @58750000000000000000000 (network is not known to be merged) reth | reth | Post-merge hard forks (timestamp based): reth | - Shanghai @1681338455 ``` -------------------------------- ### Importing Degenbot in Python Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md This Python code snippet demonstrates how to import the degenbot library within a Python interactive shell or script, confirming a successful installation. ```python >>> import degenbot >>> ``` -------------------------------- ### Start Brownie Console and Load Account Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/004_loading-a-token-smart-contract.md This snippet shows the initial steps to set up a Brownie environment. It involves navigating to the project directory, activating a virtual environment, and starting the Brownie console connected to the Avalanche mainnet. It then demonstrates loading a pre-configured user account. ```bash devil@hades:~$ cd brownie_test/ devil@hades:~/brownie_test$ source .venv/bin/activate (.venv) devil@hades:~/brownie_test$ brownie console --network avax-main Brownie v1.17.2 - Python development framework for Ethereum No project was loaded. Brownie environment is ready. >>> user = accounts.load('test_account') Enter password for "test_account": ``` -------------------------------- ### Install Flashbots Python Module Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/transaction/058_flashbots-setup-and-identity.md Installs the official Flashbots Python library using pip. This library is essential for interacting with the Flashbots network, submitting bundles, and managing identity. ```bash (.venv) devil@hades:~/bots$ pip install flashbots [...] Installing collected packages: flashbots Successfully installed flashbots-1.0.1.post1 ``` -------------------------------- ### Launch Ape Console with Ethereum Mainnet Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Command to launch the Ape console connected to the Ethereum mainnet using a Geth provider. ```bash ape console --network ethereum:mainnet:geth ``` -------------------------------- ### Ape Configuration Example (ape-config.yaml) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Demonstrates a basic Ape configuration file specifying the default ecosystem and provider for Ethereum mainnet. ```yaml default_ecosystem: ethereum hereum: mainnet: default_provider: geth geth: ethereum: mainnet: uri: https://rpc.ankr.com/eth ``` -------------------------------- ### Push Docker Image Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/177_silverback-part-i-introduction-setup-local-testing-cloud-dep.md This command pushes a Docker image to a registry, preparing it for deployment. Replace '[user]/[repo_name]' with your actual Docker Hub username and repository name. ```bash docker push [user]/[repo_name]/bot:latest ``` -------------------------------- ### Example JWT Key for Reth and Nimbus Authentication Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/120_running-a-reth-archive-node.md This is an example of a 32-byte hexadecimal key used for authenticating between the Reth client and the Nimbus beacon chain client. This key should be generated securely and stored in a file (e.g., jwt.hex) to be mounted into the Docker containers. ```text d38d658d68167fc066eb82dd3dc3a65b38264108302dabab74c761d10a4b59b0 ``` -------------------------------- ### Login to Silverback Service Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/177_silverback-part-i-introduction-setup-local-testing-cloud-dep.md Authenticates the local client with the Silverback cloud service. It prompts the user to complete authentication in their browser and obtains an access token. ```shell btd@dev:~$ silverback login ⠸ Please complete authentication in your browser.Opening in existing browser session. Successfully authenticated Getting a token... INFO: Logged in to 'https://account.apeworx.io' as 'bowtieddevil' ``` -------------------------------- ### Get Current Chain Height Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/transaction/046_mempool-backrunning.md Retrieves the height of the current blockchain, providing the latest block number. This is often used as a starting point for data fetching or synchronization. ```python newest_block = brownie.chain.height ``` -------------------------------- ### Synchronous Payment Function Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md A synchronous function that interacts with the Snowsight contract to calculate and submit payments. It retrieves payment data, calculates the amount, and sends a transaction. ```python def pay_sync(): """ A synchronous function that retrieves data from the Snowsight contract, calculates the maximum payment, and submits a payment to the Chainsight contract. """ snowsight_contract = brownie.Contract.from_explorer(SNOWSIGHT_CONTRACT_ADDRESS) block_payment = snowsight_contract.paymentPerBlock() * ( brownie.chain.height + snowsight_contract.maximumPaymentBlocks() - snowsight_contract.payments(degenbot.address)[-1] ) snowsight_contract.pay( { "from": degenbot, "value": min( block_payment, snowsight_contract.calculateMaxPayment(), ), "priority_fee": 0, } ) ``` -------------------------------- ### Updating Ubuntu Packages Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md Checks for and installs available package updates on Ubuntu systems using the apt package manager. Ensure you have an internet connection for this operation. ```bash sudo apt update sudo apt upgrade ``` -------------------------------- ### Install Degenbot Helper Locally Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/curve/124_curve-stableswap-liquidity-pool-part-i-introduction.md This command sequence outlines how to install the Degenbot helper library locally in a virtual environment. It involves creating a virtual environment, activating it, and then performing an editable install of the library from a local path. ```bash btd@main:~$ pyenv virtualenv degenbot_local btd@main:~$ pyenv activate degenbot_local (degenbot_local) btd@main:~$ pip install -e ~/code/degenbot (degenbot_local) btd@main:~$ cd ~/code/degenbot (degenbot_local) btd@main:~/code/degenbot$ git checkout curve Switched to branch 'curve' Your branch is up to date with 'origin/curve'. ``` -------------------------------- ### Get Swap Rate with Walrus Operator Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md Demonstrates the use of the Python 'Walrus Operator' (:=) to assign the result of `get_swap_rate` to a variable and immediately use it in an if condition. ```python if result := get_swap_rate( token_in_quantity=spell["balance"], token_in_address=spell["address"], token_out_address=sspell["address"], router=router_contract, ): print("Swap successful!") else: print("Swap failed.") ``` -------------------------------- ### Create Silverback Workspace Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/177_silverback-part-i-introduction-setup-local-testing-cloud-dep.md Creates a new workspace within Silverback, which manages permissions for users and clusters. Requires a name and a slug for the workspace. ```shell btd@dev:~$ silverback cluster workspaces new --name "Test Workspace" --slug "test-workspace" INFO: Logged in to 'https://silverback.apeworx.io' as 'bowtieddevil' SUCCESS: Created 'Test Workspace' (slug: 'test-workspace') ``` -------------------------------- ### Async Main Function Execution Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md Defines the main asynchronous function that orchestrates the execution of other asynchronous tasks, such as watching for pending transactions. It uses asyncio.gather to run tasks concurrently. ```python async def main(): await asyncio.gather( asyncio.create_task(watch_pending_transactions()), ) ``` -------------------------------- ### Initializing Caching for a Network Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Demonstrates the command-line interface (CLI) command to initialize a caching database for a specific network. Caching speeds up historical data retrieval. ```bash ape cache init --network ethereum:mainnet ``` -------------------------------- ### Get Token Decimals Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md This function retrieves the number of decimal places for a token. It calls the token's decimals method and includes error handling for potential exceptions. ```Python def get_token_decimals(token): try: return token.decimals.call() ``` -------------------------------- ### Install Degenbot Helper from Github Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/curve/124_curve-stableswap-liquidity-pool-part-i-introduction.md Provides instructions for installing the Degenbot helper library directly from a GitHub repository using pip. This method installs a specific branch ('curve') of the library into a new virtual environment. ```bash btd@main:~$ pyenv virtualenv degenbot_remote btd@main:~$ pyenv activate degenbot_remote (degenbot_remote) btd@main:~$ pip install git+https://github.com/bowtieddevil/degenbot.git@curve ``` -------------------------------- ### Get Token Symbol Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md This function retrieves the symbol of a token. It calls the token's symbol method and includes exception handling, re-raising any errors that occur during the process. ```Python def get_token_symbol(token): try: return token.symbol.call() except Exception as e: print(f"Exception in get_token_symbol: {e}") raise ``` -------------------------------- ### List Available Ape Networks Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Command to list all networks recognized by the installed Ape plugins. ```bash ape networks list ``` -------------------------------- ### Create SSH Directory and Authorized Keys File Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/utils/045_setting-up-a-dedicated-bot-vps.md Creates the '.ssh' directory if it doesn't exist and then opens the 'authorized_keys' file in the 'nano' text editor for pasting the public SSH key. The instructions indicate saving with CTRL+k. ```bash mkdir .ssh nano .ssh/authorized_keys ``` -------------------------------- ### Brownie Account Loading and Message Signing Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/041_snowsight-getting-started.md Demonstrates how to load a Brownie account and use its `sign_defunct_message` method to create a hexadecimal signature for authenticating with the Snowsight service. This is a key step for wallet authentication. ```python import brownie degebot = brownie.accounts.load('degenbot') signed_msg = degenbot.sign_defunct_message("Sign this message to authenticate your wallet with Snowsight.") ``` -------------------------------- ### Launching a Python shell Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/121_degenbot-pypi-release.md This command launches the Python 3 interpreter, indicated by the 'python3' command. The output shows the Python version and build details, along with a prompt for interactive use. ```bash (.venv) [btd@main bots]$ python3 Python 3.10.13 (main, Sep 2 2023, 00:54:40) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Python Flashbots Setup and Web3 Connection Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/transaction/058_flashbots-setup-and-identity.md Demonstrates the initial setup for using the Flashbots module with Python. It includes importing necessary libraries like web3.py and brownie, loading an identity account, and establishing a connection to a local Ethereum node. ```python from flashbots import flashbot from brownie import * from web3 import Web3,HTTPProvider from eth_account import Account ``` ```python id_account = accounts.load('flashbots_id') # Enter password for "flashbots_id": # [Type password, press enter. Console will not show output] ``` ```python w3 = Web3(HTTPProvider()) print(w3.isConnected()) ``` ```python signer = Account.from_key(id_account.private_key) flashbots_relay = flashbot(w3, signer) ``` ```python print(w3.flashbots.sendBundle) ``` -------------------------------- ### Arbitrage Processing Worker Setup (Python) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/uniswap/v4/171_project-uniswap-v4v2-two-pool-arbitrage-bot.md Sets up the arbitrage processing worker, including defining transaction details for balance checks and initializing a contract object. It logs the worker's start. ```python async def arb_processing_worker( async_w3: web3.AsyncWeb3, processing_queue: asyncio.Queue[ _UniswapTwoPoolCycleTesting ], completed_queue: asyncio.Queue[ tuple[ ArbitrageCalculationResult, dict, ] ], executor: ProcessPoolExecutor, all_arbs: dict[str, _UniswapTwoPoolCycleTesting], ): """ Takes pending arbitrage helpers from the queue, processes them using the process pool executor, and adds the results to the submission queue. """ v4_v2_weth_balance_check_transaction = { "to": WETH_ADDRESS, "data": web3.Web3.keccak( text="balanceOf(address)" )[:4] + eth_abi.abi.encode( types=["address"], args=[V4_V2_EXECUTOR_CONTRACT_ADDRESS], ), } v4_v2_executor_contract = async_w3.eth.contract( address=V4_V2_EXECUTOR_CONTRACT_ADDRESS, abi=V4_V2_EXECUTOR_CONTRACT_ABI, ) bot_logger.info("Starting processing worker") ``` -------------------------------- ### Install Foundry Toolkit with foundryup Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/anvil/114_local-bundle-simulation-with-anvil.md Installs the Foundry toolkit, including Anvil, Forge, Cast, and Chisel, using the foundryup command-line tool. This process downloads the latest versions and adds them to the system's PATH. ```bash curl -L https://foundry.paradigm.xyz | bash foundryup ``` -------------------------------- ### Recreate V3LiquidityPool with Tick Data (Python) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/database/100_pickling-for-faster-startup.md Demonstrates recreating a V3LiquidityPool helper by providing pre-fetched tick_data and tick_bitmap dictionaries. This is useful for initializing the helper with existing state, saving time on subsequent data fetches. ```Python >>> _tick_bitmap = lp.tick_bitmap >>> _tick_data = lp.tick_data >>> del lp >>> lp = bot.V3LiquidityPool('0xCBCdF9626bC03E24f779434178A73a0B4bad 62eD', tick_data=_tick_data, tick_bitmap=_tick_bitmap) ``` -------------------------------- ### Control Loop Timing with Start and End Times Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md Manages the execution interval of the main loop by calculating the duration of each iteration and sleeping if necessary to maintain a consistent loop time. ```python loop_end = time.time() # Control the loop timing more precisely by measuring start and end time and sleeping as needed if (loop_end - loop_start) >= LOOP_TIME: continue else: time.sleep(LOOP_TIME - (loop_end - loop_start)) continue ``` -------------------------------- ### Get Token Balance Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/misc/014_bot-building-setup-main-loop-and-swapping-logic.md This function retrieves the balance of a token for a given user. In a dry run, it returns a predefined fake balance. It includes error handling for the balance retrieval process. ```Python def get_token_balance(token, user): if DRY_RUN: # return a fake balance for testing return 10000 * 10**18 try: return token.balanceOf.call(user) except Exception as e: print(f"Exception in get_token_balance: {e}") raise ``` -------------------------------- ### Initialize WETH9 Contract and Query Balance (Python) Source: https://github.com/jimbo073/xkz9-nnntd47429ry/blob/main/core/119_introduction-to-ape-framework.md Demonstrates initializing the WETH9 contract using its address and ABI, then querying the balance of a specific address. Requires the 'ape' library and a connection to the Ethereum mainnet. ```python from ape import Contract weth = Contract( address='0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', abi=''' [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Withdrawal","type":"event"}] ''' ) weth.balanceOf('0xCBCdF9626bC03E24f779434178A73a0B4bad62eD') ```