referrerpolicy=no-referrer-when-downgrade

pallet_nfts/
common_functions.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//! Various pieces of common functionality.
19
20use crate::*;
21use alloc::vec::Vec;
22use frame_support::pallet_prelude::*;
23
24impl<T: Config<I>, I: 'static> Pallet<T, I> {
25	/// Get the owner of the item, if the item exists.
26	pub fn owner(collection: T::CollectionId, item: T::ItemId) -> Option<T::AccountId> {
27		Item::<T, I>::get(collection, item).map(|i| i.owner)
28	}
29
30	/// Get the owner of the collection, if the collection exists.
31	pub fn collection_owner(collection: T::CollectionId) -> Option<T::AccountId> {
32		Collection::<T, I>::get(collection).map(|i| i.owner)
33	}
34
35	/// Validates the signature of the given data with the provided signer's account ID.
36	///
37	/// # Errors
38	///
39	/// This function returns a [`WrongSignature`](crate::Error::WrongSignature) error if the
40	/// signature is invalid or the verification process fails.
41	pub fn validate_signature(
42		data: &Vec<u8>,
43		signature: &T::OffchainSignature,
44		signer: &T::AccountId,
45	) -> DispatchResult {
46		if signature.verify(&**data, &signer) {
47			return Ok(())
48		}
49
50		// NOTE: for security reasons modern UIs implicitly wrap the data requested to sign into
51		// <Bytes></Bytes>, that's why we support both wrapped and raw versions.
52		let prefix = b"<Bytes>";
53		let suffix = b"</Bytes>";
54		let mut wrapped: Vec<u8> = Vec::with_capacity(data.len() + prefix.len() + suffix.len());
55		wrapped.extend(prefix);
56		wrapped.extend(data);
57		wrapped.extend(suffix);
58
59		ensure!(signature.verify(&*wrapped, &signer), Error::<T, I>::WrongSignature);
60
61		Ok(())
62	}
63
64	pub(crate) fn set_next_collection_id(collection: T::CollectionId) {
65		let next_id = collection.increment();
66		NextCollectionId::<T, I>::set(next_id);
67		Self::deposit_event(Event::NextCollectionIdIncremented { next_id });
68	}
69
70	#[cfg(any(test, feature = "runtime-benchmarks"))]
71	pub fn set_next_id(id: T::CollectionId) {
72		NextCollectionId::<T, I>::set(Some(id));
73	}
74
75	#[cfg(test)]
76	pub fn get_next_id() -> T::CollectionId {
77		NextCollectionId::<T, I>::get()
78			.or(T::CollectionId::initial_value())
79			.expect("Failed to get next collection ID")
80	}
81}