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
#![deny(warnings)]
#![cfg_attr(test, feature(proc_macro_hygiene))]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod default_weights;
pub use default_weights::WeightInfo;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod migration;
#[cfg(test)]
extern crate mocktopus;
#[cfg(test)]
use mocktopus::macros::mockable;
mod ext;
pub mod types;
#[doc(inline)]
pub use crate::types::{DefaultIssueRequest, IssueRequest, IssueRequestStatus};
use crate::types::{BalanceOf, DefaultVaultId, Version};
use bitcoin::{merkle::PartialTransactionProof, types::FullTransactionProof};
use btc_relay::{BtcAddress, BtcPublicKey};
use currency::Amount;
use frame_support::{dispatch::DispatchError, ensure, pallet_prelude::Weight, traits::Get, transactional, PalletId};
use frame_system::{ensure_root, ensure_signed};
pub use pallet::*;
use sp_core::H256;
use sp_runtime::traits::{AccountIdConversion, Convert, Saturating};
use sp_std::vec::Vec;
use types::IssueRequestExt;
use vault_registry::{types::CurrencyId, CurrencySource, VaultStatus};
fn weight_for_execute_issue<T: Config>(proof: &FullTransactionProof) -> Weight {
let partial_weight = |partial_proof: &PartialTransactionProof| {
let h = partial_proof.merkle_proof.hashes.len() as u32;
let i = partial_proof.transaction.inputs.len() as u32;
let o = partial_proof.transaction.outputs.len() as u32;
let b = partial_proof.tx_encoded_len;
<T as Config>::WeightInfo::execute_issue_underpayment(h, i, o, b)
.max(<T as Config>::WeightInfo::execute_issue_exact(h, i, o, b))
.max(<T as Config>::WeightInfo::execute_issue_overpayment(h, i, o, b))
.max(<T as Config>::WeightInfo::execute_expired_issue_underpayment(
h, i, o, b,
))
.max(<T as Config>::WeightInfo::execute_expired_issue_exact(h, i, o, b))
.max(<T as Config>::WeightInfo::execute_expired_issue_overpayment(h, i, o, b))
};
partial_weight(&proof.coinbase_proof).saturating_add(partial_weight(&proof.user_tx_proof))
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config:
frame_system::Config + vault_registry::Config + btc_relay::Config + oracle::Config + fee::Config
{
#[pallet::constant]
type TreasuryPalletId: Get<PalletId>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type BlockNumberToBalance: Convert<BlockNumberFor<Self>, BalanceOf<Self>>;
type WeightInfo: WeightInfo;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
RequestIssue {
issue_id: H256,
requester: T::AccountId,
amount: BalanceOf<T>,
fee: BalanceOf<T>,
griefing_collateral: BalanceOf<T>,
griefing_currency: CurrencyId<T>,
vault_id: DefaultVaultId<T>,
vault_address: BtcAddress,
vault_public_key: BtcPublicKey,
},
IssueAmountChange {
issue_id: H256,
amount: BalanceOf<T>,
fee: BalanceOf<T>,
confiscated_griefing_collateral: BalanceOf<T>,
},
ExecuteIssue {
issue_id: H256,
requester: T::AccountId,
vault_id: DefaultVaultId<T>,
amount: BalanceOf<T>,
fee: BalanceOf<T>,
},
CancelIssue {
issue_id: H256,
requester: T::AccountId,
griefing_collateral: BalanceOf<T>,
},
IssuePeriodChange {
period: BlockNumberFor<T>,
},
}
#[pallet::error]
pub enum Error<T> {
IssueIdNotFound,
CommitPeriodExpired,
TimeNotExpired,
IssueCompleted,
IssueCancelled,
VaultNotAcceptingNewIssues,
WaitingForRelayerInitialization,
InvalidExecutor,
AmountBelowDustAmount,
}
#[pallet::storage]
#[pallet::getter(fn issue_requests)]
pub(super) type IssueRequests<T: Config> =
StorageMap<_, Blake2_128Concat, H256, DefaultIssueRequest<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn issue_period)]
pub(super) type IssuePeriod<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
#[pallet::storage]
pub(super) type IssueBtcDustValue<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
#[pallet::type_value]
pub(super) fn DefaultForStorageVersion() -> Version {
Version::V4
}
#[pallet::storage]
#[pallet::getter(fn storage_version)]
pub(super) type StorageVersion<T: Config> = StorageValue<_, Version, ValueQuery, DefaultForStorageVersion>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
pub issue_period: BlockNumberFor<T>,
pub issue_btc_dust_value: BalanceOf<T>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
IssuePeriod::<T>::put(self.issue_period);
IssueBtcDustValue::<T>::put(self.issue_btc_dust_value);
}
}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::request_issue())]
#[transactional]
pub fn request_issue(
origin: OriginFor<T>,
#[pallet::compact] amount: BalanceOf<T>,
vault_id: DefaultVaultId<T>,
griefing_currency: CurrencyId<T>,
) -> DispatchResultWithPostInfo {
let requester = ensure_signed(origin)?;
Self::_request_issue(requester, amount, vault_id, griefing_currency)?;
Ok(().into())
}
#[pallet::call_index(1)]
#[pallet::weight(weight_for_execute_issue::<T>(unchecked_transaction))]
#[transactional]
pub fn execute_issue(
origin: OriginFor<T>,
issue_id: H256,
unchecked_transaction: FullTransactionProof,
) -> DispatchResultWithPostInfo {
let executor = ensure_signed(origin)?;
Self::_execute_issue(executor, issue_id, unchecked_transaction)?;
Ok(().into())
}
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::cancel_issue())]
#[transactional]
pub fn cancel_issue(origin: OriginFor<T>, issue_id: H256) -> DispatchResultWithPostInfo {
let requester = ensure_signed(origin)?;
Self::_cancel_issue(requester, issue_id)?;
Ok(().into())
}
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::set_issue_period())]
#[transactional]
pub fn set_issue_period(origin: OriginFor<T>, period: BlockNumberFor<T>) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
<IssuePeriod<T>>::set(period);
Self::deposit_event(Event::IssuePeriodChange { period });
Ok(().into())
}
}
}
#[cfg_attr(test, mockable)]
impl<T: Config> Pallet<T> {
pub fn treasury_account_id() -> T::AccountId {
T::TreasuryPalletId::get().into_account_truncating()
}
fn _request_issue(
requester: T::AccountId,
amount_requested: BalanceOf<T>,
vault_id: DefaultVaultId<T>,
griefing_currency: CurrencyId<T>,
) -> Result<H256, DispatchError> {
let amount_requested = Amount::new(amount_requested, vault_id.wrapped_currency());
ensure!(
ext::btc_relay::is_fully_initialized::<T>()?,
Error::<T>::WaitingForRelayerInitialization
);
let vault = ext::vault_registry::get_active_vault_from_id::<T>(&vault_id)?;
ensure!(
vault.status == VaultStatus::Active(true),
Error::<T>::VaultNotAcceptingNewIssues
);
ext::vault_registry::ensure_not_banned::<T>(&vault_id)?;
let amount_collateral = amount_requested.convert_to(griefing_currency)?;
let griefing_collateral = ext::fee::get_issue_griefing_collateral::<T>(&amount_collateral)?;
griefing_collateral.lock_on(&requester)?;
ensure!(
amount_requested.ge(&Self::issue_btc_dust_value(vault_id.wrapped_currency()))?,
Error::<T>::AmountBelowDustAmount
);
ext::vault_registry::try_increase_to_be_issued_tokens::<T>(&vault_id, &amount_requested)?;
let fee = ext::fee::get_issue_fee::<T>(&amount_requested)?;
let amount_user = amount_requested.checked_sub(&fee)?;
let issue_id = ext::security::get_secure_id::<T>(&requester);
let btc_address = ext::vault_registry::register_deposit_address::<T>(&vault_id, issue_id)?;
let btc_public_key = ext::vault_registry::get_bitcoin_public_key::<T>(&vault_id.account_id)?;
let request = IssueRequest {
vault: vault_id,
opentime: ext::security::active_block_number::<T>(),
requester,
btc_address,
btc_public_key,
amount: amount_user.amount(),
fee: fee.amount(),
griefing_collateral: griefing_collateral.amount(),
griefing_currency: griefing_collateral.currency(),
period: Self::issue_period(),
btc_height: ext::btc_relay::get_best_block_height::<T>(),
status: IssueRequestStatus::Pending,
};
Self::insert_issue_request(&issue_id, &request);
Self::deposit_event(Event::RequestIssue {
issue_id,
requester: request.requester,
amount: request.amount,
fee: request.fee,
griefing_collateral: request.griefing_collateral,
griefing_currency: request.griefing_currency,
vault_id: request.vault,
vault_address: request.btc_address,
vault_public_key: request.btc_public_key,
});
Ok(issue_id)
}
fn _execute_issue(
executor: T::AccountId,
issue_id: H256,
unchecked_transaction: FullTransactionProof,
) -> Result<(), DispatchError> {
let mut issue = Self::get_issue_request_from_id(&issue_id)?;
let requester = issue.requester.clone();
let amount_transferred =
ext::btc_relay::get_and_verify_issue_payment::<T, BalanceOf<T>>(unchecked_transaction, issue.btc_address)?;
let amount_transferred = Amount::new(amount_transferred, issue.vault.wrapped_currency());
let expected_total_amount = issue.amount().checked_add(&issue.fee())?;
match issue.status {
IssueRequestStatus::Completed => return Err(Error::<T>::IssueCompleted.into()),
IssueRequestStatus::Cancelled => {
ext::vault_registry::ensure_accepting_new_issues::<T>(&issue.vault)?;
ext::vault_registry::try_increase_to_be_issued_tokens::<T>(&issue.vault, &amount_transferred)?;
if amount_transferred.lt(&expected_total_amount)? {
ensure!(requester == executor, Error::<T>::InvalidExecutor);
}
if amount_transferred.ne(&expected_total_amount)? {
let slashed = Amount::zero(issue.griefing_currency);
Self::set_issue_amount(&issue_id, &mut issue, amount_transferred, slashed)?;
}
}
IssueRequestStatus::Pending => {
let to_release_griefing_collateral = if amount_transferred.lt(&expected_total_amount)? {
ensure!(requester == executor, Error::<T>::InvalidExecutor);
Self::decrease_issue_amount(&issue_id, &mut issue, amount_transferred, expected_total_amount)?
} else {
if amount_transferred.gt(&expected_total_amount)?
&& !ext::vault_registry::is_vault_liquidated::<T>(&issue.vault)?
{
Self::try_increase_issue_amount(
&issue_id,
&mut issue,
amount_transferred,
expected_total_amount,
)?;
}
issue.griefing_collateral()
};
to_release_griefing_collateral.unlock_on(&requester)?;
}
}
let issue_amount = issue.amount();
let issue_fee = issue.fee();
let total = issue_amount.checked_add(&issue_fee)?;
ext::vault_registry::issue_tokens::<T>(&issue.vault, &total)?;
issue_amount.mint_to(&requester)?;
issue_fee.mint_to(&ext::fee::fee_pool_account_id::<T>())?;
ext::fee::distribute_rewards::<T>(&issue_fee)?;
Self::set_issue_status(issue_id, IssueRequestStatus::Completed);
Self::deposit_event(Event::ExecuteIssue {
issue_id,
requester,
vault_id: issue.vault,
amount: total.amount(),
fee: issue.fee,
});
Ok(())
}
fn _cancel_issue(requester: T::AccountId, issue_id: H256) -> Result<(), DispatchError> {
let issue = Self::get_pending_issue(&issue_id)?;
let issue_period = Self::issue_period().max(issue.period);
let to_be_slashed_collateral =
if ext::btc_relay::has_request_expired::<T>(issue.opentime, issue.btc_height, issue_period)? {
issue.griefing_collateral()
} else if issue.requester == requester {
let blocks_elapsed = ext::security::active_block_number::<T>().saturating_sub(issue.opentime);
let griefing_collateral = issue.griefing_collateral();
let slashed_collateral = ext::vault_registry::calculate_collateral::<T>(
&griefing_collateral,
&Amount::new(
T::BlockNumberToBalance::convert(blocks_elapsed),
griefing_collateral.currency(),
),
&Amount::new(
T::BlockNumberToBalance::convert(issue_period),
griefing_collateral.currency(),
),
)?
.min(&griefing_collateral)?;
let released_collateral = griefing_collateral.saturating_sub(&slashed_collateral)?;
released_collateral.unlock_on(&requester)?;
slashed_collateral
} else {
return Err(Error::<T>::TimeNotExpired.into());
};
if ext::vault_registry::is_vault_liquidated::<T>(&issue.vault)? {
to_be_slashed_collateral.unlock_on(&issue.requester)?;
} else {
ext::vault_registry::transfer_funds::<T>(
CurrencySource::UserGriefing(issue.requester.clone()),
CurrencySource::FreeBalance(Self::treasury_account_id()),
&to_be_slashed_collateral,
)?;
}
let full_amount = issue.amount().checked_add(&issue.fee())?;
ext::vault_registry::decrease_to_be_issued_tokens::<T>(&issue.vault, &full_amount)?;
Self::set_issue_status(issue_id, IssueRequestStatus::Cancelled);
Self::deposit_event(Event::CancelIssue {
issue_id,
requester,
griefing_collateral: to_be_slashed_collateral.amount(),
});
Ok(())
}
fn decrease_issue_amount(
issue_id: &H256,
issue: &mut DefaultIssueRequest<T>,
amount_transferred: Amount<T>,
expected_total_amount: Amount<T>,
) -> Result<Amount<T>, DispatchError> {
let deficit = expected_total_amount.checked_sub(&amount_transferred)?;
ext::vault_registry::decrease_to_be_issued_tokens::<T>(&issue.vault, &deficit)?;
let to_release_collateral = ext::vault_registry::calculate_collateral::<T>(
&issue.griefing_collateral(),
&amount_transferred,
&expected_total_amount,
)?;
let slashed_collateral = issue.griefing_collateral().checked_sub(&to_release_collateral)?;
ext::vault_registry::transfer_funds::<T>(
CurrencySource::UserGriefing(issue.requester.clone()),
CurrencySource::FreeBalance(Self::treasury_account_id()),
&slashed_collateral,
)?;
Self::set_issue_amount(&issue_id, issue, amount_transferred, slashed_collateral)?;
Ok(to_release_collateral)
}
fn try_increase_issue_amount(
issue_id: &H256,
issue: &mut DefaultIssueRequest<T>,
amount_transferred: Amount<T>,
expected_total_amount: Amount<T>,
) -> Result<(), DispatchError> {
let surplus_btc = amount_transferred.checked_sub(&expected_total_amount)?;
let max_allowed = ext::vault_registry::get_issuable_tokens_from_vault::<T>(&issue.vault)?;
let issue_amount = surplus_btc.min(&max_allowed)?;
if let Ok(_) = ext::vault_registry::try_increase_to_be_issued_tokens::<T>(&issue.vault, &issue_amount) {
Self::set_issue_amount(
&issue_id,
issue,
expected_total_amount.checked_add(&issue_amount)?,
Amount::zero(issue.griefing_currency),
)?;
}
Ok(())
}
pub fn get_issue_requests_for_account(account_id: T::AccountId) -> Vec<H256> {
<IssueRequests<T>>::iter()
.filter(|(_, request)| request.requester == account_id)
.map(|(key, _)| key)
.collect()
}
pub fn get_issue_requests_for_vault(vault_id: T::AccountId) -> Vec<H256> {
<IssueRequests<T>>::iter()
.filter(|(_, request)| request.vault.account_id == vault_id)
.map(|(key, _)| key)
.collect()
}
pub fn get_issue_request_from_id(issue_id: &H256) -> Result<DefaultIssueRequest<T>, DispatchError> {
let request = IssueRequests::<T>::try_get(issue_id).or(Err(Error::<T>::IssueIdNotFound))?;
match request.status {
IssueRequestStatus::Completed => Err(Error::<T>::IssueCompleted.into()),
_ => Ok(request),
}
}
pub fn get_pending_issue(issue_id: &H256) -> Result<DefaultIssueRequest<T>, DispatchError> {
let request = IssueRequests::<T>::try_get(issue_id).or(Err(Error::<T>::IssueIdNotFound))?;
match request.status {
IssueRequestStatus::Completed => Err(Error::<T>::IssueCompleted.into()),
IssueRequestStatus::Cancelled => Err(Error::<T>::IssueCancelled.into()),
IssueRequestStatus::Pending => Ok(request),
}
}
fn set_issue_amount(
issue_id: &H256,
issue: &mut DefaultIssueRequest<T>,
transferred_btc: Amount<T>,
confiscated_griefing_collateral: Amount<T>,
) -> Result<(), DispatchError> {
issue.fee = ext::fee::get_issue_fee::<T>(&transferred_btc)?.amount();
issue.amount = transferred_btc.checked_sub(&issue.fee())?.amount();
<IssueRequests<T>>::mutate_exists(issue_id, |request| {
*request = request.clone().map(|request| DefaultIssueRequest::<T> {
fee: issue.fee,
amount: issue.amount,
..request
});
});
Self::deposit_event(Event::IssueAmountChange {
issue_id: *issue_id,
amount: issue.amount,
fee: issue.fee,
confiscated_griefing_collateral: confiscated_griefing_collateral.amount(),
});
Ok(())
}
fn insert_issue_request(key: &H256, value: &DefaultIssueRequest<T>) {
<IssueRequests<T>>::insert(key, value)
}
fn set_issue_status(id: H256, status: IssueRequestStatus) {
<IssueRequests<T>>::mutate_exists(id, |request| {
*request = request
.clone()
.map(|request| DefaultIssueRequest::<T> { status, ..request });
});
}
fn issue_btc_dust_value(currency_id: CurrencyId<T>) -> Amount<T> {
Amount::new(IssueBtcDustValue::<T>::get(), currency_id)
}
}