referrerpolicy=no-referrer-when-downgrade

pallet_psm/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Amforc AG.
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//! # Peg Stability Module (PSM) Pallet
19//!
20//! Instantiable Peg Stability Modules (PSMs). Each PSM enables 1:1 swaps between an internal
21//! stablecoin and one or more approved external stablecoins, typically to maintain a peg.
22//!
23//! ## Pallet API
24//!
25//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
26//! including its configuration trait, dispatchables, storage items, events and errors.
27//!
28//! ## Terminology
29//!
30//! Throughout this pallet two distinct token roles are referenced:
31//!
32//! * **Internal** — the stablecoin a PSM issues and burns (e.g. a runtime's own USD-pegged
33//!   stablecoin). Each PSM instance is keyed by its internal asset id; multiple instances can
34//!   coexist, each with its own reserve, debt ceiling, fee destination and approved externals. Mint
35//!   operations credit the user with the internal asset; redeem operations burn it. Fees are
36//!   collected in the internal asset and forwarded to that instance's [`PsmInfo::fee_destination`].
37//! * **External** — third-party assets (e.g. USDC, USDT) approved on a specific PSM via
38//!   [`Pallet::add_external_asset`] and held in that PSM's reserve. Users deposit external to mint
39//!   internal, and burn internal to redeem external. A PSM may approve multiple externals, each
40//!   identified by `external_asset`.
41//!
42//! ## Overview
43//!
44//! A PSM strengthens its internal asset's peg by providing arbitrage opportunities:
45//! - When the internal asset trades **above** $1: Users swap external assets for the internal asset
46//!   and sell for profit.
47//! - When the internal asset trades **below** $1: Users buy cheap internal asset and swap for
48//!   external assets.
49//!
50//! This creates a price corridor bounded by the minting and redemption fees.
51//!
52//! ### Key Concepts
53//!
54//! * **PSM instance**: A configured Peg Stability Module, keyed by its internal asset id and
55//!   described by [`PsmInfo`]. Each instance has its own reserve account derived from
56//!   `blake2_256((PalletId::TYPE_ID, PalletId, internal_asset).encode())`.
57//! * **Minting**: Deposit external asset → receive internal asset (minus fee).
58//! * **Redemption**: Burn internal asset → receive external asset (minus fee).
59//! * **Reserve**: External asset balance held by a PSM's reserve account (derived, not stored).
60//! * **PSM Debt**: Total internal asset minted through a PSM, backed 1:1 by external assets in that
61//!   PSM's reserve.
62//! * **Circuit Breaker**: Per-external emergency control to disable minting or all swaps.
63//!
64//! ### Storage Invariants
65//!
66//! With the `try-runtime` feature, the pallet tests fifteen storage invariants in
67//! each block. The function `do_try_state` does these tests. It confirms that:
68//!
69//! * each decimals snapshot agrees with the live asset metadata;
70//! * each reserve covers the debt that the PSM records against it;
71//! * no storage row stays after the removal of its PSM;
72//! * no debt exists for a pair that the PSM does not approve.
73//!
74//! Six of the fifteen checks are advisory. An advisory check writes a warning to
75//! the log. It does not return an error. A permitted action can create these six
76//! states, so an error would stop the chain after a correct call:
77//!
78//! * an issuance of the internal asset below the debt of the instance;
79//! * debt above a per-asset ceiling;
80//! * debt above the ceiling of an instance;
81//! * a reserve with a balance, but with zero weight and zero debt;
82//! * live decimals of the internal asset that differ from the recorded value;
83//! * live decimals of an external asset that differ from the recorded value.
84//!
85//! The two decimal checks are advisory because an asset owner can change asset
86//! metadata at any time, and swaps use the recorded values. Drift does not change
87//! the arithmetic of the pallet. It changes what a reader of live metadata sees.
88//!
89//! The issuance check is advisory because any holder can burn the internal asset
90//! outside of the PSM, for example with XCM `BurnAsset`. A burn leaves the reserve
91//! larger than the issuance it backs. The PSM is then over-collateralised, which
92//! is a safe state. The debt that the burn leaves behind can never be redeemed.
93//! To wind the asset class down, governance mints that amount to an account that
94//! redeems it, or moves the surplus reserve out. Both are manual actions: units
95//! of the internal asset carry no record of which minter issued them, so no call
96//! can compute how much of a burn falls on this PSM.
97//!
98//! ### Fee Structure
99//!
100//! * **Minting Fee (`MintingFee`)**: Deducted from internal-asset output during minting, configured
101//!   per `(internal_asset, external_asset)` pair.
102//! * **Redemption Fee (`RedemptionFee`)**: Deducted from external-asset output during redemption,
103//!   configured per `(internal_asset, external_asset)` pair.
104//!
105//! Fees are collected in the internal asset and transferred to the instance's
106//! [`PsmInfo::fee_destination`].
107//!
108//! ### Example
109//!
110//! ```ignore
111//! // Mint internal asset by depositing USDC on the PSM
112//! let max_fee = MintingFee::<Runtime>::get(INTERNAL_ASSET_ID, USDC_ASSET_ID);
113//! Psm::mint(
114//! 	RuntimeOrigin::signed(user),
115//! 	INTERNAL_ASSET_ID,
116//! 	USDC_ASSET_ID,
117//! 	1000 * UNIT,
118//! 	max_fee,
119//! )?;
120//!
121//! // Redeem USDC by burning the internal asset
122//! let max_fee = RedemptionFee::<Runtime>::get(INTERNAL_ASSET_ID, USDC_ASSET_ID);
123//! Psm::redeem(
124//! 	RuntimeOrigin::signed(user),
125//! 	INTERNAL_ASSET_ID,
126//! 	USDC_ASSET_ID,
127//! 	1000 * UNIT,
128//! 	max_fee,
129//! )?;
130//! ```
131
132#![cfg_attr(not(feature = "std"), no_std)]
133
134extern crate alloc;
135
136pub mod weights;
137
138#[cfg(feature = "runtime-benchmarks")]
139mod benchmarking;
140#[cfg(test)]
141mod mock;
142#[cfg(test)]
143mod tests;
144
145pub use pallet::*;
146pub use weights::WeightInfo;
147
148/// Helper trait for benchmark setup.
149///
150/// Provides a way to create an external asset with the correct metadata (decimals)
151/// for benchmarks, abstracting over the deposit requirements of the underlying
152/// asset pallet.
153#[cfg(feature = "runtime-benchmarks")]
154pub trait BenchmarkHelper<AssetId, AccountId> {
155	/// Get the asset ID for a given asset index.
156	fn get_asset_id(asset_index: u32) -> AssetId;
157	/// Create an asset with metadata matching the internal asset's decimals.
158	fn create_asset(asset_id: AssetId, owner: &AccountId, decimals: u8);
159}
160
161#[frame_support::pallet]
162pub mod pallet {
163
164	use alloc::boxed::Box;
165	use codec::DecodeWithMemTracking;
166	use frame_support::{
167		pallet_prelude::*,
168		traits::{
169			fungibles::{
170				metadata::Inspect as FungiblesMetadataInspect,
171				roles::Inspect as FungiblesRolesInspect, Inspect as FungiblesInspect,
172				Mutate as FungiblesMutate,
173			},
174			tokens::{DepositConsequence, Fortitude, Precision, Preservation, Provenance},
175			CallerTrait, Consideration, EnsureOriginWithArg, Footprint, OriginTrait,
176		},
177		PalletId,
178	};
179	use frame_system::pallet_prelude::*;
180	use sp_runtime::{
181		traits::{CheckedDiv, CheckedMul, Saturating, TrailingZeroInput, Zero},
182		Perbill, Permill, TypeId,
183	};
184
185	use crate::WeightInfo;
186
187	/// Circuit breaker levels for emergency control.
188	#[derive(
189		Encode,
190		Decode,
191		DecodeWithMemTracking,
192		MaxEncodedLen,
193		TypeInfo,
194		Clone,
195		Copy,
196		PartialEq,
197		Eq,
198		Debug,
199		Default,
200	)]
201	pub enum CircuitBreakerLevel {
202		/// Normal operation, all swaps enabled.
203		#[default]
204		AllEnabled,
205		/// Minting disabled, redemptions still allowed.
206		MintingDisabled,
207		/// All swaps disabled.
208		AllDisabled,
209	}
210
211	impl CircuitBreakerLevel {
212		/// Whether this level allows minting (external → internal).
213		pub const fn allows_minting(&self) -> bool {
214			matches!(self, CircuitBreakerLevel::AllEnabled)
215		}
216
217		/// Whether this level allows redemption (internal → external).
218		pub const fn allows_redemption(&self) -> bool {
219			!matches!(self, CircuitBreakerLevel::AllDisabled)
220		}
221	}
222
223	/// Privilege level of an origin acting on a PSM instance.
224	///
225	/// Resolved by matching the incoming origin against the instance's stored
226	/// [`PsmAdminInfo::full_admin`] (`Full`) or [`PsmAdminInfo::emergency_admin`]
227	/// (`Emergency`), enabling tiered authorization over the instance's parameters.
228	#[derive(
229		Encode,
230		Decode,
231		DecodeWithMemTracking,
232		MaxEncodedLen,
233		TypeInfo,
234		Clone,
235		Copy,
236		PartialEq,
237		Eq,
238		Debug,
239		Default,
240	)]
241	pub enum PsmManagerLevel {
242		/// Full administrative access, held by the instance's `full_admin`.
243		/// Can modify all parameters including fees, ceilings, and asset management,
244		/// reassign admins, and remove the instance.
245		#[default]
246		Full,
247		/// Emergency access, held by the instance's `emergency_admin`.
248		/// Can modify circuit breaker status.
249		Emergency,
250	}
251
252	impl PsmManagerLevel {
253		/// Whether this level allows modifying minting/redemption fees.
254		pub const fn can_set_fees(&self) -> bool {
255			matches!(self, PsmManagerLevel::Full)
256		}
257
258		/// Whether this level allows modifying the circuit breaker status.
259		/// Both Full and Emergency levels can set circuit breaker.
260		pub const fn can_set_circuit_breaker(&self) -> bool {
261			matches!(self, PsmManagerLevel::Full | PsmManagerLevel::Emergency)
262		}
263
264		/// Whether this level allows modifying the PSM debt ceiling.
265		/// Only Full can set the debt ceiling.
266		pub const fn can_set_max_debt(&self) -> bool {
267			matches!(self, PsmManagerLevel::Full)
268		}
269
270		/// Whether this level allows modifying per-asset ceiling weights.
271		/// Only Full can set asset ceiling weights.
272		pub const fn can_set_asset_ceiling(&self) -> bool {
273			matches!(self, PsmManagerLevel::Full)
274		}
275
276		/// Whether this level allows adding or removing external assets.
277		pub const fn can_manage_assets(&self) -> bool {
278			matches!(self, PsmManagerLevel::Full)
279		}
280
281		/// Whether this level allows reassigning the PSM's `full_admin` / `emergency_admin`.
282		pub const fn can_manage_admins(&self) -> bool {
283			matches!(self, PsmManagerLevel::Full)
284		}
285
286		/// Whether this level allows removing the PSM instance.
287		pub const fn can_remove_psm(&self) -> bool {
288			matches!(self, PsmManagerLevel::Full)
289		}
290	}
291
292	pub(crate) type BalanceOf<T> = <<T as Config>::Fungibles as FungiblesInspect<
293		<T as frame_system::Config>::AccountId,
294	>>::Balance;
295
296	/// Suggested fee of 0.5% for minting and redemption.
297	pub(crate) struct DefaultFee;
298	impl Get<Permill> for DefaultFee {
299		fn get() -> Permill {
300			Permill::from_parts(5_000)
301		}
302	}
303
304	/// Maximum absolute difference between an external asset's decimals and the internal
305	/// asset's decimals. Bounds the scaling factor `10^diff` well below `u128::MAX`
306	/// so realistic balances cannot overflow during conversion.
307	pub const MAX_DECIMALS_DIFF: u32 = 24;
308
309	/// On-chain record of a PSM instance.
310	#[derive(
311		Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq, Debug,
312	)]
313	#[scale_info(skip_type_params(T))]
314	pub struct PsmInfo<T: Config> {
315		/// Account receiving minting and redemption fees, denominated in the internal asset.
316		pub fee_destination: T::AccountId,
317		/// This PSM instance's debt ceiling, in internal-asset units.
318		pub max_debt: BalanceOf<T>,
319		/// Minimum swap amount for this instance, in internal-asset units. Swaps whose
320		/// internal-equivalent falls below this are rejected with [`Error::BelowMinimumSwap`].
321		pub min_swap_amount: BalanceOf<T>,
322		/// Snapshot of the internal asset's decimals at install time.
323		pub internal_decimals: u8,
324		/// Number of approved external assets attached to this instance.
325		pub external_count: u32,
326	}
327
328	/// Admin origins and creation-deposit bookkeeping for a PSM instance. Always written
329	/// and removed together with the [`Psm`] entry.
330	#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq, Debug)]
331	#[scale_info(skip_type_params(T))]
332	// Kept separate from `PsmInfo` so the swap path (`mint`/`redeem`) doesn't read the
333	// admin origins, which can be large.
334	pub struct PsmAdminInfo<T: Config> {
335		/// Origin with `Full` management privileges over this PSM. Set on `create_psm` and
336		/// reassignable to any origin via `set_full_admin`.
337		pub full_admin: T::PalletsOrigin,
338		/// Origin with `Emergency` management privileges over this PSM. Set on `create_psm` and
339		/// reassignable to any origin via `set_emergency_admin`.
340		pub emergency_admin: T::PalletsOrigin,
341		/// Optional creation deposit and its depositor. Dropped on `remove_psm`, independently of
342		/// any admin reassignment.
343		pub deposit: Option<(T::AccountId, T::Consideration)>,
344	}
345
346	/// On-chain record of an external asset approved on a PSM instance.
347	#[derive(
348		Encode,
349		Decode,
350		DecodeWithMemTracking,
351		MaxEncodedLen,
352		TypeInfo,
353		Clone,
354		Copy,
355		PartialEq,
356		Eq,
357		Debug,
358	)]
359	pub struct ExternalAssetInfo {
360		/// Per-external circuit breaker status.
361		pub status: CircuitBreakerLevel,
362		/// Snapshot of the external asset's decimals at registration time.
363		pub decimals: u8,
364	}
365
366	#[pallet::config]
367	pub trait Config: frame_system::Config {
368		/// Fungibles implementation for both internal and external assets.
369		type Fungibles: FungiblesMutate<Self::AccountId, AssetId = Self::AssetId>
370			+ FungiblesMetadataInspect<Self::AccountId>
371			+ FungiblesRolesInspect<Self::AccountId>;
372
373		/// Consideration for PSM creation. Runtimes can price this from the PSM footprint or
374		/// anything else they choose.
375		type Consideration: Consideration<Self::AccountId, Footprint>;
376
377		/// Origin permitted to create a PSM for a given internal asset; succeeds with the
378		/// optional account that pays the creation consideration. Returning `None` creates without
379		/// a deposit, useful for privileged origins such as Root.
380		type CreateOrigin: EnsureOriginWithArg<
381			<Self as frame_system::Config>::RuntimeOrigin,
382			Self::AssetId,
383			Success = Option<Self::AccountId>,
384		>;
385
386		/// The aggregated origin, tying the runtime origin to [`Config::PalletsOrigin`] so PSM
387		/// admins can be matched against incoming origins.
388		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
389			+ From<Self::PalletsOrigin>
390			+ IsType<<Self as frame_system::Config>::RuntimeOrigin>;
391
392		/// The caller origin, overarching type of all pallets' origins. Stored as a PSM's
393		/// `full_admin` / `emergency_admin` and matched against incoming origins.
394		type PalletsOrigin: Parameter
395			+ From<frame_system::RawOrigin<Self::AccountId>>
396			+ CallerTrait<Self::AccountId>
397			+ MaxEncodedLen;
398
399		/// Asset identifier type.
400		type AssetId: Parameter + Member + Clone + MaybeSerializeDeserialize + MaxEncodedLen + Ord;
401
402		/// A type representing the weights required by the dispatchables of this pallet.
403		type WeightInfo: WeightInfo;
404
405		/// PalletId for deriving each PSM instance's reserve sub-account.
406		#[pallet::constant]
407		type PalletId: Get<PalletId>;
408
409		/// Maximum number of approved external assets per PSM instance.
410		#[pallet::constant]
411		type MaxExternals: Get<u32>;
412
413		/// Helper for benchmarks to create an external asset with correct metadata.
414		#[cfg(feature = "runtime-benchmarks")]
415		type BenchmarkHelper: crate::BenchmarkHelper<Self::AssetId, Self::AccountId>;
416	}
417
418	/// [`Config::CreateOrigin`] admitting a signed origin only when it owns the internal asset.
419	/// Prevents creating a PSM over an asset you don't control (PSM mint/burn bypasses the
420	/// asset's issuer checks).
421	pub struct EnsureAssetOwner<T>(core::marker::PhantomData<T>);
422
423	impl<T: Config> EnsureOriginWithArg<<T as frame_system::Config>::RuntimeOrigin, T::AssetId>
424		for EnsureAssetOwner<T>
425	{
426		type Success = Option<T::AccountId>;
427
428		fn try_origin(
429			origin: <T as frame_system::Config>::RuntimeOrigin,
430			internal_asset: &T::AssetId,
431		) -> Result<Self::Success, <T as frame_system::Config>::RuntimeOrigin> {
432			match ensure_signed(origin.clone()) {
433				Ok(who) if T::Fungibles::owner(internal_asset.clone()) == Some(who.clone()) => {
434					Ok(Some(who))
435				},
436				_ => Err(origin),
437			}
438		}
439
440		#[cfg(feature = "runtime-benchmarks")]
441		fn try_successful_origin(
442			internal_asset: &T::AssetId,
443		) -> Result<<T as frame_system::Config>::RuntimeOrigin, ()> {
444			// A signed origin of the asset's current owner satisfies the owner check.
445			let owner = T::Fungibles::owner(internal_asset.clone()).ok_or(())?;
446			Ok(frame_system::RawOrigin::Signed(owner).into())
447		}
448	}
449
450	/// The in-code storage version.
451	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
452
453	#[pallet::pallet]
454	#[pallet::storage_version(STORAGE_VERSION)]
455	pub struct Pallet<T>(_);
456
457	/// A reason for this pallet placing a hold on funds.
458	#[pallet::composite_enum]
459	pub enum HoldReason {
460		/// The deposit backing a PSM instance created via `create_psm`.
461		#[codec(index = 0)]
462		CreationDeposit,
463	}
464
465	#[pallet::hooks]
466	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
467		fn integrity_test() {
468			const ENTROPY_BYTES: usize = 32;
469			assert!(
470				<T::AccountId as MaxEncodedLen>::max_encoded_len() >= ENTROPY_BYTES,
471				"T::AccountId is too small to preserve the full PSM reserve-account entropy",
472			);
473		}
474
475		#[cfg(feature = "try-runtime")]
476		fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
477			Self::do_try_state()
478		}
479	}
480
481	/// Registered PSM instances, keyed by the internal asset id.
482	#[pallet::storage]
483	pub type Psm<T: Config> = StorageMap<_, Blake2_128Concat, T::AssetId, PsmInfo<T>, OptionQuery>;
484
485	/// Admin origins and creation-deposit bookkeeping per PSM, keyed by the internal
486	/// asset id. Held separately from [`Psm`] so swaps never decode the admin origins.
487	/// Always written and removed together with the corresponding [`Psm`] entry.
488	#[pallet::storage]
489	pub type PsmAdmin<T: Config> =
490		StorageMap<_, Blake2_128Concat, T::AssetId, PsmAdminInfo<T>, OptionQuery>;
491
492	/// Internal-asset debt minted through PSM, per `(internal, external)` pair.
493	#[pallet::storage]
494	pub type PsmDebt<T: Config> = StorageDoubleMap<
495		_,
496		Blake2_128Concat,
497		T::AssetId,
498		Blake2_128Concat,
499		T::AssetId,
500		BalanceOf<T>,
501		ValueQuery,
502	>;
503
504	/// Fee for external → internal swaps (minting), per `(internal, external)` pair.
505	/// Defaults to 0.5%.
506	#[pallet::storage]
507	pub(crate) type MintingFee<T: Config> = StorageDoubleMap<
508		_,
509		Blake2_128Concat,
510		T::AssetId,
511		Blake2_128Concat,
512		T::AssetId,
513		Permill,
514		ValueQuery,
515		DefaultFee,
516	>;
517
518	/// Fee for internal → external swaps (redemption), per `(internal, external)` pair.
519	/// Defaults to 0.5%.
520	#[pallet::storage]
521	pub(crate) type RedemptionFee<T: Config> = StorageDoubleMap<
522		_,
523		Blake2_128Concat,
524		T::AssetId,
525		Blake2_128Concat,
526		T::AssetId,
527		Permill,
528		ValueQuery,
529		DefaultFee,
530	>;
531
532	/// Per-external ceiling weight within a PSM, normalised against the sum of weights
533	/// for the same instance. Zero disables minting for that external.
534	#[pallet::storage]
535	pub(crate) type AssetCeilingWeight<T: Config> = StorageDoubleMap<
536		_,
537		Blake2_128Concat,
538		T::AssetId,
539		Blake2_128Concat,
540		T::AssetId,
541		Permill,
542		ValueQuery,
543	>;
544
545	/// Approved external assets per PSM.
546	#[pallet::storage]
547	pub(crate) type ExternalAssets<T: Config> = StorageDoubleMap<
548		_,
549		Blake2_128Concat,
550		T::AssetId,
551		Blake2_128Concat,
552		T::AssetId,
553		ExternalAssetInfo,
554		OptionQuery,
555	>;
556
557	#[pallet::event]
558	#[pallet::generate_deposit(pub(super) fn deposit_event)]
559	pub enum Event<T: Config> {
560		/// User swapped external asset for internal.
561		Minted {
562			who: T::AccountId,
563			internal_asset: T::AssetId,
564			external_asset: T::AssetId,
565			external_consumed: BalanceOf<T>,
566			internal_received: BalanceOf<T>,
567			internal_fee: BalanceOf<T>,
568		},
569		/// User swapped internal for external asset.
570		Redeemed {
571			who: T::AccountId,
572			internal_asset: T::AssetId,
573			external_asset: T::AssetId,
574			internal_consumed: BalanceOf<T>,
575			external_received: BalanceOf<T>,
576			internal_fee: BalanceOf<T>,
577		},
578		/// Minting fee updated for an asset by governance.
579		MintingFeeUpdated {
580			internal_asset: T::AssetId,
581			external_asset: T::AssetId,
582			old_value: Permill,
583			new_value: Permill,
584		},
585		/// Redemption fee updated for an asset by governance.
586		RedemptionFeeUpdated {
587			internal_asset: T::AssetId,
588			external_asset: T::AssetId,
589			old_value: Permill,
590			new_value: Permill,
591		},
592		/// PSM debt ceiling updated by governance.
593		MaxDebtUpdated {
594			internal_asset: T::AssetId,
595			old_value: BalanceOf<T>,
596			new_value: BalanceOf<T>,
597		},
598		/// Per-asset debt ceiling weight updated by governance.
599		AssetCeilingWeightUpdated {
600			internal_asset: T::AssetId,
601			external_asset: T::AssetId,
602			old_value: Permill,
603			new_value: Permill,
604		},
605		/// Per-asset circuit breaker status updated.
606		AssetStatusUpdated {
607			internal_asset: T::AssetId,
608			external_asset: T::AssetId,
609			status: CircuitBreakerLevel,
610		},
611		/// An external asset was added to the approved list.
612		ExternalAssetAdded { internal_asset: T::AssetId, external_asset: T::AssetId },
613		/// An external asset was removed from the approved list.
614		ExternalAssetRemoved { internal_asset: T::AssetId, external_asset: T::AssetId },
615		/// A PSM instance was created.
616		PsmCreated {
617			internal_asset: T::AssetId,
618			// Boxed: `PalletsOrigin` can be large and would otherwise inflate the `Event` enum.
619			full_admin: Box<T::PalletsOrigin>,
620			emergency_admin: Box<T::PalletsOrigin>,
621			fee_destination: T::AccountId,
622			max_debt: BalanceOf<T>,
623		},
624		/// A PSM instance was removed.
625		PsmRemoved { internal_asset: T::AssetId },
626		/// A PSM's `full_admin` was reassigned.
627		FullAdminChanged {
628			internal_asset: T::AssetId,
629			old_admin: Box<T::PalletsOrigin>,
630			new_admin: Box<T::PalletsOrigin>,
631		},
632		/// A PSM's `emergency_admin` was reassigned.
633		EmergencyAdminChanged {
634			internal_asset: T::AssetId,
635			old_admin: Box<T::PalletsOrigin>,
636			new_admin: Box<T::PalletsOrigin>,
637		},
638	}
639
640	#[pallet::error]
641	pub enum Error<T> {
642		/// PSM doesn't have enough external asset for redemption.
643		InsufficientReserve,
644		/// Swap would exceed PSM debt ceiling.
645		ExceedsMaxPsmDebt,
646		/// Swap amount below the instance's minimum threshold.
647		BelowMinimumSwap,
648		/// Current fee exceeds the caller-provided maximum.
649		FeeTooHigh,
650		/// `create_psm` was called with a zero `min_swap_amount`.
651		ZeroMinSwapAmount,
652		/// Minting operations are disabled (circuit breaker level >= 1).
653		MintingStopped,
654		/// All swap operations are disabled (circuit breaker level = 2).
655		AllSwapsStopped,
656		/// Asset is not an approved external asset.
657		UnsupportedAsset,
658		/// No PSM instance is registered for the given internal asset.
659		PsmNotFound,
660		/// Asset is already in the approved list.
661		AssetAlreadyApproved,
662		/// Asset does not exist.
663		AssetDoesNotExist,
664		/// Cannot remove asset: not in approved list.
665		AssetNotApproved,
666		/// Cannot remove asset: has non-zero PSM debt.
667		AssetHasDebt,
668		/// Operation requires the instance's `full_admin` (Full level); the caller only
669		/// matched the `emergency_admin` (Emergency level).
670		InsufficientPrivilege,
671		/// Maximum number of approved external assets reached.
672		TooManyAssets,
673		/// Reserved legacy error; retained to preserve error variant indices.
674		DecimalsMismatch,
675		/// The asset's decimal precision is outside the supported range.
676		DecimalsRangeExceeded,
677		/// Decimal scaling produced an arithmetic overflow.
678		ConversionOverflow,
679		/// Conversion to the counter-asset rounds to zero; swap would transfer nothing.
680		AmountTooSmallAfterConversion,
681		/// A PSM is already registered for this internal asset.
682		PsmAlreadyExists,
683		/// The PSM has non-zero outstanding debt on at least one approved external.
684		PsmHasDebt,
685		/// The PSM still has approved externals; remove them before removing the PSM.
686		PsmHasApprovedExternals,
687		/// An unexpected invariant violation occurred. This should be reported.
688		Unexpected,
689		/// An admin origin was supplied that cannot be used as an authority, such as the system
690		/// `None` origin.
691		InvalidAdminOrigin,
692		/// The PSM reserve account cannot receive the external asset.
693		ReserveCannotReceive,
694	}
695
696	#[pallet::call]
697	impl<T: Config> Pallet<T> {
698		/// Swap external asset for internal on a specific PSM instance.
699		///
700		/// ## Dispatch Origin
701		///
702		/// Must be `Signed` by the user performing the swap.
703		///
704		/// ## Details
705		///
706		/// Transfers `external_amount` of `external_asset` from the caller to the
707		/// `internal_asset`'s PSM reserve account, then mints `internal_asset` to the
708		/// caller minus the minting fee. The fee is calculated using ceiling rounding
709		/// (`mul_ceil`), ensuring the protocol never undercharges. The fee is
710		/// transferred to [`PsmInfo::fee_destination`] of the targeted instance, and waived
711		/// if that account cannot receive it.
712		///
713		/// ## Parameters
714		///
715		/// - `internal_asset`: The internal stablecoin that identifies the PSM instance.
716		/// - `external_asset`: The external asset to deposit (must be approved on
717		///   `internal_asset`).
718		/// - `external_amount`: Amount of external asset to deposit.
719		/// - `max_fee`: Maximum minting fee rate accepted by the caller.
720		///
721		/// ## Errors
722		///
723		/// - [`Error::PsmNotFound`]: If no PSM is registered for `internal_asset`.
724		/// - [`Error::UnsupportedAsset`]: If `external_asset` is not approved on this PSM.
725		/// - [`Error::MintingStopped`]: If the per-external circuit breaker is at `MintingDisabled`
726		///   or higher.
727		/// - [`Error::BelowMinimumSwap`]: If the internal-equivalent of `external_amount` is below
728		///   the instance's `min_swap_amount`.
729		/// - [`Error::FeeTooHigh`]: If the configured minting fee exceeds `max_fee`.
730		/// - [`Error::ExceedsMaxPsmDebt`]: If minting would exceed this PSM's debt ceiling
731		///   (aggregate or per-asset).
732		/// - [`Error::AmountTooSmallAfterConversion`]: If the conversion to the counter-asset
733		///   rounds to zero; swap would transfer nothing.
734		///
735		/// ## Events
736		///
737		/// - [`Event::Minted`]: Emitted on successful mint.
738		#[pallet::call_index(0)]
739		#[pallet::weight(T::WeightInfo::mint(T::MaxExternals::get()))]
740		pub fn mint(
741			origin: OriginFor<T>,
742			internal_asset: T::AssetId,
743			external_asset: T::AssetId,
744			external_amount: BalanceOf<T>,
745			max_fee: Permill,
746		) -> DispatchResult {
747			let who = ensure_signed(origin)?;
748			let info = Psm::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
749
750			let external = ExternalAssets::<T>::get(&internal_asset, &external_asset)
751				.ok_or(Error::<T>::UnsupportedAsset)?;
752			ensure!(external.status.allows_minting(), Error::<T>::MintingStopped);
753
754			let ext_decimals = external.decimals;
755			let internal_decimals = info.internal_decimals;
756
757			let internal_equivalent =
758				Self::external_to_internal(external_amount, ext_decimals, internal_decimals)?;
759			ensure!(!internal_equivalent.is_zero(), Error::<T>::AmountTooSmallAfterConversion);
760			ensure!(internal_equivalent >= info.min_swap_amount, Error::<T>::BelowMinimumSwap);
761
762			let effective_external =
763				Self::internal_to_external(internal_equivalent, ext_decimals, internal_decimals)?;
764
765			let fee_rate = MintingFee::<T>::get(&internal_asset, &external_asset);
766			ensure!(fee_rate <= max_fee, Error::<T>::FeeTooHigh);
767			let fee = fee_rate.mul_ceil(internal_equivalent);
768			// Waive the fee if the fee destination cannot receive it, so it never blocks swaps.
769			let fee = match T::Fungibles::can_deposit(
770				internal_asset.clone(),
771				&info.fee_destination,
772				fee,
773				Provenance::Minted,
774			) {
775				DepositConsequence::Success => fee,
776				_ => Zero::zero(),
777			};
778			let internal_to_user = internal_equivalent.saturating_sub(fee);
779
780			let current_total_psm_debt = Self::total_psm_debt(&internal_asset);
781			ensure!(
782				current_total_psm_debt.saturating_add(internal_equivalent) <= info.max_debt,
783				Error::<T>::ExceedsMaxPsmDebt
784			);
785
786			let current_debt = PsmDebt::<T>::get(&internal_asset, &external_asset);
787			let max_debt = Self::max_asset_debt(&internal_asset, &external_asset, &info);
788			let new_debt = current_debt.saturating_add(internal_equivalent);
789			ensure!(new_debt <= max_debt, Error::<T>::ExceedsMaxPsmDebt);
790
791			let psm_account = Self::psm_account(&internal_asset);
792			T::Fungibles::transfer(
793				external_asset.clone(),
794				&who,
795				&psm_account,
796				effective_external,
797				Preservation::Expendable,
798			)?;
799			T::Fungibles::mint_into(internal_asset.clone(), &who, internal_to_user)?;
800			if !fee.is_zero() {
801				T::Fungibles::mint_into(internal_asset.clone(), &info.fee_destination, fee)?;
802			}
803
804			PsmDebt::<T>::insert(&internal_asset, &external_asset, new_debt);
805
806			Self::deposit_event(Event::Minted {
807				who,
808				internal_asset,
809				external_asset,
810				external_consumed: effective_external,
811				internal_received: internal_to_user,
812				internal_fee: fee,
813			});
814			Ok(())
815		}
816
817		/// Swap internal for external asset on a specific PSM instance.
818		///
819		/// ## Dispatch Origin
820		///
821		/// Must be `Signed` by the user performing the swap.
822		///
823		/// ## Details
824		///
825		/// Burns `internal_amount` of `internal_asset` from the caller minus fee (transferred
826		/// to the instance's [`PsmInfo::fee_destination`], or waived if that account cannot
827		/// receive it), then transfers the resulting amount in `external_asset` from the PSM
828		/// reserve to the caller. The fee is
829		/// calculated using ceiling rounding (`mul_ceil`), ensuring the protocol never
830		/// undercharges. Redemptions use the decimals snapshotted when the PSM/external pair
831		/// was registered, allowing existing positions to unwind even if live metadata later
832		/// changes.
833		///
834		/// ## Parameters
835		///
836		/// - `internal_asset`: The internal stablecoin that identifies the PSM instance.
837		/// - `external_asset`: The external asset to receive (must be approved on
838		///   `internal_asset`).
839		/// - `internal_amount`: Amount of `internal_asset` to redeem.
840		/// - `max_fee`: Maximum redemption fee rate accepted by the caller.
841		///
842		/// ## Errors
843		///
844		/// - [`Error::PsmNotFound`]: If no PSM is registered for `internal_asset`.
845		/// - [`Error::UnsupportedAsset`]: If `external_asset` is not approved on this PSM.
846		/// - [`Error::AllSwapsStopped`]: If the per-external circuit breaker is at `AllDisabled`.
847		/// - [`Error::BelowMinimumSwap`]: If `internal_amount` is below the instance's
848		///   `min_swap_amount`.
849		/// - [`Error::FeeTooHigh`]: If the configured redemption fee exceeds `max_fee`.
850		/// - [`Error::InsufficientReserve`]: If the PSM holds less of `external_asset` than the
851		///   redemption requires.
852		/// - [`Error::AmountTooSmallAfterConversion`]: If the conversion to the counter-asset
853		///   rounds to zero; swap would transfer nothing.
854		///
855		/// ## Events
856		///
857		/// - [`Event::Redeemed`]: Emitted on successful redemption.
858		#[pallet::call_index(1)]
859		#[pallet::weight(T::WeightInfo::redeem())]
860		pub fn redeem(
861			origin: OriginFor<T>,
862			internal_asset: T::AssetId,
863			external_asset: T::AssetId,
864			internal_amount: BalanceOf<T>,
865			max_fee: Permill,
866		) -> DispatchResult {
867			let who = ensure_signed(origin)?;
868			let info = Psm::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
869
870			let external = ExternalAssets::<T>::get(&internal_asset, &external_asset)
871				.ok_or(Error::<T>::UnsupportedAsset)?;
872			ensure!(external.status.allows_redemption(), Error::<T>::AllSwapsStopped);
873
874			let ext_decimals = external.decimals;
875			let internal_decimals = info.internal_decimals;
876
877			ensure!(internal_amount >= info.min_swap_amount, Error::<T>::BelowMinimumSwap);
878
879			let fee_rate = RedemptionFee::<T>::get(&internal_asset, &external_asset);
880			ensure!(fee_rate <= max_fee, Error::<T>::FeeTooHigh);
881			let fee = fee_rate.mul_ceil(internal_amount);
882			// Waive the fee if the fee destination cannot receive it, so it never blocks swaps.
883			let mut fee = match T::Fungibles::can_deposit(
884				internal_asset.clone(),
885				&info.fee_destination,
886				fee,
887				Provenance::Extant,
888			) {
889				DepositConsequence::Success => fee,
890				_ => Zero::zero(),
891			};
892			let internal_net = internal_amount.saturating_sub(fee);
893
894			let external_out =
895				Self::internal_to_external(internal_net, ext_decimals, internal_decimals)?;
896			ensure!(
897				internal_net.is_zero() || !external_out.is_zero(),
898				Error::<T>::AmountTooSmallAfterConversion
899			);
900			// `effective_internal_net` is the internal value that round-trips to `external_out`;
901			// it is what we actually burn and what the tracked debt decreases by. Any truncation
902			// dust stays in the caller's internal balance, symmetric with `mint`, which takes
903			// only the round-tripped share of the external amount.
904			let effective_internal_net =
905				Self::external_to_internal(external_out, ext_decimals, internal_decimals)?;
906
907			let current_debt = PsmDebt::<T>::get(&internal_asset, &external_asset);
908			ensure!(current_debt >= effective_internal_net, Error::<T>::InsufficientReserve);
909
910			let reserve = Self::get_reserve(&internal_asset, &external_asset);
911			if reserve < external_out {
912				defensive!("PSM reserve is less than expected output amount");
913				return Err(Error::<T>::Unexpected.into());
914			}
915
916			// `burn_from` would also burn a remainder below `min_balance`, which this pair's debt
917			// may not cover. Send it to the fee destination along with the fee instead, if the fee
918			// destination can receive it.
919			let remainder = T::Fungibles::balance(internal_asset.clone(), &who)
920				.saturating_sub(fee.saturating_add(effective_internal_net));
921
922			let with_remainder = fee.saturating_add(remainder);
923			if remainder < T::Fungibles::minimum_balance(internal_asset.clone()) &&
924				T::Fungibles::can_deposit(
925					internal_asset.clone(),
926					&info.fee_destination,
927					with_remainder,
928					Provenance::Extant,
929				) == DepositConsequence::Success
930			{
931				fee = with_remainder;
932			}
933
934			if !fee.is_zero() {
935				T::Fungibles::transfer(
936					internal_asset.clone(),
937					&who,
938					&info.fee_destination,
939					fee,
940					Preservation::Expendable,
941				)?;
942			}
943
944			let burned = if !effective_internal_net.is_zero() {
945				T::Fungibles::burn_from(
946					internal_asset.clone(),
947					&who,
948					effective_internal_net,
949					Preservation::Expendable,
950					Precision::Exact,
951					Fortitude::Polite,
952				)?
953			} else {
954				BalanceOf::<T>::zero()
955			};
956
957			let psm_account = Self::psm_account(&internal_asset);
958			if !external_out.is_zero() {
959				T::Fungibles::transfer(
960					external_asset.clone(),
961					&psm_account,
962					&who,
963					external_out,
964					Preservation::Expendable,
965				)?;
966			}
967
968			PsmDebt::<T>::mutate(&internal_asset, &external_asset, |debt| {
969				*debt = debt.saturating_sub(burned);
970			});
971
972			Self::deposit_event(Event::Redeemed {
973				who,
974				internal_asset,
975				external_asset,
976				internal_consumed: burned.saturating_add(fee),
977				external_received: external_out,
978				internal_fee: fee,
979			});
980			Ok(())
981		}
982
983		/// Create a PSM for a given internal asset.
984		///
985		/// If [`Config::CreateOrigin`] resolves to `Some(account)`, takes a
986		/// [`Config::Consideration`] deposit from that account for the instance's footprint
987		/// (refunded on `remove_psm`). If it resolves to `None`, no deposit is taken. The
988		/// `full_admin` and `emergency_admin` origins are set from the provided arguments and may
989		/// later be reassigned via [`Pallet::set_full_admin`] / [`Pallet::set_emergency_admin`].
990		///
991		/// ## Dispatch Origin
992		///
993		/// [`Config::CreateOrigin`], parameterised by `internal_asset`. With the recommended
994		/// [`EnsureAssetOwner`] this is a signed origin that owns `internal_asset`.
995		///
996		/// ## Parameters
997		///
998		/// - `internal_asset`: The internal stablecoin keying the new PSM. Must exist in the
999		///   fungibles backend; must not already have a PSM registered.
1000		/// - `full_admin`: Origin granted full management of the new PSM.
1001		/// - `emergency_admin`: Origin granted emergency management of the new PSM.
1002		/// - `fee_destination`: Account that will receive mint/redeem fees. Fees are waived while
1003		///   it cannot receive the internal asset.
1004		/// - `max_debt`: Initial absolute internal-asset debt ceiling.
1005		/// - `min_swap_amount`: Minimum swap amount for this instance, in internal-asset units.
1006		///   Must be non-zero.
1007		///
1008		/// ## Errors
1009		///
1010		/// - [`DispatchError::BadOrigin`]: The origin is not permitted by [`Config::CreateOrigin`].
1011		/// - [`Error::InvalidAdminOrigin`]: Either admin is the system `None` origin.
1012		/// - [`Error::PsmAlreadyExists`]: A PSM is already registered for `internal_asset`.
1013		/// - [`Error::ZeroMinSwapAmount`]: `min_swap_amount` is zero.
1014		/// - [`Error::AssetDoesNotExist`]: The internal asset does not exist.
1015		/// - Any error from establishing the [`Config::Consideration`] deposit when one is needed
1016		///   (e.g. the account cannot afford it).
1017		///
1018		/// ## Events
1019		///
1020		/// - [`Event::PsmCreated`].
1021		#[pallet::call_index(2)]
1022		#[pallet::weight(T::WeightInfo::create_psm())]
1023		pub fn create_psm(
1024			origin: OriginFor<T>,
1025			internal_asset: T::AssetId,
1026			full_admin: Box<T::PalletsOrigin>,
1027			emergency_admin: Box<T::PalletsOrigin>,
1028			fee_destination: T::AccountId,
1029			max_debt: BalanceOf<T>,
1030			min_swap_amount: BalanceOf<T>,
1031		) -> DispatchResult {
1032			let maybe_depositor = T::CreateOrigin::ensure_origin(origin, &internal_asset)?;
1033			ensure!(
1034				!full_admin.is_none() && !emergency_admin.is_none(),
1035				Error::<T>::InvalidAdminOrigin
1036			);
1037			ensure!(!Psm::<T>::contains_key(&internal_asset), Error::<T>::PsmAlreadyExists);
1038			ensure!(!min_swap_amount.is_zero(), Error::<T>::ZeroMinSwapAmount);
1039			ensure!(
1040				T::Fungibles::asset_exists(internal_asset.clone()),
1041				Error::<T>::AssetDoesNotExist
1042			);
1043
1044			let deposit = maybe_depositor
1045				.map(|depositor| {
1046					T::Consideration::new(&depositor, Self::psm_creation_footprint())
1047						.map(|ticket| (depositor, ticket))
1048				})
1049				.transpose()?;
1050
1051			let full_admin = *full_admin;
1052			let emergency_admin = *emergency_admin;
1053			let internal_decimals = T::Fungibles::decimals(internal_asset.clone());
1054			Psm::<T>::insert(
1055				&internal_asset,
1056				PsmInfo::<T> {
1057					fee_destination: fee_destination.clone(),
1058					max_debt,
1059					min_swap_amount,
1060					internal_decimals,
1061					external_count: 0,
1062				},
1063			);
1064			PsmAdmin::<T>::insert(
1065				&internal_asset,
1066				PsmAdminInfo::<T> {
1067					full_admin: full_admin.clone(),
1068					emergency_admin: emergency_admin.clone(),
1069					deposit,
1070				},
1071			);
1072			Self::deposit_event(Event::PsmCreated {
1073				internal_asset,
1074				full_admin: Box::new(full_admin),
1075				emergency_admin: Box::new(emergency_admin),
1076				fee_destination,
1077				max_debt,
1078			});
1079			Ok(())
1080		}
1081
1082		/// Remove a PSM. Callable by the current `full_admin`. All approved externals
1083		/// must be removed first and aggregate PSM debt must be zero.
1084		///
1085		/// If a creation deposit was taken, it is always returned to the account that originally
1086		/// paid it, regardless of any later admin reassignment.
1087		///
1088		/// ## Dispatch Origin
1089		///
1090		/// Must match the PSM's `full_admin`.
1091		///
1092		/// ## Parameters
1093		///
1094		/// - `internal_asset`: The PSM instance to remove.
1095		///
1096		/// ## Errors
1097		///
1098		/// - [`Error::PsmNotFound`]: No PSM is registered for `internal_asset`.
1099		/// - [`Error::PsmHasApprovedExternals`]: Approved externals still exist.
1100		/// - [`Error::PsmHasDebt`]: Outstanding aggregate debt is non-zero.
1101		///
1102		/// ## Events
1103		///
1104		/// - [`Event::PsmRemoved`].
1105		#[pallet::call_index(3)]
1106		#[pallet::weight(T::WeightInfo::remove_psm())]
1107		pub fn remove_psm(origin: OriginFor<T>, internal_asset: T::AssetId) -> DispatchResult {
1108			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_remove_psm())?;
1109			let info = Psm::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
1110			ensure!(info.external_count == 0, Error::<T>::PsmHasApprovedExternals);
1111			ensure!(Self::total_psm_debt(&internal_asset).is_zero(), Error::<T>::PsmHasDebt);
1112
1113			let PsmAdminInfo { deposit, .. } =
1114				PsmAdmin::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
1115			if let Some((depositor, ticket)) = deposit {
1116				ticket.drop(&depositor)?;
1117			}
1118
1119			Psm::<T>::remove(&internal_asset);
1120			PsmAdmin::<T>::remove(&internal_asset);
1121
1122			Self::deposit_event(Event::PsmRemoved { internal_asset });
1123			Ok(())
1124		}
1125
1126		/// Set the minting fee for an `(internal_asset, external_asset)` pair.
1127		///
1128		/// ## Dispatch Origin
1129		///
1130		/// Must match the PSM instance's `full_admin` (the `Full` privilege level).
1131		///
1132		/// ## Parameters
1133		///
1134		/// - `internal_asset`: The PSM instance to configure.
1135		/// - `external_asset`: The external asset whose minting fee is being updated.
1136		/// - `fee`: The new minting fee.
1137		///
1138		/// ## Errors
1139		///
1140		/// - [`Error::InsufficientPrivilege`]: If the origin only has `Emergency` privileges.
1141		/// - [`Error::AssetNotApproved`]: If `external_asset` is not approved on `internal_asset`.
1142		///
1143		/// ## Events
1144		///
1145		/// - [`Event::MintingFeeUpdated`]: Emitted with old and new values.
1146		#[pallet::call_index(4)]
1147		#[pallet::weight(T::WeightInfo::set_minting_fee())]
1148		pub fn set_minting_fee(
1149			origin: OriginFor<T>,
1150			internal_asset: T::AssetId,
1151			external_asset: T::AssetId,
1152			fee: Permill,
1153		) -> DispatchResult {
1154			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_set_fees())?;
1155			ensure!(
1156				ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1157				Error::<T>::AssetNotApproved
1158			);
1159			let old_value = MintingFee::<T>::get(&internal_asset, &external_asset);
1160			MintingFee::<T>::insert(&internal_asset, &external_asset, fee);
1161			Self::deposit_event(Event::MintingFeeUpdated {
1162				internal_asset,
1163				external_asset,
1164				old_value,
1165				new_value: fee,
1166			});
1167			Ok(())
1168		}
1169
1170		/// Set the redemption fee for an `(internal_asset, external_asset)` pair.
1171		///
1172		/// ## Dispatch Origin
1173		///
1174		/// Must match the PSM instance's `full_admin` (the `Full` privilege level).
1175		///
1176		/// ## Parameters
1177		///
1178		/// - `internal_asset`: The PSM instance to configure.
1179		/// - `external_asset`: The external asset whose redemption fee is being updated.
1180		/// - `fee`: The new redemption fee.
1181		///
1182		/// ## Errors
1183		///
1184		/// - [`Error::InsufficientPrivilege`]: If the origin only has `Emergency` privileges.
1185		/// - [`Error::AssetNotApproved`]: If `external_asset` is not approved on `internal_asset`.
1186		///
1187		/// ## Events
1188		///
1189		/// - [`Event::RedemptionFeeUpdated`]: Emitted with old and new values.
1190		#[pallet::call_index(5)]
1191		#[pallet::weight(T::WeightInfo::set_redemption_fee())]
1192		pub fn set_redemption_fee(
1193			origin: OriginFor<T>,
1194			internal_asset: T::AssetId,
1195			external_asset: T::AssetId,
1196			fee: Permill,
1197		) -> DispatchResult {
1198			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_set_fees())?;
1199			ensure!(
1200				ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1201				Error::<T>::AssetNotApproved
1202			);
1203			let old_value = RedemptionFee::<T>::get(&internal_asset, &external_asset);
1204			RedemptionFee::<T>::insert(&internal_asset, &external_asset, fee);
1205			Self::deposit_event(Event::RedemptionFeeUpdated {
1206				internal_asset,
1207				external_asset,
1208				old_value,
1209				new_value: fee,
1210			});
1211			Ok(())
1212		}
1213
1214		/// Set the PSM debt ceiling per internal asset, shared across all approved external
1215		/// assets.
1216		///
1217		/// ## Dispatch Origin
1218		///
1219		/// Must match the PSM instance's `full_admin`; only the `Full` privilege level may use
1220		/// this call.
1221		///
1222		/// ## Parameters
1223		///
1224		/// - `internal_asset`: The PSM instance to configure.
1225		/// - `value`: The new absolute debt ceiling, in internal-asset units.
1226		///
1227		/// ## Errors
1228		///
1229		/// - [`Error::InsufficientPrivilege`]: If the origin level cannot set the debt ceiling.
1230		/// - [`Error::PsmNotFound`]: If no PSM is registered for `internal_asset`.
1231		///
1232		/// ## Events
1233		///
1234		/// - [`Event::MaxDebtUpdated`]: Emitted with old and new values.
1235		#[pallet::call_index(6)]
1236		#[pallet::weight(T::WeightInfo::set_max_debt())]
1237		pub fn set_max_debt(
1238			origin: OriginFor<T>,
1239			internal_asset: T::AssetId,
1240			value: BalanceOf<T>,
1241		) -> DispatchResult {
1242			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_set_max_debt())?;
1243			// `max_debt` only gates minting: lowering it below outstanding debt does not claw
1244			// anything back, it just pauses minting until redemptions bring the debt back under
1245			// the new ceiling.
1246			let old_value =
1247				Psm::<T>::try_mutate(&internal_asset, |maybe| -> Result<_, DispatchError> {
1248					let info = maybe.as_mut().ok_or(Error::<T>::PsmNotFound)?;
1249					Ok(core::mem::replace(&mut info.max_debt, value))
1250				})?;
1251			Self::deposit_event(Event::MaxDebtUpdated {
1252				internal_asset,
1253				old_value,
1254				new_value: value,
1255			});
1256			Ok(())
1257		}
1258
1259		/// Set the circuit breaker per external asset on a PSM instance.
1260		///
1261		/// ## Dispatch Origin
1262		///
1263		/// Must match the PSM instance's `full_admin` or `emergency_admin`; either the
1264		/// `Full` or `Emergency` privilege level may use this call.
1265		///
1266		/// ## Parameters
1267		///
1268		/// - `internal_asset`: The PSM instance to configure.
1269		/// - `external_asset`: The external asset whose status is being updated.
1270		/// - `status`: The new circuit breaker level for that external.
1271		///
1272		/// ## Errors
1273		///
1274		/// - [`Error::AssetNotApproved`]: If `external_asset` is not approved on `internal_asset`.
1275		///
1276		/// ## Events
1277		///
1278		/// - [`Event::AssetStatusUpdated`]: Emitted on a successful update.
1279		#[pallet::call_index(7)]
1280		#[pallet::weight(T::WeightInfo::set_asset_status())]
1281		pub fn set_asset_status(
1282			origin: OriginFor<T>,
1283			internal_asset: T::AssetId,
1284			external_asset: T::AssetId,
1285			status: CircuitBreakerLevel,
1286		) -> DispatchResult {
1287			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_set_circuit_breaker())?;
1288			ExternalAssets::<T>::try_mutate(
1289				&internal_asset,
1290				&external_asset,
1291				|maybe| -> DispatchResult {
1292					let info = maybe.as_mut().ok_or(Error::<T>::AssetNotApproved)?;
1293					info.status = status;
1294					Ok(())
1295				},
1296			)?;
1297			Self::deposit_event(Event::AssetStatusUpdated {
1298				internal_asset,
1299				external_asset,
1300				status,
1301			});
1302			Ok(())
1303		}
1304
1305		/// Set the ceiling weight per external asset on a PSM instance.
1306		///
1307		/// Weights are normalised against the sum of weights within the same instance:
1308		/// `max_asset_debt = (weight / sum_of_weights) * info.max_debt`.
1309		///
1310		/// ## Dispatch Origin
1311		///
1312		/// Must match the PSM instance's `full_admin`; only the `Full` privilege level may use
1313		/// this call.
1314		///
1315		/// ## Parameters
1316		///
1317		/// - `internal_asset`: The PSM instance to configure.
1318		/// - `external_asset`: The external asset whose ceiling weight is being updated.
1319		/// - `weight`: The new ceiling weight. Zero disables minting for this external.
1320		///
1321		/// ## Errors
1322		///
1323		/// - [`Error::InsufficientPrivilege`]: If the origin level cannot set ceiling weights.
1324		/// - [`Error::AssetNotApproved`]: If `external_asset` is not approved on `internal_asset`.
1325		///
1326		/// ## Events
1327		///
1328		/// - [`Event::AssetCeilingWeightUpdated`]: Emitted with old and new values.
1329		#[pallet::call_index(8)]
1330		#[pallet::weight(T::WeightInfo::set_asset_ceiling_weight())]
1331		pub fn set_asset_ceiling_weight(
1332			origin: OriginFor<T>,
1333			internal_asset: T::AssetId,
1334			external_asset: T::AssetId,
1335			weight: Permill,
1336		) -> DispatchResult {
1337			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_set_asset_ceiling())?;
1338			ensure!(
1339				ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1340				Error::<T>::AssetNotApproved
1341			);
1342			// Reweighting renormalises every external's ceiling; an external left below its new
1343			// ceiling simply can't be minted until redemptions bring its debt back down.
1344			let old_value = AssetCeilingWeight::<T>::get(&internal_asset, &external_asset);
1345			AssetCeilingWeight::<T>::insert(&internal_asset, &external_asset, weight);
1346			Self::deposit_event(Event::AssetCeilingWeightUpdated {
1347				internal_asset,
1348				external_asset,
1349				old_value,
1350				new_value: weight,
1351			});
1352			Ok(())
1353		}
1354
1355		/// Approve an external asset for a given internal asset.
1356		///
1357		/// Snapshots the external asset's live decimals at registration time and
1358		/// increments [`PsmInfo::external_count`].
1359		///
1360		/// The reserve account ([`Pallet::reserve_account`]) must already be able to receive
1361		/// `external_asset`. For a non-sufficient asset, create its asset account first (e.g. via
1362		/// `touch_other`).
1363		///
1364		/// ## Dispatch Origin
1365		///
1366		/// Must match the PSM instance's `full_admin` (the `Full` privilege level).
1367		///
1368		/// ## Parameters
1369		///
1370		/// - `internal_asset`: The PSM instance to approve the external on.
1371		/// - `external_asset`: The external asset to approve.
1372		///
1373		/// ## Errors
1374		///
1375		/// - [`Error::InsufficientPrivilege`]: If the origin only has `Emergency` privileges.
1376		/// - [`Error::PsmNotFound`]: If no PSM is registered for `internal_asset`.
1377		/// - [`Error::TooManyAssets`]: If the PSM is already at [`Config::MaxExternals`].
1378		/// - [`Error::AssetAlreadyApproved`]: If `external_asset` is already approved on this PSM.
1379		/// - [`Error::AssetDoesNotExist`]: If `external_asset` does not exist in the underlying
1380		///   fungibles backend.
1381		/// - [`Error::DecimalsRangeExceeded`]: If `|asset_decimals − internal_decimals|` exceeds
1382		///   [`MAX_DECIMALS_DIFF`].
1383		/// - [`Error::ReserveCannotReceive`]: If the reserve account cannot receive
1384		///   `external_asset`.
1385		///
1386		/// ## Events
1387		///
1388		/// - [`Event::ExternalAssetAdded`]: Emitted on a successful approval.
1389		#[pallet::call_index(9)]
1390		#[pallet::weight(T::WeightInfo::add_external_asset())]
1391		pub fn add_external_asset(
1392			origin: OriginFor<T>,
1393			internal_asset: T::AssetId,
1394			external_asset: T::AssetId,
1395		) -> DispatchResult {
1396			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_manage_assets())?;
1397			let mut info = Psm::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
1398			ensure!(
1399				!ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1400				Error::<T>::AssetAlreadyApproved
1401			);
1402			ensure!(info.external_count < T::MaxExternals::get(), Error::<T>::TooManyAssets);
1403			ensure!(
1404				T::Fungibles::asset_exists(external_asset.clone()),
1405				Error::<T>::AssetDoesNotExist
1406			);
1407
1408			let asset_decimals = T::Fungibles::decimals(external_asset.clone());
1409			ensure!(
1410				(asset_decimals.abs_diff(info.internal_decimals) as u32) <= MAX_DECIMALS_DIFF,
1411				Error::<T>::DecimalsRangeExceeded
1412			);
1413
1414			ensure!(
1415				T::Fungibles::can_deposit(
1416					external_asset.clone(),
1417					&Self::psm_account(&internal_asset),
1418					T::Fungibles::minimum_balance(external_asset.clone()),
1419					Provenance::Extant,
1420				) == DepositConsequence::Success,
1421				Error::<T>::ReserveCannotReceive
1422			);
1423
1424			ExternalAssets::<T>::insert(
1425				&internal_asset,
1426				&external_asset,
1427				ExternalAssetInfo {
1428					status: CircuitBreakerLevel::AllEnabled,
1429					decimals: asset_decimals,
1430				},
1431			);
1432			info.external_count = info.external_count.saturating_add(1);
1433			Psm::<T>::insert(&internal_asset, info);
1434
1435			Self::deposit_event(Event::ExternalAssetAdded { internal_asset, external_asset });
1436			Ok(())
1437		}
1438
1439		/// Remove an external asset from a PSM instance.
1440		///
1441		/// Wipes the external's per-instance state (status, decimals, fees, ceiling
1442		/// weight, debt counter) and decrements [`PsmInfo::external_count`]. The
1443		/// external must have zero outstanding debt on this instance.
1444		///
1445		/// ## Dispatch Origin
1446		///
1447		/// Must match the PSM instance's `full_admin` (the `Full` privilege level).
1448		///
1449		/// ## Parameters
1450		///
1451		/// - `internal_asset`: The PSM instance to remove the external from.
1452		/// - `external_asset`: The external asset to remove.
1453		///
1454		/// ## Errors
1455		///
1456		/// - [`Error::InsufficientPrivilege`]: If the origin only has `Emergency` privileges.
1457		/// - [`Error::PsmNotFound`]: If no PSM is registered for `internal_asset`.
1458		/// - [`Error::AssetNotApproved`]: If `external_asset` is not approved on this PSM.
1459		/// - [`Error::AssetHasDebt`]: If the external still has non-zero outstanding debt.
1460		///
1461		/// ## Events
1462		///
1463		/// - [`Event::ExternalAssetRemoved`]: Emitted on a successful removal.
1464		#[pallet::call_index(10)]
1465		#[pallet::weight(T::WeightInfo::remove_external_asset())]
1466		pub fn remove_external_asset(
1467			origin: OriginFor<T>,
1468			internal_asset: T::AssetId,
1469			external_asset: T::AssetId,
1470		) -> DispatchResult {
1471			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_manage_assets())?;
1472			let mut info = Psm::<T>::get(&internal_asset).ok_or(Error::<T>::PsmNotFound)?;
1473			ensure!(
1474				ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1475				Error::<T>::AssetNotApproved
1476			);
1477			ensure!(
1478				PsmDebt::<T>::get(&internal_asset, &external_asset).is_zero(),
1479				Error::<T>::AssetHasDebt
1480			);
1481			ExternalAssets::<T>::remove(&internal_asset, &external_asset);
1482			MintingFee::<T>::remove(&internal_asset, &external_asset);
1483			RedemptionFee::<T>::remove(&internal_asset, &external_asset);
1484			AssetCeilingWeight::<T>::remove(&internal_asset, &external_asset);
1485			PsmDebt::<T>::remove(&internal_asset, &external_asset);
1486			info.external_count = info.external_count.saturating_sub(1);
1487			Psm::<T>::insert(&internal_asset, info);
1488
1489			Self::deposit_event(Event::ExternalAssetRemoved { internal_asset, external_asset });
1490			Ok(())
1491		}
1492
1493		/// Reassign the PSM's `full_admin`. Callable by the current `full_admin`.
1494		///
1495		/// ## Dispatch Origin
1496		///
1497		/// Must match the PSM's current `full_admin`.
1498		///
1499		/// ## Parameters
1500		///
1501		/// - `internal_asset`: The PSM whose `full_admin` is being changed.
1502		/// - `new_admin`: The new `full_admin` origin.
1503		///
1504		/// ## Errors
1505		///
1506		/// - [`Error::PsmNotFound`]: No PSM is registered for `internal_asset`.
1507		/// - [`Error::InvalidAdminOrigin`]: `new_admin` is the system `None` origin.
1508		///
1509		/// ## Events
1510		///
1511		/// - [`Event::FullAdminChanged`].
1512		#[pallet::call_index(11)]
1513		#[pallet::weight(T::WeightInfo::set_full_admin())]
1514		pub fn set_full_admin(
1515			origin: OriginFor<T>,
1516			internal_asset: T::AssetId,
1517			new_admin: Box<T::PalletsOrigin>,
1518		) -> DispatchResult {
1519			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_manage_admins())?;
1520			ensure!(!new_admin.is_none(), Error::<T>::InvalidAdminOrigin);
1521			let new_admin = *new_admin;
1522			let old_admin = PsmAdmin::<T>::try_mutate(
1523				&internal_asset,
1524				|maybe| -> Result<T::PalletsOrigin, DispatchError> {
1525					let admin = maybe.as_mut().ok_or(Error::<T>::PsmNotFound)?;
1526					let old = core::mem::replace(&mut admin.full_admin, new_admin.clone());
1527					Ok(old)
1528				},
1529			)?;
1530			Self::deposit_event(Event::FullAdminChanged {
1531				internal_asset,
1532				old_admin: Box::new(old_admin),
1533				new_admin: Box::new(new_admin),
1534			});
1535			Ok(())
1536		}
1537
1538		/// Reassign the PSM's `emergency_admin`. Callable by the current `full_admin`.
1539		///
1540		/// ## Dispatch Origin
1541		///
1542		/// Must match the PSM's current `full_admin`.
1543		///
1544		/// ## Parameters
1545		///
1546		/// - `internal_asset`: The PSM whose `emergency_admin` is being changed.
1547		/// - `new_admin`: The new `emergency_admin` origin.
1548		///
1549		/// ## Errors
1550		///
1551		/// - [`Error::PsmNotFound`]: No PSM is registered for `internal_asset`.
1552		/// - [`Error::InvalidAdminOrigin`]: `new_admin` is the system `None` origin.
1553		///
1554		/// ## Events
1555		///
1556		/// - [`Event::EmergencyAdminChanged`].
1557		#[pallet::call_index(12)]
1558		#[pallet::weight(T::WeightInfo::set_emergency_admin())]
1559		pub fn set_emergency_admin(
1560			origin: OriginFor<T>,
1561			internal_asset: T::AssetId,
1562			new_admin: Box<T::PalletsOrigin>,
1563		) -> DispatchResult {
1564			Self::ensure_psm_admin(origin, &internal_asset, |l| l.can_manage_admins())?;
1565			ensure!(!new_admin.is_none(), Error::<T>::InvalidAdminOrigin);
1566			let new_admin = *new_admin;
1567			let old_admin = PsmAdmin::<T>::try_mutate(
1568				&internal_asset,
1569				|maybe| -> Result<T::PalletsOrigin, DispatchError> {
1570					let admin = maybe.as_mut().ok_or(Error::<T>::PsmNotFound)?;
1571					let old = core::mem::replace(&mut admin.emergency_admin, new_admin.clone());
1572					Ok(old)
1573				},
1574			)?;
1575			Self::deposit_event(Event::EmergencyAdminChanged {
1576				internal_asset,
1577				old_admin: Box::new(old_admin),
1578				new_admin: Box::new(new_admin),
1579			});
1580			Ok(())
1581		}
1582	}
1583
1584	#[pallet::view_functions]
1585	impl<T: Config> Pallet<T> {
1586		/// The reserve account of the PSM instance for `internal_asset`.
1587		pub fn reserve_account(internal_asset: T::AssetId) -> T::AccountId {
1588			Self::psm_account(&internal_asset)
1589		}
1590	}
1591
1592	impl<T: Config> Pallet<T> {
1593		/// Derive the reserve account for a PSM instance from the full hash of the pallet-id
1594		/// domain separator, pallet id, and internal asset.
1595		pub fn psm_account(internal_asset: &T::AssetId) -> T::AccountId {
1596			let entropy = (<PalletId as TypeId>::TYPE_ID, T::PalletId::get(), internal_asset)
1597				.using_encoded(sp_io::hashing::blake2_256);
1598			T::AccountId::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
1599				.expect("All byte sequences are valid `AccountId`s; qed")
1600		}
1601
1602		/// The footprint of a PSM instance as written by [`Pallet::create_psm`]: the [`Psm`]
1603		/// and [`PsmAdmin`] entries, both keyed by the internal asset id.
1604		///
1605		/// Excludes per-external storage added later via [`Pallet::add_external_asset`];
1606		/// externals are bounded by [`Config::MaxExternals`] and admin-gated rather than
1607		/// deposit-backed.
1608		pub fn psm_creation_footprint() -> Footprint {
1609			Footprint::from_parts(
1610				2,
1611				T::AssetId::max_encoded_len()
1612					.saturating_mul(2)
1613					.saturating_add(PsmInfo::<T>::max_encoded_len())
1614					.saturating_add(PsmAdminInfo::<T>::max_encoded_len()),
1615			)
1616		}
1617
1618		/// PSM debt ceiling for an instance, read from the stored [`PsmInfo`]. Returns
1619		/// zero if no PSM is installed for `internal_asset`.
1620		#[cfg(test)]
1621		pub(crate) fn max_psm_debt(internal_asset: &T::AssetId) -> BalanceOf<T> {
1622			Psm::<T>::get(internal_asset).map(|p| p.max_debt).unwrap_or_default()
1623		}
1624
1625		/// Calculate max debt for a specific external on a PSM.
1626		///
1627		/// Weights are normalised against the sum of weights within the same instance to
1628		/// fill the instance's `max_debt` ceiling. Returns zero if the external has no
1629		/// configured weight or weights sum to zero.
1630		pub(crate) fn max_asset_debt(
1631			internal_asset: &T::AssetId,
1632			external_asset: &T::AssetId,
1633			info: &PsmInfo<T>,
1634		) -> BalanceOf<T> {
1635			let asset_weight = AssetCeilingWeight::<T>::get(internal_asset, external_asset);
1636			let total_weight = Self::total_ceiling_weight(internal_asset);
1637			Self::normalised_ceiling(asset_weight, total_weight, info.max_debt)
1638		}
1639
1640		/// Sum of the configured ceiling weights across a PSM's approved externals.
1641		fn total_ceiling_weight(internal_asset: &T::AssetId) -> u32 {
1642			AssetCeilingWeight::<T>::iter_prefix(internal_asset)
1643				.map(|(_, w)| w.deconstruct())
1644				.fold(0u32, |acc, x| acc.saturating_add(x))
1645		}
1646
1647		/// A single external's normalised debt ceiling: its share of the total weight applied
1648		/// to `max_debt`. Zero if the external (or the PSM as a whole) carries no weight.
1649		fn normalised_ceiling(
1650			asset_weight: Permill,
1651			total_weight: u32,
1652			max_debt: BalanceOf<T>,
1653		) -> BalanceOf<T> {
1654			let weight = asset_weight.deconstruct();
1655			if weight == 0 || total_weight == 0 {
1656				return BalanceOf::<T>::zero();
1657			}
1658			Perbill::from_rational(weight, total_weight).mul_floor(max_debt)
1659		}
1660
1661		/// Total internal-asset debt minted through a PSM instance.
1662		pub(crate) fn total_psm_debt(internal_asset: &T::AssetId) -> BalanceOf<T> {
1663			PsmDebt::<T>::iter_prefix_values(internal_asset)
1664				.fold(BalanceOf::<T>::zero(), |acc, debt| acc.saturating_add(debt))
1665		}
1666
1667		/// Whether an external is approved on a PSM instance.
1668		#[cfg(test)]
1669		pub(crate) fn is_approved_asset(
1670			internal_asset: &T::AssetId,
1671			external_asset: &T::AssetId,
1672		) -> bool {
1673			ExternalAssets::<T>::contains_key(internal_asset, external_asset)
1674		}
1675
1676		/// Balance of an external held by a PSM instance's reserve account.
1677		pub(crate) fn get_reserve(
1678			internal_asset: &T::AssetId,
1679			external_asset: &T::AssetId,
1680		) -> BalanceOf<T> {
1681			T::Fungibles::balance(external_asset.clone(), &Self::psm_account(internal_asset))
1682		}
1683
1684		/// Convert an amount denominated in external-asset units into internal units.
1685		///
1686		/// Scales by `10^(ext_decimals - internal_decimals)` — multiplies up when internal has more
1687		/// decimals, floor-divides when it has fewer. Returns [`Error::ConversionOverflow`] if
1688		/// the scaling factor or the product does not fit in the balance type.
1689		pub(crate) fn external_to_internal(
1690			amount: BalanceOf<T>,
1691			ext_decimals: u8,
1692			internal_decimals: u8,
1693		) -> Result<BalanceOf<T>, Error<T>> {
1694			use core::cmp::Ordering::*;
1695			match ext_decimals.cmp(&internal_decimals) {
1696				Equal => Ok(amount),
1697				Less => {
1698					let diff = (internal_decimals - ext_decimals) as u32;
1699					let factor = Self::pow10(diff)?;
1700					amount.checked_mul(&factor).ok_or(Error::<T>::ConversionOverflow)
1701				},
1702				Greater => {
1703					let diff = (ext_decimals - internal_decimals) as u32;
1704					let factor = Self::pow10(diff)?;
1705					Ok(amount.checked_div(&factor).unwrap_or_else(BalanceOf::<T>::zero))
1706				},
1707			}
1708		}
1709
1710		/// Convert an amount denominated in internal units into external-asset units.
1711		///
1712		/// Inverse of [`Self::external_to_internal`]. Floor-divides when internal has more
1713		/// decimals, multiplies up when it has fewer.
1714		pub(crate) fn internal_to_external(
1715			amount: BalanceOf<T>,
1716			ext_decimals: u8,
1717			internal_decimals: u8,
1718		) -> Result<BalanceOf<T>, Error<T>> {
1719			use core::cmp::Ordering::*;
1720			match ext_decimals.cmp(&internal_decimals) {
1721				Equal => Ok(amount),
1722				Less => {
1723					let diff = (internal_decimals - ext_decimals) as u32;
1724					let factor = Self::pow10(diff)?;
1725					Ok(amount.checked_div(&factor).unwrap_or_else(BalanceOf::<T>::zero))
1726				},
1727				Greater => {
1728					let diff = (ext_decimals - internal_decimals) as u32;
1729					let factor = Self::pow10(diff)?;
1730					amount.checked_mul(&factor).ok_or(Error::<T>::ConversionOverflow)
1731				},
1732			}
1733		}
1734
1735		/// Compute `10^exp` as a [`BalanceOf`]. Returns [`Error::ConversionOverflow`] if the result
1736		/// does not fit in `u128` or in `BalanceOf<T>`.
1737		fn pow10(exp: u32) -> Result<BalanceOf<T>, Error<T>> {
1738			let factor_u128 = 10u128.checked_pow(exp).ok_or(Error::<T>::ConversionOverflow)?;
1739			factor_u128.try_into().map_err(|_| Error::<T>::ConversionOverflow)
1740		}
1741
1742		/// Authorise an operation on the PSM keyed by `internal_asset`.
1743		///
1744		/// Matches the incoming origin's caller against the PSM's stored
1745		/// [`PsmAdminInfo::full_admin`] (yielding `Full`) or [`PsmAdminInfo::emergency_admin`]
1746		/// (yielding `Emergency`). The resolved level is then checked against `required`. No
1747		/// other authority can manage a PSM.
1748		///
1749		/// We reject the `None` origin to prevent the block author from controlling PSMs with an
1750		/// admin set to `None`.
1751		pub(crate) fn ensure_psm_admin(
1752			origin: OriginFor<T>,
1753			internal_asset: &T::AssetId,
1754			required: impl Fn(PsmManagerLevel) -> bool,
1755		) -> DispatchResult {
1756			let admin = PsmAdmin::<T>::get(internal_asset).ok_or(Error::<T>::PsmNotFound)?;
1757			let caller = <T as Config>::RuntimeOrigin::from(origin).into_caller();
1758			ensure!(!caller.is_none(), DispatchError::BadOrigin);
1759			let level = if caller == admin.full_admin {
1760				PsmManagerLevel::Full
1761			} else if caller == admin.emergency_admin {
1762				PsmManagerLevel::Emergency
1763			} else {
1764				return Err(DispatchError::BadOrigin);
1765			};
1766			ensure!(required(level), Error::<T>::InsufficientPrivilege);
1767			Ok(())
1768		}
1769
1770		/// Test the storage invariants of the pallet.
1771		///
1772		/// This function runs with the `try-runtime` feature, and in tests. The
1773		/// checks occur at three levels:
1774		///
1775		/// * Checks 1 to 4, 10 and 11 run for each PSM instance.
1776		/// * Checks 5 to 9 run for each approved external asset of an instance.
1777		/// * Checks 12 to 15 run once, across all of the storage.
1778		///
1779		/// Checks 2, 4, 5, 8, 9 and 15 are advisory. They write a warning to the
1780		/// log, and they do not return an error. A permitted action can create
1781		/// each of these states: a metadata change by an asset owner for checks
1782		/// 2 and 5, a burn by a holder for check 4, a parameter change by
1783		/// governance for checks 8, 9 and 15.
1784		#[cfg(any(feature = "try-runtime", test))]
1785		pub(crate) fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1786			use sp_runtime::traits::CheckedAdd;
1787
1788			for (internal_asset, info) in Psm::<T>::iter() {
1789				// Check 1: the instance has its paired admin record.
1790				ensure!(
1791					PsmAdmin::<T>::contains_key(&internal_asset),
1792					"PSM instance without a paired PsmAdmin record"
1793				);
1794
1795				// Check 2 (advisory): live internal decimals match the PsmInfo snapshot.
1796				// Swaps use the recorded value, so drift does not change the pallet's
1797				// arithmetic; it changes what off-chain readers of live metadata see.
1798				let live_internal_decimals = T::Fungibles::decimals(internal_asset.clone());
1799				if live_internal_decimals != info.internal_decimals {
1800					log::warn!(
1801						target: "runtime::psm",
1802						"PSM {:?}: internal asset live decimals ({}) differ from the PsmInfo \
1803						snapshot ({}); swaps keep using the snapshot",
1804						internal_asset, live_internal_decimals, info.internal_decimals,
1805					);
1806				}
1807
1808				// Check 3: the minimum swap amount of the instance is not zero.
1809				// `create_psm` refuses a zero value. A migration or a manual genesis
1810				// file can bypass that check. A zero value permits swaps of dust.
1811				ensure!(!info.min_swap_amount.is_zero(), "PSM instance has a zero min_swap_amount");
1812
1813				// Check 4 (advisory): the issuance of the internal asset covers the
1814				// debt of this instance. Any holder can burn the internal asset
1815				// outside of the PSM, for example with XCM `BurnAsset`. Such a burn
1816				// leaves the reserve larger than the issuance it backs, so the PSM is
1817				// over-collateralised, which is a safe state. The debt it leaves
1818				// behind can never be redeemed. To wind the asset class down,
1819				// governance mints that amount to an account that redeems it, or
1820				// moves the surplus reserve out. See the module doc.
1821				let issuance = T::Fungibles::total_issuance(internal_asset.clone());
1822				let total_debt = Self::total_psm_debt(&internal_asset);
1823				if issuance < total_debt {
1824					log::warn!(
1825						target: "runtime::psm",
1826						"PSM {:?}: total internal issuance ({:?}) is less than total PSM \
1827						debt ({:?}); the reserve holds the difference as surplus",
1828						internal_asset, issuance, total_debt,
1829					);
1830				}
1831
1832				let mut counted = 0u32;
1833				let mut approved_debt = BalanceOf::<T>::zero();
1834				for (external_asset, external) in ExternalAssets::<T>::iter_prefix(&internal_asset)
1835				{
1836					counted = counted.saturating_add(1);
1837					let debt = PsmDebt::<T>::get(&internal_asset, &external_asset);
1838					let reserve = Self::get_reserve(&internal_asset, &external_asset);
1839
1840					// Check 5 (advisory): live external decimals match the registration
1841					// snapshot. Same rationale as check 2: the asset owner can change
1842					// metadata at any time, and swaps keep using the snapshot.
1843					let live_external_decimals = T::Fungibles::decimals(external_asset.clone());
1844					if live_external_decimals != external.decimals {
1845						log::warn!(
1846							target: "runtime::psm",
1847							"Asset {:?}/{:?}: live decimals ({}) differ from the registration \
1848							snapshot ({}); swaps keep using the snapshot",
1849							internal_asset, external_asset,
1850							live_external_decimals, external.decimals,
1851						);
1852					}
1853
1854					// Check 6: the reserve covers tracked debt, compared in external units.
1855					let debt_as_external =
1856						Self::internal_to_external(debt, external.decimals, info.internal_decimals)
1857							.map_err(|_| "Failed to convert tracked debt to external units")?;
1858					ensure!(
1859						reserve >= debt_as_external,
1860						"PSM reserve is less than tracked debt for an asset"
1861					);
1862
1863					// Check 7: summing approved debt must not overflow.
1864					approved_debt = approved_debt
1865						.checked_add(&debt)
1866						.ok_or("PSM debt overflow when summing approved externals")?;
1867
1868					// Check 8 (advisory): the debt of one asset is above its ceiling.
1869					// Governance can set a weight or `max_debt` below the debt. One
1870					// documented procedure does this on purpose: to retire an asset,
1871					// governance disables minting and sets the weight to zero, which
1872					// drives the ceiling to zero while the debt drains. The warning
1873					// still fires in that state; it is advisory for this reason.
1874					let ceiling = Self::max_asset_debt(&internal_asset, &external_asset, &info);
1875					if debt > ceiling {
1876						log::warn!(
1877							target: "runtime::psm",
1878							"Asset {:?}/{:?} debt ({:?}) exceeds ceiling ({:?})",
1879							internal_asset, external_asset, debt, ceiling,
1880						);
1881					}
1882
1883					// Check 9 (advisory): the ceiling weight and the debt are zero,
1884					// but the reserve has a balance. A donation or an error can do
1885					// this.
1886					if AssetCeilingWeight::<T>::get(&internal_asset, &external_asset).is_zero() &&
1887						debt.is_zero() && !reserve.is_zero()
1888					{
1889						log::warn!(
1890							target: "runtime::psm",
1891							"Asset {:?}/{:?} has zero ceiling, zero debt, but non-zero reserve {:?}",
1892							internal_asset, external_asset, reserve,
1893						);
1894					}
1895				}
1896
1897				// Check 10: the cached external_count matches the approved externals.
1898				ensure!(
1899					info.external_count == counted,
1900					"PsmInfo.external_count does not match the approved externals"
1901				);
1902
1903				// Check 11: the approved-external count is within the configured bound.
1904				ensure!(
1905					counted <= T::MaxExternals::get(),
1906					"ExternalAssets count exceeds MaxExternals for a PSM"
1907				);
1908			}
1909
1910			// Check 12: no `PsmDebt` row with a value exists for a pair that the PSM
1911			// does not approve. This check replaces an earlier comparison between
1912			// `total_psm_debt` and a sum of the same rows. That comparison always
1913			// held true, because both values add the same rows.
1914			for (internal_asset, external_asset, debt) in PsmDebt::<T>::iter() {
1915				if !debt.is_zero() {
1916					ensure!(
1917						ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1918						"PsmDebt entry exists for non-approved pair"
1919					);
1920				}
1921			}
1922
1923			// Check 13: no per-instance row survives without its parent PSM.
1924			for (internal_asset, _, _) in ExternalAssets::<T>::iter() {
1925				ensure!(
1926					Psm::<T>::contains_key(&internal_asset),
1927					"Orphaned ExternalAssets row without parent PSM"
1928				);
1929			}
1930			for (internal_asset, _, _) in PsmDebt::<T>::iter() {
1931				ensure!(
1932					Psm::<T>::contains_key(&internal_asset),
1933					"Orphaned PsmDebt row without parent PSM"
1934				);
1935			}
1936			for (internal_asset, _) in PsmAdmin::<T>::iter() {
1937				ensure!(
1938					Psm::<T>::contains_key(&internal_asset),
1939					"Orphaned PsmAdmin row without parent PSM"
1940				);
1941			}
1942
1943			// Check 14: no fee row or weight row exists for a pair that the PSM
1944			// does not approve. The fee extrinsics refuse assets that are not
1945			// approved, and remove_external_asset clears all three rows. A stray
1946			// weight row also shrinks the ceilings of the approved assets, because
1947			// the ceiling formula divides by the sum of the weights.
1948			for (internal_asset, external_asset, _) in MintingFee::<T>::iter() {
1949				ensure!(
1950					ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1951					"MintingFee entry exists for non-approved pair"
1952				);
1953			}
1954			for (internal_asset, external_asset, _) in RedemptionFee::<T>::iter() {
1955				ensure!(
1956					ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1957					"RedemptionFee entry exists for non-approved pair"
1958				);
1959			}
1960			for (internal_asset, external_asset, _) in AssetCeilingWeight::<T>::iter() {
1961				ensure!(
1962					ExternalAssets::<T>::contains_key(&internal_asset, &external_asset),
1963					"AssetCeilingWeight entry exists for non-approved pair"
1964				);
1965			}
1966
1967			// Check 15 (advisory): the debt of an instance is above its ceiling.
1968			// Governance can set `max_debt` below the debt.
1969			for (internal_asset, info) in Psm::<T>::iter() {
1970				let total = Self::total_psm_debt(&internal_asset);
1971				if total > info.max_debt {
1972					log::warn!(
1973						target: "runtime::psm",
1974						"PSM {:?}: total debt ({:?}) exceeds ceiling ({:?})",
1975						internal_asset, total, info.max_debt,
1976					);
1977				}
1978			}
1979
1980			Ok(())
1981		}
1982	}
1983}