Skip to content

Commit

Permalink
fix merge
Browse files Browse the repository at this point in the history
  • Loading branch information
hardingjam committed Jan 27, 2025
1 parent cc0d6ce commit 155f494
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 4,497 deletions.
32 changes: 12 additions & 20 deletions crates/js_api/src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ use base64::{engine::general_purpose::URL_SAFE, Engine};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use rain_orderbook_app_settings::{
deployment::Deployment,
gui::{
Gui, GuiDeployment, GuiFieldDefinition, GuiPreset, NameAndDescription,
ParseGuiConfigSourceError,
},
gui::{Gui, GuiDeployment, GuiFieldDefinition, GuiPreset, ParseGuiConfigSourceError},
network::Network,
order::Order,
yaml::YamlError,
Expand Down Expand Up @@ -42,8 +39,11 @@ pub struct TokenInfo {
impl_all_wasm_traits!(TokenInfo);

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Tsify)]
pub struct DeploymentDetails(BTreeMap<String, NameAndDescription>);
impl_all_wasm_traits!(DeploymentDetails);
pub struct GuiDetails {
name: String,
description: String,
}
impl_all_wasm_traits!(GuiDetails);

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[wasm_bindgen]
Expand Down Expand Up @@ -87,7 +87,7 @@ impl DotrainOrderGui {
let gui = self
.dotrain_order
.dotrain_yaml()
.get_gui(Some(self.selected_deployment.clone()))?
.get_gui()?
.ok_or(GuiError::GuiConfigNotFound)?;
Ok(gui)
}
Expand Down Expand Up @@ -146,19 +146,11 @@ impl DotrainOrderGui {
Ok(token_info)
}

#[wasm_bindgen(js_name = "getStrategyDetails")]
pub async fn get_strategy_details(dotrain: String) -> Result<NameAndDescription, GuiError> {
let dotrain_order = DotrainOrder::new(dotrain, None).await?;
let details = Gui::parse_strategy_details(dotrain_order.dotrain_yaml().documents.clone())?;
Ok(details)
}

#[wasm_bindgen(js_name = "getDeploymentDetails")]
pub async fn get_deployment_details(dotrain: String) -> Result<DeploymentDetails, GuiError> {
let dotrain_order = DotrainOrder::new(dotrain, None).await?;
let deployment_details =
Gui::parse_deployment_details(dotrain_order.dotrain_yaml().documents.clone())?;
Ok(DeploymentDetails(deployment_details.into_iter().collect()))
#[wasm_bindgen(js_name = "getGuiDetails")]
pub fn get_gui_details(&self) -> Result<GuiDetails, GuiError> {
let (name, description) =
Gui::parse_gui_details(self.dotrain_order.dotrain_yaml().documents.clone())?;
Ok(GuiDetails { name, description })
}
}

Expand Down
129 changes: 68 additions & 61 deletions crates/settings/src/gui.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{
yaml::{
context::{Context, GuiContextTrait},
default_document, get_hash_value, optional_hash, optional_string, optional_vec,
require_string, require_vec, YamlError, YamlParsableHash, YamlParseableValue,
context::Context, default_document, get_hash_value, optional_hash, optional_string,
optional_vec, require_string, require_vec, YamlError, YamlParsableHash, YamlParseableValue,
},
Deployment, Token, TokenRef,
};
Expand Down Expand Up @@ -249,15 +248,6 @@ pub struct Gui {
#[cfg(target_family = "wasm")]
impl_all_wasm_traits!(Gui);

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(target_family = "wasm", derive(Tsify))]
pub struct NameAndDescription {
pub name: String,
pub description: String,
}
#[cfg(target_family = "wasm")]
impl_all_wasm_traits!(NameAndDescription);

