Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ serde = { version = "1.0.152", features = ["derive"] }
toml = "0.5.10"
futures = "0.3"
url = "2.3.1"
bigdecimal = "0.3.0"
anyhow = "1.0"
serenity = "0.11.5"
serde_json = "1.0.96"
lazy_static = "1.4.0"
reqwest = "0.11.18"
num-integer = "0.1.45"
starknet = { git = "https://github.com/xJonathanLEI/starknet-rs", rev = "c974e5cb42e8d8344cee910b76005ec46b4dd3ed" }
starknet-id = { git = "https://github.com/starknet-id/starknetid.rs", rev = "2b30c2453b96789a628c86d2edebb1023fa2e77d" }
starknet = { git = "https://github.com/xJonathanLEI/starknet-rs", rev = "85906137d634c86b07de20fa33071e5cf186ce21" }
starknet-id = { git = "https://github.com/starknet-id/starknetid.rs", rev = "04958762b3085311d4f0d865941295a6411a694b" }
serde_derive = "1.0.183"
env_logger = "0.10.0"
tonic = "0.10.0"
prost = "0.12.1"
bigdecimal = { version = "0.4", features = ["serde"] }

[build-dependencies]
tonic-build = "0.10.0"
101 changes: 46 additions & 55 deletions bot/src/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ use chrono::Utc;
use futures::stream::{self, StreamExt};
use mongodb::options::FindOneOptions;
use starknet::accounts::ConnectedAccount;
use starknet::core::types::Call;
use starknet::{
accounts::{Account, Call, SingleOwnerAccount},
core::types::FieldElement,
accounts::{Account, SingleOwnerAccount},
core::types::Felt,
macros::selector,
providers::{jsonrpc::HttpTransport, JsonRpcClient},
signers::LocalWallet,
Expand All @@ -34,7 +35,7 @@ use crate::utils::{from_uint256, hex_to_bigdecimal, to_uint256};
use crate::{config::Config, models::AppState};

lazy_static::lazy_static! {
static ref RENEW_TIME: FieldElement = FieldElement::from_dec_str("365").unwrap();
static ref RENEW_TIME: Felt = Felt::from_dec_str("365").unwrap();
}

/// Filters out entries that were renewed less than 364 days ago
Expand All @@ -52,15 +53,15 @@ pub async fn get_domains_ready_for_renewal(
config: &Config,
state: &Arc<AppState>,
logger: &Logger,
) -> Result<HashMap<FieldElement, AggregateResults>> {
) -> Result<HashMap<Felt, AggregateResults>> {
let mut results = get_auto_renewal_data(config, state).await?;
let mut results_altcoins = get_auto_renewal_altcoins_data(config, state).await?;

// Filter out entries that were renewed less than 364 days ago
filter_recent_renewals(&mut results);
filter_recent_renewals(&mut results_altcoins);

let mut grouped_results: HashMap<FieldElement, AggregateResults> = HashMap::new();
let mut grouped_results: HashMap<Felt, AggregateResults> = HashMap::new();

if results.is_empty() && results_altcoins.is_empty() {
logger.warning("No domains to renew".to_string());
Expand All @@ -81,14 +82,12 @@ pub async fn get_domains_ready_for_renewal(
// merge all results together
results.extend(results_altcoins.iter().cloned());

println!("renewers_mapping: {:?}", config.renewers_mapping);

// Fetch balances for all renewers
let renewer_and_erc20: Vec<(String, String)> = results
.iter()
.map(|result| {
let test = config
.renewers_mapping
.get(&result.auto_renew_contract)
.unwrap();
(
result.renewer_address.clone(),
// get the erc20 address for the given auto_renew_contract
Expand Down Expand Up @@ -138,25 +137,24 @@ pub async fn get_domains_ready_for_renewal(
.cloned()
.expect("Balance not found for this erc20");
let renewal_price_eth = get_renewal_price_eth(result.domain.clone());
let renewal_price =
if FieldElement::from_hex_be(erc20).unwrap() == config.contract.erc20 {
renewal_price_eth
} else {
match get_altcoin_quote(config, erc20.to_string()).await {
Ok(quote) => {
(quote * renewal_price_eth)
/ BigInt::from_str("1000000000000000000").unwrap()
}
Err(e) => {
// in case get_altcoin_quote endpoint returns an error we panic with the error
logger.severe(format!(
"Error while fetching quote on starknetid server: {:?}",
e
));
panic!("Error while fetching quote on starknetid server: {:?}", e)
}
let renewal_price = if Felt::from_hex(erc20).unwrap() == config.contract.erc20 {
renewal_price_eth
} else {
match get_altcoin_quote(config, erc20.to_string()).await {
Ok(quote) => {
(quote * renewal_price_eth)
/ BigInt::from_str("1000000000000000000").unwrap()
}
};
Err(e) => {
// in case get_altcoin_quote endpoint returns an error we panic with the error
logger.severe(format!(
"Error while fetching quote on starknetid server: {:?}",
e
));
panic!("Error while fetching quote on starknetid server: {:?}", e)
}
}
};
let output = process_aggregate_result(
state,
result.clone(),
Expand Down Expand Up @@ -227,7 +225,7 @@ async fn process_aggregate_result(
return None;
}

let renewer_addr = FieldElement::from_hex_be(&result.renewer_address).unwrap();
let renewer_addr = Felt::from_hex(&result.renewer_address).unwrap();
// map the vec of approval_values to get the approval_value for the erc20_addr selected
let erc20_allowance = if let Some(approval_value) = result
.approval_values
Expand All @@ -243,9 +241,9 @@ async fn process_aggregate_result(

// Check user meta hash
let mut tax_price = BigDecimal::from(0);
let mut meta_hash = FieldElement::ZERO;
let mut meta_hash = Felt::ZERO;
if let Some(hash) = result.meta_hash {
meta_hash = FieldElement::from_hex_be(&hash).unwrap();
meta_hash = Felt::from_hex(&hash).unwrap();
if hash != "0" {
let decimal_meta_hash =
BigInt::parse_bytes(hash.trim_start_matches("0x").as_bytes(), 16).unwrap();
Expand Down Expand Up @@ -322,7 +320,7 @@ pub async fn renew_domains(
config: &Config,
account: &SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
mut aggregate_results: AggregateResults,
auto_renew_contract: &FieldElement,
auto_renew_contract: &Felt,
logger: &Logger,
) -> Result<()> {
logger.info(format!(
Expand All @@ -341,13 +339,12 @@ pub async fn renew_domains(
&& !aggregate_results.meta_hashes.is_empty()
{
let size = aggregate_results.domains.len().min(75);
let domains_to_renew: Vec<FieldElement> =
aggregate_results.domains.drain(0..size).collect();
let renewers: Vec<FieldElement> = aggregate_results.renewers.drain(0..size).collect();
let domains_to_renew: Vec<Felt> = aggregate_results.domains.drain(0..size).collect();
let renewers: Vec<Felt> = aggregate_results.renewers.drain(0..size).collect();
let domain_prices: Vec<BigDecimal> =
aggregate_results.domain_prices.drain(0..size).collect();
let tax_prices: Vec<BigDecimal> = aggregate_results.tax_prices.drain(0..size).collect();
let meta_hashes: Vec<FieldElement> = aggregate_results.meta_hashes.drain(0..size).collect();
let meta_hashes: Vec<Felt> = aggregate_results.meta_hashes.drain(0..size).collect();

match send_transaction(
account,
Expand Down Expand Up @@ -379,7 +376,7 @@ pub async fn renew_domains(
});

// We only inscrease nonce if no error occurred in the previous transaction
nonce += FieldElement::ONE;
nonce += Felt::ONE;
}
Err(e) => {
if e.to_string().contains("Error while estimating fee") {
Expand Down Expand Up @@ -436,20 +433,16 @@ pub async fn renew_domains(

pub async fn send_transaction(
account: &SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
auto_renew_contract: FieldElement,
auto_renew_contract: Felt,
aggregate_results: AggregateResults,
nonce: FieldElement,
) -> Result<FieldElement> {
let mut calldata: Vec<FieldElement> = Vec::new();
calldata
.push(FieldElement::from_dec_str(&aggregate_results.domains.len().to_string()).unwrap());
nonce: Felt,
) -> Result<Felt> {
let mut calldata: Vec<Felt> = Vec::new();
calldata.push(Felt::from_dec_str(&aggregate_results.domains.len().to_string()).unwrap());
calldata.extend_from_slice(&aggregate_results.domains);
calldata
.push(FieldElement::from_dec_str(&aggregate_results.renewers.len().to_string()).unwrap());
calldata.push(Felt::from_dec_str(&aggregate_results.renewers.len().to_string()).unwrap());
calldata.extend_from_slice(&aggregate_results.renewers);
calldata.push(
FieldElement::from_dec_str(&aggregate_results.domain_prices.len().to_string()).unwrap(),
);
calldata.push(Felt::from_dec_str(&aggregate_results.domain_prices.len().to_string()).unwrap());

println!("domains:");
for x in &aggregate_results.domains {
Expand Down Expand Up @@ -482,31 +475,29 @@ pub async fn send_transaction(
calldata.push(high);
}

calldata
.push(FieldElement::from_dec_str(&aggregate_results.tax_prices.len().to_string()).unwrap());
calldata.push(Felt::from_dec_str(&aggregate_results.tax_prices.len().to_string()).unwrap());
for tax_price in &aggregate_results.tax_prices {
let (low, high) = to_uint256(tax_price.to_bigint().unwrap());
calldata.push(low);
calldata.push(high);
}
calldata.push(
FieldElement::from_dec_str(&aggregate_results.meta_hashes.len().to_string()).unwrap(),
);
calldata.push(Felt::from_dec_str(&aggregate_results.meta_hashes.len().to_string()).unwrap());
calldata.extend_from_slice(&aggregate_results.meta_hashes);

let execution = account
.execute(vec![Call {
.execute_v3(vec![Call {
to: auto_renew_contract,
selector: selector!("batch_renew"),
calldata: calldata.clone(),
}])
.fee_estimate_multiplier(5.0f64);
.gas_estimate_multiplier(5.0f64);
// .fee_estimate_multiplier(5.0f64);

match execution.estimate_fee().await {
Ok(_) => match execution
.nonce(nonce)
// harcode max fee to 10$ = 0.0028 ETH
.max_fee(FieldElement::from(2800000000000000_u64))
// .max_fee(Felt::from(2800000000000000_u64))
.send()
.await
{
Expand Down
24 changes: 12 additions & 12 deletions bot/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use serde::de::MapAccess;
use serde::de::Visitor;
use serde::Deserialize;
use serde::Deserializer;
use starknet::core::types::FieldElement;
use starknet::core::types::Felt;
use std::collections::HashMap;
use std::env;
use std::fmt;
Expand All @@ -18,12 +18,12 @@ macro_rules! pub_struct {
}

pub_struct!(Clone, Deserialize; Contract {
starknetid: FieldElement,
naming: FieldElement,
renewal: FieldElement,
erc20: FieldElement,
pricing: FieldElement,
multicall: FieldElement,
starknetid: Felt,
naming: Felt,
renewal: Felt,
erc20: Felt,
pricing: Felt,
multicall: Felt,
});

pub_struct!(Clone, Deserialize; Database {
Expand All @@ -34,8 +34,8 @@ pub_struct!(Clone, Deserialize; Database {
});

pub_struct!(Clone, Deserialize; MyAccount {
private_key: FieldElement,
address: FieldElement,
private_key: Felt,
address: Felt,
});

pub_struct!(Clone, Deserialize; Renewals {
Expand Down Expand Up @@ -71,8 +71,8 @@ pub_struct!(Clone, Deserialize; Server {
});

pub_struct!(Clone, Deserialize; Renewer {
address: FieldElement,
renewal_contract: FieldElement,
address: Felt,
renewal_contract: Felt,
});

pub_struct!(Clone; Config {
Expand All @@ -84,7 +84,7 @@ pub_struct!(Clone; Config {
rpc: Rpc,
watchtower: Watchtower,
server: Server,
renewers_mapping: HashMap<FieldElement, FieldElement>,
renewers_mapping: HashMap<Felt, Felt>,
});

impl<'de> Deserialize<'de> for Config {
Expand Down
22 changes: 11 additions & 11 deletions bot/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bigdecimal::BigDecimal;
use bson::DateTime;
use mongodb::Database;
use serde::{Deserialize, Serialize};
use starknet::core::types::FieldElement;
use starknet::core::types::Felt;

pub struct AppState {
pub db: Database,
Expand Down Expand Up @@ -57,27 +57,27 @@ pub struct DomainAggregateResult {
pub last_renewal: Option<i64>,
pub meta_hash: Option<String>,
pub _cursor: Cursor,
pub auto_renew_contract: FieldElement,
pub auto_renew_contract: Felt,
pub approval_values: Vec<AutoRenewAllowance>,
}

pub struct AggregateResult {
pub domain: FieldElement,
pub renewer_addr: FieldElement,
pub domain: Felt,
pub renewer_addr: Felt,
pub domain_price: BigDecimal,
pub tax_price: BigDecimal,
pub meta_hash: FieldElement,
pub auto_renew_contract: FieldElement,
pub meta_hash: Felt,
pub auto_renew_contract: Felt,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AggregateResults {
pub domains: Vec<FieldElement>,
pub renewers: Vec<FieldElement>,
pub domains: Vec<Felt>,
pub renewers: Vec<Felt>,
pub domain_prices: Vec<BigDecimal>,
pub tax_prices: Vec<BigDecimal>,
pub meta_hashes: Vec<FieldElement>,
pub auto_renew_contracts: Vec<FieldElement>,
pub meta_hashes: Vec<Felt>,
pub auto_renew_contracts: Vec<Felt>,
}

#[derive(Serialize, Deserialize, Debug)]
Expand All @@ -102,7 +102,7 @@ pub struct States {

#[derive(Debug, Clone)]
pub struct TxResult {
pub tx_hash: FieldElement,
pub tx_hash: Felt,
pub reverted: Option<bool>,
pub revert_reason: Option<String>,
pub domains_renewed: usize,
Expand Down
3 changes: 1 addition & 2 deletions bot/src/pipelines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use anyhow::Result;
use bson::{doc, Bson};
use chrono::{Duration, Utc};
use futures::TryStreamExt;
use starknet::core::types::FieldElement;
use std::sync::Arc;

use crate::{
Expand All @@ -18,7 +17,7 @@ pub async fn get_auto_renewal_data(
let auto_renews_collection = state.db.collection::<Domain>("auto_renew_flows");
let min_expiry_date = Utc::now() + Duration::days(config.renewals.expiry_days);
let erc20_addr = to_hex(config.contract.erc20);
let auto_renew_contract = FieldElement::to_string(&config.contract.renewal);
let auto_renew_contract = to_hex(config.contract.renewal);
println!("timestamp: {}", min_expiry_date.timestamp());
// Define aggregate pipeline
let pipeline = vec![
Expand Down
Loading