Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Move contracts/arbiter to arbmod repository + Minor fixes #368

Merged
merged 23 commits into from
Jun 26, 2023
Merged

Conversation

kinrezC
Copy link
Contributor

@kinrezC kinrezC commented Jun 20, 2023

  • Fix broken sed to rewrite codehash in v2-periphery
  • Since the git submodules are there we don't need to forge install each submodule independently

@kinrezC kinrezC added the 🚧 WIP 🚧 DO NOT MERGE THIS PR label Jun 20, 2023
@Autoparallel
Copy link
Collaborator

  • Fix broken sed to rewrite codehash in v2-periphery
  • Since the git submodules are there we don't need to forge install each submodule independently

Note: Do not merge until I fix the (likely) broken paths for the arbmod bindings + we aren't sure about how moving the contracts to arbmod will impact devx

@kinrezC I had issues when I did not install the submodules independently (especially with V3). When you give this a final check, make sure to do it in a fresh clone of the repo. This has given me nothing but grief.

@kinrezC kinrezC removed the 🚧 WIP 🚧 DO NOT MERGE THIS PR label Jun 23, 2023
@kinrezC
Copy link
Contributor Author

kinrezC commented Jun 23, 2023

  • Fix broken sed to rewrite codehash in v2-periphery
  • Since the git submodules are there we don't need to forge install each submodule independently

Note: Do not merge until I fix the (likely) broken paths for the arbmod bindings + we aren't sure about how moving the contracts to arbmod will impact devx

@kinrezC I had issues when I did not install the submodules independently (especially with V3). When you give this a final check, make sure to do it in a fresh clone of the repo. This has given me nothing but grief.

sure i'll try now

edit: works for me @Autoparallel

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see we switch from the arbiter contracts to using the arbmod submodule, is that directory up to date? We have all the same contracts in both

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah i updated it

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we missing a mod.rs for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should address this in a different PR

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wont compile without it, or let us see the compile errors that should be resolved with the PR colin and I had from main

Copy link
Collaborator

@0xJepsen 0xJepsen Jun 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should just use the one we had here

use std::error::Error;

use ethers::types::U256;
use eyre::Result;
use ruint::Uint;
use simulate::{
    agent::{simple_arbitrageur::NextTx, Agent, AgentType},
    environment::contract::{IsDeployed, SimulationContract},
    manager::SimulationManager,
    stochastic::price_process::{PriceProcess, PriceProcessType, OU},
    utils::unpack_execution,
};

use crate::simulate::portfolio::arbitrage::compute_arb_size;

pub mod arbitrage;
pub mod startup;

#[derive(Clone)]
pub struct PoolParams {
    priority_fee: u16,
    fee: u16,
    volatility: u16,
    duration: u16,
    strike: u128,
    price: u128,
}

impl PoolParams {
    pub fn new(
        priority_fee: u16,
        fee: u16,
        volatility: u16,
        duration: u16,
        strike: u128,
        price: u128,
    ) -> Self {
        Self {
            priority_fee,
            fee,
            volatility,
            duration,
            strike,
            price,
        }
    }
}

