Skip to content

Commit a20a0c8

Browse files
committed
refactor: leverage StacksRpc
1 parent 059faea commit a20a0c8

File tree

7 files changed

+114
-144
lines changed

7 files changed

+114
-144
lines changed

src/indexer/chains/bitcoin.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub fn standardize_bitcoin_block(
3939
let block = rpc.get_block(&block_hash).unwrap();
4040

4141
for txdata in block.txdata.iter() {
42+
// TODO: retrieve stacks transactions
4243
// let _ = tx.send(DevnetEvent::debug(format!(
4344
// "Tx.out: {:?}", txdata.output
4445
// )));

src/indexer/chains/stacks.rs

Lines changed: 29 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::types::{
55
Operation, OperationIdentifier, OperationStatusKind, OperationType, StacksBlockData,
66
StacksBlockMetadata, StacksTransactionData, StacksTransactionMetadata, TransactionIdentifier,
77
};
8-
use crate::utils::stacks::{transactions, StacksRpc};
8+
use crate::utils::stacks::StacksRpc;
99
use clarity_repl::clarity::codec::transaction::TransactionPayload;
1010
use clarity_repl::clarity::codec::{StacksMessageCodec, StacksTransaction};
1111
use clarity_repl::clarity::types::Value as ClarityValue;
@@ -299,62 +299,33 @@ pub fn get_standardized_fungible_currency_from_asset_class_id(
299299
None => {
300300
let comps = asset_class_id.split("::").collect::<Vec<&str>>();
301301
let principal = comps[0].split(".").collect::<Vec<&str>>();
302-
303-
let get_symbol_request_url = format!(
304-
"{}/v2/contracts/call-read/{}/{}/get-symbol",
305-
node_url, principal[0], principal[1],
306-
);
307-
308-
println!("get_standardized_fungible_currency_from_asset_class_id");
309-
310-
let symbol_res: ContractReadonlyCall = reqwest::blocking::get(&get_symbol_request_url)
311-
.expect("Unable to retrieve account")
312-
.json()
313-
.expect("Unable to parse contract");
314-
315-
let raw_value = match symbol_res.result.strip_prefix("0x") {
316-
Some(raw_value) => raw_value,
317-
_ => panic!(),
318-
};
319-
let value_bytes = match hex_bytes(&raw_value) {
320-
Ok(bytes) => bytes,
321-
_ => panic!(),
322-
};
323-
324-
let symbol = match ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) {
325-
Ok(value) => value.expect_result_ok().expect_u128(),
326-
_ => panic!(),
327-
};
328-
329-
let get_decimals_request_url = format!(
330-
"{}/v2/contracts/call-read/{}/{}/get-decimals",
331-
node_url, principal[0], principal[1],
332-
);
333-
334-
let decimals_res: ContractReadonlyCall =
335-
reqwest::blocking::get(&get_decimals_request_url)
336-
.expect("Unable to retrieve account")
337-
.json()
338-
.expect("Unable to parse contract");
339-
340-
let raw_value = match decimals_res.result.strip_prefix("0x") {
341-
Some(raw_value) => raw_value,
342-
_ => panic!(),
343-
};
344-
let value_bytes = match hex_bytes(&raw_value) {
345-
Ok(bytes) => bytes,
346-
_ => panic!(),
347-
};
348-
349-
let value = match ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) {
350-
Ok(value) => value.expect_result_ok().expect_u128(),
351-
_ => panic!(),
352-
};
353-
354-
let entry = AssetClassCache {
355-
symbol: format!("{}", symbol),
356-
decimals: value as u8,
357-
};
302+
let contract_address = principal[0];
303+
let contract_name = principal[1];
304+
305+
let stacks_rpc = StacksRpc::new(&node_url);
306+
let value = stacks_rpc
307+
.call_read_only_fn(
308+
&contract_address,
309+
&contract_name,
310+
"get-symbol",
311+
vec![],
312+
contract_address,
313+
)
314+
.expect("Unable to retrieve symbol");
315+
let symbol = value.expect_result_ok().expect_ascii();
316+
317+
let value = stacks_rpc
318+
.call_read_only_fn(
319+
&contract_address,
320+
&contract_name,
321+
"get-decimals",
322+
vec![],
323+
&contract_address,
324+
)
325+
.expect("Unable to retrieve decimals");
326+
let decimals = value.expect_result_ok().expect_u128() as u8;
327+
328+
let entry = AssetClassCache { symbol, decimals };
358329

359330
let currency = Currency {
360331
symbol: entry.symbol.clone(),
@@ -385,7 +356,7 @@ pub fn get_standardized_fungible_currency_from_asset_class_id(
385356
pub fn get_standardized_non_fungible_currency_from_asset_class_id(
386357
asset_class_id: &str,
387358
asset_id: &str,
388-
asset_class_cache: &mut HashMap<String, AssetClassCache>,
359+
_asset_class_cache: &mut HashMap<String, AssetClassCache>,
389360
) -> Currency {
390361
Currency {
391362
symbol: asset_class_id.into(),

src/indexer/mod.rs

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
pub mod chains;
22

33
use crate::types::{BitcoinBlockData, BlockIdentifier, StacksBlockData};
4+
use crate::utils::stacks::{PoxInfo, StacksRpc};
45
use rocket::serde::json::Value as JsonValue;
56
use std::collections::{HashMap, VecDeque};
67

@@ -27,19 +28,6 @@ pub struct StacksChainContext {
2728
pox_info: PoxInfo,
2829
}
2930

30-
#[derive(Deserialize, Debug, Clone, Default)]
31-
pub struct PoxInfo {
32-
pub contract_id: String,
33-
pub pox_activation_threshold_ustx: u64,
34-
pub first_burnchain_block_height: u64,
35-
pub prepare_phase_block_length: u32,
36-
pub reward_phase_block_length: u32,
37-
pub reward_slots: u32,
38-
pub reward_cycle_id: u32,
39-
pub total_liquid_supply_ustx: u64,
40-
pub next_cycle: PoxCycle,
41-
}
42-
4331
impl PoxInfo {
4432
pub fn default() -> PoxInfo {
4533
PoxInfo {
@@ -55,11 +43,6 @@ impl PoxInfo {
5543
}
5644
}
5745

58-
#[derive(Deserialize, Debug, Clone, Default)]
59-
pub struct PoxCycle {
60-
pub min_threshold_ustx: u64,
61-
}
62-
6346
impl StacksChainContext {
6447
pub fn new() -> StacksChainContext {
6548
StacksChainContext {
@@ -146,16 +129,15 @@ impl Indexer {
146129
StacksChainEvent::ChainUpdatedWithBlock(block)
147130
}
148131

149-
pub fn get_updated_pox_info(&mut self) -> PoxInfo {
150-
// std::thread::spawn(move || {
151-
// let pox_url = format!("{}/v2/pox", node_url);
152-
153-
// if let Ok(reponse) = reqwest::blocking::get(pox_url) {
154-
// if let Ok(update) = reponse.json() {
155-
// pox_info = update
156-
// }
157-
// }
158-
132+
pub fn get_updated_pox_info(&mut self, block: &StacksBlockData) -> PoxInfo {
133+
let pox_cycle_len = self.stacks_context.pox_info.prepare_phase_block_length
134+
+ self.stacks_context.pox_info.reward_phase_block_length;
135+
if block.metadata.pox_cycle_position == pox_cycle_len - 2 {
136+
let stacks_rpc = StacksRpc::new(&self.config.stacks_node_rpc_url);
137+
if let Ok(pox_info) = stacks_rpc.get_pox_info() {
138+
self.stacks_context.pox_info = pox_info;
139+
}
140+
}
159141
self.stacks_context.pox_info.clone()
160142
}
161143
}

src/integrate/events_observer.rs

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
use super::DevnetEvent;
2-
use crate::indexer::{
3-
chains, BitcoinChainEvent, Indexer, IndexerConfig, PoxInfo, StacksChainEvent,
4-
};
2+
use crate::indexer::{chains, BitcoinChainEvent, Indexer, IndexerConfig, StacksChainEvent};
53
use crate::integrate::{MempoolAdmissionData, ServiceStatusData, Status};
64
use crate::poke::load_session;
75
use crate::publish::{publish_contract, Network};
86
use crate::types::{self, DevnetConfig};
97
use crate::utils;
10-
use crate::utils::stacks::{transactions, StacksRpc};
8+
use crate::utils::stacks::{transactions, PoxInfo, StacksRpc};
119
use base58::FromBase58;
1210
use clarity_repl::clarity::representations::ClarityName;
1311
use clarity_repl::clarity::types::{BuffData, SequenceData, TupleData, Value as ClarityValue};
@@ -292,23 +290,23 @@ pub fn handle_new_block(
292290
// Standardize the structure of the block, and identify the
293291
// kind of update that this new block would imply, taking
294292
// into account the last 7 blocks.
295-
let (chain_update, pox_info) = match indexer.inner().write() {
293+
let (pox_info, block) = match indexer.inner().write() {
296294
Ok(mut indexer) => {
297295
let chain_event = indexer.handle_stacks_block(marshalled_block.into_inner());
298-
(chain_event, indexer.get_updated_pox_info())
299-
}
300-
_ => {
301-
return Json(json!({
302-
"status": 200,
303-
"result": "Ok",
304-
}))
296+
// Contextual: Devnet is an environment under control,
297+
// with 1 miner. As such we will ignore Reorgs handling.
298+
match chain_event {
299+
StacksChainEvent::ChainUpdatedWithBlock(block) => {
300+
(indexer.get_updated_pox_info(&block), block)
301+
}
302+
_ => {
303+
return Json(json!({
304+
"status": 200,
305+
"result": "Ok",
306+
}))
307+
}
308+
}
305309
}
306-
};
307-
308-
// Contextual: Devnet is an environment under control,
309-
// with 1 miner. As such we will ignore Reorgs handling.
310-
let block = match chain_update {
311-
StacksChainEvent::ChainUpdatedWithBlock(block) => block,
312310
_ => {
313311
return Json(json!({
314312
"status": 200,
@@ -402,7 +400,8 @@ pub fn handle_new_block(
402400
data = "<new_microblock>"
403401
)]
404402
pub fn handle_new_microblocks(
405-
_config: &State<Arc<RwLock<EventObserverConfig>>>,
403+
_config: &State<Arc<Mutex<EventObserverConfig>>>,
404+
_indexer: &State<Arc<RwLock<Indexer>>>,
406405
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
407406
new_microblock: Json<NewMicroBlock>,
408407
) -> Json<JsonValue> {
@@ -567,10 +566,10 @@ pub fn publish_stacking_orders(
567566

568567
transactions += 1;
569568

570-
let stacks_rpc = StacksRpc::new(node_url.clone());
569+
let stacks_rpc = StacksRpc::new(&node_url);
571570
let default_fee = 1000;
572571
let nonce = stacks_rpc
573-
.get_nonce(account.address.to_string())
572+
.get_nonce(&account.address)
574573
.expect("Unable to retrieve nonce");
575574

576575
let stx_amount = pox_info.next_cycle.min_threshold_ustx * pox_stacking_order.slots;

src/publish/mod.rs

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::poke::load_session;
22
use crate::utils::mnemonic;
3+
use crate::utils::stacks::StacksRpc;
34
use clarity_repl::clarity::codec::transaction::{
45
StacksTransaction, StacksTransactionSigner, TransactionAnchorMode, TransactionAuth,
56
TransactionPayload, TransactionPostConditionMode, TransactionPublicKeyEncoding,
@@ -44,7 +45,7 @@ pub fn publish_contract(
4445
contract: &InitialContract,
4546
deployers_lookup: &BTreeMap<String, Account>,
4647
deployers_nonces: &mut BTreeMap<String, u64>,
47-
node: &str,
48+
node_url: &str,
4849
deployment_fee_rate: u64,
4950
network: &Network,
5051
) -> Result<(String, u64), String> {
@@ -75,20 +76,14 @@ pub fn publish_contract(
7576
let anchor_mode = TransactionAnchorMode::Any;
7677
let tx_fee = deployment_fee_rate * contract.code.len() as u64;
7778

79+
let stacks_rpc = StacksRpc::new(&node_url);
80+
7881
let nonce = match deployers_nonces.get(&deployer.name) {
7982
Some(nonce) => *nonce,
8083
None => {
81-
let request_url = format!(
82-
"{host}/v2/accounts/{addr}",
83-
host = node,
84-
addr = deployer.address,
85-
);
86-
87-
let response: Balance = reqwest::blocking::get(&request_url)
88-
.expect("Unable to retrieve account")
89-
.json()
90-
.expect("Unable to parse contract");
91-
let nonce = response.nonce;
84+
let nonce = stacks_rpc
85+
.get_nonce(&deployer.address)
86+
.expect("Unable to retrieve account");
9287
deployers_nonces.insert(deployer.name.clone(), nonce);
9388
nonce
9489
}
@@ -137,20 +132,10 @@ pub fn publish_contract(
137132
tx_signer.sign_origin(&wrapped_secret_key).unwrap();
138133
let signed_tx = tx_signer.get_tx().unwrap();
139134

140-
let tx_bytes = signed_tx.serialize_to_vec();
141-
let client = reqwest::blocking::Client::new();
142-
let path = format!("{}/v2/transactions", node);
143-
let res = client
144-
.post(&path)
145-
.header("Content-Type", "application/octet-stream")
146-
.body(tx_bytes)
147-
.send()
148-
.unwrap();
149-
150-
if !res.status().is_success() {
151-
return Err(format!("{}", res.text().unwrap()));
152-
}
153-
let txid: String = res.json().unwrap();
135+
let txid = match stacks_rpc.post_transaction(signed_tx) {
136+
Ok(res) => res.txid,
137+
Err(e) => return Err(format!("{:?}", e)),
138+
};
154139
deployers_nonces.insert(deployer.name.clone(), nonce + 1);
155140
Ok((txid, nonce))
156141
}

src/utils/stacks/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#[allow(dead_code)]
22
pub mod rpc_client;
33
pub mod transactions;
4-
pub use rpc_client::StacksRpc;
4+
5+
pub use rpc_client::{PoxInfo, StacksRpc};

0 commit comments

Comments
 (0)