Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EPROD 982 change how operation split is scheduled #200

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
7 changes: 0 additions & 7 deletions src/bridge-did/src/operations/rune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use ic_exports::ic_cdk::api::management_canister::bitcoin::Utxo;
use serde::{Deserialize, Serialize};

use crate::events::MintedEventData;
use crate::op_id::OperationId;
use crate::order::{MintOrder, SignedOrders};
use crate::runes::{DidTransaction, RuneName, RuneToWrap, RuneWithdrawalPayload};

Expand Down Expand Up @@ -55,10 +54,4 @@ pub enum RuneBridgeWithdrawOp {
pub enum RuneBridgeOp {
Deposit(RuneBridgeDepositOp),
Withdraw(RuneBridgeWithdrawOp),
/// The operation has been split into multiple operations
/// e.g. two runes deposit in a single call
OperationSplit {
wallet_address: H160,
new_operation_ids: Vec<OperationId>,
},
}
84 changes: 23 additions & 61 deletions src/rune-bridge/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,6 @@ impl Operation for RuneBridgeOpImpl {
RuneBridgeOp::Withdraw(RuneBridgeWithdrawOp::TransactionSent { .. }) => Err(
Error::FailedToProgress("TransactionSent task cannot be progressed".into()),
),
RuneBridgeOp::OperationSplit {
wallet_address,
new_operation_ids,
} => {
log::debug!("RuneBridgeOp::OperationSplit {wallet_address} {new_operation_ids:?}");
Self::schedule_operation_split(ctx, new_operation_ids).await
}
};
Ok(OperationProgress::Progress(next_step?))
}
Expand All @@ -146,7 +139,6 @@ impl Operation for RuneBridgeOpImpl {
RuneBridgeOp::Withdraw(RuneBridgeWithdrawOp::CreateTransaction { .. }) => false,
RuneBridgeOp::Withdraw(RuneBridgeWithdrawOp::SendTransaction { .. }) => false,
RuneBridgeOp::Withdraw(RuneBridgeWithdrawOp::TransactionSent { .. }) => true,
RuneBridgeOp::OperationSplit { .. } => false,
}
}

Expand Down Expand Up @@ -179,7 +171,6 @@ impl Operation for RuneBridgeOpImpl {
RuneBridgeOp::Withdraw(RuneBridgeWithdrawOp::TransactionSent {
from_address, ..
}) => from_address.clone(),
RuneBridgeOp::OperationSplit { wallet_address, .. } => wallet_address.clone(),
}
}

Expand All @@ -191,9 +182,7 @@ impl Operation for RuneBridgeOpImpl {
.with_fixed_backoff_policy(2)
.with_max_retries_policy(10),
),
RuneBridgeOp::Deposit(_)
| RuneBridgeOp::Withdraw(_)
| RuneBridgeOp::OperationSplit { .. } => Some(
RuneBridgeOp::Deposit(_) | RuneBridgeOp::Withdraw(_) => Some(
TaskOptions::new()
.with_max_retries_policy(10)
.with_fixed_backoff_policy(5),
Expand All @@ -203,58 +192,35 @@ impl Operation for RuneBridgeOpImpl {
}

impl RuneBridgeOpImpl {
fn split(state: RuntimeState<Self>, wallet_address: H160, operations: Vec<Self>) -> Self {
let mut state = state.borrow_mut();
let ids = operations
.into_iter()
.map(|op| state.operations.new_operation(op, None))
.collect();
Self(RuneBridgeOp::OperationSplit {
wallet_address,
new_operation_ids: ids,
})
}

fn split_or_update(
state: RuntimeState<Self>,
wallet_address: H160,
mut operations: Vec<Self>,
) -> Self {
fn split(state: RuntimeState<Self>, mut operations: Vec<Self>) -> Self {
debug_assert!(
!operations.is_empty(),
"operations list must contain at least one operation"
);

if operations.len() > 1 {
Self::split(state, wallet_address, operations)
} else {
operations.remove(0)
}
}

async fn schedule_operation_split(
ctx: RuntimeState<Self>,
operation_ids: Vec<OperationId>,
) -> BTFResult<Self> {
let state = ctx.borrow();

let mut operations = operation_ids
.into_iter()
.filter_map(|id| state.operations.get(id).map(|op| (id, op)))
.collect::<Vec<_>>();
log::debug!("splitting {} operations", operations.len());

log::debug!("Splitting operation: {operations:?}");
// get first
let self_update = operations.remove(0);

let (_, next_op) = operations.pop().ok_or(Error::FailedToProgress(
"no operations to split".to_string(),
))?;
// schedule remaining ops
let runtime = get_runtime();
let runtime_mut = runtime.borrow_mut();

// schedule the rest of the operations
for (id, operation) in operations {
get_runtime().borrow_mut().schedule_operation(id, operation);
}
let mut state = state.borrow_mut();
operations
.into_iter()
.flat_map(|op| {
let id = state.operations.new_operation(op, None);
log::debug!("created new operation on split {id}");
state.operations.get(id).map(|op| (id, op))
})
.for_each(|(id, operation)| {
log::debug!("scheduling split operation {id}");
runtime_mut.schedule_operation(id, operation);
});

Ok(next_op)
self_update
}

async fn await_inputs(
Expand Down Expand Up @@ -324,11 +290,7 @@ impl RuneBridgeOpImpl {
)));
}

Ok(Self::split_or_update(
state.clone(),
dst_address,
operations,
))
Ok(Self::split(state.clone(), operations))
}

async fn await_confirmations(
Expand Down Expand Up @@ -357,7 +319,7 @@ impl RuneBridgeOpImpl {
})
.collect();

Ok(Self::split_or_update(ctx, dst_address, operations))
Ok(Self::split(ctx, operations))
}

