Skip to content

Commit

Permalink
progress WIP
Browse files Browse the repository at this point in the history
Removed some additional bounds and cleaned up some structs and impls. There's still a bit of a battle with deserialization here, but we can get through it.
  • Loading branch information
Autoparallel committed Apr 23, 2024
1 parent 48b2175 commit e2464d2
Show file tree
Hide file tree
Showing 9 changed files with 219 additions and 258 deletions.
14 changes: 7 additions & 7 deletions kit/src/behaviors/allocate/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;

pub trait AllocateType<E>: Debug + Serialize + Clone
pub trait AllocateType<E>
where
E: Send + 'static,
{
Expand Down Expand Up @@ -44,9 +44,9 @@ where
#[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(
Expand All @@ -61,9 +61,9 @@ where
#[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.");
Expand Down
32 changes: 13 additions & 19 deletions kit/src/behaviors/creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ pub struct Config<P: PoolType> {
impl<P> Behavior<()> for Create<Config<P>>
where
P: PoolType + Send + Sync + 'static,
P::StrategyContract: Send,
P::SolverContract: Send,
{
type Processor = ();
async fn startup(
Expand Down Expand Up @@ -100,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();
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,
}
72 changes: 53 additions & 19 deletions kit/src/behaviors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,13 @@ 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 @@ -46,22 +42,60 @@ where
#[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_raw().await {
// TODO: Okay annoyingly if we try to deserialize into this immediately it
// works. But we can't use the message types enum.
let data: PoolCreation<P> = serde_json::from_str(&msg.data).unwrap();
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;
}
}
}
}
130 changes: 40 additions & 90 deletions kit/src/behaviors/swap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ use self::{bindings::erc20::ERC20, pool::InputToken};
use super::*;
use crate::behaviors::token::Response;

pub trait SwapType<E>: Debug + Serialize + Clone {
pub trait SwapType<E> {
fn compute_swap_amount(event: E) -> (eU256, InputToken);
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Swap<S: State, T: SwapType<E>, E> {
pub struct Swap<S, T, E>
where
S: State,
T: SwapType<E>,
{
// to get tokens on start up
pub token_admin: String,
pub update: String,
Expand All @@ -16,12 +20,20 @@ pub struct Swap<S: State, T: SwapType<E>, E> {
pub _phantom: PhantomData<E>,
}

// TODO: This needs to be configurable in some way to make the `SwapType` become
// transparent and useful.
// Should also get some data necessary for mint amounts and what not.
#[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>,
phantom: PhantomData<P>,
}

impl<P: PoolType> Default for Config<P> {
fn default() -> Self {
Self {
phantom: PhantomData,
}
}
}

#[derive(Debug, Clone, State)]
Expand All @@ -31,27 +43,12 @@ pub struct Processing<P: PoolType> {
pub pool: Pool<P>,
}

#[derive(Debug)]
struct SwapTodo<P: PoolType> {
deployment_data: Option<DeploymentData>,
#[allow(clippy::type_complexity)]
pool_creation: Option<(
PoolId, // Pool ID
TokenList, // Token List
LiquidityToken, // Liquidity Token
<P as PoolType>::Parameters,
<P as PoolType>::AllocationData,
)>,
}

#[async_trait::async_trait]
impl<P, T, E> Behavior<()> for Swap<Config<P>, T, E>
where
P: PoolType + Send + Sync + 'static,
P::StrategyContract: Send,
P::SolverContract: Send,
T: SwapType<E> + Send + Sync + 'static + for<'a> Deserialize<'a>,
E: Debug + Send + Sync + 'static,
P: PoolType + Send,
T: SwapType<E> + Send,
E: Send,
{
// type Processor = Swap<Processing<P>, T, E>;
type Processor = ();
Expand All @@ -60,67 +57,28 @@ where
client: Arc<ArbiterMiddleware>,
mut messager: Messager,
) -> Result<Self::Processor> {
// Make a "TODO" list.
// This is the data I need to recieve to do my job
let mut todo: SwapTodo<P> = SwapTodo {
deployment_data: None,
pool_creation: None,
};

// Loop through the messager until we check off the boxes for this TODO list.
debug!("Updater is looping through their TODO list.");
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!("Updater: Got all the data.\n{:#?}", todo);
break;
}
}
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!("Updater: Got all the data.\n{:#?}", todo);
break;
}
}
_ => continue,
}
} else {
debug!("Updater got some other message variant it could ignore.");
continue;
}
}
debug!("Updater has checked off their TODO list.");
// TODO: Here we probably need to filter on the `PoolCreation` so that we get
// the correct pool.
let completed_todo = GetPoolTodo::<P>::complete(&mut messager).await;
let (deployment_data, pool_creation) = (
completed_todo.deployment_data.unwrap(),
completed_todo.pool_creation.unwrap(),
);

let (strategy_contract, solver_contract) =
P::get_contracts(todo.deployment_data.as_ref().unwrap(), client.clone());
let dfmm = DFMM::new(todo.deployment_data.unwrap().dfmm, client.clone());
debug!("Got DFMM and the strategy contracts.");
P::get_contracts(&deployment_data, client.clone());
let dfmm = DFMM::new(deployment_data.dfmm, client.clone());

// Get the intended tokens for the pool and do approvals.
let mut tokens: Vec<ArbiterToken<ArbiterMiddleware>> = Vec::new();
for tkn in self.data.token_list.drain(..) {
messager
.send(
To::Agent(self.token_admin.clone()),
TokenAdminQuery::AddressOf(tkn.clone()),
)
.await
.unwrap();
let token = ArbiterToken::new(
messager.get_next::<eAddress>().await.unwrap().data,
client.clone(),
);
for token_address in pool_creation.tokens.into_iter() {
let token = ArbiterToken::new(token_address, client.clone());
let name = token.name().call().await?;
messager
.send(
To::Agent(self.token_admin.clone()),
TokenAdminQuery::MintRequest(MintRequest {
token: tkn,
token: name,
mint_to: client.address(),
mint_amount: 100_000_000_000,
}),
Expand All @@ -142,21 +100,13 @@ where
tokens.push(token);
}

let lp_address = todo.pool_creation.clone().unwrap().2;
let lp_token = ERC20::new(lp_address, client.clone());
let instance = P::create_instance(
strategy_contract,
solver_contract,
todo.pool_creation.clone().unwrap().3,
);

// build pool for processor and stream
let pool = Pool::<P> {
id: todo.pool_creation.clone().unwrap().0,
let _pool = Pool::<P> {
id: pool_creation.id,
dfmm,
instance,
instance: P::create_instance(strategy_contract, solver_contract, pool_creation.params),
tokens,
liquidity_token: lp_token,
liquidity_token: ERC20::new(pool_creation.liquidity_token, client.clone()),
};
// TODO: We need to come back around and adjust this.
// match self.swap_type.get_stream(messager.clone()) {
Expand Down Expand Up @@ -184,8 +134,8 @@ where
impl<P, T, E> Processor<E> for Swap<Processing<P>, T, E>
where
P: PoolType + Send + Sync,
T: SwapType<E> + Send + Sync + 'static,
E: Send + Sync + 'static,
T: SwapType<E> + 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 'Swap' behavior.")
Expand Down
Loading

0 comments on commit e2464d2

Please sign in to comment.