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	DebugNoBound,
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, Debug, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, TypeInfo, MaxEncodedLen,
107)]
108#[scale_info(skip_type_params(C))]
109#[codec(mel_bound())]
110pub struct BalanceSwapAction<AccountId, C: ReservableCurrency<AccountId>> {
111	value: <C as Currency<AccountId>>::Balance,
112	_marker: PhantomData<C>,
113}
114
115impl<AccountId, C> BalanceSwapAction<AccountId, C>
116where
117	C: ReservableCurrency<AccountId>,
118{
119	/// Create a new swap action value of balance.
120	pub fn new(value: <C as Currency<AccountId>>::Balance) -> Self {
121		Self { value, _marker: PhantomData }
122	}
123}
124
125impl<AccountId, C> Deref for BalanceSwapAction<AccountId, C>
126where
127	C: ReservableCurrency<AccountId>,
128{
129	type Target = <C as Currency<AccountId>>::Balance;
130
131	fn deref(&self) -> &Self::Target {
132		&self.value
133	}
134}
135
136impl<AccountId, C> DerefMut for BalanceSwapAction<AccountId, C>
137where
138	C: ReservableCurrency<AccountId>,
139{
140	fn deref_mut(&mut self) -> &mut Self::Target {
141		&mut self.value
142	}
143}
144
145impl<T: Config, AccountId, C> SwapAction<AccountId, T> for BalanceSwapAction<AccountId, C>
146where
147	C: ReservableCurrency<AccountId>,
148{
149	fn reserve(&self, source: &AccountId) -> DispatchResult {
150		C::reserve(source, self.value)
151	}
152
153	fn claim(&self, source: &AccountId, target: &AccountId) -> bool {
154		C::repatriate_reserved(source, target, self.value, BalanceStatus::Free).is_ok()
155	}
156
157	fn weight(&self) -> Weight {
158		T::DbWeight::get().reads_writes(1, 1)
159	}
160
161	fn cancel(&self, source: &AccountId) {
162		C::unreserve(source, self.value);
163	}
164}
165
166pub use pallet::*;
167
168#[frame::pallet]
169pub mod pallet {
170	use super::*;
171
172	/// Atomic swap's pallet configuration trait.
173	#[pallet::config]
174	pub trait Config: frame_system::Config {
175		/// The overarching event type.
176		#[allow(deprecated)]
177		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
178		/// Swap action.
179		type SwapAction: SwapAction<Self::AccountId, Self> + Parameter + MaxEncodedLen;
180		/// Limit of proof size.
181		///
182		/// Atomic swap is only atomic if once the proof is revealed, both parties can submit the
183		/// proofs on-chain. If A is the one that generates the proof, then it requires that either:
184		/// - A's blockchain has the same proof length limit as B's blockchain.
185		/// - Or A's blockchain has shorter proof length limit as B's blockchain.
186		///
187		/// If B sees A is on a blockchain with larger proof length limit, then it should kindly
188		/// refuse to accept the atomic swap request if A generates the proof, and asks that B
189		/// generates the proof instead.
190		#[pallet::constant]
191		type ProofLimit: Get<u32>;
192	}
193
194	#[pallet::pallet]
195	pub struct Pallet<T>(_);
196
197	#[pallet::storage]
198	pub type PendingSwaps<T: Config> = StorageDoubleMap<
199		_,
200		Twox64Concat,
201		T::AccountId,
202		Blake2_128Concat,
203		HashedProof,
204		PendingSwap<T>,
205	>;
206
207	#[pallet::error]
208	pub enum Error<T> {
209		/// Swap already exists.
210		AlreadyExist,
211		/// Swap proof is invalid.
212		InvalidProof,
213		/// Proof is too large.
214		ProofTooLarge,
215		/// Source does not match.
216		SourceMismatch,
217		/// Swap has already been claimed.
218		AlreadyClaimed,
219		/// Swap does not exist.
220		NotExist,
221		/// Claim action mismatch.
222		ClaimActionMismatch,
223		/// Duration has not yet passed for the swap to be cancelled.
224		DurationNotPassed,
225	}
226
227	/// Event of atomic swap pallet.
228	#[pallet::event]
229	#[pallet::generate_deposit(pub(super) fn deposit_event)]
230	pub enum Event<T: Config> {
231		/// Swap created.
232		NewSwap { account: T::AccountId, proof: HashedProof, swap: PendingSwap<T> },
233		/// Swap claimed. The last parameter indicates whether the execution succeeds.
234		SwapClaimed { account: T::AccountId, proof: HashedProof, success: bool },
235		/// Swap cancelled.
236		SwapCancelled { account: T::AccountId, proof: HashedProof },
237	}
238
239	#[pallet::call]
240	impl<T: Config> Pallet<T> {
241		/// Register a new atomic swap, declaring an intention to send funds from origin to target
242		/// on the current blockchain. The target can claim the fund using the revealed proof. If
243		/// the fund is not claimed after `duration` blocks, then the sender can cancel the swap.
244		///
245		/// The dispatch origin for this call must be _Signed_.
246		///
247		/// - `target`: Receiver of the atomic swap.
248		/// - `hashed_proof`: The blake2_256 hash of the secret proof.
249		/// - `balance`: Funds to be sent from origin.
250		/// - `duration`: Locked duration of the atomic swap. For safety reasons, it is recommended
251		///   that the revealer uses a shorter duration than the counterparty, to prevent the
252		///   situation where the revealer reveals the proof too late around the end block.
253		#[pallet::call_index(0)]
254		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1).ref_time().saturating_add(40_000_000))]
255		pub fn create_swap(
256			origin: OriginFor<T>,
257			target: T::AccountId,
258			hashed_proof: HashedProof,
259			action: T::SwapAction,
260			duration: BlockNumberFor<T>,
261		) -> DispatchResult {
262			let source = ensure_signed(origin)?;
263			ensure!(
264				!PendingSwaps::<T>::contains_key(&target, hashed_proof),
265				Error::<T>::AlreadyExist
266			);
267
268			action.reserve(&source)?;
269
270			let swap = PendingSwap {
271				source,
272				action,
273				end_block: frame_system::Pallet::<T>::block_number() + duration,
274			};
275			PendingSwaps::<T>::insert(target.clone(), hashed_proof, swap.clone());
276
277			Self::deposit_event(Event::NewSwap { account: target, proof: hashed_proof, swap });
278
279			Ok(())
280		}
281
282		/// Claim an atomic swap.
283		///
284		/// The dispatch origin for this call must be _Signed_.
285		///
286		/// - `proof`: Revealed proof of the claim.
287		/// - `action`: Action defined in the swap, it must match the entry in blockchain. Otherwise
288		///   the operation fails. This is used for weight calculation.
289		#[pallet::call_index(1)]
290		#[pallet::weight(
291			T::DbWeight::get().reads_writes(1, 1)
292				.saturating_add(action.weight())
293				.ref_time()
294				.saturating_add(40_000_000)
295				.saturating_add((proof.len() as u64).saturating_mul(100))
296		)]
297		pub fn claim_swap(
298			origin: OriginFor<T>,
299			proof: Vec<u8>,
300			action: T::SwapAction,
301		) -> DispatchResult {
302			ensure!(proof.len() <= T::ProofLimit::get() as usize, Error::<T>::ProofTooLarge);
303
304			let target = ensure_signed(origin)?;
305			let hashed_proof = blake2_256(&proof);
306
307			let swap =
308				PendingSwaps::<T>::get(&target, hashed_proof).ok_or(Error::<T>::InvalidProof)?;
309			ensure!(swap.action == action, Error::<T>::ClaimActionMismatch);
310
311			let succeeded = swap.action.claim(&swap.source, &target);
312
313			PendingSwaps::<T>::remove(target.clone(), hashed_proof);
314
315			Self::deposit_event(Event::SwapClaimed {
316				account: target,
317				proof: hashed_proof,
318				success: succeeded,
319			});
320
321			Ok(())
322		}
323
324		/// Cancel an atomic swap. Only possible after the originally set duration has passed.
325		///
326		/// The dispatch origin for this call must be _Signed_.
327		///
328		/// - `target`: Target of the original atomic swap.
329		/// - `hashed_proof`: Hashed proof of the original atomic swap.
330		#[pallet::call_index(2)]
331		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1).ref_time().saturating_add(40_000_000))]
332		pub fn cancel_swap(
333			origin: OriginFor<T>,
334			target: T::AccountId,
335			hashed_proof: HashedProof,
336		) -> DispatchResult {
337			let source = ensure_signed(origin)?;
338
339			let swap = PendingSwaps::<T>::get(&target, hashed_proof).ok_or(Error::<T>::NotExist)?;
340			ensure!(swap.source == source, Error::<T>::SourceMismatch);
341			ensure!(
342				frame_system::Pallet::<T>::block_number() >= swap.end_block,
343				Error::<T>::DurationNotPassed,
344			);
345
346			swap.action.cancel(&swap.source);
347			PendingSwaps::<T>::remove(&target, hashed_proof);
348
349			Self::deposit_event(Event::SwapCancelled { account: target, proof: hashed_proof });
350
351			Ok(())
352		}
353	}
354}