Skip to content

Commit

Permalink
Update breez-sdk mock to the new pay on-chain API (#1111)
Browse files Browse the repository at this point in the history
* Bump uniffi to 0.28.0 (#1108)

* Move `ParseError` to errors (#1105)

* Migrate to the new pay on-chain API (#1102)

* Update breez-sdk mock to the new pay on-chain API
  • Loading branch information
andrei-21 authored Jun 18, 2024
1 parent f78ab82 commit f0b625c
Show file tree
Hide file tree
Showing 9 changed files with 201 additions and 156 deletions.
61 changes: 26 additions & 35 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ sha2 = { version = "0.10.8", features = [] }
simplelog = { version = "0.12.2" }
thiserror = "1.0.61"
tokio = { version = "1.38.0", features = ["rt-multi-thread", "time", "sync"] }
uniffi = "0.27.0"
uniffi = "0.28.0"
uuid = { version = "1.8.0", features = ["v5"] }

[features]
Expand Down Expand Up @@ -99,7 +99,7 @@ lazy_static = "1.4.0"

[build-dependencies]
camino = "1.1.7"
uniffi_bindgen = "0.27.0"
uniffi_bindgen = "0.28.0"

# Use some of the binary size reduction strategies from https://github.com/johnthagen/min-sized-rust
[profile.release]
Expand Down
4 changes: 2 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use camino::Utf8Path;
use std::env;
use uniffi_bindgen::bindings::kotlin::gen_kotlin::KotlinBindingGenerator;
use uniffi_bindgen::bindings::swift::gen_swift::SwiftBindingGenerator;
use uniffi_bindgen::bindings::KotlinBindingGenerator;
use uniffi_bindgen::bindings::SwiftBindingGenerator;

fn main() {
let udl_file = Utf8Path::new("src/lipalightninglib.udl");
Expand Down
12 changes: 6 additions & 6 deletions examples/node/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use uniffi_lipalightninglib::{
ExchangeRate, FailedSwapInfo, FiatValue, IncomingPaymentInfo, InvoiceCreationMetadata,
InvoiceDetails, LightningNode, LiquidityLimit, LnUrlPayDetails, LnUrlWithdrawDetails,
MaxRoutingFeeMode, OfferInfo, OfferKind, OutgoingPaymentInfo, PaymentInfo, PaymentMetadata,
Recipient, TzConfig,
RangeHit, Recipient, TzConfig,
};

pub(crate) fn poll_for_user_input(node: &LightningNode, log_file_path: &str) {
Expand Down Expand Up @@ -1346,11 +1346,11 @@ fn sweep(node: &LightningNode, address: String) -> Result<String> {
}

fn clear_wallet_info(node: &LightningNode) -> Result<()> {
ensure!(
node.is_clear_wallet_feasible()?,
"Clearing the wallet isn't feasible at the moment due to the available funds being \
either too low or too high"
);
match node.check_clear_wallet_feasibility()? {
RangeHit::Below { min } => bail!("Balance is below min: {}", amount_to_string(&min)),
RangeHit::In => (),
RangeHit::Above { max } => bail!("Balance is above max: {}", amount_to_string(&max)),
};

let clear_wallet_info = node.prepare_clear_wallet()?;

Expand Down
70 changes: 47 additions & 23 deletions mock/breez-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const OPENING_FEE_PARAMS_PROMISE: &str = "promite";

const SWAP_MIN_AMOUNT_SAT: u64 = 1_000;
const SWAP_MAX_AMOUNT_SAT: u64 = 1_000_000;
const SWAP_FEE_SAT: u64 = 1_500;
const SWAPPER_ROUTING_FEE_SAT: u64 = 150;
const SWAP_TX_WEIGHT: u64 = 800;
const SAT_PER_VBYTE: u64 = 12;
const SWAP_FEE_PERCENTAGE: f64 = 0.5;
Expand All @@ -53,19 +53,20 @@ pub use breez_sdk_core::{
InputType, InvoicePaidDetails, LNInvoice, ListPaymentsRequest, LnPaymentDetails,
LnUrlPayRequest, LnUrlPayRequestData, LnUrlPayResult, LnUrlWithdrawRequest,
LnUrlWithdrawRequestData, LnUrlWithdrawResult, MetadataItem, Network, NodeConfig,
OpenChannelFeeRequest, OpeningFeeParams, OpeningFeeParamsMenu, Payment, PaymentDetails,
PaymentFailedData, PaymentStatus, PaymentType, PaymentTypeFilter,
OnchainPaymentLimitsResponse, OpenChannelFeeRequest, OpeningFeeParams, OpeningFeeParamsMenu,
PayOnchainRequest, Payment, PaymentDetails, PaymentFailedData, PaymentStatus, PaymentType,
PaymentTypeFilter, PrepareOnchainPaymentRequest, PrepareOnchainPaymentResponse,
PrepareRedeemOnchainFundsRequest, PrepareRefundRequest, ReceiveOnchainRequest,
ReceivePaymentRequest, ReceivePaymentResponse, RedeemOnchainFundsRequest, RefundRequest,
ReportIssueRequest, ReportPaymentFailureDetails, ReverseSwapFeesRequest, SendOnchainRequest,
SendPaymentRequest, SignMessageRequest, SwapStatus, UnspentTransactionOutput,
SendPaymentRequest, SignMessageRequest, SwapAmountType, SwapStatus, UnspentTransactionOutput,
};
use breez_sdk_core::{
ChannelState, Config, LspInformation, MaxReverseSwapAmountResponse, NodeState,
OpenChannelFeeResponse, PrepareRedeemOnchainFundsResponse, PrepareRefundResponse,
RecommendedFees, RedeemOnchainFundsResponse, RefundResponse, ReverseSwapInfo,
ReverseSwapPairInfo, ReverseSwapStatus, SendOnchainResponse, SendPaymentResponse,
ServiceHealthCheckResponse, SignMessageResponse, SwapInfo,
ChannelState, Config, LspInformation, NodeState, OpenChannelFeeResponse, PayOnchainResponse,
PrepareRedeemOnchainFundsResponse, PrepareRefundResponse, RecommendedFees,
RedeemOnchainFundsResponse, RefundResponse, ReverseSwapInfo, ReverseSwapPairInfo,
ReverseSwapStatus, SendPaymentResponse, ServiceHealthCheckResponse, SignMessageResponse,
SwapInfo,
};
use chrono::Utc;
use hex::FromHex;
Expand Down Expand Up @@ -820,40 +821,63 @@ impl BreezServices {
})
}

pub async fn max_reverse_swap_amount(&self) -> SdkResult<MaxReverseSwapAmountResponse> {
pub async fn onchain_payment_limits(&self) -> SdkResult<OnchainPaymentLimitsResponse> {
let balance_sat = get_balance_msat() / 1000;
let total_sat = if balance_sat > SWAP_FEE_SAT {
balance_sat - SWAP_FEE_SAT
let (min_sat, max_sat) = if balance_sat > SWAPPER_ROUTING_FEE_SAT {
(
SWAPPER_ROUTING_FEE_SAT,
balance_sat - SWAPPER_ROUTING_FEE_SAT,
)
} else {
0
(0, 0)
};
Ok(OnchainPaymentLimitsResponse { min_sat, max_sat })
}

Ok(MaxReverseSwapAmountResponse { total_sat })
pub async fn prepare_onchain_payment(
&self,
req: PrepareOnchainPaymentRequest,
) -> Result<PrepareOnchainPaymentResponse, SendOnchainError> {
let fees_lockup = 500;
let fees_claim = 500;
let total_fees = ((req.amount_sat as f64) / 100.0 * SWAP_FEE_PERCENTAGE) as u64
+ fees_lockup
+ fees_claim;
let recipient_amount_sat = req.amount_sat - total_fees;
Ok(PrepareOnchainPaymentResponse {
fees_hash: "this-should-be-a-hash.dummy".to_string(),
fees_percentage: SWAP_FEE_PERCENTAGE,
fees_lockup,
fees_claim,
sender_amount_sat: req.amount_sat,
recipient_amount_sat,
total_fees,
})
}

pub async fn send_onchain(
pub async fn pay_onchain(
&self,
req: SendOnchainRequest,
) -> Result<SendOnchainResponse, SendOnchainError> {
if req.amount_sat < SWAP_MIN_AMOUNT_SAT {
req: PayOnchainRequest,
) -> Result<PayOnchainResponse, SendOnchainError> {
if req.prepare_res.sender_amount_sat < SWAP_MIN_AMOUNT_SAT {
return Err(SendOnchainError::PaymentFailed {
err: "Insufficient funds".to_string(),
});
}

let now = Utc::now().timestamp();

let amount_msat = req.amount_sat * 1_000;
let amount_msat = req.prepare_res.sender_amount_sat * 1_000;

let routing_fee_msat = rand::thread_rng().gen_range(1000..4000);
let routing_fee_msat = SWAPPER_ROUTING_FEE_SAT * 1000;
send_payment_mock_channels(amount_msat + routing_fee_msat);

let reverse_swap_info = ReverseSwapInfo {
id: now.to_string(),
claim_pubkey: req.onchain_recipient_address,
claim_pubkey: req.recipient_address,
lockup_txid: Some("LOCKUP-TXID-DUMMY".to_string()),
claim_txid: Some("CLAIM-TXID-DUMMY".to_string()),
onchain_amount_sat: req.amount_sat,
onchain_amount_sat: req.prepare_res.sender_amount_sat,
status: ReverseSwapStatus::Initial,
};

Expand All @@ -880,7 +904,7 @@ impl BreezServices {
self.event_listener
.on_event(BreezEvent::PaymentSucceed { details: payment });

Ok(SendOnchainResponse { reverse_swap_info })
Ok(PayOnchainResponse { reverse_swap_info })
}

pub async fn list_refundables(&self) -> SdkResult<Vec<SwapInfo>> {
Expand Down
26 changes: 26 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,32 @@ impl NotificationHandlingErrorCode {
}
}

/// Enum representing possible errors why parsing could fail.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
/// Parsing failed because parsed string was not complete.
/// Additional characters are needed to make the string valid.
/// It makes parsed string a valid prefix of a valid string.
#[error("Incomplete")]
Incomplete,

/// Parsing failed because an unexpected character at position `at` was met.
/// The character **has to be removed**.
#[error("InvalidCharacter at {at}")]
InvalidCharacter { at: u32 },
}

impl From<parser::ParseError> for ParseError {
fn from(error: parser::ParseError) -> Self {
match error {
parser::ParseError::Incomplete => ParseError::Incomplete,
parser::ParseError::UnexpectedCharacter(at) | parser::ParseError::ExcessSuffix(at) => {
ParseError::InvalidCharacter { at: at as u32 }
}
}
}
}

#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum ParsePhoneNumberPrefixError {
#[error("Incomplete")]
Expand Down
Loading

0 comments on commit f0b625c

Please sign in to comment.