Skip to content

Commit 059faea

Browse files
committed
refactor: introduce publish_initial_contracts and publish_stacking_orders
1 parent fdb5f83 commit 059faea

File tree

2 files changed

+180
-147
lines changed

2 files changed

+180
-147
lines changed

src/indexer/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ use crate::types::{BitcoinBlockData, BlockIdentifier, StacksBlockData};
44
use rocket::serde::json::Value as JsonValue;
55
use std::collections::{HashMap, VecDeque};
66

7+
#[allow(dead_code)]
78
pub enum BitcoinChainEvent {
89
ChainUpdatedWithBlock(BitcoinBlockData),
910
ChainUpdatedWithReorg(Vec<BitcoinBlockData>),
1011
}
1112

13+
#[allow(dead_code)]
1214
pub enum StacksChainEvent {
1315
ChainUpdatedWithBlock(StacksBlockData),
1416
ChainUpdatedWithReorg(Vec<StacksBlockData>),

src/integrate/events_observer.rs

Lines changed: 178 additions & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use super::DevnetEvent;
2-
use crate::indexer::{chains, BitcoinChainEvent, Indexer, IndexerConfig, StacksChainEvent};
2+
use crate::indexer::{
3+
chains, BitcoinChainEvent, Indexer, IndexerConfig, PoxInfo, StacksChainEvent,
4+
};
35
use crate::integrate::{MempoolAdmissionData, ServiceStatusData, Status};
46
use crate::poke::load_session;
57
use crate::publish::{publish_contract, Network};
@@ -285,7 +287,7 @@ pub fn handle_new_block(
285287
init_status: &State<Arc<RwLock<DevnetInitializationStatus>>>,
286288
indexer: &State<Arc<RwLock<Indexer>>>,
287289
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
288-
mut marshalled_block: Json<JsonValue>,
290+
marshalled_block: Json<JsonValue>,
289291
) -> Json<JsonValue> {
290292
// Standardize the structure of the block, and identify the
291293
// kind of update that this new block would imply, taking
@@ -345,76 +347,18 @@ pub fn handle_new_block(
345347
if let Ok(mut init_status_writer) = init_status.inner().write() {
346348
if init_status_writer.contracts_left_to_deploy.len() > 0 {
347349
if let Ok(config_reader) = config.lock() {
348-
let node_url = format!(
349-
"http://localhost:{}",
350-
config_reader.devnet_config.stacks_node_rpc_port
351-
);
352-
353-
// How many contracts left?
354-
let contracts_left = init_status_writer.contracts_left_to_deploy.len();
355-
let tx_chaining_limit = 25;
356-
let blocks_required = 1 + (contracts_left / tx_chaining_limit);
357-
let contracts_to_deploy_in_blocks = if blocks_required == 1 {
358-
contracts_left
359-
} else {
360-
contracts_left / blocks_required
361-
};
362-
363-
let mut contracts_to_deploy = vec![];
364-
365-
for _ in 0..contracts_to_deploy_in_blocks {
366-
let contract = init_status_writer
367-
.contracts_left_to_deploy
368-
.pop_front()
369-
.unwrap();
370-
contracts_to_deploy.push(contract);
371-
}
372-
373-
let moved_node_url = node_url.clone();
374-
375-
let mut deployers_lookup = BTreeMap::new();
376-
for account in config_reader.accounts.iter() {
377-
if account.name == "deployer" {
378-
deployers_lookup.insert("*".into(), account.clone());
350+
if let Some(count) = publish_initial_contracts(
351+
&config_reader.devnet_config,
352+
&config_reader.accounts,
353+
&mut init_status_writer,
354+
) {
355+
if let Ok(tx) = devnet_events_tx.lock() {
356+
let _ = tx.send(DevnetEvent::success(format!(
357+
"Will publish {} contracts",
358+
count
359+
)));
379360
}
380361
}
381-
382-
let mut deployers_nonces = BTreeMap::new();
383-
deployers_nonces.insert("deployer".to_string(), init_status_writer.deployer_nonce);
384-
init_status_writer.deployer_nonce += contracts_to_deploy.len() as u64;
385-
386-
if let Ok(tx) = devnet_events_tx.lock() {
387-
let _ = tx.send(DevnetEvent::success(format!(
388-
"Will broadcast {} transactions",
389-
contracts_to_deploy.len()
390-
)));
391-
}
392-
393-
// Move the transactions submission to another thread, the clock on that thread is ticking,
394-
// and blocking our stacks-node
395-
std::thread::spawn(move || {
396-
for contract in contracts_to_deploy.into_iter() {
397-
match publish_contract(
398-
&contract,
399-
&deployers_lookup,
400-
&mut deployers_nonces,
401-
&moved_node_url,
402-
1,
403-
&Network::Devnet,
404-
) {
405-
Ok((_txid, _nonce)) => {
406-
// let _ = tx_clone.send(DevnetEvent::success(format!(
407-
// "Contract {} broadcasted in mempool (txid: {}, nonce: {})",
408-
// contract.name.unwrap(), txid, nonce
409-
// )));
410-
}
411-
Err(_err) => {
412-
// let _ = tx_clone.send(DevnetEvent::error(err.to_string()));
413-
break;
414-
}
415-
}
416-
}
417-
});
418362
}
419363
}
420364
}
@@ -425,83 +369,20 @@ pub fn handle_new_block(
425369
pox_info.prepare_phase_block_length + pox_info.reward_phase_block_length;
426370
if block.metadata.pox_cycle_position == (pox_cycle_length - 2) {
427371
if let Ok(config_reader) = config.lock() {
428-
// let tx_clone = tx.clone();
429-
let node_url = format!(
430-
"http://localhost:{}",
431-
config_reader.devnet_config.stacks_node_rpc_port
432-
);
433-
434372
let bitcoin_block_height = block.metadata.bitcoin_anchor_block_identifier.index;
435-
let accounts = config_reader.accounts.clone();
436-
let pox_stacking_orders = config_reader.devnet_config.pox_stacking_orders.clone();
437-
std::thread::spawn(move || {
438-
let pox_url = format!("{}/v2/pox", node_url);
439-
440-
for pox_stacking_order in pox_stacking_orders.into_iter() {
441-
if pox_stacking_order.start_at_cycle == (pox_info.reward_cycle_id + 1) {
442-
let mut account = None;
443-
while let Some(e) = accounts.iter().next() {
444-
if e.name == pox_stacking_order.wallet {
445-
account = Some(e);
446-
}
447-
}
448-
let account = match account {
449-
Some(account) => account,
450-
_ => continue,
451-
};
452-
453-
let stacks_rpc = StacksRpc::new(node_url.clone());
454-
let default_fee = 1000;
455-
let nonce = stacks_rpc
456-
.get_nonce(account.address.to_string())
457-
.expect("Unable to retrieve nonce");
458-
459-
let stx_amount =
460-
pox_info.next_cycle.min_threshold_ustx * pox_stacking_order.slots;
461-
let (_, _, account_secret_keu) =
462-
types::compute_addresses(&account.mnemonic, &account.derivation, false);
463-
let addr_bytes = pox_stacking_order
464-
.btc_address
465-
.from_base58()
466-
.expect("Unable to get bytes from btc address");
467-
468-
let addr_bytes = Hash160::from_bytes(&addr_bytes[1..21]).unwrap();
469-
let addr_version = AddressHashMode::SerializeP2PKH;
470-
let stack_stx_tx = transactions::build_contrat_call_transaction(
471-
pox_info.contract_id.clone(),
472-
"stack-stx".into(),
473-
vec![
474-
ClarityValue::UInt(stx_amount.into()),
475-
ClarityValue::Tuple(
476-
TupleData::from_data(vec![
477-
(
478-
ClarityName::try_from("version".to_owned()).unwrap(),
479-
ClarityValue::buff_from_byte(addr_version as u8),
480-
),
481-
(
482-
ClarityName::try_from("hashbytes".to_owned()).unwrap(),
483-
ClarityValue::Sequence(SequenceData::Buffer(
484-
BuffData {
485-
data: addr_bytes.as_bytes().to_vec(),
486-
},
487-
)),
488-
),
489-
])
490-
.unwrap(),
491-
),
492-
ClarityValue::UInt((bitcoin_block_height - 1).into()),
493-
ClarityValue::UInt(pox_stacking_order.duration.into()),
494-
],
495-
nonce,
496-
default_fee,
497-
&hex_bytes(&account_secret_keu).unwrap(),
498-
);
499-
let _ = stacks_rpc
500-
.post_transaction(stack_stx_tx)
501-
.expect("Unable to broadcast transaction");
502-
}
373+
if let Some(count) = publish_stacking_orders(
374+
&config_reader.devnet_config,
375+
&config_reader.accounts,
376+
&pox_info,
377+
bitcoin_block_height as u32,
378+
) {
379+
if let Ok(tx) = devnet_events_tx.lock() {
380+
let _ = tx.send(DevnetEvent::success(format!(
381+
"Will broadcast {} stacking orders",
382+
count
383+
)));
503384
}
504-
});
385+
}
505386
}
506387
}
507388

@@ -589,6 +470,156 @@ pub fn handle_drop_mempool_tx() -> Json<JsonValue> {
589470
}))
590471
}
591472

592-
pub fn publish_initial_contracts() {}
473+
pub fn publish_initial_contracts(
474+
devnet_config: &DevnetConfig,
475+
accounts: &Vec<Account>,
476+
init_status: &mut DevnetInitializationStatus,
477+
) -> Option<usize> {
478+
let contracts_left = init_status.contracts_left_to_deploy.len();
479+
if contracts_left == 0 {
480+
return None;
481+
}
482+
483+
let node_url = format!("http://localhost:{}", devnet_config.stacks_node_rpc_port);
484+
let tx_chaining_limit = 25;
485+
let blocks_required = 1 + (contracts_left / tx_chaining_limit);
486+
let contracts_to_deploy_in_blocks = if blocks_required == 1 {
487+
contracts_left
488+
} else {
489+
contracts_left / blocks_required
490+
};
491+
492+
let mut contracts_to_deploy = vec![];
493+
494+
for _ in 0..contracts_to_deploy_in_blocks {
495+
let contract = init_status.contracts_left_to_deploy.pop_front().unwrap();
496+
contracts_to_deploy.push(contract);
497+
}
498+
499+
let moved_node_url = node_url.clone();
500+
501+
let mut deployers_lookup = BTreeMap::new();
502+
for account in accounts.iter() {
503+
if account.name == "deployer" {
504+
deployers_lookup.insert("*".into(), account.clone());
505+
}
506+
}
507+
508+
let mut deployers_nonces = BTreeMap::new();
509+
deployers_nonces.insert("deployer".to_string(), init_status.deployer_nonce);
510+
let contract_to_deploy_len = contracts_to_deploy.len();
511+
init_status.deployer_nonce += contract_to_deploy_len as u64;
512+
513+
// Move the transactions submission to another thread, the clock on that thread is ticking,
514+
// and blocking our stacks-node
515+
std::thread::spawn(move || {
516+
for contract in contracts_to_deploy.into_iter() {
517+
match publish_contract(
518+
&contract,
519+
&deployers_lookup,
520+
&mut deployers_nonces,
521+
&moved_node_url,
522+
1,
523+
&Network::Devnet,
524+
) {
525+
Ok((_txid, _nonce)) => {
526+
// let _ = tx_clone.send(DevnetEvent::success(format!(
527+
// "Contract {} broadcasted in mempool (txid: {}, nonce: {})",
528+
// contract.name.unwrap(), txid, nonce
529+
// )));
530+
}
531+
Err(_err) => {
532+
// let _ = tx_clone.send(DevnetEvent::error(err.to_string()));
533+
break;
534+
}
535+
}
536+
}
537+
});
538+
539+
Some(contract_to_deploy_len)
540+
}
541+
542+
pub fn publish_stacking_orders(
543+
devnet_config: &DevnetConfig,
544+
accounts: &Vec<Account>,
545+
pox_info: &PoxInfo,
546+
bitcoin_block_height: u32,
547+
) -> Option<usize> {
548+
if devnet_config.pox_stacking_orders.len() == 0 {
549+
return None;
550+
}
551+
552+
let node_url = format!("http://localhost:{}", devnet_config.stacks_node_rpc_port);
553+
let mut transactions = 0;
593554

594-
pub fn submit_stacking_orders() {}
555+
for pox_stacking_order in devnet_config.pox_stacking_orders.iter() {
556+
if pox_stacking_order.start_at_cycle == (pox_info.reward_cycle_id + 1) {
557+
let mut account = None;
558+
while let Some(e) = accounts.iter().next() {
559+
if e.name == pox_stacking_order.wallet {
560+
account = Some(e);
561+
}
562+
}
563+
let account = match account {
564+
Some(account) => account,
565+
_ => continue,
566+
};
567+
568+
transactions += 1;
569+
570+
let stacks_rpc = StacksRpc::new(node_url.clone());
571+
let default_fee = 1000;
572+
let nonce = stacks_rpc
573+
.get_nonce(account.address.to_string())
574+
.expect("Unable to retrieve nonce");
575+
576+
let stx_amount = pox_info.next_cycle.min_threshold_ustx * pox_stacking_order.slots;
577+
let (_, _, account_secret_keu) =
578+
types::compute_addresses(&account.mnemonic, &account.derivation, false);
579+
let addr_bytes = pox_stacking_order
580+
.btc_address
581+
.from_base58()
582+
.expect("Unable to get bytes from btc address");
583+
584+
let addr_bytes = Hash160::from_bytes(&addr_bytes[1..21]).unwrap();
585+
let addr_version = AddressHashMode::SerializeP2PKH;
586+
let stack_stx_tx = transactions::build_contrat_call_transaction(
587+
pox_info.contract_id.clone(),
588+
"stack-stx".into(),
589+
vec![
590+
ClarityValue::UInt(stx_amount.into()),
591+
ClarityValue::Tuple(
592+
TupleData::from_data(vec![
593+
(
594+
ClarityName::try_from("version".to_owned()).unwrap(),
595+
ClarityValue::buff_from_byte(addr_version as u8),
596+
),
597+
(
598+
ClarityName::try_from("hashbytes".to_owned()).unwrap(),
599+
ClarityValue::Sequence(SequenceData::Buffer(BuffData {
600+
data: addr_bytes.as_bytes().to_vec(),
601+
})),
602+
),
603+
])
604+
.unwrap(),
605+
),
606+
ClarityValue::UInt((bitcoin_block_height - 1).into()),
607+
ClarityValue::UInt(pox_stacking_order.duration.into()),
608+
],
609+
nonce,
610+
default_fee,
611+
&hex_bytes(&account_secret_keu).unwrap(),
612+
);
613+
std::thread::spawn(move || {
614+
let _ = stacks_rpc
615+
.post_transaction(stack_stx_tx)
616+
.expect("Unable to broadcast transaction");
617+
});
618+
}
619+
}
620+
if transactions > 0 {
621+
Some(transactions)
622+
} else {
623+
None
624+
}
625+
}

0 commit comments

Comments
 (0)