Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor/test/behaviors #137

Merged
merged 14 commits into from
Apr 26, 2024
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.

8 changes: 4 additions & 4 deletions kit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ keywords = ["ethereum", "smart-contracts", "automated market makers"]
readme = "../README.md"

[dependencies]
arbiter-core = { git = "https://github.com/primitivefinance/arbiter.git", rev = "aff29d30" }
arbiter-engine = { git = "https://github.com/primitivefinance/arbiter.git", rev = "aff29d30" }
arbiter-macros = { git = "https://github.com/primitivefinance/arbiter.git", rev = "aff29d30" }
arbiter-bindings = { git = "https://github.com/primitivefinance/arbiter.git", rev = "aff29d30" }
arbiter-core = { git = "https://github.com/primitivefinance/arbiter.git", rev = "360f4a7f" }
arbiter-engine = { git = "https://github.com/primitivefinance/arbiter.git", rev = "360f4a7f" }
arbiter-macros = { git = "https://github.com/primitivefinance/arbiter.git", rev = "360f4a7f" }
arbiter-bindings = { git = "https://github.com/primitivefinance/arbiter.git", rev = "360f4a7f" }

# Ethereum
ethers = "2.0.13"
Expand Down
35 changes: 13 additions & 22 deletions kit/src/behaviors/allocate/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use super::*;

pub trait AllocateType<E>: Debug + Serialize + Clone
pub trait AllocateType<E>
where
E: Send + 'static,
{
// TODO: This should probably be how we do it, but this generic `P` gets
// annoying fn change_allocation_amount(&mut self, event: E) ->
// Option<P::AllocationData>;
fn change_allocation_amount(&mut self, event: E) -> Option<Vec<eI256>>;
fn get_stream(&self) -> Pin<Box<dyn Stream<Item = E> + Send + Sync>>;
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand All @@ -24,11 +23,12 @@ where
_phantom_e: PhantomData<E>,
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, State)]
pub struct Config<P: PoolType> {
pub allocation_data: P::AllocationData,
}

#[derive(State)]
pub struct Processing<P, E>
where
P: PoolType,
Expand All @@ -40,43 +40,34 @@ where
_phantom: PhantomData<E>,
}

impl<P: PoolType> State for Config<P> {
type Data = Self;
}

impl<P, E> State for Processing<P, E>
where
P: PoolType,
E: Send + 'static,
{
type Data = Self;
}

#[allow(unused_variables)]
#[async_trait::async_trait]
impl<A, P, E> Behavior<E> for Allocate<A, E, Config<P>>
where
A: AllocateType<E> + Debug + Send + Sync + 'static + for<'a> Deserialize<'a>,
P: PoolType + Debug + Send + Sync + 'static,
E: Debug + Send + Sync + 'static,
A: AllocateType<E> + Send,
P: PoolType + Send,
E: Send + 'static,
{
type Processor = Allocate<A, E, Processing<P, E>>;
async fn startup(
&mut self,
client: Arc<ArbiterMiddleware>,
messager: Messager,
) -> Result<Option<(Self::Processor, EventStream<E>)>> {
) -> Result<Self::Processor> {
todo!();
}
}

#[async_trait::async_trait]
impl<A, P, E> Processor<E> for Allocate<A, E, Processing<P, E>>
where
A: AllocateType<E> + Debug + Send + Sync + 'static,
P: PoolType + Debug + Send + Sync + 'static,
E: Debug + Send + Sync + 'static,
A: AllocateType<E> + Send,
P: PoolType + Send,
E: Send + 'static,
{
async fn get_stream(&mut self) -> Result<Option<EventStream<E>>> {
todo!("We have not implemented the 'get_stream' method yet for the 'Allocate' behavior.");
}
async fn process(&mut self, _event: E) -> Result<ControlFlow> {
Ok(ControlFlow::Halt)
}
Expand Down
42 changes: 16 additions & 26 deletions kit/src/behaviors/creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,25 @@ pub struct Create<S: State> {
pub data: S::Data,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize, State)]
pub struct Config<P: PoolType> {
pub base_config: BaseConfig,
pub params: P::Parameters,
pub allocation_data: P::AllocationData,
pub token_list: Vec<String>,
}

impl<P: PoolType> State for Config<P> {
type Data = Self;
}

#[async_trait::async_trait]
impl<P> Behavior<()> for Create<Config<P>>
where
P: PoolType + Send + Sync + 'static,
P::StrategyContract: Send,
P::SolverContract: Send,
{
type Processor = ();
async fn startup(
&mut self,
client: Arc<ArbiterMiddleware>,
mut messager: Messager,
) -> Result<Option<(Self::Processor, EventStream<()>)>> {
) -> Result<Self::Processor> {
// Receive the `DeploymentData` from the `Deployer` agent and use it to get the
// contracts.
debug!("Starting the creator");
Expand Down Expand Up @@ -104,23 +98,19 @@ where

debug!("Pool created!\n {:#?}", pool);

let pool_creation = (
pool.id,
pool.tokens.iter().map(|t| t.address()).collect::<Vec<_>>(),
pool.liquidity_token.address(),
params,
self.data.allocation_data.clone(),
);
messager.send(To::All, pool_creation).await.unwrap();
Ok(None)
messager
.send(
To::All,
PoolCreation::<P> {
id: pool.id,
tokens: pool.tokens.iter().map(|t| t.address()).collect::<Vec<_>>(),
liquidity_token: pool.liquidity_token.address(),
params,
allocation_data: self.data.allocation_data.clone(),
},
)
.await
.unwrap();
Ok(())
}
}

