Skip to content

Commit

Permalink
Merge branch '2024-02-05-chore-consistent-vault-ordering' into 2024-0…
Browse files Browse the repository at this point in the history
…2-03-gui-vault-balance-changes
  • Loading branch information
mattyg committed Feb 6, 2024
2 parents ca8982f + c3cfdf0 commit 5ddff74
Show file tree
Hide file tree
Showing 14 changed files with 779 additions and 20 deletions.
15 changes: 6 additions & 9 deletions crates/common/src/add_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ pub struct AddOrderArgs {

impl AddOrderArgs {
/// Parse an Io array from from frontmatter field (i.e. validInputs or validOutputs)
fn try_parse_frontmatter_io(
&self,
pub(crate) fn try_parse_frontmatter_io(
io_yamls: StrictYaml,
io_field_name: &str,
) -> Result<Vec<IO>, AddOrderArgsError> {
Expand Down Expand Up @@ -129,8 +128,7 @@ impl AddOrderArgs {
}

/// Parse dotrain frontmatter to extract deployer, validInputs and validOutputs
fn try_parse_frontmatter(
&self,
pub(crate) fn try_parse_frontmatter(
frontmatter: &str,
) -> Result<(Address, Vec<IO>, Vec<IO>), AddOrderArgsError> {
// Parse dotrain document frontmatter
Expand All @@ -147,11 +145,11 @@ impl AddOrderArgs {
AddOrderArgsError::FrontmatterFieldInvalid("orderbook.order.deployer".into())
})?;

let valid_inputs: Vec<IO> = self.try_parse_frontmatter_io(
let valid_inputs: Vec<IO> = Self::try_parse_frontmatter_io(
frontmatter_yaml[0]["orderbook"]["order"]["validInputs"].clone(),
"validInputs",
)?;
let valid_outputs: Vec<IO> = self.try_parse_frontmatter_io(
let valid_outputs: Vec<IO> = Self::try_parse_frontmatter_io(
frontmatter_yaml[0]["orderbook"]["order"]["validOutputs"].clone(),
"validOutputs",
)?;
Expand Down Expand Up @@ -208,7 +206,7 @@ impl AddOrderArgs {

// Prepare call
let (deployer, valid_inputs, valid_outputs) =
self.try_parse_frontmatter(dotrain_doc.front_matter().as_str())?;
Self::try_parse_frontmatter(dotrain_doc.front_matter().as_str())?;
let (bytecode, constants) = self
.try_parse_rainlang(rpc_url, deployer, rainlang.clone())
.await?;
Expand Down Expand Up @@ -267,10 +265,9 @@ orderbook:
decimals: 18
vaultId: 0x2
";
let args = AddOrderArgs { dotrain: "".into() };

let (deployer, valid_inputs, valid_outputs) =
args.try_parse_frontmatter(frontmatter).unwrap();
AddOrderArgs::try_parse_frontmatter(frontmatter).unwrap();

assert_eq!(
deployer,
Expand Down
45 changes: 44 additions & 1 deletion crates/common/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::transaction::TransactionArgsError;
use crate::{add_order::AddOrderArgsError, transaction::TransactionArgsError};
use alloy_dyn_abi::JsonAbiExt;
use alloy_ethers_typecast::{client::LedgerClientError, transaction::WritableClientError};
use alloy_json_abi::Error as AlloyError;
Expand Down Expand Up @@ -40,6 +40,27 @@ pub enum AbiDecodedErrorType {
},
}

impl From<AbiDecodedErrorType> for String {
fn from(value: AbiDecodedErrorType) -> Self {
value.to_string()
}
}

impl std::fmt::Display for AbiDecodedErrorType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AbiDecodedErrorType::Unknown => {
f.write_str("native parser panicked with unknown error!")
}
AbiDecodedErrorType::Known { name, args, .. } => f.write_str(&format!(
"native parser panicked with: {}\n{}",
name,
args.join("\n")
)),
}
}
}

/// decodes an error returned from calling a contract by searching its selector in registry
pub async fn abi_decode_error<'a>(
error_data: &[u8],
Expand Down Expand Up @@ -148,6 +169,28 @@ impl<'a> From<PoisonError<MutexGuard<'a, HashMap<String, ForkedEvm>>>> for ForkC
}
}

#[derive(Debug, Error)]
pub enum ForkParseError {
#[error("ForkCall error: {0}")]
ForkCallFailed(ForkCallError<'static>),
#[error("{0}")]
AbiDecodedError(AbiDecodedErrorType),
#[error("Invalid Front Matter error: {0}")]
InvalidFrontMatter(#[from] AddOrderArgsError),
}

impl From<AbiDecodedErrorType> for ForkParseError {
fn from(value: AbiDecodedErrorType) -> Self {
Self::AbiDecodedError(value)
}
}

impl From<ForkCallError<'static>> for ForkParseError {
fn from(value: ForkCallError<'static>) -> Self {
Self::ForkCallFailed(value)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
57 changes: 57 additions & 0 deletions crates/common/src/fork.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
use super::error::ForkCallError;
use super::error::{abi_decode_error, AbiDecodedErrorType};
use crate::add_order::AddOrderArgs;
use crate::error::ForkParseError;
use alloy_primitives::hex::decode;
use alloy_sol_types::SolCall;
use forker::*;
use once_cell::sync::Lazy;
use rain_interpreter_bindings::DeployerISP::iParserCall;
use rain_interpreter_bindings::IExpressionDeployerV3::deployExpression2Call;
use rain_interpreter_bindings::IParserV1::parseCall;
use revm::primitives::Bytes;
use std::{collections::HashMap, sync::Mutex};

const FROM_ADDRESS: &str = "0x5855A7b48a1f9811392B89F18A8e27347EF84E42";

/// static hashmap of fork evm instances, used for caching instances between runs
pub static FORKS: Lazy<Mutex<HashMap<String, ForkedEvm>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
Expand Down Expand Up @@ -54,6 +63,54 @@ pub async fn fork_call<'a>(
}
}

/// checks the front matter validity and parses the given rainlang string
/// with the deployer parsed from the front matter
/// returns abi encoded expression config on Ok variant
pub async fn fork_parse_rainlang(
rainlang_string: &str,
front_matter: &str,
fork_url: &str,
fork_block_number: u64,
) -> Result<Bytes, ForkParseError> {
let deployer = AddOrderArgs::try_parse_frontmatter(front_matter)?.0;

let calldata = iParserCall {}.abi_encode();
let parser_address = fork_call(
fork_url,
fork_block_number,
&decode(FROM_ADDRESS).unwrap(),
deployer.as_slice(),
&calldata,
)
.await??;

let calldata = parseCall {
data: rainlang_string.as_bytes().to_vec(),
}
.abi_encode();
let expression_config = fork_call(
fork_url,
fork_block_number,
&decode(FROM_ADDRESS).unwrap(),
&parser_address,
&calldata,
)
.await??;

let mut calldata = deployExpression2Call::SELECTOR.to_vec();
calldata.extend_from_slice(&expression_config);
fork_call(
fork_url,
fork_block_number,
&decode(FROM_ADDRESS).unwrap(),
deployer.as_slice(),
&calldata,
)
.await??;

Ok(expression_config)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
3 changes: 3 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
'';
additionalBuildInputs = [
pkgs.typeshare
pkgs.wasm-bindgen-cli
rainix.rust-toolchain.${system}
rainix.rust-build-inputs.${system}
];
};
ob-tauri-test = rainix.mkTask.${system} {
Expand Down
Loading

0 comments on commit 5ddff74

Please sign in to comment.