This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Pallet: Atomic Swap #6349
Merged
Merged
Pallet: Atomic Swap #6349
Changes from 15 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
b029265
Init atomic swap pallet
sorpaas eb0fbef
Implement module swap operations
sorpaas b08c1ea
Add successful swap test
sorpaas 0b4454f
Bump node spec_version
sorpaas c3f88f5
Fix storage name
sorpaas f885efb
Add ProofLimit parameter to prevent proof size being too large
sorpaas 8ce4cce
Add missing events
sorpaas 3088ff1
Basic weight support
sorpaas 8e18344
Add basic docs
sorpaas 47877fa
Mark swap on claim
sorpaas d51b1de
Add additional expire handler
sorpaas fe70944
Update frame/atomic-swap/src/lib.rs
sorpaas fa2a85e
Add docs on ProofLimit
sorpaas 7148509
Merge branch 'sp-atomic-swap' of https://github.com/paritytech/substr…
sorpaas b71ca91
Fix test
sorpaas 2aa173b
Return Ok(()) even when the transfer fails
sorpaas ad36185
Remove retry logic
sorpaas a46db72
succeed -> succeeded
sorpaas 96b1392
Add docs on duration -- revealer should use duration shorter than cou…
sorpaas fad3708
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas 9cc2350
Missing trait type
sorpaas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| [package] | ||
| name = "pallet-atomic-swap" | ||
| version = "2.0.0-rc3" | ||
| authors = ["Parity Technologies <[email protected]>"] | ||
| edition = "2018" | ||
| license = "Apache-2.0" | ||
| homepage = "https://substrate.dev" | ||
| repository = "https://github.com/paritytech/substrate/" | ||
| description = "FRAME atomic swap pallet" | ||
|
|
||
| [package.metadata.docs.rs] | ||
| targets = ["x86_64-unknown-linux-gnu"] | ||
|
|
||
| [dependencies] | ||
| serde = { version = "1.0.101", optional = true } | ||
| codec = { package = "parity-scale-codec", version = "1.3.0", default-features = false } | ||
| frame-support = { version = "2.0.0-rc3", default-features = false, path = "../support" } | ||
| frame-system = { version = "2.0.0-rc3", default-features = false, path = "../system" } | ||
| sp-runtime = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/runtime" } | ||
| sp-std = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/std" } | ||
| sp-io = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/io" } | ||
| sp-core = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/core" } | ||
|
|
||
| [dev-dependencies] | ||
| pallet-balances = { version = "2.0.0-rc3", default-features = false, path = "../balances" } | ||
|
|
||
| [features] | ||
| default = ["std"] | ||
| std = [ | ||
| "serde", | ||
| "codec/std", | ||
| "frame-support/std", | ||
| "frame-system/std", | ||
| "sp-runtime/std", | ||
| "sp-std/std", | ||
| "sp-io/std", | ||
| "sp-core/std", | ||
| "pallet-balances/std", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,280 @@ | ||
| // This file is part of Substrate. | ||
|
|
||
| // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. | ||
| // 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. | ||
|
|
||
| //! # Atomic swap support pallet | ||
|
|
||
| // Ensure we're `no_std` when compiling for Wasm. | ||
| #![cfg_attr(not(feature = "std"), no_std)] | ||
|
|
||
| mod tests; | ||
|
|
||
| use sp_std::prelude::*; | ||
| use sp_io::hashing::blake2_256; | ||
| use frame_support::{ | ||
| decl_module, decl_storage, decl_event, decl_error, ensure, | ||
| traits::{Get, Currency, ReservableCurrency, BalanceStatus}, | ||
| weights::Weight, | ||
| dispatch::DispatchResult, | ||
| }; | ||
| use frame_system::{self as system, ensure_signed}; | ||
| use codec::{Encode, Decode}; | ||
| use sp_runtime::{RuntimeDebug, traits::Saturating}; | ||
|
|
||
| /// Pending atomic swap operation. | ||
| #[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode)] | ||
| pub struct PendingSwap<AccountId, Balance, BlockNumber> { | ||
| /// Source of the swap. | ||
| pub source: AccountId, | ||
| /// Balance value of the swap. | ||
| pub balance: Balance, | ||
| /// End block of the lock. | ||
| pub end_block: BlockNumber, | ||
| /// Whether the swap has already been claimed. | ||
| pub claimed: bool, | ||
| } | ||
|
|
||
| /// Balance type from the pallet's point of view. | ||
| pub type BalanceFor<T> = <<T as Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance; | ||
|
|
||
| /// AccountId type from the pallet's point of view. | ||
| pub type AccountIdFor<T> = <T as frame_system::Trait>::AccountId; | ||
|
|
||
| /// BlockNumber type from the pallet's point of view. | ||
| pub type BlockNumberFor<T> = <T as frame_system::Trait>::BlockNumber; | ||
|
|
||
| /// PendingSwap type from the pallet's point of view. | ||
| pub type PendingSwapFor<T> = PendingSwap<AccountIdFor<T>, BalanceFor<T>, BlockNumberFor<T>>; | ||
|
|
||
| /// Hashed proof type. | ||
| pub type HashedProof = [u8; 32]; | ||
|
|
||
| /// Atomic swap's pallet configuration trait. | ||
| pub trait Trait: frame_system::Trait { | ||
| /// The overarching event type. | ||
| type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; | ||
| /// The currency mechanism. | ||
| type Currency: ReservableCurrency<Self::AccountId>; | ||
| /// Limit of proof size. | ||
| /// | ||
| /// Atomic swap is only atomic if once the proof is revealed, both parties can submit the proofs | ||
| /// on-chain. If A is the one that generates the proof, then it requires that either: | ||
| /// - A's blockchain has the same proof length limit as B's blockchain. | ||
| /// - Or A's blockchain has shorter proof length limit as B's blockchain. | ||
| /// | ||
| /// If B sees A is on a blockchain with larger proof length limit, then it should kindly refuse | ||
| /// to accept the atomic swap request if A generates the proof, and asks that B generates the | ||
| /// proof instead. | ||
| type ProofLimit: Get<u32>; | ||
| /// Block when the swap completely expires. | ||
| type ExpireDuration: Get<BlockNumberFor<Self>>; | ||
| } | ||
|
|
||
| decl_storage! { | ||
| trait Store for Module<T: Trait> as AtomicSwap { | ||
| pub PendingSwaps: double_map | ||
| hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) HashedProof | ||
| => Option<PendingSwapFor<T>>; | ||
| } | ||
| } | ||
|
|
||
| decl_error! { | ||
| pub enum Error for Module<T: Trait> { | ||
| /// Swap already exists. | ||
| AlreadyExist, | ||
| /// Swap proof is invalid. | ||
| InvalidProof, | ||
| /// Proof is too large. | ||
| ProofTooLarge, | ||
| /// Source does not match. | ||
| SourceMismatch, | ||
| /// Swap has already been claimed. | ||
| AlreadyClaimed, | ||
| /// Swap does not exist. | ||
| NotExist, | ||
| /// Duration has not yet passed for the swap to be cancelled. | ||
| DurationNotPassed, | ||
| } | ||
| } | ||
|
|
||
| decl_event!( | ||
| /// Event of atomic swap pallet. | ||
| pub enum Event<T> where | ||
| Balance = BalanceFor<T>, | ||
| AccountId = AccountIdFor<T>, | ||
| PendingSwap = PendingSwapFor<T>, | ||
| { | ||
| /// Swap created. | ||
| NewSwap(AccountId, HashedProof, PendingSwap), | ||
| /// Swap claimed. | ||
| SwapClaimed(AccountId, HashedProof, Balance), | ||
| /// Swap claim failed its execution. The last parameter indicates whether retry is possible. | ||
| SwapClaimFailed(AccountId, HashedProof, bool), | ||
| /// Swap cancelled. | ||
| SwapCancelled(AccountId, HashedProof), | ||
| } | ||
| ); | ||
|
|
||
| decl_module! { | ||
| /// Module definition of atomic swap pallet. | ||
| pub struct Module<T: Trait> for enum Call where origin: T::Origin { | ||
| type Error = Error<T>; | ||
|
|
||
| fn deposit_event() = default; | ||
|
|
||
| /// Register a new atomic swap, declaring an intention to send funds from origin to target | ||
| /// on the current blockchain. The target can claim the fund using the revealed proof. If | ||
| /// the fund is not claimed after `duration` blocks, then the sender can cancel the swap. | ||
| /// | ||
| /// The dispatch origin for this call must be _Signed_. | ||
| /// | ||
| /// - `target`: Receiver of the atomic swap. | ||
| /// - `hashed_proof`: The blake2_256 hash of the secret proof. | ||
| /// - `balance`: Funds to be sent from origin. | ||
| /// - `duration`: Locked duration of the atomic swap. | ||
| #[weight = T::DbWeight::get().reads_writes(1, 1).saturating_add(40_000_000)] | ||
| fn create_swap( | ||
| origin, | ||
| target: AccountIdFor<T>, | ||
| hashed_proof: HashedProof, | ||
| balance: BalanceFor<T>, | ||
| duration: BlockNumberFor<T>, | ||
| ) { | ||
| let source = ensure_signed(origin)?; | ||
| ensure!( | ||
| !PendingSwaps::<T>::contains_key(&target, hashed_proof), | ||
| Error::<T>::AlreadyExist | ||
| ); | ||
|
|
||
| T::Currency::reserve(&source, balance)?; | ||
|
|
||
| let swap = PendingSwap { | ||
| source, | ||
| balance, | ||
| end_block: frame_system::Module::<T>::block_number() + duration, | ||
| claimed: false, | ||
| }; | ||
| PendingSwaps::<T>::insert(target.clone(), hashed_proof.clone(), swap.clone()); | ||
|
|
||
| Self::deposit_event( | ||
| RawEvent::NewSwap(target, hashed_proof, swap) | ||
| ); | ||
| } | ||
|
|
||
| /// Claim an atomic swap. | ||
| /// | ||
| /// The dispatch origin for this call must be _Signed_. | ||
| /// | ||
| /// - `proof`: Revealed proof of the claim. | ||
| #[weight = T::DbWeight::get().reads_writes(2, 2) | ||
| .saturating_add(40_000_000) | ||
| .saturating_add((proof.len() as Weight).saturating_mul(100)) | ||
| ] | ||
| fn claim_swap( | ||
| origin, | ||
| proof: Vec<u8>, | ||
| ) -> DispatchResult { | ||
| ensure!( | ||
| proof.len() <= T::ProofLimit::get() as usize, | ||
| Error::<T>::ProofTooLarge, | ||
| ); | ||
|
|
||
| let target = ensure_signed(origin)?; | ||
| let hashed_proof = blake2_256(&proof); | ||
|
|
||
| let mut swap = PendingSwaps::<T>::get(&target, hashed_proof) | ||
| .ok_or(Error::<T>::InvalidProof)?; | ||
| swap.claimed = true; | ||
|
|
||
| match T::Currency::repatriate_reserved( | ||
| &swap.source, | ||
| &target, | ||
| swap.balance, | ||
| BalanceStatus::Free, | ||
| ) { | ||
| Err(e) => { | ||
| let expired = frame_system::Module::<T>::block_number() > | ||
| swap.end_block.saturating_add(T::ExpireDuration::get()); | ||
| if expired { | ||
| PendingSwaps::<T>::remove(target.clone(), hashed_proof.clone()); | ||
|
|
||
| Self::deposit_event( | ||
| RawEvent::SwapClaimFailed(target, hashed_proof, false) | ||
| ); | ||
| } else { | ||
| PendingSwaps::<T>::insert(target.clone(), hashed_proof.clone(), swap); | ||
|
|
||
| Self::deposit_event( | ||
| RawEvent::SwapClaimFailed(target, hashed_proof, true) | ||
| ); | ||
| } | ||
|
|
||
| Err(e.into()) | ||
| }, | ||
| Ok(_) => { | ||
| PendingSwaps::<T>::remove(target.clone(), hashed_proof.clone()); | ||
|
|
||
| Self::deposit_event( | ||
| RawEvent::SwapClaimed(target, hashed_proof, swap.balance) | ||
| ); | ||
|
|
||
| Ok(()) | ||
| }, | ||
|
|
||
| } | ||
| } | ||
|
|
||
| /// Cancel an atomic swap. Only possible after the originally set duration has passed. | ||
| /// | ||
| /// The dispatch origin for this call must be _Signed_. | ||
| /// | ||
| /// - `target`: Target of the original atomic swap. | ||
| /// - `hashed_proof`: Hashed proof of the original atomic swap. | ||
| #[weight = T::DbWeight::get().reads_writes(1, 1).saturating_add(40_000_000)] | ||
| fn cancel_swap( | ||
| origin, | ||
| target: AccountIdFor<T>, | ||
| hashed_proof: HashedProof, | ||
| ) { | ||
| let source = ensure_signed(origin)?; | ||
|
|
||
| let swap = PendingSwaps::<T>::get(&target, hashed_proof) | ||
| .ok_or(Error::<T>::NotExist)?; | ||
| ensure!( | ||
| !swap.claimed, | ||
| Error::<T>::AlreadyClaimed, | ||
| ); | ||
| ensure!( | ||
| swap.source == source, | ||
sorpaas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Error::<T>::SourceMismatch, | ||
| ); | ||
| ensure!( | ||
| frame_system::Module::<T>::block_number() >= swap.end_block, | ||
| Error::<T>::DurationNotPassed, | ||
| ); | ||
|
|
||
| T::Currency::unreserve( | ||
| &swap.source, | ||
| swap.balance, | ||
| ); | ||
| PendingSwaps::<T>::remove(&target, hashed_proof.clone()); | ||
|
|
||
| Self::deposit_event( | ||
| RawEvent::SwapCancelled(target, hashed_proof) | ||
| ); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.