Skip to content

Commit

Permalink
wip: behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
0xJepsen committed Apr 10, 2024
1 parent 9675e36 commit 764761f
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 89 deletions.
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 80 additions & 6 deletions kit/src/behaviors/creator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use super::*;
use crate::pool::{Pool, PoolType};
use crate::{behaviors::deployer::DeploymentData, pool::{constant_sum::ConstantSumPool, Pool, PoolType}};
use arbiter_engine::machine::{Behavior, Configuration, Processing, Processor, State};
use futures_util::StreamExt;
use bindings::{constant_sum::ConstantSum, constant_sum_solver::ConstantSumSolver, dfmm::DFMM};
use serde::de::DeserializeOwned;

// Idea: Let's make a behavior that has two states:
// State 1. This is for configuration and it should have everything be `Serialize`/`Deserialize` so that it can be read in from a config.
Expand Down Expand Up @@ -29,25 +32,96 @@ pub struct PoolProcessor<P: PoolType> {
impl<P, E> Behavior<E> for PoolCreator<Configuration<PoolConfig<P>>>
where
P: PoolType + Send + Sync + 'static,
E: Send + Sync + 'static,
E: Send + Sync + 'static + DeserializeOwned,
{
type Processor = PoolCreator<Processing<PoolProcessor<P>>>;
async fn startup(
&mut self,
_client: Arc<ArbiterMiddleware>,
_messager: Messager,
client: Arc<ArbiterMiddleware>,
messager: Messager,
) -> Result<Option<(Self::Processor, EventStream<E>)>> {
todo!()

let mut stream = messager.stream()?;
let res = stream.next().await.unwrap();
let data: String =
serde_json::from_str(&res.data).expect("Failed to
deserialize message data");
let parsed_data: DeploymentData =
serde_json::from_str(&data).expect("Failed to deserialize
token data");

let token_x = ArbiterToken::new(parsed_data.token_x, client.clone());
let token_y = ArbiterToken::new(parsed_data.token_y, client);
let (strategy_contract, solver_contract) = P::get_contracts(&parsed_data, client);
let dfmm = DFMM::new(parsed_data.dfmm, client);
let init_data = self.data.initial_allocation_data.clone();
let pool = P::create_pool(self.data.initial_allocation_data, vec![token_x, token_y], strategy_contract, solver_contract, dfmm).await?;
trace!("Pool created at {:?}", pool.id);
Ok(None)
}
}

#[async_trait::async_trait]
impl<P, E> Processor<E> for PoolCreator<Processing<PoolProcessor<P>>>
where
P: PoolType + Send + Sync + 'static,
E: Send + Sync + 'static,
E: Send + Sync + 'static + DeserializeOwned,
{
async fn process(&mut self, _event: E) -> Result<ControlFlow> {
Ok(ControlFlow::Halt)
}
}

mod test {
use std::str::FromStr;

use arbiter_engine::{agent::Agent, world::World};
use ethers::types::Address;
use futures_util::StreamExt;
use tracing_subscriber::FmtSubscriber;

use crate::behaviors::deployer::{Deployer, DeploymentData};
use crate::behaviors::Behaviors::Creator;
use self::{bindings::constant_sum_solver::ConstantSumParams, pool::constant_sum::{ConstantSumInitData, ConstantSumPool}};

use super::*;

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn deployer_behavior_test() {
let subscriber = FmtSubscriber::builder().finish();
tracing::subscriber::set_global_default(subscriber).unwrap();

let mut world = World::new("test");
let messager = world.messager.clone();

let agent = Agent::builder("token_admin_agent");
let creator = Agent::builder("pool_creator_agent");
world.add_agent(creator.with_behavior(PoolCreator::<Configuration<PoolConfig<ConstantSumPool>>>
{ data: PoolConfig {
params: ConstantSumParams {
price: 0.into(),
swap_fee: 0.into(),
controller: Address::zero(),
},
initial_allocation_data: ConstantSumInitData {
name: "Test Pool".to_string(),
symbol: "TP".to_string(),
reserve_x: 0.into(),
reserve_y: 0.into(),
token_x_name: "Token X".to_string(),
token_y_name: "Token Y".to_string(),
params: ConstantSumParams {
price: eU256::zero(),
swap_fee: eU256::zero(),
controller: Address::zero(),
},
},
token_list: vec![Address::zero(), Address::zero()],
}
}));

world.add_agent(agent.with_behavior(Deployer {}));

world.run().await.unwrap();
}
}
158 changes: 82 additions & 76 deletions kit/src/behaviors/deployer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use arbiter_bindings::bindings::weth::WETH;
use bindings::{
constant_sum::ConstantSum, dfmm::DFMM, geometric_mean::GeometricMean, log_normal::LogNormal,
constant_sum::ConstantSum, dfmm::DFMM, geometric_mean::GeometricMean, log_normal::LogNormal, constant_sum_solver::ConstantSumSolver
};
use ethers::types::Address;

Expand All @@ -17,6 +17,7 @@ pub struct DeploymentData {
pub geometric_mean: Address,
pub log_normal: Address,
pub constant_sum: Address,
pub constant_sum_solver: Address,
pub token_x: Address,
pub token_y: Address,
}
Expand Down Expand Up @@ -73,13 +74,18 @@ impl Behavior<()> for Deployer {
.send()
.await?;

let cs_solver = ConstantSumSolver::deploy(client.clone(), constant_sum.address())?
.send()
.await?;

let deployment_data = DeploymentData {
n_token_geometric_mean: n_token_geometric_mean.address(),
weth: weth.address(),
dfmm: dfmm.address(),
geometric_mean: geometric_mean.address(),
log_normal: log_normal.address(),
constant_sum: constant_sum.address(),
constant_sum_solver: cs_solver.address(),
token_x: token_x.address(),
token_y: token_y.address(),
};
Expand All @@ -91,78 +97,78 @@ impl Behavior<()> for Deployer {
}
}

// #[cfg(test)]
// mod tests {
// use std::str::FromStr;

// use arbiter_engine::{agent::Agent, world::World};
// use ethers::types::Address;
// use futures_util::StreamExt;
// use tracing_subscriber::FmtSubscriber;

// use crate::behaviors::deployer::{Deployer, DeploymentData};

// #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
// async fn deployer_behavior_test() {
// let subscriber = FmtSubscriber::builder().finish();
// tracing::subscriber::set_global_default(subscriber).unwrap();

// let mut world = World::new("test");
// let messager = world.messager.clone();

// let agent = Agent::builder("token_admin_agent");
// world.add_agent(agent.with_behavior(Deployer {}));

// world.run().await.unwrap();
// let mut stream = messager.stream().expect("Failed to get messager
// stream");

// if let Some(res) = stream.next().await {
// let token_res_data = &res.data;
// println!("{}", token_res_data);

// let data: String =
// serde_json::from_str(token_res_data).expect("Failed to
// deserialize message data");

// let parsed_data: DeploymentData =
// serde_json::from_str(&data).expect("Failed to deserialize
// token data");

// println!("{:?}", parsed_data);

// assert_eq!(
//
// Address::from_str("0xb00efcb70090a21d46660adf95a16ec69623f694").unwrap(),
// parsed_data.weth
// );
// assert_eq!(
//
// Address::from_str("0x27781b40bd019ccb1dcb0c809135db71222e9353").unwrap(),
// parsed_data.dfmm
// );
// assert_eq!(
//
// Address::from_str("0x6e0035324097bfc66442e2d3f37ef378fb3750b2").unwrap(),
// parsed_data.geometric_mean
// );
// assert_eq!(
//
// Address::from_str("0x4be050270d209ef9f0c0435736c731767486279f").unwrap(),
// parsed_data.log_normal
// );
// assert_eq!(
//
// Address::from_str("0xaeb166f1355c6254d01a54317ef8d4d21bfcb4b0").unwrap(),
// parsed_data.constant_sum
// );
// assert_eq!(
//
// Address::from_str("0xa4bb88cbfc92d86ae00842dcfa5a1ac32b0714b3").unwrap(),
// parsed_data.n_token_geometric_mean
// );
// } else {
// panic!("No message received");
// }
// }
// }
#[cfg(test)]
mod tests {
use std::str::FromStr;

use arbiter_engine::{agent::Agent, world::World};
use ethers::types::Address;
use futures_util::StreamExt;
use tracing_subscriber::FmtSubscriber;

use crate::behaviors::deployer::{Deployer, DeploymentData};

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn deployer_behavior_test() {
let subscriber = FmtSubscriber::builder().finish();
tracing::subscriber::set_global_default(subscriber).unwrap();

let mut world = World::new("test");
let messager = world.messager.clone();

let agent = Agent::builder("token_admin_agent");
world.add_agent(agent.with_behavior(Deployer {}));

world.run().await.unwrap();
let mut stream = messager.stream().expect("Failed to get messager
stream");

if let Some(res) = stream.next().await {
let token_res_data = &res.data;
println!("{}", token_res_data);

let data: String =
serde_json::from_str(token_res_data).expect("Failed to
deserialize message data");

let parsed_data: DeploymentData =
serde_json::from_str(&data).expect("Failed to deserialize
token data");

println!("{:?}", parsed_data);

assert_eq!(

Address::from_str("0xb00efcb70090a21d46660adf95a16ec69623f694").unwrap(),
parsed_data.weth
);
assert_eq!(

Address::from_str("0x27781b40bd019ccb1dcb0c809135db71222e9353").unwrap(),
parsed_data.dfmm
);
assert_eq!(

Address::from_str("0x6e0035324097bfc66442e2d3f37ef378fb3750b2").unwrap(),
parsed_data.geometric_mean
);
assert_eq!(

Address::from_str("0x4be050270d209ef9f0c0435736c731767486279f").unwrap(),
parsed_data.log_normal
);
assert_eq!(

Address::from_str("0xaeb166f1355c6254d01a54317ef8d4d21bfcb4b0").unwrap(),
parsed_data.constant_sum
);
assert_eq!(

Address::from_str("0xa4bb88cbfc92d86ae00842dcfa5a1ac32b0714b3").unwrap(),
parsed_data.n_token_geometric_mean
);
} else {
panic!("No message received");
}
}
}
2 changes: 1 addition & 1 deletion kit/src/behaviors/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::Arc;

use arbiter_bindings::bindings::arbiter_token::ArbiterToken;
use bindings::arbiter_token::ArbiterToken;
use arbiter_engine::{
machine::{Behavior, Configuration, ControlFlow, EventStream},
messager::{Messager, To},
Expand Down
10 changes: 9 additions & 1 deletion kit/src/pool/constant_sum.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
use std::sync::Arc;

use bindings::{
constant_sum::ConstantSum,
constant_sum_solver::{ConstantSumParams, ConstantSumSolver},
shared_types::InitParams,
};
use ethers::etherscan::Client;

use self::behaviors::deployer::DeploymentData;

use super::*;

Expand Down Expand Up @@ -48,8 +53,11 @@ impl PoolType for ConstantSumPool {
type SolverContract = ConstantSumSolver<ArbiterMiddleware>;
type AllocationData = ConstantSumAllocationData;

fn get_contracts(deployment: &DeploymentData, client: Arc<ArbiterMiddleware>) -> (Self::StrategyContract, Self::SolverContract) {
(ConstantSum::new(deployment.constant_sum, client.clone()), ConstantSumSolver::new(deployment.constant_sum_solver, client))
}

async fn create_pool(
&self,
init_data: Self::InitializationData,
token_list: Vec<ArbiterToken<ArbiterMiddleware>>,
strategy_contract: Self::StrategyContract,
Expand Down
Loading

0 comments on commit 764761f

Please sign in to comment.