referrerpolicy=no-referrer-when-downgrade

pallet_atomic_swap/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Atomic Swap
19//!
20//! A pallet for atomically sending funds.
21//!
22//! - [`Config`]
23//! - [`Call`]
24//! - [`Pallet`]
25//!
26//! ## Overview
27//!
28//! A pallet for atomically sending funds from an origin to a target. A proof
29//! is used to allow the target to approve (claim) the swap. If the swap is not
30//! claimed within a specified duration of time, the sender may cancel it.
31//!
32//! ## Interface
33//!
34//! ### Dispatchable Functions
35//!
36//! * [`create_swap`](Call::create_swap) - called by a sender to register a new atomic swap
37//! * [`claim_swap`](Call::claim_swap) - called by the target to approve a swap
38//! * [`cancel_swap`](Call::cancel_swap) - may be called by a sender after a specified duration
39
40// Ensure we're `no_std` when compiling for Wasm.
41#![cfg_attr(not(feature = "std"), no_std)]
42
43mod tests;
44
45extern crate alloc;
46
47use alloc::vec::Vec;
48use codec::{Decode, DecodeWithMemTracking, Encode};
49use core::{
50	marker::PhantomData,
51	ops::{Deref, DerefMut},
52};
53use frame::{
54	prelude::*,
55	traits::{BalanceStatus, Currency, ReservableCurrency},
56};
57use scale_info::TypeInfo;
58
59/// Pending atomic swap operation.
60#[derive(
61	Clone,
62	Eq,
63	PartialEq,
64	RuntimeDebugNoBound,
65	Encode,
66	Decode,
67	DecodeWithMemTracking,
68	TypeInfo,
69	MaxEncodedLen,
70)]
71#[scale_info(skip_type_params(T))]
72#[codec(mel_bound())]
73pub struct PendingSwap<T: Config> {
74	/// Source of the swap.
75	pub source: T::AccountId,
76	/// Action of this swap.
77	pub action: T::SwapAction,
78	/// End block of the lock.
79	pub end_block: BlockNumberFor<T>,
80}
81
82/// Hashed proof type.
83pub type HashedProof = [u8; 32];
84
85/// Definition of a pending atomic swap action. It contains the following three phrases:
86///
87/// - **Reserve**: reserve the resources needed for a swap. This is to make sure that **Claim**
88/// succeeds with best efforts.
89/// - **Claim**: claim any resources reserved in the first phrase.
90/// - **Cancel**: cancel any resources reserved in the first phrase.
91pub trait SwapAction<AccountId, T: Config> {
92	/// Reserve the resources needed for the swap, from the given `source`. The reservation is
93	/// allowed to fail. If that is the case, the the full swap creation operation is cancelled.
94	fn reserve(&self, source: &AccountId) -> DispatchResult;
95	/// Claim the reserved resources, with `source` and `target`. Returns whether the claim
96	/// succeeds.
97	fn claim(&self, source: &AccountId, target: &AccountId) -> bool;
98	/// Weight for executing the operation.
99	fn weight(&self) -> Weight;
100	/// Cancel the resources reserved in `source`.
101	fn cancel(&self, source: &AccountId);
102}
103
104/// A swap action that only allows transferring balances.
105#[derive(
106	Clone,
107	RuntimeDebug,
108	Eq,
109	PartialEq,
110	Encode,
111	Decode,
112	DecodeWithMemTracking,
113	TypeInfo,
114	MaxEncodedLen,
115)]
116#[scale_info(skip_type_params(C))]
117#[codec(mel_bound())]
118pub struct BalanceSwapAction<AccountId, C: ReservableCurrency<AccountId>> {
119	value: <C as Currency<AccountId>>::Balance,
120	_marker: PhantomData<C>,
121}
122
123impl<AccountId, C> BalanceSwapAction<AccountId, C>
124where
125	C: ReservableCurrency<AccountId>,
126{
127	/// Create a new swap action value of balance.
128	pub fn new(value: <C as Currency<AccountId>>::Balance) -> Self {
129		Self { value, _marker: PhantomData }
130	}
131}
132
133impl<AccountId, C> Deref for BalanceSwapAction<AccountId, C>
134where
135	C: ReservableCurrency<AccountId>,
136{
137	type Target = <C as Currency<AccountId>>::Balance;
138
139	fn deref(&self) -> &Self::Target {
140		&self.value
141	}
142}
143
144impl<AccountId, C> DerefMut for BalanceSwapAction<AccountId, C>
145where
146	C: ReservableCurrency<AccountId>,
147{
148	fn deref_mut(&mut self) -> &mut Self::Target {
149		&mut self.value
150	}
151}
152
153impl<T: Config, AccountId, C> SwapAction<AccountId, T> for BalanceSwapAction<AccountId, C>
154where
155	C: ReservableCurrency<AccountId>,
156{
157	fn reserve(&self, source: &AccountId) -> DispatchResult {
158		C::reserve(source, self.value)
159	}
160
161	fn claim(&self, source: &AccountId, target: &AccountId) -> bool {
162		C::repatriate_reserved(source, target, self.value, BalanceStatus::Free).is_ok()
163	}
164
165	fn weight(&self) -> Weight {
166		T::DbWeight::get().reads_writes(1, 1)
167	}
168
169	fn cancel(&self, source: &AccountId) {
170		C::unreserve(source, self.value);
171	}
172}
173
174pub use pallet::*;
175
176#[frame::pallet]
177pub mod pallet {
178	use super::*;
179
180	/// Atomic swap's pallet configuration trait.
181	#[pallet::config]
182	pub trait Config: frame_system::Config {
183		/// The overarching event type.
184		#[allow(deprecated)]
185		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
186		/// Swap action.
187		type SwapAction: SwapAction<Self::AccountId, Self> + Parameter + MaxEncodedLen;
188		/// Limit of proof size.
189		///
190		/// Atomic swap is only atomic if once the proof is revealed, both parties can submit the
191		/// proofs on-chain. If A is the one that generates the proof, then it requires that either:
192		/// - A's blockchain has the same proof length limit as B's blockchain.
193		/// - Or A's blockchain has shorter proof length limit as B's blockchain.
194		///
195		/// If B sees A is on a blockchain with larger proof length limit, then it should kindly
196		/// refuse to accept the atomic swap request if A generates the proof, and asks that B
197		/// generates the proof instead.
198		#[pallet::constant]
199		type ProofLimit: Get<u32>;
200	}
201
202	#[pallet::pallet]
203	pub struct Pallet<T>(_);
204
205	#[pallet::storage]
206	pub type PendingSwaps<T: Config> = StorageDoubleMap<
207		_,
208		Twox64Concat,
209		T::AccountId,
210		Blake2_128Concat,
211		HashedProof,
212		PendingSwap<T>,
213	>;
214
215	#[pallet::error]
216	pub enum Error<T> {
217		/// Swap already exists.
218		AlreadyExist,
219		/// Swap proof is invalid.
220		InvalidProof,
221		/// Proof is too large.
222		ProofTooLarge,
223		/// Source does not match.
224		SourceMismatch,
225		/// Swap has already been claimed.
226		AlreadyClaimed,
227		/// Swap does not exist.
228		NotExist,
229		/// Claim action mismatch.
230		ClaimActionMismatch,
231		/// Duration has not yet passed for the swap to be cancelled.
232		DurationNotPassed,
233	}
234
235	/// Event of atomic swap pallet.
236	#[pallet::event]
237	#[pallet::generate_deposit(pub(super) fn deposit_event)]
238	pub enum Event<T: Config> {
239		/// Swap created.
240		NewSwap { account: T::AccountId, proof: HashedProof, swap: PendingSwap<T> },
241		/// Swap claimed. The last parameter indicates whether the execution succeeds.
242		SwapClaimed { account: T::AccountId, proof: HashedProof, success: bool },
243		/// Swap cancelled.
244		SwapCancelled { account: T::AccountId, proof: HashedProof },
245	}
246
247	#[pallet::call]
248	impl<T: Config> Pallet<T> {
249		/// Register a new atomic swap, declaring an intention to send funds from origin to target
250		/// on the current blockchain. The target can claim the fund using the revealed proof. If
251		/// the fund is not claimed after `duration` blocks, then the sender can cancel the swap.
252		///
253		/// The dispatch origin for this call must be _Signed_.
254		///
255		/// - `target`: Receiver of the atomic swap.
256		/// - `hashed_proof`: The blake2_256 hash of the secret proof.
257		/// - `balance`: Funds to be sent from origin.
258		/// - `duration`: Locked duration of the atomic swap. For safety reasons, it is recommended
259		///   that the revealer uses a shorter duration than the counterparty, to prevent the
260		///   situation where the revealer reveals the proof too late around the end block.
261		#[pallet::call_index(0)]
262		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1).ref_time().saturating_add(40_000_000))]
263		pub fn create_swap(
264			origin: OriginFor<T>,
265			target: T::AccountId,
266			hashed_proof: HashedProof,
267			action: T::SwapAction,
268			duration: BlockNumberFor<T>,
269		) -> DispatchResult {
270			let source = ensure_signed(origin)?;
271			ensure!(
272				!PendingSwaps::<T>::contains_key(&target, hashed_proof),
273				Error::<T>::AlreadyExist
274			);
275
276			action.reserve(&source)?;
277
278			let swap = PendingSwap {
279				source,
280				action,
281				end_block: frame_system::Pallet::<T>::block_number() + duration,
282			};
283			PendingSwaps::<T>::insert(target.clone(), hashed_proof, swap.clone());
284
285			Self::deposit_event(Event::NewSwap { account: target, proof: hashed_proof, swap });
286
287			Ok(())
288		}
289
290		/// Claim an atomic swap.
291		///
292		/// The dispatch origin for this call must be _Signed_.
293		///
294		/// - `proof`: Revealed proof of the claim.
295		/// - `action`: Action defined in the swap, it must match the entry in blockchain. Otherwise
296		///   the operation fails. This is used for weight calculation.
297		#[pallet::call_index(1)]
298		#[pallet::weight(
299			T::DbWeight::get().reads_writes(1, 1)
300				.saturating_add(action.weight())
301				.ref_time()
302				.saturating_add(40_000_000)
303				.saturating_add((proof.len() as u64).saturating_mul(100))
304		)]
305		pub fn claim_swap(
306			origin: OriginFor<T>,
307			proof: Vec<u8>,
308			action: T::SwapAction,
309		) -> DispatchResult {
310			ensure!(proof.len() <= T::ProofLimit::get() as usize, Error::<T>::ProofTooLarge);
311
312			let target = ensure_signed(origin)?;
313			let hashed_proof = blake2_256(&proof);
314
315			let swap =
316				PendingSwaps::<T>::get(&target, hashed_proof).ok_or(Error::<T>::InvalidProof)?;
317			ensure!(swap.action == action, Error::<T>::ClaimActionMismatch);
318
319			let succeeded = swap.action.claim(&swap.source, &target);
320
321			PendingSwaps::<T>::remove(target.clone(), hashed_proof);
322
323			Self::deposit_event(Event::SwapClaimed {
324				account: target,
325				proof: hashed_proof,
326				success: succeeded,
327			});
328
329			Ok(())
330		}
331
332		/// Cancel an atomic swap. Only possible after the originally set duration has passed.
333		///
334		/// The dispatch origin for this call must be _Signed_.
335		///
336		/// - `target`: Target of the original atomic swap.
337		/// - `hashed_proof`: Hashed proof of the original atomic swap.
338		#[pallet::call_index(2)]
339		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1).ref_time().saturating_add(40_000_000))]
340		pub fn cancel_swap(
341			origin: OriginFor<T>,
342			target: T::AccountId,
343			hashed_proof: HashedProof,
344		) -> DispatchResult {
345			let source = ensure_signed(origin)?;
346
347			let swap = PendingSwaps::<T>::get(&target, hashed_proof).ok_or(Error::<T>::NotExist)?;
348			ensure!(swap.source == source, Error::<T>::SourceMismatch);
349			ensure!(
350				frame_system::Pallet::<T>::block_number() >= swap.end_block,
351				Error::<T>::DurationNotPassed,
352			);
353
354			swap.action.cancel(&swap.source);
355			PendingSwaps::<T>::remove(&target, hashed_proof);
356
357			Self::deposit_event(Event::SwapCancelled { account: target, proof: hashed_proof });
358
359			Ok(())
360		}
361	}
362}