-
Notifications
You must be signed in to change notification settings - Fork 11
/
lib.rs
770 lines (695 loc) · 23.4 KB
/
lib.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
// This file is part of Webb.
// Copyright (C) 2021-2023 Webb Technologies Inc.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # VAnchor Module
//!
//! A simple module for building variable Anchors.
//!
//! ## Overview
//!
//! The VAnchor module provides functionality for the following:
//!
//! * Creating new instances
//!
//! * Making transactions with variable amount of tokens
//!
//! The supported dispatchable functions are documented in the [`Call`] enum.
//!
//! ## Interface
//!
//! ### Permissionless Functions
//!
//! * `create`: Creates an vanchor and inserts an element into the on-chain merkle tree.
//! * `transact`: Allows the withdrawel of variable asset sizes but requires a zero-knowledge proof
//! of an unspent (UTXO) in an anchors merkle tree specified by TreeId.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
#[cfg(test)]
pub mod mock;
#[cfg(test)]
mod test_utils;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_circom;
#[cfg(test)]
mod zerokit_utils;
mod benchmarking;
mod benchmarking_utils;
use codec::{Decode, Encode};
use frame_support::{dispatch::DispatchResult, ensure, pallet_prelude::DispatchError, traits::Get};
use orml_traits::{
arithmetic::{Signed, Zero},
MultiCurrency, MultiCurrencyExtended,
};
use pallet_token_wrapper::traits::TokenWrapperInterface;
use sp_runtime::traits::Saturating;
use webb_primitives::{
field_ops::IntoPrimeField,
hasher::InstanceHasher,
key_storage::KeyStorageInterface,
linkable_tree::{LinkableTreeInspector, LinkableTreeInterface},
traits::vanchor::{VAnchorConfig, VAnchorInspector, VAnchorInterface},
types::{
vanchor::{ExtData, ProofData, VAnchorMetadata},
ElementTrait, IntoAbiToken,
},
utils::reverse_element_encoder,
verifier::*,
webb_proposals::ResourceId,
};
use sp_runtime::traits::{AccountIdConversion, AtLeast32Bit};
use sp_std::{
convert::{TryFrom, TryInto},
prelude::*,
};
pub mod weights;
pub use weights::WeightInfo;
/// Type alias for the orml_traits::MultiCurrency::Balance type
pub type BalanceOf<T, I> =
<<T as Config<I>>::Currency as MultiCurrency<<T as frame_system::Config>::AccountId>>::Balance;
/// Type alias for the orml_traits::MultiCurrency::Balance type
pub type AmountOf<T, I> = <<T as Config<I>>::Currency as MultiCurrencyExtended<
<T as frame_system::Config>::AccountId,
>>::Amount;
/// Type alias for the orml_traits::MultiCurrency::CurrencyId type
pub type CurrencyIdOf<T, I> = <<T as pallet::Config<I>>::Currency as MultiCurrency<
<T as frame_system::Config>::AccountId,
>>::CurrencyId;
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, PalletId};
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
/// The module configuration trait.
pub trait Config<I: 'static = ()>:
frame_system::Config + pallet_linkable_tree::Config<I>
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::constant]
type PalletId: Get<PalletId>;
/// The tree type
type LinkableTree: LinkableTreeInterface<pallet_linkable_tree::LinkableTreeConfigration<Self, I>>
+ LinkableTreeInspector<pallet_linkable_tree::LinkableTreeConfigration<Self, I>>;
/// The key storage type
type KeyStorage: KeyStorageInterface<Self::AccountId>;
/// Proposal nonce type
type ProposalNonce: Encode
+ Decode
+ Parameter
+ AtLeast32Bit
+ Default
+ Copy
+ MaxEncodedLen
+ From<Self::LeafIndex>
+ Into<Self::LeafIndex>;
/// The verifier
type VAnchorVerifier: VAnchorVerifierModule;
/// The ethereum hash function for hashing external data (to match Solidity protocol)
type EthereumHasher: InstanceHasher;
/// A trait to map amount elements into a prime field.
type IntoField: IntoPrimeField<AmountOf<Self, I>>;
/// Currency type for taking deposits
type Currency: MultiCurrencyExtended<Self::AccountId>;
/// An arbitrary execution function to execute after deposits/insertions are made
type PostDepositHook: PostDepositHook<Self, I>;
/// Max external amount
type MaxExtAmount: Get<BalanceOf<Self, I>>;
/// Max fee amount
type MaxFee: Get<BalanceOf<Self, I>>;
/// Max currency ID value for signaling a strict transact without unwrapping
type MaxCurrencyId: Get<CurrencyIdOf<Self, I>>;
/// TokenWrapper Interface
type TokenWrapper: TokenWrapperInterface<
Self::AccountId,
CurrencyIdOf<Self, I>,
BalanceOf<Self, I>,
Self::ProposalNonce,
>;
/// Native currency id
#[pallet::constant]
type NativeCurrencyId: Get<CurrencyIdOf<Self, I>>;
/// WeightInfo for pallet
type WeightInfo: WeightInfo;
}
#[pallet::storage]
#[pallet::getter(fn max_deposit_amount)]
pub type MaxDepositAmount<T: Config<I>, I: 'static = ()> =
StorageValue<_, BalanceOf<T, I>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn min_withdraw_amount)]
pub type MinWithdrawAmount<T: Config<I>, I: 'static = ()> =
StorageValue<_, BalanceOf<T, I>, ValueQuery>;
/// The map of trees to their anchor metadata
#[pallet::storage]
#[pallet::getter(fn vanchors)]
pub type VAnchors<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Blake2_128Concat,
T::TreeId,
VAnchorMetadata<T::AccountId, CurrencyIdOf<T, I>>,
OptionQuery,
>;
/// The map of trees to their spent nullifier hashes
#[pallet::storage]
#[pallet::getter(fn nullifier_hashes)]
pub type NullifierHashes<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::TreeId,
Blake2_128Concat,
T::Element,
bool,
ValueQuery,
>;
/// The proposal nonce used to prevent replay attacks on execute_proposal
#[pallet::storage]
#[pallet::getter(fn proposal_nonce)]
pub type ProposalNonce<T: Config<I>, I: 'static = ()> =
StorageValue<_, T::ProposalNonce, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// New tree created
VAnchorCreation {
tree_id: T::TreeId,
},
/// Transaction has been made
Transaction {
transactor: T::AccountId,
tree_id: T::TreeId,
leafs: Vec<T::Element>,
encrypted_output1: Vec<u8>,
encrypted_output2: Vec<u8>,
amount: AmountOf<T, I>,
},
/// Deposit hook has executed successfully
Deposit {
depositor: T::AccountId,
tree_id: T::TreeId,
leaf: T::Element,
},
MaxDepositAmountChanged {
max_deposit_amount: BalanceOf<T, I>,
},
MinWithdrawAmountChanged {
min_withdraw_amount: BalanceOf<T, I>,
},
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// Invalid transaction proof
InvalidTransactionProof,
/// Variable Anchor not found.
NoVAnchorFound,
/// Invalid nullifier that is already used
/// (this error is returned when a nullifier is used twice)
AlreadyRevealedNullifier,
// Invalid external amount
InvalidExtAmount,
// Maximum deposit amount exceeded
InvalidDepositAmount,
// Maximum withdraw amount exceeded
InvalidWithdrawAmount,
// Invalid external data
InvalidExtData,
// Invalid input nullifiers
InvalidInputNullifiers,
// Invalid fee
InvalidFee,
// Invalid public amount
InvalidPublicAmount,
/// Invalid nonce
InvalidNonce,
}
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {}
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
pub phantom: (PhantomData<T>, PhantomData<I>),
pub max_deposit_amount: BalanceOf<T, I>,
pub min_withdraw_amount: BalanceOf<T, I>,
pub vanchors: Vec<(CurrencyIdOf<T, I>, u32)>,
}
#[cfg(feature = "std")]
impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
fn default() -> Self {
Self {
phantom: Default::default(),
max_deposit_amount: BalanceOf::<T, I>::default(),
min_withdraw_amount: BalanceOf::<T, I>::default(),
vanchors: Vec::new(),
}
}
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> GenesisBuild<T, I> for GenesisConfig<T, I> {
fn build(&self) {
MaxDepositAmount::<T, I>::put(self.max_deposit_amount);
MinWithdrawAmount::<T, I>::put(self.min_withdraw_amount);
let mut ctr: u32 = 1;
self.vanchors.iter().for_each(|(asset_id, max_edges)| {
let _ = <Pallet<T, I> as VAnchorInterface<_>>::create(
None,
30,
*max_edges,
*asset_id,
T::ProposalNonce::from(ctr),
)
.map_err(|_| panic!("Failed to create vanchor"));
ctr = ctr.saturating_add(1);
});
}
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
#[pallet::weight(<T as pallet::Config<I>>::WeightInfo::create(*depth as u32))]
#[pallet::call_index(0)]
pub fn create(
origin: OriginFor<T>,
max_edges: u32,
depth: u8,
asset: CurrencyIdOf<T, I>,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
let tree_id = <Self as VAnchorInterface<_>>::create(
None,
depth,
max_edges,
asset,
ProposalNonce::<T, I>::get().saturating_add(T::ProposalNonce::from(1u32)),
)?;
Self::deposit_event(Event::VAnchorCreation { tree_id });
Ok(().into())
}
#[pallet::weight(<T as pallet::Config<I>>::WeightInfo::transact())]
#[pallet::call_index(1)]
pub fn transact(
origin: OriginFor<T>,
id: T::TreeId,
proof_data: ProofData<T::Element>,
ext_data: ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
<Self as VAnchorInterface<_>>::transact(sender, id, proof_data, ext_data)?;
Ok(().into())
}
#[pallet::weight(<T as pallet::Config<I>>::WeightInfo::register_and_transact())]
#[pallet::call_index(2)]
pub fn register_and_transact(
origin: OriginFor<T>,
owner: T::AccountId,
public_key: Vec<u8>,
id: T::TreeId,
proof_data: ProofData<T::Element>,
ext_data: ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
<Self as VAnchorInterface<_>>::register_and_transact(
owner, public_key, sender, id, proof_data, ext_data,
)?;
Ok(().into())
}
#[pallet::weight(<T as pallet::Config<I>>::WeightInfo::set_max_deposit_amount())]
#[pallet::call_index(3)]
pub fn set_max_deposit_amount(
origin: OriginFor<T>,
max_deposit_amount: BalanceOf<T, I>,
nonce: T::ProposalNonce,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
<Self as VAnchorInterface<_>>::set_max_deposit_amount(max_deposit_amount, nonce)?;
Ok(().into())
}
#[pallet::weight(<T as pallet::Config<I>>::WeightInfo::set_min_withdraw_amount())]
#[pallet::call_index(4)]
pub fn set_min_withdraw_amount(
origin: OriginFor<T>,
min_withdraw_amount: BalanceOf<T, I>,
nonce: T::ProposalNonce,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
<Self as VAnchorInterface<_>>::set_min_withdraw_amount(min_withdraw_amount, nonce)?;
Ok(().into())
}
}
}
pub struct VAnchorConfiguration<T: Config<I>, I: 'static>(
core::marker::PhantomData<T>,
core::marker::PhantomData<I>,
);
impl<T: Config<I>, I: 'static> VAnchorConfig for VAnchorConfiguration<T, I> {
type AccountId = T::AccountId;
type Amount = AmountOf<T, I>;
type Balance = BalanceOf<T, I>;
type ChainId = T::ChainId;
type CurrencyId = CurrencyIdOf<T, I>;
type Element = T::Element;
type LeafIndex = T::LeafIndex;
type TreeId = T::TreeId;
type ProposalNonce = T::ProposalNonce;
}
impl<T: Config<I>, I: 'static> VAnchorInterface<VAnchorConfiguration<T, I>> for Pallet<T, I> {
fn create(
creator: Option<T::AccountId>,
depth: u8,
max_edges: u32,
asset: CurrencyIdOf<T, I>,
nonce: T::ProposalNonce,
) -> Result<T::TreeId, DispatchError> {
// Nonce should be greater than the proposal nonce in storage
Self::validate_and_set_nonce(nonce)?;
let id = T::LinkableTree::create(creator.clone(), max_edges, depth)?;
VAnchors::<T, I>::insert(id, VAnchorMetadata { creator, asset });
Ok(id)
}
fn register_and_transact(
owner: T::AccountId,
public_key: Vec<u8>,
transactor: T::AccountId,
id: T::TreeId,
proof_data: ProofData<T::Element>,
ext_data: ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(), DispatchError> {
// First Register
T::KeyStorage::register(owner, public_key)?;
// Then Transact
<Self as VAnchorInterface<_>>::transact(transactor, id, proof_data, ext_data)?;
Ok(())
}
fn transact(
transactor: T::AccountId,
id: T::TreeId,
proof_data: ProofData<T::Element>,
ext_data: ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(), DispatchError> {
// Double check the number of roots
T::LinkableTree::ensure_max_edges(id, proof_data.roots.len())?;
// Check if local root is known
T::LinkableTree::ensure_known_root(id, proof_data.roots[0])?;
// Check if neighbor roots are known
T::LinkableTree::ensure_known_neighbor_roots(id, &proof_data.roots[1..].to_vec())?;
// Ensure all input nullifiers are unused
for nullifier in &proof_data.input_nullifiers {
Self::ensure_nullifier_unused(id, *nullifier)?;
}
// Get the vanchor
let vanchor = Self::get_vanchor(id)?;
// Compute hash of abi encoded ext_data, reduced into field from config
let computed_ext_data_hash = T::EthereumHasher::hash(&ext_data.encode_abi(), &[])
.map_err(|_| Error::<T, I>::InvalidExtData)?;
// Ensure that the passed external data hash matches the computed one
ensure!(
proof_data.ext_data_hash.to_bytes() == computed_ext_data_hash,
Error::<T, I>::InvalidExtData
);
// Making sure that public amount and fee are correct
ensure!(ext_data.fee < T::MaxFee::get(), Error::<T, I>::InvalidFee);
let ext_amount_unsigned: BalanceOf<T, I> = ext_data
.ext_amount
.abs()
.try_into()
.map_err(|_| Error::<T, I>::InvalidExtAmount)?;
ensure!(ext_amount_unsigned < T::MaxExtAmount::get(), Error::<T, I>::InvalidExtAmount);
// Verify public amount for proof
let (calculated_public_element, public_amount) = Self::calculate_public_amount(&ext_data)?;
ensure!(
proof_data.public_amount == calculated_public_element,
Error::<T, I>::InvalidPublicAmount
);
// Handle proof verification
Self::handle_proof_verification(&proof_data)?;
// Flag nullifiers as used
for nullifier in &proof_data.input_nullifiers {
Self::add_nullifier_hash(id, *nullifier)?;
}
// Handle the deposit / withdrawal shield/unshield portions
Self::handle_asset_action(&transactor, &vanchor, &ext_data)?;
// Check if the fee is non-zero
Self::handle_fee(&vanchor, &ext_data)?;
// Check if the gas-refund is non-zero
Self::handle_refund(&transactor, &ext_data)?;
// Insert output commitments into the tree
for comm in &proof_data.output_commitments {
T::LinkableTree::insert_in_order(id, *comm)?;
}
// Deposit transaction event
Self::deposit_event(Event::Transaction {
transactor,
tree_id: id,
leafs: proof_data.output_commitments,
encrypted_output1: ext_data.encrypted_output1,
encrypted_output2: ext_data.encrypted_output2,
amount: public_amount,
});
Ok(())
}
fn add_nullifier_hash(id: T::TreeId, nullifier_hash: T::Element) -> Result<(), DispatchError> {
NullifierHashes::<T, I>::insert(id, nullifier_hash, true);
Ok(())
}
fn add_edge(
id: T::TreeId,
src_chain_id: T::ChainId,
root: T::Element,
latest_leaf_index: T::LeafIndex,
src_resource_id: ResourceId,
) -> Result<(), DispatchError> {
T::LinkableTree::add_edge(id, src_chain_id, root, latest_leaf_index, src_resource_id)
}
fn update_edge(
id: T::TreeId,
src_chain_id: T::ChainId,
root: T::Element,
latest_leaf_index: T::LeafIndex,
src_resource_id: ResourceId,
) -> Result<(), DispatchError> {
T::LinkableTree::update_edge(id, src_chain_id, root, latest_leaf_index, src_resource_id)
}
fn set_max_deposit_amount(
max_deposit_amount: BalanceOf<T, I>,
nonce: T::ProposalNonce,
) -> Result<(), DispatchError> {
// Nonce should be greater than the proposal nonce in storage
Self::validate_and_set_nonce(nonce)?;
MaxDepositAmount::<T, I>::put(max_deposit_amount);
Self::deposit_event(Event::MaxDepositAmountChanged { max_deposit_amount });
Ok(())
}
fn set_min_withdraw_amount(
min_withdraw_amount: BalanceOf<T, I>,
nonce: T::ProposalNonce,
) -> Result<(), DispatchError> {
// Nonce should be greater than the proposal nonce in storage
Self::validate_and_set_nonce(nonce)?;
MinWithdrawAmount::<T, I>::put(min_withdraw_amount);
Self::deposit_event(Event::MinWithdrawAmountChanged { min_withdraw_amount });
Ok(())
}
}
impl<T: Config<I>, I: 'static> VAnchorInspector<VAnchorConfiguration<T, I>> for Pallet<T, I> {
fn is_nullifier_used(tree_id: T::TreeId, nullifier_hash: T::Element) -> bool {
NullifierHashes::<T, I>::contains_key(tree_id, nullifier_hash)
}
fn ensure_nullifier_unused(id: T::TreeId, nullifier: T::Element) -> Result<(), DispatchError> {
ensure!(!Self::is_nullifier_used(id, nullifier), Error::<T, I>::AlreadyRevealedNullifier);
Ok(())
}
fn has_edge(id: T::TreeId, src_chain_id: T::ChainId) -> bool {
T::LinkableTree::has_edge(id, src_chain_id)
}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub fn account_id() -> T::AccountId {
T::PalletId::get().into_account_truncating()
}
pub fn get_vanchor(
id: T::TreeId,
) -> Result<VAnchorMetadata<T::AccountId, CurrencyIdOf<T, I>>, DispatchError> {
let vanchor = VAnchors::<T, I>::get(id);
ensure!(vanchor.is_some(), Error::<T, I>::NoVAnchorFound);
Ok(vanchor.unwrap())
}
pub fn validate_and_set_nonce(nonce: T::ProposalNonce) -> Result<(), DispatchError> {
// Nonce should be greater than the proposal nonce in storage
let proposal_nonce = ProposalNonce::<T, I>::get();
ensure!(proposal_nonce < nonce, Error::<T, I>::InvalidNonce);
// Nonce should increment by a maximum of 1,048
ensure!(
nonce <= proposal_nonce + T::ProposalNonce::from(1_048u32),
Error::<T, I>::InvalidNonce
);
// Set the new nonce
ProposalNonce::<T, I>::set(nonce);
Ok(())
}
pub fn calculate_public_amount(
ext_data: &ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(T::Element, AmountOf<T, I>), DispatchError> {
// Public amount can also be negative, in which
// case it would wrap around the field, so we should check if FIELD_SIZE -
// public_amount == proof_data.public_amount, in case of a negative ext_amount
let fee_amount =
AmountOf::<T, I>::try_from(ext_data.fee).map_err(|_| Error::<T, I>::InvalidFee)?;
let calc_public_amount = ext_data.ext_amount - fee_amount;
let calc_public_amount_bytes = T::IntoField::into_field(calc_public_amount);
// Return the public amount as a field element
Ok((T::Element::from_bytes(&calc_public_amount_bytes), calc_public_amount))
}
pub fn handle_proof_verification(
proof_data: &ProofData<T::Element>,
) -> Result<(), DispatchError> {
let chain_id_type = T::LinkableTree::get_chain_id_type();
// Construct public inputs
let mut bytes = Vec::new();
bytes.extend_from_slice(proof_data.public_amount.to_bytes());
bytes.extend_from_slice(proof_data.ext_data_hash.to_bytes());
for null in &proof_data.input_nullifiers {
bytes.extend_from_slice(null.to_bytes());
}
for comm in &proof_data.output_commitments {
bytes.extend_from_slice(comm.to_bytes());
}
bytes.extend_from_slice(&chain_id_type.using_encoded(reverse_element_encoder));
for root in &proof_data.roots {
bytes.extend_from_slice(root.to_bytes());
}
// Verify the zero-knowledge proof
let res = T::VAnchorVerifier::verify(
&bytes,
&proof_data.proof,
proof_data.roots.len().try_into().unwrap_or_default(),
proof_data.input_nullifiers.len().try_into().unwrap_or_default(),
)?;
ensure!(res, Error::<T, I>::InvalidTransactionProof);
Ok(())
}
pub fn handle_fee(
vanchor: &VAnchorMetadata<T::AccountId, CurrencyIdOf<T, I>>,
ext_data: &ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(), DispatchError> {
let fee_exists = ext_data.fee > BalanceOf::<T, I>::zero();
if fee_exists {
// Send fee to the relayer
<T as Config<I>>::Currency::transfer(
vanchor.asset,
&Self::account_id(),
&ext_data.relayer,
ext_data.fee,
)?;
}
Ok(())
}
pub fn handle_refund(
transactor: &T::AccountId,
ext_data: &ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(), DispatchError> {
let refund_exists = ext_data.refund > BalanceOf::<T, I>::zero();
if refund_exists {
// Send gas-refund to the recipient
<T as Config<I>>::Currency::transfer(
T::NativeCurrencyId::get(),
transactor,
&ext_data.recipient,
ext_data.refund,
)?;
}
Ok(())
}
pub fn handle_asset_action(
transactor: &T::AccountId,
vanchor: &VAnchorMetadata<T::AccountId, CurrencyIdOf<T, I>>,
ext_data: &ExtData<T::AccountId, AmountOf<T, I>, BalanceOf<T, I>, CurrencyIdOf<T, I>>,
) -> Result<(), DispatchError> {
// If external amount is positive then we are depositing
let is_deposit = ext_data.ext_amount.is_positive();
// If external amount is negative then we are withdrawing
let is_negative = ext_data.ext_amount.is_negative();
// Get the absolute amount for either action
let abs_amount: BalanceOf<T, I> = ext_data
.ext_amount
.abs()
.try_into()
.map_err(|_| Error::<T, I>::InvalidExtAmount)?;
// Check if the transaction is a deposit or a withdrawal
if is_deposit {
ensure!(
abs_amount <= MaxDepositAmount::<T, I>::get(),
Error::<T, I>::InvalidDepositAmount
);
// If the token is not the same as the vanchor asset then
// we need to wrap the tokens into the vanchor asset
if ext_data.token != vanchor.asset {
// Wrap tokens from the transactor's account
T::TokenWrapper::wrap(
transactor.clone(),
ext_data.token,
vanchor.asset,
abs_amount,
Self::account_id(),
)?;
} else {
// Deposit tokens to the pallet from the transactor's account
<T as Config<I>>::Currency::transfer(
vanchor.asset,
transactor,
&Self::account_id(),
abs_amount,
)?;
}
} else if is_negative {
ensure!(
abs_amount >= MinWithdrawAmount::<T, I>::get(),
Error::<T, I>::InvalidWithdrawAmount
);
// If the token is not the same as the vanchor asset then
// we need to unwrap the tokens from the vanchor asset
if ext_data.token != vanchor.asset {
// Unwrap to recipient account
T::TokenWrapper::unwrap(
Self::account_id(),
vanchor.asset,
ext_data.token,
abs_amount,
ext_data.recipient.clone(),
)?;
} else {
// Withdraw to recipient account
<T as Config<I>>::Currency::transfer(
vanchor.asset,
&Self::account_id(),
&ext_data.recipient,
abs_amount,
)?;
}
}
Ok(())
}
}
pub trait PostDepositHook<T: Config<I>, I: 'static> {
fn post_deposit(depositor: T::AccountId, id: T::TreeId, leaf: T::Element) -> DispatchResult;
}
impl<T: Config<I>, I: 'static> PostDepositHook<T, I> for () {
fn post_deposit(_: T::AccountId, _: T::TreeId, _: T::Element) -> DispatchResult {
Ok(())
}
}