/// Run a simulation.
pub fn run() -> Result<(), Box<dyn Error>> {
    // Create a `SimulationManager` that runs simulations in their `SimulationEnvironment`.
    let mut manager = SimulationManager::new();
    // Define the pool arguments
    let pool_args = PoolParams::new(
        100_u16,
        100_u16,
        100_u16,
        65535_u16,
        10_000_000_000_000_000_000u128,
        10_000_000_000_000_000_000u128,
    );
    // Define liquidity arguments
    let delta_liquidity = 10_i128.pow(19);
    // Run the startup script
    let (contracts, _pool_data, pool_id) =
        startup::run(&mut manager, pool_args.clone(), delta_liquidity)?;

    // Start the arbitrageur
    let arbitrageur = manager.agents.get("arbitrageur").unwrap();

    // Intialize the arbitrageur with the prices from the two exchanges.
    let arbitrageur = match arbitrageur {
        AgentType::SimpleArbitrageur(base_arbitrageur) => base_arbitrageur,
        _ => panic!(),
    };
    let liquid_exchange_xy_price = arbitrageur.call_contract(
        &mut manager.environment,
        &contracts.liquid_exchange_xy,
        contracts.liquid_exchange_xy.encode_function("price", ())?,
        Uint::ZERO,
    );
    let liquid_exchange_xy_price = unpack_execution(liquid_exchange_xy_price)?;
    let liquid_exchange_xy_price: U256 = contracts
        .liquid_exchange_xy
        .decode_output("price", liquid_exchange_xy_price)?;
    let portfolio_price = arbitrageur.call_contract(
        &mut manager.environment,
        &contracts.portfolio,
        contracts
            .portfolio
            .encode_function("getSpotPrice", pool_id)?,
        Uint::ZERO,
    );
    let portfolio_price = unpack_execution(portfolio_price)?;
    let portfolio_price: U256 = contracts
        .liquid_exchange_xy
        .decode_output("price", portfolio_price)?;
    let mut prices = arbitrageur.prices.lock().unwrap();
    prices[0] = liquid_exchange_xy_price.into();
    prices[1] = portfolio_price.into();
    drop(prices);

    println!("Initial prices for Arbitrageur: {:#?}", arbitrageur.prices);

    let (handle, rx) = arbitrageur.detect_arbitrage();

    // Get prices
    let ou = OU::new(0.001, 50.0, 1.0);
    let price_process = PriceProcess::new(
        PriceProcessType::OU(ou),
        0.01,
        "trade".to_string(),
        5,
        1.0,
        1,
    );
    let prices = price_process.generate_price_path().1;
    // Run the simulation
    // Update the first price
    let liquid_exchange = &contracts.liquid_exchange_xy;
    let price = prices[0];
    update_price(&mut manager, liquid_exchange, price)?;
    let mut index: usize = 1;
    while let Ok((next_tx, _sell_asset)) = rx.recv() {
        // TODO: We need to be careful with these `sell_asset` variables.
        println!("Entered Main's `while let` with index: {}", index);
        if index >= prices.len() {
            println!("Reached end of price path\n");
            manager.shut_down();
            break;
        }
        let price = prices[index];
        assert!(price > 0.0);
        let ratio = U256::from((price * 1_000_000_000_000_000_000.0_f64).round() as i128);
        let arb_amount = compute_arb_size(
            &mut manager,
            pool_args.clone(),
            delta_liquidity,
            pool_id,
            &contracts.portfolio,
            ratio,
        )?;
        let input = arb_amount.input.as_u128();
        let sell_asset = arb_amount.sell_asset;
        match next_tx {
            NextTx::Swap => {
                arbitrage::swap(
                    &mut manager,
                    &contracts.portfolio,
                    pool_id,
                    input,
                    sell_asset,
                )?;
                // TODO: Update the price of the Portfolio pool.
                update_price(&mut manager, liquid_exchange, price)?;
                index += 1;
                continue;
            }
            NextTx::UpdatePrice => {
                update_price(&mut manager, liquid_exchange, price)?;
                index += 1;
                continue;
            }
            NextTx::None => {
                println!("Can't update prices\n");
                continue;
            }
        }
    }

    handle.join().unwrap();

    println!("=======================================");
    println!("🎉 Simulation Completed 🎉");
    println!("=======================================");

    Ok(())
}

/// Update prices on the liquid exchange.
fn update_price(
    manager: &mut SimulationManager,
    liquid_exchange: &SimulationContract<IsDeployed>,
    price: f64,
) -> Result<(), Box<dyn Error>> {
    let admin = manager.agents.get("admin").unwrap();
    println!("Updating price...");
    println!("Price from price path: {}\n", price);
    let wad_price = simulate::utils::float_to_wad(price);
    // println!("WAD price: {}", wad_price);
    let call_data = liquid_exchange.encode_function("setPrice", wad_price)?;
    admin.call_contract(
        &mut manager.environment,
        liquid_exchange,
        call_data,
        Uint::from(0),
    );

    Ok(())
}`

@0xJepsen
Copy link
Collaborator

Some tests are failing too.

@kinrezC
Copy link
Contributor Author

kinrezC commented Jun 26, 2023

might've cracked it... just waiting to see if tests pass!

@0xJepsen 0xJepsen self-requested a review June 26, 2023 15:44
Copy link
Collaborator

@0xJepsen 0xJepsen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm

@0xJepsen 0xJepsen merged commit 6bf442c into main Jun 26, 2023
@Autoparallel Autoparallel deleted the matt/cleanup branch August 10, 2023 12:47
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants