Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Siddharth2207 committed Dec 27, 2023
1 parent 192f30d commit 8be3a1f
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 53 deletions.
11 changes: 7 additions & 4 deletions orderbook-rs/Cargo.lock

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

3 changes: 3 additions & 0 deletions orderbook-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ alloy-primitives = { version = "0.5.3" }
alloy-sol-types = { version = "0.5.3", features = ["json"] }
alloy-dyn-abi = { version = "0.5.3"}
hex = "0.4.3"
rustc-hex = "2.1.0"
url = "2.5.0"
thiserror = "1.0.52"
43 changes: 43 additions & 0 deletions orderbook-rs/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use thiserror::Error;
use url::ParseError;
use ethers::contract::ContractError;
use ethers::providers::ProviderError;
use ethers::providers::{Http, Provider};
use rustc_hex::FromHexError;
use ethers::middleware::signer::SignerMiddlewareError;
use ethers::signers::Ledger;


/// RainOrderbookError
/// Enum representing errors thrown by the crate
#[derive(Error, Debug)]
pub enum RainOrderbookError{
#[error("Invalid RPC URL")]
InvalidRPC{
#[from]
source: ParseError
},
#[error("Invalid Contract Function Call")]
InvalidContractFunctionCall{
#[from]
source: ContractError<Provider<Http>>
},
#[error("Invalid Address")]
InvalidAddress{
#[from]
source: FromHexError
},
#[error("Failed to confirm transaction")]
TransactionConfirmationError{
#[from]
source: ProviderError
},
#[error("Error in Transaction")]
TransactionError{
#[from]
source: SignerMiddlewareError<Provider<Http>, Ledger>
},
#[error("Failed to fetch Transaction Receipt")]
TransactionReceiptError,

}
12 changes: 7 additions & 5 deletions orderbook-rs/src/gasoracle/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use ethers::middleware::gas_oracle::GasCategory;
use ethers::prelude::gas_oracle::blocknative::Response as BlockNativeResponse;
use reqwest::{header::AUTHORIZATION, Client};
use url::Url;

/// Bloacknative Base Url for fetching blockprices
static BLOCKNATIVE_BLOCKPRICES_URL: &'static str = "https://api.blocknative.com/gasprices/blockprices";

