Skip to content

Commit ecffcc3

Browse files
committed
use gas params from toml files
1 parent dbcf7e3 commit ecffcc3

File tree

4 files changed

+67
-15
lines changed

4 files changed

+67
-15
lines changed

src/chains/osmosis/osmosis_pool_service.rs

+47-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ use super::osmosis_transaction::broadcast_tx;
1111
use osmosis_std::types::osmosis::gamm::v1beta1::{MsgSwapExactAmountOut, SwapAmountOutRoute, MsgSwapExactAmountIn, SwapAmountInRoute};
1212
use osmosis_std::types::cosmos::base::v1beta1::Coin as OsmosisCoin;
1313

14+
use serde_json::json;
15+
use cosmrs::proto::cosmos::tx::v1beta1::{SimulateRequest, SimulateResponse};
16+
1417
use cosmrs::tendermint::{block::Height, chain::Id};
1518
use cosmrs::tx::{Body, Fee, AuthInfo, SignDoc, Tx};
1619
use cosmrs::Any;
@@ -22,6 +25,46 @@ use prost::Message;
2225

2326
use reqwest::Client;
2427

28+
// TODO: WIP Function to simulate a transaction cost
29+
pub async fn simulate_tx(tx: Tx) -> Result<()> {
30+
// Step 1: Encode the transaction into the protobuf format
31+
let proto_tx: cosmrs::proto::cosmos::tx::v1beta1::Tx = tx.into();
32+
let mut tx_bytes = Vec::new();
33+
proto_tx.encode(&mut tx_bytes).map_err(|e| anyhow::anyhow!("Failed to encode Tx: {}", e))?;
34+
35+
// Step 2: Convert the tx bytes to Base64
36+
let tx_base64 = base64::encode(&tx_bytes);
37+
38+
// Step 3: Prepare the request body
39+
let simulate_body = json!({
40+
"tx_bytes": tx_base64
41+
});
42+
43+
// Step 4: Make the request to the simulate endpoint
44+
let client = Client::new();
45+
let simulate_url = "https://lcd.osmotest5.osmosis.zone/cosmos/tx/v1beta1/simulate".to_string();
46+
let response = client
47+
.post(simulate_url)
48+
.json(&simulate_body)
49+
.send()
50+
.await?;
51+
52+
// Step 5: Parse the response
53+
let response_json = response.json::<serde_json::Value>().await.map_err(|e| anyhow::anyhow!("Failed to parse response: {}", e))?;
54+
55+
// Step 6: Extract relevant data
56+
if let Some(simulate_response) = response_json.get("gas_info") {
57+
let gas_used = simulate_response["gas_used"].as_str();
58+
let gas_wanted = simulate_response["gas_wanted"].as_str();
59+
60+
println!("Gas Used: {:?}, Gas Wanted: {:?}", gas_used, gas_wanted);
61+
} else {
62+
println!("Failed to get gas info from response: {:?}", response_json);
63+
}
64+
65+
Ok(())
66+
}
67+
2568
pub async fn perform_swap(
2669
signer: &Signer,
2770
pool_id: u64,
@@ -44,7 +87,7 @@ pub async fn perform_swap(
4487

4588
// Step 3. Get the current block height
4689
let current_height = get_current_block_height().await.map_err(|e| anyhow::anyhow!("Failed to get current block height: {}", e))?;
47-
let timeout_height = current_height + 1000; // Set a future timeout height
90+
let timeout_height = current_height + 200; // Set a future timeout height
4891

4992
// Step 4. Create TxBody
5093
let tx_body = Body {
@@ -62,8 +105,8 @@ pub async fn perform_swap(
62105
// Step 6: Create AuthInfo with fee details
63106
let fee = Fee::from_amount_and_gas(CosmosCoin {
64107
denom: "uosmo".parse().unwrap(),
65-
amount: Decimal::from(320_000u64),
66-
}, 350_000);
108+
amount: Decimal::from(CONFIG.gas_config.amount),
109+
}, CONFIG.gas_config.gas_limit);
67110
let auth_info = AuthInfo {
68111
signer_infos: vec![signer_info],
69112
fee,
@@ -77,6 +120,7 @@ pub async fn perform_swap(
77120

78121
// Step 8: Create and broadcast the transaction
79122
let tx_parsed = Tx::from_bytes(&tx_bytes).map_err(|e| anyhow::anyhow!("Failed to parse transaction bytes: {}", e))?;
123+
// simulate_tx(tx_parsed.clone()).await?;
80124
broadcast_tx(tx_parsed, sender_address, pool_id, coin_in, coin_out, amount, swap_type, min_price).await
81125
}
82126

src/chains/osmosis/osmosis_transaction.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use regex::Regex;
1414
use cosmrs::tx::Tx;
1515
use prost::Message;
1616
use crate::utils::format_token_amount_with_denom;
17-
use log::{info, error, warn};
17+
use log::{info, error, warn, debug};
1818

1919

2020
#[derive(Serialize, Deserialize, Debug)]
@@ -53,7 +53,7 @@ pub async fn broadcast_tx(
5353
let broadcast_url = get_osmosis_broadcast_tx_url();
5454
let broadcast_body = json!({
5555
"tx_bytes": tx_base64,
56-
"mode": 2
56+
"mode": "BROADCAST_MODE_ASYNC"
5757
});
5858
let response = client.post(broadcast_url)
5959
.json(&broadcast_body)
@@ -71,8 +71,14 @@ pub async fn broadcast_tx(
7171
info!(">>> Transaction broadcasted");
7272

7373
// Store the broadcasted transaction
74-
let txhash = response_json["tx_response"]["txhash"].as_str().unwrap();
75-
let code = response_json["tx_response"]["code"].as_u64();
74+
let txhash = match response_json["tx_response"]["txhash"].as_str() {
75+
Some(hash) => hash,
76+
None => return Err(anyhow::anyhow!("Failed to get txhash from response")),
77+
};
78+
let code = match response_json["tx_response"]["code"].as_u64() {
79+
Some(code) => Some(code),
80+
None => return Err(anyhow::anyhow!("Failed to get code from response")),
81+
};
7682
let raw_log = response_json["tx_response"]["raw_log"].as_str().map(String::from);
7783
let _ = store_broadcasted_transaction(
7884
sender_address,
@@ -272,7 +278,7 @@ async fn poll_transaction_status(txhash: &str, account_id: &str) -> Result<Optio
272278
Ok((code, raw_log, gas_used, tokens_in, tokens_out)) => {
273279
if code.is_some() {
274280
// Transaction was executed
275-
update_transaction_status(txhash, account_id, "executed", code, raw_log, gas_used, tokens_in, tokens_out).await?;
281+
update_transaction(txhash, account_id, "executed", code, raw_log, gas_used, tokens_in, tokens_out).await?;
276282
return Ok(code);
277283
} else {
278284
info!("... Transaction not yet confirmed");
@@ -290,8 +296,8 @@ async fn poll_transaction_status(txhash: &str, account_id: &str) -> Result<Optio
290296
}
291297

292298

293-
// Function to update the transaction status in the JSON file
294-
async fn update_transaction_status(
299+
// Function to update the transaction details in the JSON file
300+
async fn update_transaction(
295301
txhash: &str,
296302
account_id: &str,
297303
status: &str,
@@ -320,6 +326,8 @@ async fn update_transaction_status(
320326
transaction["tokens_in"] = json!(tokens_in);
321327
transaction["tokens_out"] = json!(tokens_out);
322328

329+
debug!("update_transaction: {}", transaction);
330+
323331
// Write the updated transactions back to the file
324332
fs::write(file_path, serde_json::to_string_pretty(&transactions)?)?;
325333
}
@@ -331,7 +339,7 @@ async fn update_transaction_status(
331339
// Function to handle timeout scenario
332340
async fn update_transaction_with_timeout(txhash: &str) -> Result<(), Box<dyn std::error::Error>> {
333341
// Implement your logic to update the transaction with timeout error here
334-
update_transaction_status(txhash, "account_id", "timeout", None, None, None, None, None).await?;
342+
update_transaction(txhash, "account_id", "timeout", None, None, None, None, None).await?;
335343
Ok(())
336344
}
337345

src/config/prod.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ osmosis_tx_details_url = "https://lcd.osmosis.zone/cosmos/tx/v1beta1/txs/{}"
88

99
[gas_config]
1010
token = "OSMO"
11-
amount = 320000
12-
gas_limit = 350000
11+
amount = 50_000
12+
gas_limit = 300_000
1313

1414
[env_constants]
1515
pool_id = 1721

src/config/test.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ osmosis_tx_details_url = "https://lcd.osmotest5.osmosis.zone/cosmos/tx/v1beta1/t
88

99
[gas_config]
1010
token = "TOSMO"
11-
amount = 320_000
12-
gas_limit = 350_000
11+
amount = 50_000
12+
gas_limit = 250_00
1313

1414
[env_constants]
1515
pool_id = 15

0 commit comments

Comments
 (0)