async fn create_withdrawal_transaction(payload: RuneWithdrawalPayload) -> BTFResult<Self> {
Expand Down
66 changes: 1 addition & 65 deletions src/rune-bridge/src/ops/tests/await_confirmations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ use bridge_did::error::Error;
use bridge_did::runes::{RuneInfo, RuneToWrap};
use did::H160;
use ic_exports::ic_cdk::api::management_canister::bitcoin::{Outpoint, Utxo};
use ic_exports::ic_kit::MockContext;
use ordinals::Rune;
use snapbox::{assert_data_eq, str};

use crate::core::utxo_handler::test::TestUtxoHandler;
use crate::core::utxo_handler::UtxoHandlerError;
use crate::ops::{tests, RuneBridgeDepositOp, RuneBridgeOp, RuneBridgeOpImpl};
use crate::ops::{tests, RuneBridgeOpImpl};

fn get_utxo() -> Utxo {
Utxo {
Expand Down Expand Up @@ -124,66 +123,3 @@ async fn await_confirmations_utxo_already_used() {

assert_data_eq!(message, str!["utxo is already used to create mint orders"]);
}

#[tokio::test]
async fn await_confirmations_one_mint_order() {
let utxo_handler = TestUtxoHandler::ok();
let result = RuneBridgeOpImpl::await_confirmations(
tests::test_state(),
&utxo_handler,
tests::sender(),
get_utxo(),
get_to_wrap(1),
)
.await;

let Ok(operation) = result else {
panic!("Wrong result: {result:?}");
};

assert!(matches!(
operation,
RuneBridgeOpImpl(RuneBridgeOp::Deposit(
RuneBridgeDepositOp::SignMintOrder { .. }
))
));
}

#[tokio::test]
async fn await_confirmations_multiple_mint_orders() {
MockContext::new().inject();

const COUNT: usize = 3;
let utxo_handler = TestUtxoHandler::ok();
let state = tests::test_state();
let result = RuneBridgeOpImpl::await_confirmations(
state.clone(),
&utxo_handler,
tests::sender(),
get_utxo(),
get_to_wrap(COUNT),
)
.await;

let Ok(RuneBridgeOpImpl(RuneBridgeOp::OperationSplit {
new_operation_ids,
wallet_address,
})) = result
else {
panic!("Wrong result: {result:?}");
};

assert_eq!(new_operation_ids.len(), COUNT);

for operation_id in new_operation_ids {
let operation = state.borrow().operations.get(operation_id).unwrap();
assert!(matches!(
operation,
RuneBridgeOpImpl(RuneBridgeOp::Deposit(
RuneBridgeDepositOp::SignMintOrder { .. }
))
));
}

assert_eq!(wallet_address, tests::sender());
}
64 changes: 2 additions & 62 deletions src/rune-bridge/src/ops/tests/await_inputs.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use std::str::FromStr;

use bridge_did::error::Error;
use bridge_did::runes::{RuneName, RuneToWrap};
use bridge_did::runes::RuneName;
use ic_exports::ic_cdk::api::management_canister::bitcoin::{Outpoint, Utxo};
use ic_exports::ic_kit::MockContext;
use snapbox::{assert_data_eq, str};

use crate::core::rune_inputs::mock::TestRuneInputProvider;
use crate::core::rune_inputs::{GetInputsError, RuneInput};
use crate::ops::{tests, RuneBridgeDepositOp, RuneBridgeOp, RuneBridgeOpImpl};
use crate::ops::{tests, RuneBridgeOpImpl};

#[tokio::test]
async fn await_inputs_returns_error_if_no_inputs() {
Expand Down Expand Up @@ -252,62 +251,3 @@ async fn await_inputs_returns_error_if_no_token_address() {

assert_data_eq!(message, str!["wrapped token address for rune A not found"]);
}

#[tokio::test]
async fn await_inputs_returns_correct_operation_single_input() {
let input = rune_input("A", 1000);
let provider = TestRuneInputProvider::with_input(input.clone());
let result = RuneBridgeOpImpl::await_inputs(
tests::test_state(),
&provider,
tests::sender(),
tests::dst_tokens(),
None,
)
.await;
assert_eq!(
result,
Ok(RuneBridgeOpImpl(RuneBridgeOp::Deposit(
RuneBridgeDepositOp::AwaitConfirmations {
dst_address: tests::sender(),
utxo: input.utxo,
runes_to_wrap: vec![RuneToWrap {
rune_info: provider.rune_info(&RuneName::from_str("A").unwrap()),
amount: 1000,
wrapped_address: tests::token_address(3),
}],
}
)))
);
}

#[tokio::test]
async fn await_inputs_returns_correct_operation_multiple_inputs() {
MockContext::new().inject();

let inputs = vec![rune_input("A", 1000), rune_input("B", 2000)];
let provider = TestRuneInputProvider::with_inputs(&inputs);
let state = tests::test_state();
let result = RuneBridgeOpImpl::await_inputs(
state.clone(),
&provider,
tests::sender(),
tests::dst_tokens(),
None,
)
.await;

let Ok(RuneBridgeOpImpl(RuneBridgeOp::OperationSplit {
wallet_address,
new_operation_ids,
})) = result
else {
panic!("Incorrect operation returned")
};

for operation in new_operation_ids {
assert!(state.borrow().operations.get(operation).is_some());
}

assert_eq!(wallet_address, tests::sender());
}
Loading