/// Blocknative Gas Oracle.
/// Returns max priority fee and max fee from blocknative api.
Expand All @@ -13,11 +17,9 @@ pub async fn gas_price_oracle(
api_key: Option<String>,
chain_id: u64,
) -> anyhow::Result<(f64, f64)> {
let client = Client::new();
let url = format!(
"{}{}",
"https://api.blocknative.com/gasprices/blockprices?chainid=", chain_id
);
let client = Client::new();
let mut url = Url::parse(BLOCKNATIVE_BLOCKPRICES_URL.into())? ;
url.set_query(Some(format!("chainid={}",chain_id).as_str()));
let mut request = client.get(url);
if let Some(api_key) = api_key.as_ref() {
request = request.header(AUTHORIZATION, api_key);
Expand Down
42 changes: 19 additions & 23 deletions orderbook-rs/src/interpreter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
use crate::registry::{IExpressionDeployerV3, IParserV1};
use crate::{registry::{IExpressionDeployerV3, IParserV1}, errors::RainOrderbookError};
use alloy_primitives::{Address, Bytes, U256};
use anyhow::anyhow;
use ethers::{
providers::{Http, Provider},
types::H160,
};
use std::str::FromStr;
use std::sync::Arc;
use tracing::error;

/// Get RainInterpreterNPE2, RainterpreterStoreNPE2 and RainterpreterParserNPE2 addresses corresponding to a RainterpreterExpressionDeployerNPE2 contract.
///
Expand All @@ -18,38 +16,39 @@ use tracing::error;
pub async fn get_disp(
deployer_npe2: Address,
rpc_url: String,
) -> anyhow::Result<(Address, Address, Address)> {
) -> Result<(Address, Address, Address),RainOrderbookError> {
let provider = match Provider::<Http>::try_from(rpc_url.clone()) {
Ok(provider) => provider,
Err(err) => {
error!("INVALID RPC URL");
return Err(anyhow!(err));
Ok(provider) => provider,
Err(err) => {
return Err(RainOrderbookError::InvalidRPC { source: err })
}
};

let deployer_npe2_address = H160::from_str(&deployer_npe2.to_string()).unwrap();
let deployer_npe2_address = match H160::from_str(&deployer_npe2.to_string()){
Ok(deployer) => deployer,
Err(err) => {
return Err(RainOrderbookError::InvalidAddress { source: err })
}
};
let deployer_npe2 =
IExpressionDeployerV3::new(deployer_npe2_address, Arc::new(provider.clone()));

let interpreter = match deployer_npe2.i_interpreter().call().await {
Ok(i_interpreter) => i_interpreter,
Err(err) => {
error!("iInterpreter");
return Err(anyhow!(err));
Err(err) => {
return Err(RainOrderbookError::InvalidContractFunctionCall { source: err })
}
};
let store = match deployer_npe2.i_store().call().await {
Ok(i_store) => i_store,
Err(err) => {
error!("iStore");
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidContractFunctionCall { source: err })
}
};
let parser = match deployer_npe2.i_parser().call().await {
Ok(i_parser) => i_parser,
Err(err) => {
error!("iParser");
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidContractFunctionCall { source: err })
}
};

Expand All @@ -70,20 +69,18 @@ pub async fn parse_rainstring(
parser_address: Address,
rainstring: String,
rpc_url: String,
) -> anyhow::Result<(Bytes, Vec<U256>)> {
) -> Result<(Bytes, Vec<U256>),RainOrderbookError> {
let provider = match Provider::<Http>::try_from(rpc_url.clone()) {
Ok(provider) => provider,
Err(err) => {
error!("INVALID RPC URL");
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidRPC { source: err })
}
};

let parser_address = match H160::from_str(&parser_address.to_string()) {
Ok(parser) => parser,
Err(err) => {
error!("INVALID PARSER");
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidAddress { source: err })
}
};
let rain_parser = IParserV1::new(parser_address, Arc::new(provider.clone()));
Expand All @@ -95,8 +92,7 @@ pub async fn parse_rainstring(
{
Ok(parse_result) => parse_result,
Err(err) => {
error!("FAILED TO PARSE");
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidContractFunctionCall { source: err })
}
};

Expand Down
1 change: 1 addition & 0 deletions orderbook-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pub mod interpreter;
pub mod orderbook;
pub mod registry;
pub mod transaction;
pub mod errors;
13 changes: 5 additions & 8 deletions orderbook-rs/src/orderbook/add_order/v3.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use crate::{
interpreter::{get_disp, parse_rainstring},
registry::IOrderBookV3::{self, EvaluableConfigV3, OrderConfigV2, IO},
registry::IOrderBookV3::{self, EvaluableConfigV3, OrderConfigV2, IO}, errors::RainOrderbookError,
};
use alloy_primitives::Address;
use alloy_sol_types::SolCall;
use anyhow::anyhow;
use tracing::error;


/// Returns [IOrderBookV3::addOrderCall] transaction data encoded with
/// the function selector, encoding [IOrderBookV3::OrderConfigV2] built from
Expand All @@ -24,20 +23,18 @@ pub async fn add_ob_order(
output_vaults: Vec<IO>,
rainlang_order_string: String,
rpc_url: String,
) -> anyhow::Result<Vec<u8>> {
) -> Result<Vec<u8>,RainOrderbookError> {
let (_, _, rain_parser) = match get_disp(deployer_address.clone(), rpc_url.clone()).await {
Ok(parse_result) => parse_result,
Err(err) => {
error!("DISP");
return Err(anyhow!(err));
return Err(err)
}
};
let (bytecode, constants) =
match parse_rainstring(rain_parser, rainlang_order_string, rpc_url.clone()).await {
Ok(parse_result) => parse_result,
Err(err) => {
error!("FAILED TO PARSE");
return Err(anyhow!(err));
return Err(err)
}
};

Expand Down
26 changes: 13 additions & 13 deletions orderbook-rs/src/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
use alloy_primitives::{Address, U256};

use anyhow::anyhow;
// use anyhow::anyhow;
use ethers::prelude::SignerMiddleware;
use ethers::types::TransactionReceipt;
use ethers::{
providers::{Http, Middleware, Provider},
types::{Eip1559TransactionRequest, H160, U64},
utils::parse_units,
};
use ethers_signers::Ledger;
use std::str::FromStr;
use tracing::{error, info, warn};
use tracing::{info, warn};

use crate::errors::RainOrderbookError;
use crate::gasoracle::gas_price_oracle;

/// Sign and submit transaction on chain via [Ledger] wallet.
Expand All @@ -30,12 +32,11 @@ pub async fn execute_transaction(
rpc_url: String,
wallet: Ledger,
blocknative_api_key: Option<String>,
) -> anyhow::Result<()> {
) -> Result<TransactionReceipt,RainOrderbookError> {
let provider = match Provider::<Http>::try_from(rpc_url.clone()) {
Ok(provider) => provider,
Err(err) => {
error!("INVALID RPC URL: {}", err);
return Err(anyhow!(err));
return Err(RainOrderbookError::InvalidRPC { source: err })
}
};

Expand Down Expand Up @@ -67,32 +68,31 @@ pub async fn execute_transaction(

let tx_result = client.send_transaction(tx, None).await;

match tx_result {
let receipt = match tx_result {
Ok(tx_result) => {
info!("Transaction submitted. Awaiting block confirmations...");
let approve_receipt = match tx_result.confirmations(1).await {
Ok(receipt) => match receipt {
Some(receipt) => receipt,
None => {
error!("FAILED TO FETCH RECEIPT");
return Err(anyhow!("Failed to fetch receipt."));
return Err(RainOrderbookError::TransactionReceiptError)
}
},
Err(err) => {
error!("FAILED TO CONFIRM TRANSACTION : {}", err);
return Err(anyhow!(err));
return Err(RainOrderbookError::TransactionConfirmationError { source: err })
}
};
info!("Transaction Confirmed!!");
info!(
"✅ Hash : 0x{}",
hex::encode(approve_receipt.transaction_hash.as_bytes().to_vec())
);
approve_receipt
}
Err(err) => {
error!("TRANSACTION REJECTED : {}", err);
return Err(RainOrderbookError::TransactionError { source: err })
}
}
};

Ok(())
Ok(receipt)
}

0 comments on commit 8be3a1f

Please sign in to comment.