impl Gui {
pub fn parse_deployment_keys(
documents: Vec<Arc<RwLock<StrictYaml>>>,
Expand Down Expand Up @@ -319,9 +309,9 @@ impl Gui {
Ok(None)
}

pub fn parse_strategy_details(
pub fn parse_gui_details(
documents: Vec<Arc<RwLock<StrictYaml>>>,
) -> Result<NameAndDescription, YamlError> {
) -> Result<(String, String), YamlError> {
for document in documents {
let document_read = document.read().map_err(|_| YamlError::ReadLockError)?;

Expand All @@ -342,57 +332,82 @@ impl Gui {
Some("description field must be a string in gui".to_string()),
)?;

return Ok(NameAndDescription { name, description });
return Ok((name, description));
}
}
Err(YamlError::ParseError("gui details not found".to_string()))
}

pub fn parse_deployment_details(
pub fn parse_field_presets(
documents: Vec<Arc<RwLock<StrictYaml>>>,
) -> Result<HashMap<String, NameAndDescription>, YamlError> {
let mut deployment_details = HashMap::new();

deployment_key: &str,
field_binding: &str,
) -> Result<Option<Vec<GuiPreset>>, YamlError> {
for document in documents {
let document_read = document.read().map_err(|_| YamlError::ReadLockError)?;

if let Some(gui) = optional_hash(&document_read, "gui") {
let deployments = gui
.get(&StrictYaml::String("deployments".to_string()))
.ok_or(YamlError::ParseError(
"deployments field missing in gui".to_string(),
))?
.as_hash()
.ok_or(YamlError::ParseError(
if let Some(StrictYaml::Hash(deployments_hash)) =
gui.get(&StrictYaml::String("deployments".to_string()))
{
if let Some(StrictYaml::Hash(deployment_hash)) =
deployments_hash.get(&StrictYaml::String(deployment_key.to_string()))
{
if let Some(StrictYaml::Array(fields)) =
deployment_hash.get(&StrictYaml::String("fields".to_string()))
{
for (field_index, field) in fields.iter().enumerate() {
if let StrictYaml::Hash(field_hash) = field {
if let Some(StrictYaml::String(binding)) =
field_hash.get(&StrictYaml::String("binding".to_string()))
{
if binding == field_binding {
return match optional_vec(field, "presets") {
Some(presets) => {
let preset_vec = presets.iter().enumerate()
.map(|(preset_index, preset_yaml)| {
let name = optional_string(preset_yaml, "name");
let value = require_string(
preset_yaml,
Some("value"),
Some(format!(
"preset value must be a string for preset index: {preset_index} for field index: {field_index} in gui deployment: {deployment_key}",
))
)?;

Ok(GuiPreset {
id: preset_index.to_string(),
name,
value,
})
})
.collect::<Result<Vec<_>, YamlError>>()?;
Ok(Some(preset_vec))
}
None => Ok(None),
};
}
} else {
return Err(YamlError::ParseError(format!(
"binding string missing for field index: {field_index} in gui deployment: {deployment_key}",
)));
}
}
}
} else {
return Err(YamlError::ParseError(format!(
"fields list missing in gui deployment: {deployment_key}"
)));
}
}
} else {
return Err(YamlError::ParseError(
"deployments field must be a map in gui".to_string(),
))?;

for (key_yaml, deployment_yaml) in deployments {
let deployment_key = key_yaml.as_str().unwrap_or_default().to_string();

let name = require_string(
deployment_yaml,
Some("name"),
Some(format!(
"name string missing in gui deployment: {deployment_key}"
)),
)?;

let description = require_string(
deployment_yaml,
Some("description"),
Some(format!(
"description string missing in gui deployment: {deployment_key}"
)),
)?;

deployment_details
.insert(deployment_key, NameAndDescription { name, description });
));
}
}
}

Ok(deployment_details)
Ok(None)
}
}

Expand All @@ -406,7 +421,7 @@ impl YamlParseableValue for Gui {

fn parse_from_yaml_optional(
documents: Vec<Arc<RwLock<StrictYaml>>>,
context: Option<&Context>,
_: Option<&Context>,
) -> Result<Option<Self>, YamlError> {
let mut gui_res: Option<Gui> = None;
let mut gui_deployments_res: HashMap<String, GuiDeployment> = HashMap::new();
Expand Down Expand Up @@ -454,15 +469,7 @@ impl YamlParseableValue for Gui {
for (deployment_name, deployment_yaml) in deployments {
let deployment_name = deployment_name.as_str().unwrap_or_default().to_string();

if let Some(context) = context {
if let Some(current_deployment) = context.get_current_deployment() {
if current_deployment != &deployment_name {
continue;
}
}
}

let mut context = Context::from_context(context);
let mut context = Context::new();

let select_tokens = match optional_vec(deployment_yaml, "select-tokens") {
Some(tokens) => Some(
Expand Down
10 changes: 1 addition & 9 deletions crates/settings/src/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use strict_yaml_rust::StrictYaml;
use thiserror::Error;
use typeshare::typeshare;
use yaml::{
context::{Context, GuiContextTrait, SelectTokensContext},
context::{Context, SelectTokensContext},
default_document, optional_string, require_hash, require_string, require_vec, YamlError,
YamlParsableHash,
};
Expand Down Expand Up @@ -367,14 +367,6 @@ impl YamlParsableHash for Order {
for (key_yaml, order_yaml) in orders_hash {
let order_key = key_yaml.as_str().unwrap_or_default().to_string();

if let Some(context) = context {
if let Some(current_order) = context.get_current_order() {
if current_order != &order_key {
continue;
}
}
}

let mut network: Option<Arc<Network>> = None;

let deployer = match optional_string(order_yaml, "deployer") {
Expand Down
33 changes: 9 additions & 24 deletions crates/settings/src/yaml/dotrain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,8 @@ impl DotrainYaml {
Deployment::parse_from_yaml(self.documents.clone(), key, None)
}

pub fn get_gui(&self, current_deployment: Option<String>) -> Result<Option<Gui>, YamlError> {
let mut context = Context::new();
if let Some(deployment) = current_deployment {
context.add_current_deployment(deployment);
}
Gui::parse_from_yaml_optional(self.documents.clone(), Some(&context))
pub fn get_gui(&self) -> Result<Option<Gui>, YamlError> {
Gui::parse_from_yaml_optional(self.documents.clone(), None)
}
}

Expand Down Expand Up @@ -363,7 +359,7 @@ mod tests {
"order1"
);

let gui = dotrain_yaml.get_gui(None).unwrap().unwrap();
let gui = dotrain_yaml.get_gui().unwrap().unwrap();
assert_eq!(gui.name, "Test gui");
assert_eq!(gui.description, "Test description");
assert_eq!(gui.deployments.len(), 1);
Expand All @@ -389,20 +385,9 @@ mod tests {
assert_eq!(select_tokens.len(), 1);
assert_eq!(select_tokens[0], "token2");

let details = Gui::parse_strategy_details(dotrain_yaml.documents.clone()).unwrap();
assert_eq!(details.name, "Test gui");
assert_eq!(details.description, "Test description");

let deployment_details =
Gui::parse_deployment_details(dotrain_yaml.documents.clone()).unwrap();
assert_eq!(
deployment_details.get("deployment1").unwrap().name,
"Test deployment"
);
assert_eq!(
deployment_details.get("deployment1").unwrap().description,
"Test description"
);
let (name, description) = Gui::parse_gui_details(dotrain_yaml.documents.clone()).unwrap();
assert_eq!(name, "Test gui");
assert_eq!(description, "Test description");

let deployment_keys = Gui::parse_deployment_keys(dotrain_yaml.documents.clone()).unwrap();
assert_eq!(deployment_keys.len(), 1);
Expand Down Expand Up @@ -608,7 +593,7 @@ mod tests {
fn test_handlebars() {
let dotrain_yaml = DotrainYaml::new(vec![HANDLEBARS_YAML.to_string()], false).unwrap();

let gui = dotrain_yaml.get_gui(None).unwrap().unwrap();
let gui = dotrain_yaml.get_gui().unwrap().unwrap();
let deployment = gui.deployments.get("deployment1").unwrap();

assert_eq!(
Expand Down Expand Up @@ -699,7 +684,7 @@ orders:
);

let dotrain_yaml = DotrainYaml::new(vec![missing_input_token_yaml], false).unwrap();
let error = dotrain_yaml.get_gui(None).unwrap_err();
let error = dotrain_yaml.get_gui().unwrap_err();
assert_eq!(
error,
YamlError::ParseError(
Expand All @@ -709,7 +694,7 @@ orders:
);

let dotrain_yaml = DotrainYaml::new(vec![missing_output_token_yaml], false).unwrap();
let error = dotrain_yaml.get_gui(None).unwrap_err();
let error = dotrain_yaml.get_gui().unwrap_err();
assert_eq!(
error,
YamlError::ParseError(
Expand Down
24 changes: 4 additions & 20 deletions packages/orderbook/test/js_api/gui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import {
AllFieldValuesResult,
AllowancesResult,
ApprovalCalldataResult,
DeploymentDetails,
DeploymentKeys,
DepositAndAddOrderCalldataResult,
DepositCalldataResult,
Gui,
GuiDeployment,
NameAndDescription,
GuiDetails,
TokenDeposit,
TokenInfo
} from '../../dist/types/js_api.js';
Expand Down Expand Up @@ -366,25 +365,10 @@ describe('Rain Orderbook JS API Package Bindgen Tests - Gui', async function ()
const guiConfig = gui.getGuiConfig() as Gui;
assert.equal(guiConfig.name, 'Fixed limit');
assert.equal(guiConfig.description, 'Fixed limit order strategy');
});

it('should get strategy details', async () => {
const strategyDetails: NameAndDescription =
await DotrainOrderGui.getStrategyDetails(dotrainWithGui);
assert.equal(strategyDetails.name, 'Fixed limit');
assert.equal(strategyDetails.description, 'Fixed limit order strategy');
});

it('should get deployment details', async () => {
const deploymentDetails: DeploymentDetails =
await DotrainOrderGui.getDeploymentDetails(dotrainWithGui);
const entries = Array.from(deploymentDetails.entries());
assert.equal(entries[0][0], 'other-deployment');
assert.equal(entries[0][1].name, 'Test test');
assert.equal(entries[0][1].description, 'Test test test');
assert.equal(entries[1][0], 'some-deployment');
assert.equal(entries[1][1].name, 'Buy WETH with USDC on Base.');
assert.equal(entries[1][1].description, 'Buy WETH with USDC for fixed price on Base network.');
const guiDetails: GuiDetails = gui.getGuiDetails();
assert.equal(guiDetails.name, 'Fixed limit');
assert.equal(guiDetails.description, 'Fixed limit order strategy');
});

it('should get token infos', async () => {
Expand Down
Loading

0 comments on commit 155f494

Please sign in to comment.