This repository was archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.rs
More file actions
501 lines (427 loc) · 15.7 KB
/
api.rs
File metadata and controls
501 lines (427 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use crate::calc;
use crate::cfd;
use crate::cfd::models::Cfd;
use crate::cfd::models::Order;
use crate::cfd::models::Position;
use crate::config;
use crate::connection;
use crate::db;
use crate::faucet;
use crate::logger;
use crate::offer;
use crate::offer::Offer;
use crate::wallet;
use crate::wallet::Balance;
use crate::wallet::LightningTransaction;
use anyhow::Context;
use anyhow::Result;
use flutter_rust_bridge::StreamSink;
use flutter_rust_bridge::SyncReturn;
use lightning_invoice::Invoice;
use lightning_invoice::InvoiceDescription;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use state::Storage;
use std::ops::Add;
use std::path::Path;
use std::str::FromStr;
use std::time::SystemTime;
use time::Duration;
pub use time::OffsetDateTime;
use tokio::runtime::Runtime;
pub struct Address {
pub address: String,
}
#[derive(Clone)]
pub struct BitcoinTxHistoryItem {
pub sent: u64,
pub received: u64,
pub txid: String,
pub fee: u64,
pub is_confirmed: bool,
/// Timestamp since epoch
///
/// Confirmation timestamp as prt blocktime if confirmed, otherwise current time since epoch is
/// returned.
pub timestamp: u64,
}
impl Address {
pub fn new(address: String) -> Address {
Address { address }
}
}
#[derive(Clone)]
pub enum ChannelState {
Unavailable,
Establishing,
Disconnected,
Available,
}
fn get_channel_state() -> ChannelState {
match wallet::get_first_channel_details() {
Some(channel_details) => {
if channel_details.is_usable {
ChannelState::Available
} else if channel_details.is_channel_ready {
// an unusable, but ready channel indicates that the maker might be
// disconnected.
ChannelState::Disconnected
} else {
// if the channel is not usable and not ready - we are currently establishing a
// channel with the maker.
ChannelState::Establishing
}
}
None => ChannelState::Unavailable,
}
}
pub struct LightningInvoice {
pub description: String,
pub amount_sats: f64,
pub timestamp: u64,
pub payee: String,
pub expiry: u64,
}
pub fn decode_invoice(invoice: String) -> Result<LightningInvoice> {
anyhow::ensure!(!invoice.is_empty(), "received empty invoice");
let invoice = &Invoice::from_str(&invoice).context("Could not parse invoice string")?;
let description = match invoice.description() {
InvoiceDescription::Direct(direct) => direct.to_string(),
InvoiceDescription::Hash(_) => "".to_string(),
};
// can't use as_millis as the frb does not support u128
let timestamp = invoice
.timestamp()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs();
let expiry = SystemTime::now()
.add(Duration::seconds(invoice.expiry_time().as_secs() as i64))
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs();
Ok(LightningInvoice {
description,
timestamp,
expiry,
amount_sats: (invoice.amount_milli_satoshis().expect("amount") as f64 / 1000.0),
payee: invoice.payee_pub_key().expect("payee pubkey").to_string(),
})
}
#[derive(Clone)]
pub enum Event {
Init(String),
Ready,
Offer(Option<Offer>),
WalletInfo(Option<WalletInfo>),
ChannelState(ChannelState),
}
#[derive(Clone)]
pub struct WalletInfo {
pub balance: Balance,
pub bitcoin_history: Vec<BitcoinTxHistoryItem>,
pub lightning_history: Vec<LightningTransaction>,
}
impl WalletInfo {
async fn build_wallet_info() -> Result<WalletInfo> {
let balance = wallet::get_balance()?;
let bitcoin_history = WalletInfo::get_bitcoin_tx_history().await?;
let lightning_history = wallet::get_lightning_history().await?;
Ok(WalletInfo {
balance,
bitcoin_history,
lightning_history,
})
}
async fn get_bitcoin_tx_history() -> Result<Vec<BitcoinTxHistoryItem>> {
let tx_history = wallet::get_bitcoin_tx_history()
.await?
.into_iter()
.map(|tx| {
let (is_confirmed, timestamp) = match tx.confirmation_time {
None => (false, OffsetDateTime::now_utc().unix_timestamp() as u64),
Some(blocktime) => (true, blocktime.timestamp),
};
BitcoinTxHistoryItem {
sent: tx.sent,
received: tx.received,
txid: tx.txid.to_string(),
fee: tx.fee.unwrap_or(0),
is_confirmed,
timestamp,
}
})
.collect::<Vec<_>>();
Ok(tx_history)
}
}
/// Lazily creates a multi threaded runtime with the the number of worker threads corresponding to
/// the number of available cores.
fn runtime() -> Result<&'static Runtime> {
static RUNTIME: Storage<Runtime> = Storage::new();
if RUNTIME.try_get().is_none() {
let runtime = Runtime::new()?;
RUNTIME.set(runtime);
}
Ok(RUNTIME.get())
}
pub fn refresh_wallet_info() -> Result<WalletInfo> {
runtime()?.block_on(async {
wallet::sync()?;
WalletInfo::build_wallet_info().await
})
}
pub fn run(stream: StreamSink<Event>, app_dir: String) -> Result<()> {
let network = config::network();
anyhow::ensure!(!app_dir.is_empty(), "app_dir must not be empty");
let runtime = runtime()?;
runtime.block_on(async move {
stream.add(Event::Init(format!("Initialising {network} wallet")));
wallet::init_wallet(Path::new(app_dir.as_str()))?;
stream.add(Event::Init("Initialising database".to_string()));
db::init_db(
&Path::new(app_dir.as_str())
.join(network.to_string())
.join("taker.sqlite"),
)
.await?;
stream.add(Event::Init("Starting full ldk node".to_string()));
let background_processor = wallet::run_ldk()?;
stream.add(Event::Init("Fetching an offer".to_string()));
stream.add(Event::Offer(offer::get_offer().await.ok()));
stream.add(Event::Init("Fetching your balance".to_string()));
stream.add(Event::WalletInfo(
WalletInfo::build_wallet_info().await.ok(),
));
stream.add(Event::Init("Checking channel state".to_string()));
stream.add(Event::ChannelState(get_channel_state()));
stream.add(Event::Init("Ready".to_string()));
stream.add(Event::Ready);
// spawn a connection task keeping the connection with the maker alive.
runtime.spawn(async move {
let peer_info = config::maker_peer_info();
loop {
let peer_manager = wallet::get_peer_manager();
connection::connect(peer_manager, peer_info).await;
// add a delay before retrying to connect
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
});
let offer_stream = stream.clone();
runtime.spawn(async move {
loop {
offer_stream.add(Event::Offer(offer::get_offer().await.ok()));
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
});
runtime.spawn(async {
loop {
wallet::sync().unwrap_or_else(|e| tracing::error!(?e, "Failed to sync wallet"));
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
}
});
let wallet_info_stream = stream.clone();
runtime.spawn(async move {
loop {
match WalletInfo::build_wallet_info().await {
Ok(wallet_info) => {
let _ = wallet_info_stream.add(Event::WalletInfo(Some(wallet_info)));
}
Err(e) => tracing::error!(?e, "Failed to build wallet info"),
}
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
});
let channel_state_stream = stream.clone();
runtime.spawn(async move {
loop {
channel_state_stream.add(Event::ChannelState(get_channel_state()));
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
});
runtime.spawn_blocking(move || {
let mut background_processor = background_processor;
loop {
// background processor joins on a sync thread, meaning that join here will block a
// full thread, which is dis-encouraged to do in async code.
if let Err(err) = background_processor.join() {
tracing::warn!(?err, "Background processor stopped unexpected");
}
tracing::info!("Restarting lightning node");
background_processor = wallet::start_background_processor();
}
});
Ok(())
})
}
pub fn get_balance() -> Result<Balance> {
wallet::get_balance()
}
pub fn sync() -> Result<()> {
wallet::sync()
}
pub fn get_address() -> Result<Address> {
Ok(Address::new(wallet::get_address()?.to_string()))
}
pub fn maker_peer_info() -> String {
config::maker_peer_info().to_string()
}
pub fn node_id() -> String {
wallet::node_id().to_string()
}
pub fn network() -> SyncReturn<String> {
SyncReturn(config::network().to_string())
}
pub fn open_channel(taker_amount: u64) -> Result<()> {
runtime()?.block_on(async {
let peer_info = config::maker_peer_info();
wallet::open_channel(peer_info, taker_amount).await
})
}
pub fn close_channel() -> Result<()> {
runtime()?.block_on(async {
let peer_info = config::maker_peer_info();
wallet::close_channel(peer_info.pubkey, false).await
})
}
pub fn send_to_address(address: String, amount: u64) -> Result<String> {
anyhow::ensure!(!address.is_empty(), "cannot send to an empty address");
let address = address.parse()?;
let txid = wallet::send_to_address(address, amount)?;
let txid = txid.to_string();
Ok(txid)
}
pub fn list_cfds() -> Result<Vec<Cfd>> {
runtime()?.block_on(async {
let mut conn = db::acquire().await?;
cfd::load_cfds(&mut conn).await
})
}
pub fn open_cfd(order: Order) -> Result<()> {
runtime()?.block_on(async { cfd::open(&order).await })
}
pub fn call_faucet(address: String) -> Result<String> {
anyhow::ensure!(
!address.is_empty(),
"Cannot call faucet because of empty address"
);
runtime()?.block_on(async { faucet::call_faucet(address).await })
}
pub fn get_fee_recommendation() -> Result<u32> {
wallet::get_fee_recommendation()
}
/// Settles a CFD with the given taker and maker amounts in sats
pub fn settle_cfd(cfd: Cfd, offer: Offer) -> Result<()> {
runtime()?.block_on(async { cfd::settle(&cfd, &offer).await })
}
/// Initialise logging infrastructure for Rust
pub fn init_logging(sink: StreamSink<logger::LogEntry>) {
logger::create_log_stream(sink)
}
pub fn get_seed_phrase() -> Vec<String> {
// The flutter rust bridge generator unfortunately complains when wrapping a ZeroCopyBuffer with
// a Result. Hence we need to copy here (data isn't too big though, so that should be ok).
wallet::get_seed_phrase()
}
pub fn send_lightning_payment(invoice: String) -> Result<()> {
anyhow::ensure!(!invoice.is_empty(), "Cannot pay empty invoice");
runtime()?.block_on(async { wallet::send_lightning_payment(&invoice).await })
}
pub fn create_lightning_invoice(
amount_sats: u64,
expiry_secs: u32,
description: String,
) -> Result<String> {
runtime()?
.block_on(async { wallet::create_invoice(amount_sats, expiry_secs, description).await })
}
// Note, this implementation has to be on the api level as otherwise it wouldn't be generated
// through frb. TODO: Provide multiple rust targets to the code generation so that this code can be
// nicer structured.
impl Order {
/// Calculate the taker's margin in BTC.
pub fn margin_taker(&self) -> SyncReturn<f64> {
SyncReturn(Self::calculate_margin(
self.open_price,
self.quantity,
self.leverage,
))
}
/// Calculate the total margin in BTC.
pub(crate) fn margin_total(&self) -> f64 {
let margin_taker = self.margin_taker().0;
let margin_maker = self.margin_maker();
margin_taker + margin_maker
}
/// Calculate the maker's margin in BTC.
fn margin_maker(&self) -> f64 {
Self::calculate_margin(self.open_price, self.quantity, 1)
}
/// Calculate the margin in BTC.
fn calculate_margin(opening_price: f64, quantity: i64, leverage: i64) -> f64 {
let quantity = Decimal::from(quantity);
let open_price = Decimal::try_from(opening_price).expect("to fit into decimal");
let leverage = Decimal::from(leverage);
if open_price == Decimal::ZERO || leverage == Decimal::ZERO {
// just to avoid div by 0 errors
return 0.0;
}
let margin = quantity / (open_price * leverage);
let margin =
margin.round_dp_with_strategy(8, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
margin.to_f64().expect("price to fit into f64")
}
pub fn calculate_expiry(&self) -> SyncReturn<i64> {
SyncReturn(
OffsetDateTime::now_utc()
.saturating_add(Duration::days(30))
.unix_timestamp(),
)
}
pub fn calculate_liquidation_price(&self) -> SyncReturn<f64> {
let initial_price = Decimal::try_from(self.open_price).expect("Price to fit");
tracing::trace!("Initial price: {}", self.open_price);
let leverage = Decimal::from(self.leverage);
let liquidation_price = match self.position {
Position::Long => {
calc::inverse::calculate_long_liquidation_price(leverage, initial_price)
}
Position::Short => {
calc::inverse::calculate_short_liquidation_price(leverage, initial_price)
}
};
let liquidation_price = liquidation_price.to_f64().expect("price to fit into f64");
tracing::trace!("Liquidation_price: {liquidation_price}");
SyncReturn(liquidation_price)
}
/// Calculate the profit or loss in BTC.
pub fn calculate_profit_taker(&self, closing_price: f64) -> Result<SyncReturn<f64>> {
let margin = self.margin_taker().0;
let payout = self.calculate_payout_at_price(closing_price)?;
let pnl = payout - margin;
tracing::trace!(%pnl, %payout, %margin,"Calculated taker's PnL");
Ok(SyncReturn(pnl))
}
pub(crate) fn calculate_payout_at_price(&self, closing_price: f64) -> Result<f64> {
let uncapped_pnl_long = {
let opening_price = Decimal::try_from(self.open_price)?;
let closing_price = Decimal::try_from(closing_price)?;
if opening_price == Decimal::ZERO || closing_price == Decimal::ZERO {
return Ok(0.0);
}
let quantity = Decimal::from(self.quantity);
let uncapped_pnl = (quantity / opening_price) - (quantity / closing_price);
let uncapped_pnl = uncapped_pnl
.round_dp_with_strategy(8, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
uncapped_pnl
.to_f64()
.context("Could not convert Decimal to f64")?
};
let margin = self.margin_taker().0;
let payout = match self.position {
Position::Long => margin + uncapped_pnl_long,
Position::Short => margin - uncapped_pnl_long,
};
let payout = payout.max(0.0);
let payout = payout.min(self.margin_total());
Ok(payout)
}
}