-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrpc.rs
1533 lines (1338 loc) · 44.9 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 std::{future::Future, ops::Range, sync::Arc, time::Duration};
use async_trait::async_trait;
#[cfg(any(feature = "standalone-metadata", feature = "parachain-metadata-foucoco"))]
use codec::Encode;
use futures::{future::join_all, stream::StreamExt, FutureExt, SinkExt};
use jsonrpsee::core::{client::Client, JsonValue};
use subxt::{
blocks::ExtrinsicEvents,
client::OnlineClient,
events::StaticEvent,
metadata::DecodeWithMetadata,
rpc::rpc_params,
storage::{address::Yes, StorageAddress},
tx::TxPayload,
Error as BasicError,
};
use tokio::{sync::RwLock, time::timeout};
use module_oracle_rpc_runtime_api::BalanceWrapper;
#[cfg(feature = "testing-utils")]
use primitives::Hash;
use crate::{
conn::{new_websocket_client, new_websocket_client_with_retry},
error::Recoverability,
metadata, notify_retry,
types::*,
AccountId, Error, RetryPolicy, ShutdownSender, SpacewalkRuntime, SpacewalkSigner, SubxtError,
};
pub type UnsignedFixedPoint = FixedU128;
// sanity check to be sure that testing-utils is not accidentally selected
#[cfg(all(any(test, feature = "testing-utils"), not(feature = "standalone-metadata")))]
compile_error!("Tests are only supported for the standalone-metadata");
cfg_if::cfg_if! {
if #[cfg(feature = "standalone-metadata")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1..100;
// This has to match the `spec_name` in the runtime, otherwise the runtime will be rejected.
pub const DEFAULT_SPEC_NAME: &str = "spacewalk-standalone";
// The prefix for the testchain is 42
pub const SS58_PREFIX: u16 = 42;
} else if #[cfg(feature = "parachain-metadata-pendulum")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1..100;
pub const DEFAULT_SPEC_NAME: &str = "pendulum";
pub const SS58_PREFIX: u16 = 56;
} else if #[cfg(feature = "parachain-metadata-amplitude")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1..1000;
pub const DEFAULT_SPEC_NAME: &str = "amplitude";
pub const SS58_PREFIX: u16 = 57;
} else if #[cfg(feature = "parachain-metadata-foucoco")] {
const DEFAULT_SPEC_VERSION: Range<u32> = 1..1000;
pub const DEFAULT_SPEC_NAME: &str = "foucoco";
pub const SS58_PREFIX: u16 = 57;
}
}
// timeout before retrying parachain calls (5 minutes)
const TRANSACTION_TIMEOUT: Duration = Duration::from_secs(300); // 5 minutes
// number of storage entries to fetch at a time
const DEFAULT_PAGE_SIZE: u32 = 10;
pub(crate) type FeeRateUpdateSender = tokio::sync::broadcast::Sender<FixedU128>;
pub type FeeRateUpdateReceiver = tokio::sync::broadcast::Receiver<FixedU128>;
#[derive(Clone)]
pub struct SpacewalkParachain {
signer: Arc<RwLock<SpacewalkSigner>>,
account_id: AccountId,
api: OnlineClient<SpacewalkRuntime>,
shutdown_tx: ShutdownSender,
fee_rate_update_tx: FeeRateUpdateSender,
pub native_currency_id: CurrencyId,
pub relay_chain_currency_id: CurrencyId,
}
impl SpacewalkParachain {
pub async fn new(
rpc_client: Client,
signer: Arc<RwLock<SpacewalkSigner>>,
shutdown_tx: ShutdownSender,
) -> Result<Self, Error> {
let account_id = signer.read().await.account_id().clone();
let api = OnlineClient::<SpacewalkRuntime>::from_rpc_client(Arc::new(rpc_client)).await?;
let runtime_version = api.rpc().runtime_version(None).await?;
let default_spec_name = &JsonValue::default();
let spec_name = runtime_version.other.get("specName").unwrap_or(default_spec_name);
if spec_name == DEFAULT_SPEC_NAME {
log::info!("spec_name={}", spec_name);
} else {
return Err(Error::ParachainMetadataMismatch(
DEFAULT_SPEC_NAME.into(),
spec_name.as_str().unwrap_or_default().into(),
))
}
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 relay_chain_currency_id =
api.constants().at(¤cy_constants.get_relay_chain_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,
shutdown_tx,
signer,
account_id,
fee_rate_update_tx,
native_currency_id: CurrencyId::Native,
relay_chain_currency_id,
};
Ok(parachain_rpc)
}
/// This function is used in integration tests to manually 'seal' ie create blocks.
#[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<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: Arc<RwLock<SpacewalkSigner>>,
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: Arc<RwLock<SpacewalkSigner>>,
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: Arc<RwLock<SpacewalkSigner>>,
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 with_retry<Call>(&self, call: Call) -> Result<ExtrinsicEvents<SpacewalkRuntime>, Error>
where
Call: TxPayload,
{
notify_retry::<Error, _, _, _, _, _>(
|| async {
let signer = self.signer.read().await;
match timeout(TRANSACTION_TIMEOUT, async {
let tx_progress =
self.api.tx().sign_and_submit_then_watch_default(&call, &*signer).await?;
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(ok) => Ok(ok),
Err(err) => match err.is_invalid_transaction() {
Some(Recoverability::Recoverable(data)) =>
Err(RetryPolicy::Skip(Error::InvalidTransaction(data))),
Some(Recoverability::Unrecoverable(data)) =>
Err(RetryPolicy::Throw(Error::InvalidTransaction(data))),
None => {
// Handle other errors
if err.is_pool_too_low_priority() {
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
}
#[cfg(test)]
async fn get_fresh_nonce(&self) -> u32 {
// For getting the nonce, use latest, possibly non-finalized block.
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();
on_chain_nonce.saturating_add(1)
}
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?)
}
pub async fn get_finalized_block_hash(&self) -> Result<Option<H256>, Error> {
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(SpacewalkHeader) -> R,
R: Future<Output = Result<(), Error>>,
{
let mut sub = self.api.rpc().subscribe_finalized_block_headers().await?;
loop {
on_block(sub.next().await.ok_or(Error::ChannelClosed)??).await?;
}
}
/// 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(BasicError)>(&self, on_error: E) -> Result<(), Error> {
let mut sub = self.api.blocks().subscribe_finalized().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.api.blocks().subscribe_finalized().await?;
let (tx, mut rx) = futures::channel::mpsc::channel(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 block = result?;
let events = block.events().await?;
for event in events.iter() {
match event {
Ok(event) => {
// Try to convert to target event
let target_event = event.as_event::<T>();
if let Ok(Some(target_event)) = target_event {
log::trace!("event: {:?}", target_event);
if tx.clone().send(target_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(())
}
/// 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(
subxt::ext::sp_runtime::MultiAddress::Id(recipient),
CurrencyId::XCM(0),
100,
);
let nonce = self.get_fresh_nonce().await;
let signer = self.signer.read().await.clone();
self.api
.tx()
.create_signed_with_nonce(&call, &signer, nonce, Default::default())
.unwrap()
.submit_and_watch()
.await
.unwrap();
// now call with outdated nonce
let result = self
.api
.tx()
.create_signed_with_nonce(&call, &signer, 0, Default::default())
.unwrap()
.submit_and_watch()
.await;
assert!(result.is_err());
result.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(
subxt::ext::sp_runtime::MultiAddress::Id(recipient),
CurrencyId::XCM(0),
100,
);
let nonce = self.get_fresh_nonce().await;
let signer = self.signer.read().await.clone();
// submit tx but don't watch
self.api
.tx()
.create_signed_with_nonce(&call, &signer, nonce, Default::default())
.unwrap()
.submit()
.await
.unwrap();
// should call with the same nonce
let result = self
.api
.tx()
.create_signed_with_nonce(&call, &signer, nonce, Default::default())
.unwrap()
.submit_and_watch()
.await;
assert!(result.is_err());
result.unwrap_err().into()
}
}
#[async_trait]
pub trait UtilFuncs {
/// Gets the current height of the parachain
async fn get_current_chain_height(&self) -> Result<u32, 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_trait]
impl UtilFuncs for SpacewalkParachain {
async fn get_current_chain_height(&self) -> Result<u32, Error> {
let height_query = metadata::storage().system().number();
let height = self.api.storage().fetch(&height_query, None).await?;
match height {
Some(height) => Ok(height),
None => Err(Error::BlockNotFound),
}
}
fn get_native_currency_id(&self) -> CurrencyId {
self.native_currency_id
}
fn is_this_vault(&self, vault_id: &VaultId) -> bool {
&vault_id.account_id == self.get_account_id()
}
fn get_account_id(&self) -> &AccountId {
&self.account_id
}
}
#[async_trait]
pub trait VaultRegistryPallet {
async fn get_vault(&self, vault_id: &VaultId) -> Result<SpacewalkVault, Error>;
async fn get_vaults_by_account_id(&self, account_id: &AccountId)
-> Result<Vec<VaultId>, Error>;
async fn get_all_vaults(&self) -> Result<Vec<SpacewalkVault>, Error>;
async fn register_vault(&self, vault_id: &VaultId, collateral: u128) -> Result<(), Error>;
async fn deposit_collateral(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error>;
async fn withdraw_collateral(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error>;
async fn get_public_key(&self) -> Result<Option<StellarPublicKeyRaw>, Error>;
async fn register_public_key(&self, public_key: StellarPublicKeyRaw) -> Result<(), Error>;
async fn get_required_collateral_for_wrapped(
&self,
amount_wrapped_asset: u128,
wrapped_currency_id: CurrencyId,
collateral_currency_id: CurrencyId,
) -> Result<u128, Error>;
async fn get_required_collateral_for_vault(&self, vault_id: VaultId) -> Result<u128, Error>;
async fn get_vault_total_collateral(&self, vault_id: VaultId) -> Result<u128, Error>;
async fn get_collateralization_from_vault(
&self,
vault_id: VaultId,
only_issued: bool,
) -> Result<u128, Error>;
}
#[async_trait]
impl VaultRegistryPallet for SpacewalkParachain {
/// Fetch a specific vault by ID.
///
/// # Arguments
/// * `vault_id` - account ID of the vault
///
/// # Errors
/// * `VaultNotFound` - if the rpc returned a default value rather than the vault we want
/// * `VaultLiquidated` - if the vault is liquidated
async fn get_vault(&self, vault_id: &VaultId) -> Result<SpacewalkVault, Error> {
let query = metadata::storage().vault_registry().vaults(&vault_id.clone());
match self.query_finalized(query).await? {
Some(SpacewalkVault { status: VaultStatus::Liquidated, .. }) =>
Err(Error::VaultLiquidated),
Some(vault) if &vault.id == vault_id => Ok(vault),
_ => Err(Error::VaultNotFound),
}
}
async fn get_vaults_by_account_id(
&self,
account_id: &AccountId,
) -> Result<Vec<VaultId>, Error> {
let head = self.get_finalized_block_hash().await?;
let result = self
.api
.rpc()
.request("vaultRegistry_getVaultsByAccountId", rpc_params![account_id, head])
.await?;
Ok(result)
}
/// Fetch all active vaults.
async fn get_all_vaults(&self) -> Result<Vec<SpacewalkVault>, Error> {
let mut vaults = Vec::new();
let head = self.get_finalized_block_hash().await?;
let key_addr = metadata::storage().vault_registry().vaults_root();
let mut iter = self.api.storage().iter(key_addr, DEFAULT_PAGE_SIZE, head).await?;
while let Some((_, account)) = iter.next().await? {
if let VaultStatus::Active(..) = account.status {
vaults.push(account);
}
}
Ok(vaults)
}
/// Submit extrinsic to register a vault.
///
/// # Arguments
/// * `collateral` - deposit
/// * `public_key` - Stellar public key
async fn register_vault(&self, vault_id: &VaultId, collateral: u128) -> Result<(), Error> {
// TODO: check MinimumDeposit
if collateral == 0 {
return Err(Error::InsufficientFunds)
}
let register_vault_tx = metadata::tx()
.vault_registry()
.register_vault(vault_id.currencies.clone(), collateral);
self.with_retry(register_vault_tx).await?;
Ok(())
}
/// Locks additional collateral as a security against stealing the
/// Stellar assets locked with it.
///
/// # Arguments
/// * `amount` - the amount of extra collateral to lock
async fn deposit_collateral(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error> {
let deposit_collateral_tx = metadata::tx()
.vault_registry()
.deposit_collateral(vault_id.currencies.clone(), amount);
self.with_retry(deposit_collateral_tx).await?;
Ok(())
}
/// Withdraws `amount` of the collateral from the amount locked by
/// the vault corresponding to the origin account
/// The collateral left after withdrawal must be more than MinimumCollateralVault
/// and above the SecureCollateralThreshold. Collateral that is currently
/// being used to back issued tokens remains locked until the Vault
/// is used for a redeem request (full release can take multiple redeem requests).
///
/// # Arguments
/// * `amount` - the amount of collateral to withdraw
async fn withdraw_collateral(&self, vault_id: &VaultId, amount: u128) -> Result<(), Error> {
let withdraw_collateral_tx = metadata::tx()
.vault_registry()
.withdraw_collateral(vault_id.currencies.clone(), amount);
self.with_retry(withdraw_collateral_tx).await?;
Ok(())
}
async fn get_public_key(&self) -> Result<Option<StellarPublicKeyRaw>, Error> {
let query = metadata::storage()
.vault_registry()
.vault_stellar_public_key(self.get_account_id());
self.query_finalized(query).await
}
/// Update the default Stellar public key for the vault corresponding to the signer.
///
/// # Arguments
/// * `public_key` - the new public key of the vault
async fn register_public_key(&self, public_key: StellarPublicKeyRaw) -> Result<(), Error> {
let register_public_key_tx =
metadata::tx().vault_registry().register_public_key(public_key);
self.with_retry(register_public_key_tx).await?;
Ok(())
}
/// Custom RPC that calculates the exact collateral required to cover the Stellar amount.
///
/// # Arguments
/// * `amount_wrapped_asset` - amount of the wrapped Stellar asset to convert
async fn get_required_collateral_for_wrapped(
&self,
amount_wrapped_asset: u128,
wrapped_currency_id: CurrencyId,
collateral_currency_id: CurrencyId,
) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: BalanceWrapper<_> = self
.api
.rpc()
.request(
"vaultRegistry_getRequiredCollateralForWrapped",
rpc_params![
BalanceWrapper { amount: amount_wrapped_asset },
wrapped_currency_id,
collateral_currency_id,
head
],
)
.await?;
Ok(result.amount)
}
/// Get the amount of collateral required for the given vault to be at the
/// current SecureCollateralThreshold with the current exchange rate
async fn get_required_collateral_for_vault(&self, vault_id: VaultId) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: BalanceWrapper<_> = self
.api
.rpc()
.request("vaultRegistry_getRequiredCollateralForVault", rpc_params![vault_id, head])
.await?;
Ok(result.amount)
}
async fn get_vault_total_collateral(&self, vault_id: VaultId) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: BalanceWrapper<_> = self
.api
.rpc()
.request("vaultRegistry_getVaultTotalCollateral", rpc_params![vault_id, head])
.await?;
Ok(result.amount)
}
async fn get_collateralization_from_vault(
&self,
vault_id: VaultId,
only_issued: bool,
) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: UnsignedFixedPoint = self
.api
.rpc()
.request(
"vaultRegistry_getCollateralizationFromVault",
rpc_params![vault_id, only_issued, head],
)
.await?;
Ok(result.into_inner())
}
}
#[async_trait]
pub trait CollateralBalancesPallet {
async fn get_free_balance(&self, currency_id: CurrencyId) -> Result<Balance, Error>;
async fn get_native_balance_for_id(&self, id: &AccountId) -> 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 SpacewalkParachain {
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_native_balance_for_id(&self, id: &AccountId) -> Result<Balance, Error> {
let head = self.get_finalized_block_hash().await?;
let query = metadata::storage().system().account(id);
let result = self.api.storage().fetch(&query, head).await?;
Ok(result.map(|x| x.data.free).unwrap_or_default())
}
async fn get_free_balance_for_id(
&self,
id: AccountId,
currency_id: CurrencyId,
) -> Result<Balance, Error> {
let head = self.get_finalized_block_hash().await?;
let query = metadata::storage().tokens().accounts(&id, ¤cy_id);
let result = self.api.storage().fetch(&query, head).await?;
Ok(result.map(|x| x.free).unwrap_or_default())
}
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 head = self.get_finalized_block_hash().await?;
let query = metadata::storage().tokens().accounts(&id, ¤cy_id);
let result = self.api.storage().fetch(&query, head).await?;
Ok(result.map(|x| x.reserved).unwrap_or_default())
}
async fn transfer_to(
&self,
recipient: &AccountId,
amount: u128,
currency_id: CurrencyId,
) -> Result<(), Error> {
let transfer_tx = metadata::tx().tokens().transfer(
subxt::ext::sp_runtime::MultiAddress::Id(recipient.clone()),
currency_id,
amount,
);
let signer = self.signer.read().await;
self.api.tx().sign_and_submit_then_watch_default(&transfer_tx, &*signer).await?;
Ok(())
}
}
#[async_trait]
pub trait OraclePallet {
async fn get_exchange_rate(
&self,
blockchain: Vec<u8>,
symbol: Vec<u8>,
) -> Result<FixedU128, Error>;
async fn get_oracle_keys(&self) -> Result<Vec<OracleKey>, Error>;
async fn feed_values(&self, values: Vec<((Vec<u8>, Vec<u8>), FixedU128)>) -> Result<(), Error>;
async fn currency_to_usd(&self, amount: u128, currency_id: CurrencyId) -> Result<u128, Error>;
async fn usd_to_currency(&self, amount: u128, currency_id: CurrencyId) -> Result<u128, Error>;
fn on_fee_rate_change(&self) -> FeeRateUpdateReceiver;
}
#[async_trait]
impl OraclePallet for SpacewalkParachain {
/// Returns the last exchange rate in planck per satoshis, the time at which it was set
/// and the configured max delay.
async fn get_exchange_rate(
&self,
blockchain: Vec<u8>,
symbol: Vec<u8>,
) -> Result<FixedU128, Error> {
use crate::metadata::runtime_types::dia_oracle::dia::AssetId;
let asset_id = AssetId { blockchain, symbol };
self.query_finalized_or_error(
metadata::storage().dia_oracle_module().coin_infos_map(&asset_id),
)
.await
.map(|coin_info| FixedU128::from_inner(coin_info.price))
}
/// Returns the last exchange rate in planck per satoshis, the time at which it was set
/// and the configured max delay.
async fn get_oracle_keys(&self) -> Result<Vec<OracleKey>, Error> {
self.query_finalized_or_error(metadata::storage().oracle().oracle_keys()).await
}
/// Sets the current exchange rate (i.e. DOT/XLM)
///
/// # Arguments
/// * `value` - the current exchange rate
async fn feed_values(&self, values: Vec<((Vec<u8>, Vec<u8>), FixedU128)>) -> Result<(), Error> {
if values.is_empty() {
return Err(Error::FeedingEmptyList)
}
use crate::metadata::runtime_types::dia_oracle::dia::CoinInfo;
let now = std::time::SystemTime::now();
let since_the_epoch =
now.duration_since(std::time::UNIX_EPOCH).expect("Time went backwards");
let time = since_the_epoch.as_secs();
let mut coin_infos = vec![];
for ((blockchain, symbol), price) in values {
log::info!("Setting price for {:?}/{:?} to {:?}", blockchain, symbol, price);
let coin_info = CoinInfo {
symbol: symbol.clone(),
name: vec![],
blockchain: blockchain.clone(),
supply: 0,
last_update_timestamp: time,
price: price.into_inner(),
};
coin_infos.push(((blockchain, symbol), coin_info));
}
self.with_retry(metadata::tx().dia_oracle_module().set_updated_coin_infos(coin_infos))
.await?;
Ok(())
}
/// Converts the amount of wrapped Stellar assets to the collateral currency, based on the
/// current set exchange rate.
async fn currency_to_usd(&self, amount: u128, currency_id: CurrencyId) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: BalanceWrapper<_> = self
.api
.rpc()
.request(
"oracle_currencyToUsd",
rpc_params![BalanceWrapper { amount }, currency_id, head],
)
.await?;
Ok(result.amount)
}
/// Converts the amount of collateral currency to the specified wrapped asset, based on the
/// current set exchange rate.
async fn usd_to_currency(&self, amount: u128, currency_id: CurrencyId) -> Result<u128, Error> {
let head = self.get_finalized_block_hash().await?;
let result: BalanceWrapper<_> = self
.api
.rpc()
.request(
"oracle_usdToCurrency",
rpc_params![BalanceWrapper { amount }, currency_id, head],
)
.await?;
Ok(result.amount)
}
fn on_fee_rate_change(&self) -> FeeRateUpdateReceiver {
self.fee_rate_update_tx.subscribe()
}
}
#[async_trait]
pub trait SecurityPallet {
async fn get_parachain_status(&self) -> Result<StatusCode, Error>;
async fn get_error_codes(&self) -> Result<Vec<ErrorCode>, Error>;
/// Gets the current active block number of the parachain
async fn get_current_active_block_number(&self) -> Result<u32, Error>;
}
#[async_trait]
impl SecurityPallet for SpacewalkParachain {
/// Get the current security status of the parachain.
/// Should be one of; `Running`, `Error` or `Shutdown`.
async fn get_parachain_status(&self) -> Result<StatusCode, Error> {
self.query_finalized_or_error(metadata::storage().security().parachain_status())
.await
}
/// Return any `ErrorCode`s set in the security module.
async fn get_error_codes(&self) -> Result<Vec<ErrorCode>, Error> {
self.query_finalized_or_error(metadata::storage().security().errors()).await
}
/// Gets the current active block number of the parachain
async fn get_current_active_block_number(&self) -> Result<u32, Error> {
self.query_finalized_or_default(metadata::storage().security().active_block_count())
.await
}
}
#[async_trait]
pub trait IssuePallet {
/// Request a new issue
async fn request_issue(
&self,
amount: u128,
vault_id: &VaultId,
) -> Result<RequestIssueEvent, Error>;
/// Execute an issue request by providing a Stellar transaction inclusion proof
async fn execute_issue(
&self,
issue_id: H256,
tx_envelope_xdr_encoded: &[u8],
envelopes_xdr_encoded: &[u8],
tx_set_xdr_encoded: &[u8],
) -> Result<(), Error>;
/// Cancel an ongoing issue request
async fn cancel_issue(&self, issue_id: H256) -> Result<(), Error>;
async fn get_issue_request(&self, issue_id: H256) -> Result<SpacewalkIssueRequest, Error>;
async fn get_vault_issue_requests(