forked from interlay/interbtc-clients
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.rs
1942 lines (1703 loc) · 70.4 KB
/
rpc.rs
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
assets::LendingAssets,
conn::{new_websocket_client, new_websocket_client_with_retry},
metadata, notify_retry,
types::*,
AccountId, AssetRegistry, CurrencyId, Error, InterBtcRuntime, InterBtcSigner, RetryPolicy, RichH256Le, SubxtError,
};
pub use crate::ShutdownSender;
use async_trait::async_trait;
use codec::{Decode, Encode};
use futures::{future::join_all, stream::StreamExt, FutureExt, SinkExt, Stream};
use module_oracle_rpc_runtime_api::BalanceWrapper;
use primitives::UnsignedFixedPoint;
use serde_json::Value;
use std::{collections::BTreeSet, future::Future, ops::Range, sync::Arc, time::Duration};
use subxt::{
blocks::ExtrinsicEvents,
client::OnlineClient,
events::StaticEvent,
metadata::DecodeWithMetadata,
rpc::{rpc_params, RpcClientT},
storage::{address::Yes, StorageAddress},
tx::TxPayload,
};
use tokio::{
sync::RwLock,
time::{sleep, timeout},
};
// timeout before retrying parachain calls (5 minutes)
const TRANSACTION_TIMEOUT: Duration = Duration::from_secs(300);
// timeout before re-verifying block header inclusion
const BLOCK_WAIT_TIMEOUT: Duration = Duration::from_secs(6);
// number of storage entries to fetch at a time
const DEFAULT_PAGE_SIZE: u32 = 10;
/// Keys in storage maps are prefixed by two `twox_128` hashes: the pallet name and the
/// storage item names. Then, depending on the `hash_fn` hasher the map uses, the layout
/// looks as follows:
/// `twox_128("PalletName") ++ twox_128("ItemName") ++ hash_fn(key) ++ key`
const BLAKE2_128_HASH_PREFIX_LENGTH: usize = 48;
const TWOX_64_HASH_PREFIX_LENGTH: usize = 40;
// sanity check to be sure that testing-utils is not accidentally selected
#[cfg(all(
any(test, feature = "testing-utils"),
not(feature = "parachain-metadata-kintsugi-testnet")
))]
compile_error!("Tests are only supported for the kintsugi testnet metadata");
cfg_if::cfg_if! {
if #[cfg(feature = "parachain-metadata-interlay")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1021000..1022000;
pub const DEFAULT_SPEC_NAME: &str = "interlay-parachain";
pub const SS58_PREFIX: u16 = 2032;
} else if #[cfg(feature = "parachain-metadata-kintsugi")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1021000..1022000;
pub const DEFAULT_SPEC_NAME: &str = "kintsugi-parachain";
pub const SS58_PREFIX: u16 = 2092;
} else if #[cfg(feature = "parachain-metadata-interlay-testnet")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1021000..1022000;
pub const DEFAULT_SPEC_NAME: &str = "testnet-interlay";
pub const SS58_PREFIX: u16 = 2032;
} else if #[cfg(feature = "parachain-metadata-kintsugi-testnet")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1021000..1022000;
pub const DEFAULT_SPEC_NAME: &str = "testnet-kintsugi";
pub const SS58_PREFIX: u16 = 2092;
}
}
pub(crate) type FeeRateUpdateSender = tokio::sync::broadcast::Sender<FixedU128>;
pub type FeeRateUpdateReceiver = tokio::sync::broadcast::Receiver<FixedU128>;
#[derive(Clone)]
pub struct InterBtcParachain {
api: Arc<OnlineClient<InterBtcRuntime>>,
nonce: Arc<RwLock<u32>>,
signer: InterBtcSigner,
account_id: AccountId,
shutdown_tx: ShutdownSender,
fee_rate_update_tx: FeeRateUpdateSender,
pub native_currency_id: CurrencyId,
pub relay_chain_currency_id: CurrencyId,
pub wrapped_currency_id: CurrencyId,
}
impl InterBtcParachain {
pub async fn new<P: RpcClientT>(
rpc_client: P,
signer: InterBtcSigner,
shutdown_tx: ShutdownSender,
) -> Result<Self, Error> {
let account_id = signer.account_id().clone();
let api = OnlineClient::from_rpc_client(Arc::new(rpc_client)).await?;
let runtime_version = api.rpc().runtime_version(None).await?;
let spec_name: String = runtime_version
.other
.get("specName")
.and_then(|value| value.as_str())
.map(ToString::to_string)
.unwrap_or_default();
if DEFAULT_SPEC_NAME == spec_name {
log::info!("spec_name={}", spec_name);
} else {
return Err(Error::ParachainMetadataMismatch(DEFAULT_SPEC_NAME.into(), spec_name));
}
if DEFAULT_SPEC_VERSION.contains(&runtime_version.spec_version) {
log::info!("spec_version={}", runtime_version.spec_version);
log::info!("transaction_version={}", runtime_version.transaction_version);
} else {
return Err(Error::InvalidSpecVersion(
DEFAULT_SPEC_VERSION.start,
DEFAULT_SPEC_VERSION.end,
runtime_version.spec_version,
));
}
let currency_constants = metadata::constants().currency();
let native_currency_id = api.constants().at(¤cy_constants.get_native_currency_id())?;
let relay_chain_currency_id = api.constants().at(¤cy_constants.get_relay_chain_currency_id())?;
let wrapped_currency_id = api.constants().at(¤cy_constants.get_wrapped_currency_id())?;
// low capacity channel since we generally only care about the newest value, so it's ok
// if we miss an event
let (fee_rate_update_tx, _) = tokio::sync::broadcast::channel(2);
let parachain_rpc = Self {
api: Arc::new(api),
nonce: Arc::new(RwLock::new(0)),
signer: signer,
account_id,
shutdown_tx,
fee_rate_update_tx,
native_currency_id,
relay_chain_currency_id,
wrapped_currency_id,
};
parachain_rpc.store_assets_metadata().await?;
#[cfg(any(
feature = "parachain-metadata-kintsugi-testnet",
feature = "parachain-metadata-interlay-testnet"
))]
parachain_rpc.store_lend_tokens().await?;
Ok(parachain_rpc)
}
#[cfg(feature = "testing-utils")]
pub async fn manual_seal(&self) {
// rather than adding a conditional dependency on substrate, just re-define the
// struct. We don't really care about the contents anyway, and if this is ever
// to change upstream we'll know from failing tests
#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
pub struct ImportedAux {
/// Only the header has been imported. Block body verification was skipped.
pub header_only: bool,
/// Clear all pending justification requests.
pub clear_justification_requests: bool,
/// Request a justification for the given block.
pub needs_justification: bool,
/// Received a bad justification.
pub bad_justification: bool,
/// Whether the block that was imported is the new best block.
pub is_new_best: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
pub struct CreatedBlock<Hash> {
/// hash of the created block.
pub hash: Hash,
/// some extra details about the import operation
pub aux: ImportedAux,
}
let head = self.get_finalized_block_hash().await.unwrap();
let _: CreatedBlock<interbtc_runtime::Hash> = self
.api
.rpc()
.request("engine_createBlock", rpc_params![true, true, head])
.await
.expect("failed to create block");
}
pub async fn from_url(url: &str, signer: InterBtcSigner, shutdown_tx: ShutdownSender) -> Result<Self, Error> {
let ws_client = new_websocket_client(url, None, None).await?;
Self::new(ws_client, signer, shutdown_tx).await
}
pub async fn from_url_with_retry(
url: &str,
signer: InterBtcSigner,
connection_timeout: Duration,
shutdown_tx: ShutdownSender,
) -> Result<Self, Error> {
Self::from_url_and_config_with_retry(url, signer, None, None, connection_timeout, shutdown_tx).await
}
pub async fn from_url_and_config_with_retry(
url: &str,
signer: InterBtcSigner,
max_concurrent_requests: Option<usize>,
max_notifs_per_subscription: Option<usize>,
connection_timeout: Duration,
shutdown_tx: ShutdownSender,
) -> Result<Self, Error> {
let ws_client = new_websocket_client_with_retry(
url,
max_concurrent_requests,
max_notifs_per_subscription,
connection_timeout,
)
.await?;
Self::new(ws_client, signer, shutdown_tx).await
}
async fn get_fresh_nonce(&self) -> u32 {
// For getting the nonce, use latest, possibly non-finalized block.
// TODO: we might want to wait until the latest block is actually finalized
// query account info in order to get the nonce value used for communication
let storage_key = metadata::storage().system().account(&self.account_id);
let on_chain_nonce = self
.api
.storage()
.fetch(&storage_key, None)
.await
.transpose()
.and_then(|x| x.ok())
.map(|x| x.nonce)
.unwrap_or_default();
let mut next_nonce = self.nonce.write().await;
let ret = if on_chain_nonce > *next_nonce {
log::info!("Synced to on-chain nonce: {}", on_chain_nonce);
on_chain_nonce
} else {
*next_nonce
};
*next_nonce = ret.saturating_add(1);
ret
}
async fn query_finalized<Address>(
&self,
address: Address,
) -> Result<Option<<Address::Target as DecodeWithMetadata>::Target>, Error>
where
Address: StorageAddress<IsFetchable = Yes>,
{
let hash = self.get_finalized_block_hash().await?;
Ok(self.api.storage().fetch(&address, hash).await?)
}
async fn query_finalized_or_error<Address>(
&self,
address: Address,
) -> Result<<Address::Target as DecodeWithMetadata>::Target, Error>
where
Address: StorageAddress<IsFetchable = Yes>,
{
self.query_finalized(address).await?.ok_or(Error::StorageItemNotFound)
}
async fn query_finalized_or_default<Address>(
&self,
address: Address,
) -> Result<<Address::Target as DecodeWithMetadata>::Target, Error>
where
Address: StorageAddress<IsFetchable = Yes, IsDefaultable = Yes>,
{
let hash = self.get_finalized_block_hash().await?;
Ok(self.api.storage().fetch_or_default(&address, hash).await?)
}
/// Gets a copy of the signer with a unique nonce
async fn with_unique_signer<Call>(&self, call: Call) -> Result<ExtrinsicEvents<InterBtcRuntime>, Error>
where
Call: TxPayload,
{
notify_retry::<Error, _, _, _, _, _>(
|| async {
let nonce = self.get_fresh_nonce().await;
match timeout(TRANSACTION_TIMEOUT, async {
let tx_progress = self
.api
.tx()
.create_signed_with_nonce(&call, &self.signer, nonce, Default::default())?
.submit_and_watch()
.await?;
if cfg!(feature = "testing-utils") {
tx_progress.wait_for_in_block().await?.wait_for_success().await
} else {
tx_progress.wait_for_finalized_success().await
}
})
.await
{
Err(_) => {
log::warn!("Timeout on transaction submission - restart required");
let _ = self.shutdown_tx.send(());
Err(Error::Timeout)
}
Ok(x) => Ok(x?),
}
},
|result| async {
match result.map_err(Into::<Error>::into) {
Ok(te) => Ok(te),
Err(err) => {
if let Some(data) = err.is_invalid_transaction() {
Err(RetryPolicy::Skip(Error::InvalidTransaction(data)))
} else if err.is_pool_too_low_priority().is_some() {
Err(RetryPolicy::Skip(Error::PoolTooLowPriority))
} else if err.is_block_hash_not_found_error() {
log::info!("Re-sending transaction after apparent fork");
Err(RetryPolicy::Skip(Error::BlockHashNotFound))
} else {
Err(RetryPolicy::Throw(err))
}
}
}
},
)
.await
}
pub async fn get_finalized_block_hash(&self) -> Result<Option<H256>, Error> {
if cfg!(feature = "testing-utils") {
Ok(None)
} else {
Ok(Some(self.api.rpc().finalized_head().await?))
}
}
/// Subscribe to new parachain blocks.
pub async fn on_block<F, R>(&self, on_block: F) -> Result<(), Error>
where
F: Fn(InterBtcHeader) -> R,
R: Future<Output = Result<(), Error>>,
{
let mut sub = if cfg!(feature = "testing-utils") {
self.api.blocks().subscribe_best().await?
} else {
self.api.blocks().subscribe_finalized().await?
};
loop {
on_block(
sub.next()
.await
.ok_or(Error::ChannelClosed)?
.map(|x| x.header().clone())?,
)
.await?;
}
}
/// Wait for the block at the given height
/// Note: will always wait at least one block.
pub async fn wait_for_block(&self, height: u32) -> Result<(), Error> {
let mut sub = if cfg!(feature = "testing-utils") {
self.api.blocks().subscribe_best().await?
} else {
self.api.blocks().subscribe_finalized().await?
};
while let Some(block) = sub.next().await {
if block?.number() >= height {
return Ok(());
}
}
Err(Error::ChannelClosed)
}
/// Sleep for `delay` parachain blocks
pub async fn delay_for_blocks(&self, delay: u32) -> Result<(), Error> {
if delay == 0 {
return Ok(());
}
let starting_parachain_height = self.get_current_chain_height().await?;
self.wait_for_block(starting_parachain_height + delay).await
}
async fn subscribe_events(
&self,
) -> Result<impl Stream<Item = Result<subxt::events::Events<InterBtcRuntime>, SubxtError>> + Unpin, Error> {
if cfg!(feature = "testing-utils") {
Ok(self
.api
.blocks()
.subscribe_best()
.await?
.then(|x| async move { x?.events().await })
.boxed())
} else {
Ok(self
.api
.blocks()
.subscribe_finalized()
.await?
.then(|x| async move { x?.events().await })
.boxed())
}
}
/// Subscription service that should listen forever, only returns if the initial subscription
/// cannot be established. Calls `on_error` when an error event has been received, or when an
/// event has been received that failed to be decoded into a raw event.
///
/// # Arguments
/// * `on_error` - callback for decoding errors, is not allowed to take too long
pub async fn on_event_error<E: Fn(SubxtError)>(&self, on_error: E) -> Result<(), Error> {
let mut sub = self.subscribe_events().await?;
loop {
match sub.next().await {
Some(Err(err)) => on_error(err), // report error
Some(Ok(_)) => {} // do nothing
None => break Ok(()), // end of stream
}
}
}
/// Subscription service that should listen forever, only returns if the initial subscription
/// cannot be established. This function uses two concurrent tasks: one for the event listener,
/// and one that calls the given callback. This allows the callback to take a long time to
/// complete without breaking the rpc communication, which could otherwise happen. Still, since
/// the queue of callbacks is processed sequentially, some care should be taken that the queue
/// does not overflow. `on_error` is called when the event has successfully been decoded into a
/// raw_event, but failed to decode into an event of type `T`
///
/// # Arguments
/// * `on_event` - callback for events, is allowed to sometimes take a longer time
/// * `on_error` - callback for decoding error, is not allowed to take too long
pub async fn on_event<T, F, R, E>(&self, mut on_event: F, on_error: E) -> Result<(), Error>
where
T: StaticEvent + core::fmt::Debug,
F: FnMut(T) -> R,
R: Future<Output = ()>,
E: Fn(SubxtError),
{
let mut sub = self.subscribe_events().await?;
let (tx, mut rx) = futures::channel::mpsc::channel::<T>(32);
// two tasks: one for event listening and one for callback calling
futures::future::try_join(
async move {
let tx = &tx;
while let Some(result) = sub.next().fuse().await {
let event_stream = result
.iter()
.flat_map(|events| {
events
.iter()
.map(|x| x.and_then(|y| y.as_event::<T>().map_err(|err| err.into())))
})
.filter_map(|x| x.transpose());
for result in event_stream {
match result {
Ok(event) => {
log::trace!("event: {:?}", event);
if tx.clone().send(event).await.is_err() {
break;
}
}
Err(err) => on_error(err),
}
}
}
Result::<(), _>::Err(Error::ChannelClosed)
},
async move {
loop {
// block until we receive an event from the other task
match rx.next().fuse().await {
Some(event) => {
on_event(event).await;
}
None => {
return Result::<(), _>::Err(Error::ChannelClosed);
}
}
}
},
)
.await?;
Ok(())
}
async fn batch(&self, calls: Vec<EncodedCall>) -> Result<(), Error> {
self.with_unique_signer(metadata::tx().utility().batch(calls)).await?;
Ok(())
}
/// Emulate the POOL_INVALID_TX error using token transfer extrinsics.
#[cfg(test)]
pub async fn get_invalid_tx_error(&self, recipient: AccountId) -> Error {
let call = metadata::tx().tokens().transfer(recipient, Token(DOT), 100);
let nonce = self.get_fresh_nonce().await;
self.api
.tx()
.create_signed_with_nonce(&call, &self.signer, nonce, Default::default())
.unwrap()
.submit_and_watch()
.await
.unwrap();
// now call with outdated nonce
self.api
.tx()
.create_signed_with_nonce(&call, &self.signer, 0, Default::default())
.unwrap()
.submit_and_watch()
.await
.unwrap_err()
.into()
}
/// Emulate the POOL_TOO_LOW_PRIORITY error using token transfer extrinsics.
#[cfg(test)]
pub async fn get_too_low_priority_error(&self, recipient: AccountId) -> Error {
let call = metadata::tx().tokens().transfer(recipient, Token(DOT), 100);
let nonce = self.get_fresh_nonce().await;
// submit tx but don't watch
self.api
.tx()
.create_signed_with_nonce(&call, &self.signer, nonce, Default::default())
.unwrap()
.submit()
.await
.unwrap();
// should call with the same nonce
self.api
.tx()
.create_signed_with_nonce(&call, &self.signer, nonce, Default::default())
.unwrap()
.submit_and_watch()
.await
.unwrap_err()
.into()
}
#[cfg(test)]
pub async fn register_dummy_assets(&self) -> Result<(), Error> {
let metadatas = ["ABC", "TEst", "QQQ"].map(|symbol| GenericAssetMetadata {
decimals: 10,
location: None,
name: b"irrelevant".to_vec(),
symbol: symbol.as_bytes().to_vec(),
existential_deposit: 0,
additional: metadata::runtime_types::interbtc_primitives::CustomMetadata {
fee_per_second: 0,
coingecko_id: vec![],
},
});
let registration_calls = metadatas
.map(|metadata| {
EncodedCall::AssetRegistry(
metadata::runtime_types::orml_asset_registry::module::Call::register_asset {
metadata: metadata.clone(),
asset_id: None,
},
)
})
.to_vec();
let batch = EncodedCall::Utility(metadata::runtime_types::pallet_utility::pallet::Call::batch {
calls: registration_calls,
});
self.with_unique_signer(metadata::tx().sudo().sudo(batch)).await?;
Ok(())
}
#[cfg(test)]
fn lending_mock_market_from_id(&self, id: u32) -> metadata::runtime_types::loans::types::Market<Balance> {
use primitives::{Rate, Ratio};
use sp_runtime::FixedPointNumber;
metadata::runtime_types::loans::types::Market::<Balance> {
close_factor: Ratio::from_percent(50),
collateral_factor: Ratio::from_percent(50),
liquidation_threshold: Ratio::from_percent(55),
liquidate_incentive: Rate::from_inner(Rate::DIV / 100 * 110),
state: metadata::runtime_types::loans::types::MarketState::Pending,
rate_model: metadata::runtime_types::loans::rate_model::InterestRateModel::Jump(
metadata::runtime_types::loans::rate_model::JumpModel {
base_rate: Rate::from_inner(Rate::DIV / 100 * 2),
jump_rate: Rate::from_inner(Rate::DIV / 100 * 10),
full_rate: Rate::from_inner(Rate::DIV / 100 * 32),
jump_utilization: Ratio::from_percent(80),
},
),
reserve_factor: Ratio::from_percent(15),
liquidate_incentive_reserved_factor: Ratio::from_percent(3),
supply_cap: 1_000_000_000_000_000_000_000u128,
borrow_cap: 1_000_000_000_000_000_000_000u128,
lend_token_id: CurrencyId::LendToken(id),
}
}
#[cfg(test)]
pub async fn register_lending_markets(&self) -> Result<(), Error> {
let add_market_txs = [ForeignAsset(1), Token(KINT)]
.iter()
.enumerate()
.map(|(i, asset_id)| {
EncodedCall::Loans(metadata::runtime_types::loans::pallet::Call::add_market {
asset_id: *asset_id,
market: self.lending_mock_market_from_id(i as u32),
})
})
.collect();
let batch = EncodedCall::Utility(metadata::runtime_types::pallet_utility::pallet::Call::batch {
calls: add_market_txs,
});
self.with_unique_signer(metadata::tx().sudo().sudo(batch)).await?;
Ok(())
}
pub async fn store_assets_metadata(&self) -> Result<(), Error> {
AssetRegistry::extend(self.get_foreign_assets_metadata().await?)
}
#[cfg(any(
feature = "parachain-metadata-kintsugi-testnet",
feature = "parachain-metadata-interlay-testnet"
))]
pub async fn store_lend_tokens(&self) -> Result<(), Error> {
let lend_tokens = self.get_lend_tokens().await?;
LendingAssets::extend(lend_tokens)
}
/// Cache registered assets and updates
pub async fn listen_for_registered_assets(&self) -> Result<(), Error> {
futures::future::try_join(
self.on_event::<RegisteredAssetEvent, _, _, _>(
|event| async move {
if let Err(err) = AssetRegistry::insert(event.asset_id, event.metadata) {
log::error!("Failed to register asset {}: {}", event.asset_id, err);
}
},
|_| {},
),
self.on_event::<UpdatedAssetEvent, _, _, _>(
|event| async move {
if let Err(err) = AssetRegistry::insert(event.asset_id, event.metadata) {
log::error!("Failed to update asset {}: {}", event.asset_id, err);
}
},
|_| {},
),
)
.await?;
Ok(())
}
/// Cache new markets and updates
#[cfg(any(
feature = "parachain-metadata-kintsugi-testnet",
feature = "parachain-metadata-interlay-testnet"
))]
pub async fn listen_for_lending_markets(&self) -> Result<(), Error> {
futures::future::try_join(
self.on_event::<NewMarketEvent, _, _, _>(
|event| async move {
if let Err(err) = LendingAssets::insert(event.underlying_currency_id, event.market.lend_token_id) {
log::error!(
"Failed to register lend token {:?}: {}",
event.underlying_currency_id,
err
);
}
},
|_| {},
),
self.on_event::<UpdatedMarketEvent, _, _, _>(
|event| async move {
if let Err(err) = LendingAssets::insert(event.underlying_currency_id, event.market.lend_token_id) {
log::error!(
"Failed to update lend token {:?}: {}",
event.underlying_currency_id,
err
);
}
},
|_| {},
),
)
.await?;
Ok(())
}
/// Listen to fee_rate changes and broadcast new values on the fee_rate_update_tx channel
pub async fn listen_for_fee_rate_changes(&self) -> Result<(), Error> {
self.on_event::<FeedValuesEvent, _, _, _>(
|event| async move {
for (key, value) in event.values {
if let OracleKey::FeeEstimation = key {
let _ = self.fee_rate_update_tx.send(value);
}
}
},
|_error| {
// Don't propagate error, it's unlikely to be useful.
// We assume critical errors will cause the system to restart.
// Note that we can't send the error itself due to the channel requiring
// the type to be clonable, which Error isn't
},
)
.await?;
Ok(())
}
fn strip_blake2_key_prefix(raw_key: &[u8]) -> &[u8] {
&raw_key[BLAKE2_128_HASH_PREFIX_LENGTH..]
}
fn strip_twox64_key_prefix(raw_key: &[u8]) -> &[u8] {
&raw_key[TWOX_64_HASH_PREFIX_LENGTH..]
}
}
#[async_trait]
pub trait UtilFuncs {
/// Gets the current height of the parachain
async fn get_current_chain_height(&self) -> Result<u32, Error>;
async fn get_rpc_properties(&self) -> Result<serde_json::Map<String, Value>, Error>;
/// Gets the ID of the native currency.
fn get_native_currency_id(&self) -> CurrencyId;
/// Get the address of the configured signer.
fn get_account_id(&self) -> &AccountId;
fn is_this_vault(&self, vault_id: &VaultId) -> bool;
async fn get_foreign_assets_metadata(&self) -> Result<Vec<(u32, AssetMetadata)>, Error>;
async fn get_foreign_asset_metadata(&self, id: u32) -> Result<AssetMetadata, Error>;
#[cfg(any(
feature = "parachain-metadata-kintsugi-testnet",
feature = "parachain-metadata-interlay-testnet"
))]
async fn get_lend_tokens(&self) -> Result<Vec<(CurrencyId, CurrencyId)>, Error>;
async fn get_decoded_storage_keys<T, U, F>(
&self,
key_addr: KeyStorageAddress<T>,
get_raw_key: F,
) -> Result<Vec<(U, T)>, Error>
where
T: Decode + Send + 'static,
U: Decode + Send + 'static,
F: Fn(&[u8]) -> &[u8] + Send + 'static;
}
#[async_trait]
impl UtilFuncs for InterBtcParachain {
async fn get_current_chain_height(&self) -> Result<u32, Error> {
self.query_finalized_or_error(metadata::storage().system().number())
.await
}
async fn get_rpc_properties(&self) -> Result<serde_json::Map<String, Value>, Error> {
Ok(self.api.rpc().system_properties().await?)
}
fn get_native_currency_id(&self) -> CurrencyId {
self.native_currency_id
}
fn get_account_id(&self) -> &AccountId {
&self.account_id
}
fn is_this_vault(&self, vault_id: &VaultId) -> bool {
&vault_id.account_id == self.get_account_id()
}
async fn get_decoded_storage_keys<T, U, F>(
&self,
key_addr: KeyStorageAddress<T>,
get_raw_key: F,
) -> Result<Vec<(U, T)>, Error>
where
T: Decode + Send + 'static,
U: Decode + Send + 'static,
F: Fn(&[u8]) -> &[u8] + Send + 'static,
{
let head = self.get_finalized_block_hash().await?;
let mut iter = self.api.storage().iter(key_addr, DEFAULT_PAGE_SIZE, head).await?;
let mut ret = Vec::new();
while let Some((key, value)) = iter.next().await? {
let raw_key = key.0.clone();
// last bytes are the raw key
let mut key = get_raw_key(raw_key.as_slice());
let decoded_key = U::decode(&mut key)?;
ret.push((decoded_key, value));
}
Ok(ret)
}
async fn get_foreign_assets_metadata(&self) -> Result<Vec<(u32, AssetMetadata)>, Error> {
let key_addr = metadata::storage().asset_registry().metadata_root();
self.get_decoded_storage_keys(key_addr, Self::strip_twox64_key_prefix)
.await
}
#[cfg(any(
feature = "parachain-metadata-kintsugi-testnet",
feature = "parachain-metadata-interlay-testnet"
))]
async fn get_lend_tokens(&self) -> Result<Vec<(CurrencyId, CurrencyId)>, Error> {
let key_addr = metadata::storage().loans().markets_root();
let markets = self
.get_decoded_storage_keys::<_, CurrencyId, _>(key_addr, Self::strip_blake2_key_prefix)
.await?;
let ret = markets
.into_iter()
.map(|(underlying_currency_id, market)| (underlying_currency_id, market.lend_token_id))
.collect();
Ok(ret)
}
async fn get_foreign_asset_metadata(&self, id: u32) -> Result<AssetMetadata, Error> {
self.query_finalized(metadata::storage().asset_registry().metadata(&id))
.await?
.ok_or(Error::AssetNotFound)
}
}
#[async_trait]
pub trait CollateralBalancesPallet {
async fn get_free_balance(&self, currency_id: CurrencyId) -> Result<Balance, Error>;
async fn get_free_balance_for_id(&self, id: AccountId, currency_id: CurrencyId) -> Result<Balance, Error>;
async fn get_reserved_balance(&self, currency_id: CurrencyId) -> Result<Balance, Error>;
async fn get_reserved_balance_for_id(&self, id: AccountId, currency_id: CurrencyId) -> Result<Balance, Error>;
async fn transfer_to(&self, recipient: &AccountId, amount: u128, currency_id: CurrencyId) -> Result<(), Error>;
}
#[async_trait]
impl CollateralBalancesPallet for InterBtcParachain {
async fn get_free_balance(&self, currency_id: CurrencyId) -> Result<Balance, Error> {
Ok(Self::get_free_balance_for_id(self, self.account_id.clone(), currency_id).await?)
}
async fn get_free_balance_for_id(&self, id: AccountId, currency_id: CurrencyId) -> Result<Balance, Error> {
let storage_key = metadata::storage().tokens().accounts(&id, ¤cy_id);
Ok(self.query_finalized_or_default(storage_key).await?.free)
}
async fn get_reserved_balance(&self, currency_id: CurrencyId) -> Result<Balance, Error> {
Ok(Self::get_reserved_balance_for_id(self, self.account_id.clone(), currency_id).await?)
}
async fn get_reserved_balance_for_id(&self, id: AccountId, currency_id: CurrencyId) -> Result<Balance, Error> {
let storage_key = metadata::storage().tokens().accounts(&id, ¤cy_id);
Ok(self.query_finalized_or_default(storage_key).await?.reserved)
}
async fn transfer_to(&self, recipient: &AccountId, amount: u128, currency_id: CurrencyId) -> Result<(), Error> {
self.with_unique_signer(metadata::tx().tokens().transfer(recipient.clone(), currency_id, amount))
.await?;
Ok(())
}
}
#[async_trait]
pub trait ReplacePallet {
/// Request the replacement of a new vault ownership
///
/// # Arguments
///
/// * `&self` - sender of the transaction
/// * `amount` - amount of [Wrapped]
async fn request_replace(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error>;
/// Withdraw a request of vault replacement
///
/// # Arguments
///
/// * `&self` - sender of the transaction: the old vault
/// * `amount` - the amount of [Wrapped] to replace
async fn withdraw_replace(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error>;
/// Accept request of vault replacement
///
/// # Arguments
///
/// * `&self` - the initiator of the transaction: the new vault
/// * `old_vault` - the vault to replace
/// * `amount_btc` - the amount of [Wrapped] to replace
/// * `collateral` - the collateral for replacement
/// * `btc_address` - the address to send funds to
async fn accept_replace(
&self,
new_vault: &VaultId,
old_vault: &VaultId,
amount_btc: u128,
collateral: u128,
btc_address: BtcAddress,
) -> Result<(), Error>;
//
/// Execute vault replacement
///
/// # Arguments
///
/// * `&self` - sender of the transaction: the old vault
/// * `replace_id` - the ID of the replacement request
/// * 'merkle_proof' - the merkle root of the block
/// * `raw_tx` - the transaction id in bytes
async fn execute_replace(&self, replace_id: H256, merkle_proof: &[u8], raw_tx: &[u8]) -> Result<(), Error>;
/// Cancel vault replacement
///
/// # Arguments
///
/// * `&self` - sender of the transaction: the new vault
/// * `replace_id` - the ID of the replacement request
async fn cancel_replace(&self, replace_id: H256) -> Result<(), Error>;
/// Get all replace requests accepted by the given vault
async fn get_new_vault_replace_requests(
&self,
account_id: AccountId,
) -> Result<Vec<(H256, InterBtcReplaceRequest)>, Error>;
/// Get all replace requests made by the given vault
async fn get_old_vault_replace_requests(
&self,
account_id: AccountId,
) -> Result<Vec<(H256, InterBtcReplaceRequest)>, Error>;
/// Get the time difference in number of blocks between when a replace
/// request is created and required completion time by a vault
async fn get_replace_period(&self) -> Result<u32, Error>;
/// Get a replace request from storage
async fn get_replace_request(&self, replace_id: H256) -> Result<InterBtcReplaceRequest, Error>;
/// Gets the minimum btc amount for replace requests
async fn get_replace_dust_amount(&self) -> Result<u128, Error>;
}
#[async_trait]
impl ReplacePallet for InterBtcParachain {
async fn request_replace(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error> {
self.with_unique_signer(
metadata::tx()
.replace()
.request_replace(vault_id.currencies.clone(), amount),
)
.await?;
Ok(())
}
async fn withdraw_replace(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error> {
self.with_unique_signer(
metadata::tx()
.replace()
.withdraw_replace(vault_id.currencies.clone(), amount),
)
.await?;
Ok(())
}
async fn accept_replace(
&self,
new_vault: &VaultId,
old_vault: &VaultId,
amount_btc: u128,
collateral: u128,
btc_address: BtcAddress,
) -> Result<(), Error> {
self.with_unique_signer(metadata::tx().replace().accept_replace(
new_vault.currencies.clone(),
old_vault.clone(),
amount_btc,
collateral,
btc_address,