// TODO: We should be able to use this but it is currently hard to work with due
// to `serde::Deserialize`
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct PoolCreation<P: PoolType> {
pub id: eU256,
pub params: P::Parameters,
pub allocation_data: P::AllocationData,
}
30 changes: 2 additions & 28 deletions kit/src/behaviors/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,58 +35,34 @@ impl Behavior<()> for Deploy {
&mut self,
client: Arc<ArbiterMiddleware>,
messager: Messager,
) -> Result<Option<(Self::Processor, EventStream<()>)>> {
) -> Result<Self::Processor> {
let weth = WETH::deploy(client.clone(), ())?.send().await?;
trace!("WETH deployed at {:?}", weth.address());

let dfmm = DFMM::deploy(client.clone(), weth.address())?.send().await?;
trace!("DFMM deployed at {:?}", dfmm.address());

let geometric_mean = GeometricMean::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!("GeometricMean deployed at {:?}", geometric_mean.address());

let geometric_mean_solver = GeometricMeanSolver::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!(
"GeometricMeanSolver deployed at {:?}",
geometric_mean.address()
);

let log_normal = LogNormal::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!("LogNormal deployed at {:?}", log_normal.address());

let log_normal_solver = LogNormalSolver::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!(
"LogNormalSolver deployed at {:?}",
log_normal_solver.address()
);

let constant_sum = ConstantSum::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!("ConstantSum deployed at {:?}", constant_sum.address());

let constant_sum_solver = ConstantSumSolver::deploy(client.clone(), dfmm.address())?
.send()
.await?;
trace!("ConstantSumSolver deployed at {:?}", constant_sum.address());

let n_token_geometric_mean = NTokenGeometricMean::deploy(client.clone(), dfmm.address())?
.send()
.await?;

let n_token_geometric_mean_solver =
NTokenGeometricMeanSolver::deploy(client.clone(), dfmm.address())?
.send()
.await?;

let deployment_data = DeploymentData {
weth: weth.address(),
dfmm: dfmm.address(),
Expand All @@ -99,10 +75,8 @@ impl Behavior<()> for Deploy {
constant_sum: constant_sum.address(),
constant_sum_solver: constant_sum_solver.address(),
};

debug!("Deployments completed: {:#?}", deployment_data);

messager.send(To::All, deployment_data).await?;
Ok(None)
Ok(())
}
}
75 changes: 53 additions & 22 deletions kit/src/behaviors/mod.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
use std::{boxed::Box, marker::PhantomData, pin::Pin, sync::Arc};
use std::{boxed::Box, marker::PhantomData, sync::Arc};

use arbiter_engine::{
machine::{Behavior, ControlFlow, EventStream, Processor, State},
messager::{Message, Messager, To},
};
#[allow(unused)]
use arbiter_macros::Behaviors;
use arbiter_macros::{Behaviors, State};
use bindings::{arbiter_token::ArbiterToken, dfmm::DFMM};
use futures_util::Stream;
pub use token::{MintRequest, TokenAdminQuery};

use self::{
creator::Create,
deploy::{Deploy, DeploymentData},
pool::PoolType,
pool::{PoolCreation, PoolType},
token::TokenAdmin,
};
use super::*;

pub const MAX: eU256 = eU256::MAX;

type PoolId = eU256;
type TokenList = Vec<eAddress>;
type LiquidityToken = eAddress;

pub mod allocate;
pub mod creator;
pub mod deploy;
Expand All @@ -40,29 +35,65 @@ pub enum Behaviors<P: PoolType> {
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(bound = "P: PoolType")]
pub enum MessageTypes<P>
where
P: PoolType,
{
#[serde(untagged)]
Deploy(DeploymentData),
#[serde(untagged)]
// TODO: This is super weird. The following commented out version with `PoolCreation<P>`
// doesn't compile. Create(creator::PoolCreation<P>),
// TODO: BUT, this line where the tuple struct has the exact same data as `PoolCreation<P>`
// DOES compile. I'm not sure how to go about making this work nicely, but at least this works
// for now.
Create(
(
eU256, // Pool ID
Vec<eAddress>, // Token List
eAddress, // Liquidity Token
P::Parameters,
P::AllocationData,
),
),
Create(PoolCreation<P>),
#[serde(untagged)]
TokenAdmin(token::Response),
#[serde(untagged)]
Update(P::Parameters),
}

#[derive(Debug)]
struct GetPoolTodo<P: PoolType> {
deployment_data: Option<DeploymentData>,
pool_creation: Option<PoolCreation<P>>,
}

impl<P: PoolType> GetPoolTodo<P> {
async fn complete(messager: &mut Messager) -> Self {
// Make an undone "TODO" list.
let mut todo: GetPoolTodo<P> = GetPoolTodo {
deployment_data: None,
pool_creation: None,
};
let id = messager.id.clone();
// Loop through the messager until we check off the boxes for this TODO list.
debug!("{:#?} is looping through their TODO list.", id.clone());
loop {
if let Ok(msg) = messager.get_next::<MessageTypes<P>>().await {
match msg.data {
MessageTypes::Deploy(deploy_data) => {
debug!("Updater: Got deployment data: {:?}", deploy_data);
todo.deployment_data = Some(deploy_data);
if todo.pool_creation.is_some() {
debug!("{:#?}: Got all the data.\n{:#?}", id.clone(), todo);
break todo;
}
}
MessageTypes::Create(pool_creation) => {
debug!("Updater: Got pool creation data: {:?}", pool_creation);
todo.pool_creation = Some(pool_creation);
if todo.deployment_data.is_some() {
debug!("{:#?}: Got all the data.\n{:#?}", id.clone(), todo);
break todo;
}
}
_ => continue,
}
} else {
debug!(
"{:#?} got some other message variant it could ignore.",
id.clone()
);
continue;
}
}
}
}
Loading
Loading