Skip to content

Commit

Permalink
Add evm bid
Browse files Browse the repository at this point in the history
  • Loading branch information
danimhr committed Dec 11, 2024
1 parent 903651a commit cfada1c
Show file tree
Hide file tree
Showing 6 changed files with 154 additions and 92 deletions.
18 changes: 9 additions & 9 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion sdk/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ express-relay-api-types = { version = "0.0.0", path = "../../auction-server/api-
reqwest = { version = "0.12.9", features = ["json"] }
url = "2.5.4"
serde = { workspace = true }
strum = { workspace = true }
serde_json = { workspace = true }
tokio-tungstenite = { version = "0.24.0", features = ["native-tls"] }
tokio-stream = { workspace = true, features = ["sync"] }
Expand Down
1 change: 1 addition & 0 deletions sdk/rust/simple-searcher/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ tokio = { version = "1.42.0", features = ["macros", "rt-multi-thread"] }
time = { workspace = true }
tokio-stream = { workspace = true }
rand = "0.8.5"
clap = { version = "4.5.23", features = ["derive", "env"] }
94 changes: 76 additions & 18 deletions sdk/rust/simple-searcher/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use {
anyhow,
Result,
},
clap::Parser,
express_relay_client::{
api_types::{
opportunity::{
Expand All @@ -15,7 +16,6 @@ use {
},
ethers::types::U256,
evm::BidParamsEvm,
ChainId,
Client,
ClientConfig,
WsClient,
Expand All @@ -29,28 +29,61 @@ use {
tokio_stream::StreamExt,
};


#[derive(Parser, Clone, Debug)]
pub struct RunOptions {
/// The http url of the express relay server.
#[arg(long = "server-url")]
#[arg(env = "SERVER_URL")]
pub server_url: String,

/// EVM private key in hex format.
#[arg(long = "private-key-evm")]
#[arg(env = "PRIVATE_KEY_EVM")]
pub private_key_evm: Option<String>,

/// SVM private key in base58 format.
#[arg(long = "private-key-svm")]
#[arg(env = "PRIVATE_KEY_SVM")]
pub private_key_svm: Option<String>,

/// Chain ids to subscribe to.
#[arg(long = "chain-ids", required = true)]
#[arg(env = "CHAIN_IDS")]
pub chains: Vec<String>,
}


async fn random() -> U256 {
let mut rng = rand::thread_rng();
U256::from(rng.gen::<u128>())
}

async fn handle_opportunity(ws_client: WsClient, opportunity: Opportunity) -> Result<()> {
async fn handle_opportunity(
ws_client: WsClient,
opportunity: Opportunity,
private_key: String,
) -> Result<()> {
// Assess the opportunity to see if it is worth bidding
// For the sake of this example, we will always bid
let bid = match opportunity {
opportunity::Opportunity::Evm(opportunity) => {
// Assess opportunity
Client::new_bid(
opportunity,
BidParamsEvm {
amount: U256::from(100),
amount: U256::from(5_000_000_000_000_000_000_i128),
nonce: random().await,
deadline: U256::from(
(OffsetDateTime::now_utc() + Duration::days(1)).unix_timestamp(),
),
},
private_key,
)
.await
}
opportunity::Opportunity::Svm(opportunity) => Client::new_bid(opportunity, 2).await,
opportunity::Opportunity::Svm(opportunity) => {
Client::new_bid(opportunity, 2, private_key).await
}
}
.map_err(|e| {
println!("Failed to create bid: {:?}", e);
Expand All @@ -67,10 +100,17 @@ async fn handle_opportunity(ws_client: WsClient, opportunity: Opportunity) -> Re

#[tokio::main]
async fn main() -> Result<()> {
let args: RunOptions = RunOptions::parse();
let ws_url = if args.server_url.starts_with("http") {
args.server_url.replace("http", "ws")
} else {
args.server_url.replace("https", "wss")
};

let client = Client::try_new(ClientConfig {
http_url: "http://127.0.0.1:9000".to_string(),
ws_url: "ws://127.0.0.1:9000".to_string(),
api_key: Some("Test".to_string()),
http_url: args.server_url,
ws_url,
api_key: Some("Test".to_string()),
})
.map_err(|e| {
eprintln!("Failed to create client: {:?}", e);
Expand All @@ -79,7 +119,7 @@ async fn main() -> Result<()> {

let opportunities = client
.get_opportunities(Some(GetOpportunitiesQueryParams {
chain_id: Some(ChainId::DevelopmentSvm.to_string()),
chain_id: Some(args.chains[0].clone()),
mode: OpportunityMode::Historical,
permission_key: None,
limit: 100,
Expand All @@ -98,13 +138,10 @@ async fn main() -> Result<()> {
anyhow!("Failed to connect websocket")
})?;

ws_client
.chain_subscribe(vec![ChainId::DevelopmentEvm, ChainId::DevelopmentSvm])
.await
.map_err(|e| {
eprintln!("Failed to subscribe chains: {:?}", e);
anyhow!("Failed to subscribe chains")
})?;
ws_client.chain_subscribe(args.chains).await.map_err(|e| {
eprintln!("Failed to subscribe chains: {:?}", e);
anyhow!("Failed to subscribe chains")
})?;

let mut stream = ws_client.get_update_stream();
let mut block_hash_map = HashMap::new();
Expand All @@ -120,8 +157,29 @@ async fn main() -> Result<()> {

match update {
ServerUpdateResponse::NewOpportunity { opportunity } => {
println!("New opportunity: {:?}", opportunity);
tokio::spawn(handle_opportunity(ws_client.clone(), opportunity));
let private_key = match opportunity {
Opportunity::Evm(_) => {
println!("EVM opportunity Received");
args.private_key_evm.clone()
}
Opportunity::Svm(_) => {
println!("SVM opportunity Received");
args.private_key_svm.clone()
}
};

match private_key {
Some(private_key) => {
tokio::spawn(handle_opportunity(
ws_client.clone(),
opportunity,
private_key,
));
}
None => {
eprintln!("Private key not provided");
}
}
}
ServerUpdateResponse::SvmChainUpdate { update } => {
block_hash_map.insert(update.chain_id.clone(), update.blockhash);
Expand Down
40 changes: 19 additions & 21 deletions sdk/rust/src/evm.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use {
crate::{
ChainId,
ClientError,
},
crate::ClientError,
ethers::{
contract::abigen,
providers::{
Expand Down Expand Up @@ -30,14 +27,12 @@ use {
},
},
express_relay_api_types::opportunity::{
OpportunityCreateV1Evm,
OpportunityEvm,
OpportunityParamsEvm,
OpportunityParamsV1Evm,
},
std::{
str::FromStr,
sync::Arc,
},
std::sync::Arc,
};

abigen!(
Expand All @@ -61,20 +56,18 @@ pub struct BidParamsEvm {
pub nonce: ethers::types::U256,
}

struct Config {
weth: Address,
adapter_factory_contract: Address,
#[allow(dead_code)]
express_relay_contract: Address,
permit2: Address,
adapter_bytecode_hash: [u8; 32],
chain_id_num: u64,
pub struct Config {
pub weth: Address,
pub adapter_factory_contract: Address,
pub express_relay_contract: Address,
pub permit2: Address,
pub adapter_bytecode_hash: [u8; 32],
pub chain_id_num: u64,
}

fn get_config(chain_id: &str) -> Result<Config, ClientError> {
let chain_id = ChainId::from_str(chain_id).map_err(|_| ClientError::ChainNotSupported)?;
pub fn get_config(chain_id: &str) -> Result<Config, ClientError> {
match chain_id {
ChainId::DevelopmentEvm => Ok(Config {
"development" => Ok(Config {
weth: "0x5FC8d32690cc91D4c39d9d3abcBD16989F875707"
.parse()
.expect("Invalid Ethereum address"),
Expand Down Expand Up @@ -104,7 +97,7 @@ pub fn make_permitted_tokens(
bid_params: BidParamsEvm,
) -> Result<Vec<TokenPermissions>, ClientError> {
let config = get_config(opportunity.get_chain_id())?;
let OpportunityParamsEvm::V1(OpportunityParamsV1Evm(params)) = opportunity.params;
let params = get_params(opportunity);
let mut permitted_tokens: Vec<TokenPermissions> = params
.sell_tokens
.clone()
Expand Down Expand Up @@ -135,7 +128,7 @@ pub fn make_opportunity_execution_params(
bid_params: BidParamsEvm,
executor: Address,
) -> Result<ExecutionParams, ClientError> {
let OpportunityParamsEvm::V1(OpportunityParamsV1Evm(params)) = opportunity.params.clone();
let params = get_params(opportunity.clone());
Ok(ExecutionParams {
permit: PermitBatchTransferFrom {
permitted: make_permitted_tokens(opportunity, bid_params.clone())?,
Expand Down Expand Up @@ -282,3 +275,8 @@ pub fn make_adapter_calldata(

Ok(calldata)
}

pub fn get_params(opportunity: OpportunityEvm) -> OpportunityCreateV1Evm {
let OpportunityParamsEvm::V1(OpportunityParamsV1Evm(params)) = opportunity.params;
params
}
Loading

0 comments on commit cfada1c

Please sign in to comment.