difftreelog
Merge pull request #148 from usetech-llc/feature/NFTPAR-373_chain_extensions
in: master
Chain extensions
10 files changed
.devcontainer/Dockerfilediffbeforeafterboth--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -3,6 +3,9 @@
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive && \
apt-get -y install --no-install-recommends libssl-dev pkg-config libclang-dev clang
+RUN curl -L -o- https://github.com/WebAssembly/binaryen/releases/download/version_101/binaryen-version_101-x86_64-linux.tar.gz | \
+ tar xz --strip-components=1 -C /usr
+
USER vscode
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash && \
@@ -11,4 +14,5 @@
nvm install v12.20.1 && \
rustup toolchain install nightly-2021-03-01 && \
rustup default nightly-2021-03-01 && \
- rustup target add wasm32-unknown-unknown
\ No newline at end of file
+ rustup target add wasm32-unknown-unknown && \
+ cargo install cargo-contract
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5395,37 +5395,37 @@
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
-source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
+ "nft-data-structs",
+ "pallet-contracts",
+ "pallet-nft",
+ "pallet-nft-transaction-payment",
"parity-scale-codec",
+ "serde",
+ "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
+ "substrate-test-utils",
]
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
+source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
- "nft-data-structs",
- "pallet-contracts",
- "pallet-nft",
- "pallet-nft-transaction-payment",
"parity-scale-codec",
- "serde",
- "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
- "substrate-test-utils",
]
[[package]]
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -566,10 +566,14 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, sender)?;
- <WhiteList<T>>::insert(collection_id, address, true);
-
+ Self::toggle_white_list_internal(
+ &sender,
+ &collection,
+ &address,
+ true,
+ )?;
+
Ok(())
}
@@ -591,9 +595,13 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, sender)?;
- <WhiteList<T>>::remove(collection_id, address);
+ Self::toggle_white_list_internal(
+ &sender,
+ &collection,
+ &address,
+ false,
+ )?;
Ok(())
}
@@ -983,43 +991,10 @@
pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
-
- Self::token_exists(&target_collection, item_id)?;
-
- // Transfer permissions check
- let bypasses_limits = target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(
- &target_collection,
- sender.clone(),
- );
+ let collection = Self::get_collection(collection_id)?;
- let allowance_limit = if bypasses_limits {
- None
- } else if let Some(amount) = Self::owned_amount(
- sender.clone(),
- &target_collection,
- item_id,
- ) {
- Some(amount)
- } else {
- fail!(Error::<T>::NoPermission);
- };
-
- if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(&target_collection, &sender)?;
- Self::check_white_list(&target_collection, &spender)?;
- }
-
- let allowance: u128 = amount
- .checked_add(<Allowances<T>>::get(collection_id, (item_id, &sender, &spender)))
- .ok_or(Error::<T>::NumOverflow)?;
- if let Some(limit) = allowance_limit {
- ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
- }
- <Allowances<T>>::insert(collection_id, (item_id, sender.clone(), spender.clone()), allowance);
+ Self::approve_internal(sender, spender, &collection, item_id, amount)?;
- Self::deposit_event(RawEvent::Approved(target_collection.id, item_id, sender, spender, allowance));
Ok(())
}
@@ -1047,46 +1022,10 @@
pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
-
- // Check approval
- let approval: u128 = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));
-
- // Limits check
- Self::is_correct_transfer(&target_collection, &recipient)?;
+ let collection = Self::get_collection(collection_id)?;
- // Transfer permissions check
- ensure!(
- approval >= value ||
- (
- target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(&target_collection, sender.clone())
- ),
- Error::<T>::NoPermission
- );
-
- if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(&target_collection, &sender)?;
- Self::check_white_list(&target_collection, &recipient)?;
- }
-
- // Reduce approval by transferred amount or remove if remaining approval drops to 0
- if approval.saturating_sub(value) > 0 {
- <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);
- }
- else {
- <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));
- }
-
- match target_collection.mode
- {
- CollectionMode::NFT => Self::transfer_nft(&target_collection, item_id, from.clone(), recipient.clone())?,
- CollectionMode::Fungible(_) => Self::transfer_fungible(&target_collection, value, &from, &recipient)?,
- CollectionMode::ReFungible => Self::transfer_refungible(&target_collection, item_id, value, from.clone(), recipient.clone())?,
- _ => ()
- };
+ Self::transfer_from_internal(sender, from, recipient, &collection, item_id, value)?;
- Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, from, recipient, value));
Ok(())
}
@@ -1127,24 +1066,10 @@
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
- Self::token_exists(&target_collection, item_id)?;
+ let collection = Self::get_collection(collection_id)?;
- ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
-
- // Modify permissions check
- ensure!(Self::is_item_owner(sender.clone(), &target_collection, item_id) ||
- Self::is_owner_or_admin_permissions(&target_collection, sender.clone()),
- Error::<T>::NoPermission);
+ Self::set_variable_meta_data_internal(sender, &collection, item_id, data)?;
- match target_collection.mode
- {
- CollectionMode::NFT => Self::set_nft_variable_data(&target_collection, item_id, data)?,
- CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&target_collection, item_id, data)?,
- CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
- _ => fail!(Error::<T>::UnexpectedCollectionType)
- };
-
Ok(())
}
@@ -1516,6 +1441,164 @@
Ok(())
}
+ pub fn approve_internal(
+ sender: T::AccountId,
+ spender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ Self::token_exists(&collection, item_id)?;
+
+ // Transfer permissions check
+ let bypasses_limits = collection.limits.owner_can_transfer &&
+ Self::is_owner_or_admin_permissions(
+ &collection,
+ sender.clone(),
+ );
+
+ let allowance_limit = if bypasses_limits {
+ None
+ } else if let Some(amount) = Self::owned_amount(
+ sender.clone(),
+ &collection,
+ item_id,
+ ) {
+ Some(amount)
+ } else {
+ fail!(Error::<T>::NoPermission);
+ };
+
+ if collection.access == AccessMode::WhiteList {
+ Self::check_white_list(&collection, &sender)?;
+ Self::check_white_list(&collection, &spender)?;
+ }
+
+ let allowance: u128 = amount
+ .checked_add(<Allowances<T>>::get(collection.id, (item_id, &sender, &spender)))
+ .ok_or(Error::<T>::NumOverflow)?;
+ if let Some(limit) = allowance_limit {
+ ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
+ }
+ <Allowances<T>>::insert(collection.id, (item_id, &sender, &spender), allowance);
+
+ Self::deposit_event(RawEvent::Approved(collection.id, item_id, sender, spender, allowance));
+ Ok(())
+ }
+
+ pub fn transfer_from_internal(
+ sender: T::AccountId,
+ from: T::AccountId,
+ recipient: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ // Check approval
+ let approval: u128 = <Allowances<T>>::get(collection.id, (item_id, &from, &sender));
+
+ // Limits check
+ Self::is_correct_transfer(&collection, &recipient)?;
+
+ // Transfer permissions check
+ ensure!(
+ approval >= amount ||
+ (
+ collection.limits.owner_can_transfer &&
+ Self::is_owner_or_admin_permissions(&collection, sender.clone())
+ ),
+ Error::<T>::NoPermission
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ Self::check_white_list(&collection, &sender)?;
+ Self::check_white_list(&collection, &recipient)?;
+ }
+
+ // Reduce approval by transferred amount or remove if remaining approval drops to 0
+ let allowance = approval.saturating_sub(amount);
+ if allowance > 0 {
+ <Allowances<T>>::insert(collection.id, (item_id, &from, &sender), allowance);
+ } else {
+ <Allowances<T>>::remove(collection.id, (item_id, &from, &sender));
+ }
+
+ match collection.mode {
+ CollectionMode::NFT => {
+ Self::transfer_nft(&collection, item_id, from.clone(), recipient.clone())?
+ }
+ CollectionMode::Fungible(_) => {
+ Self::transfer_fungible(&collection, amount, &from, &recipient)?
+ }
+ CollectionMode::ReFungible => {
+ Self::transfer_refungible(&collection, item_id, amount, from.clone(), recipient.clone())?
+ }
+ _ => ()
+ };
+
+ Ok(())
+ }
+
+ pub fn set_variable_meta_data_internal(
+ sender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResult {
+ Self::token_exists(&collection, item_id)?;
+
+ ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
+
+ // Modify permissions check
+ ensure!(Self::is_item_owner(sender.clone(), &collection, item_id) ||
+ Self::is_owner_or_admin_permissions(&collection, sender.clone()),
+ Error::<T>::NoPermission);
+
+ match collection.mode
+ {
+ CollectionMode::NFT => Self::set_nft_variable_data(&collection, item_id, data)?,
+ CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&collection, item_id, data)?,
+ CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
+ _ => fail!(Error::<T>::UnexpectedCollectionType)
+ };
+
+ Ok(())
+ }
+
+ pub fn create_multiple_items_internal(
+ sender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ owner: T::AccountId,
+ items_data: Vec<CreateItemData>,
+ ) -> DispatchResult {
+ Self::can_create_items_in_collection(&collection, &sender, &owner, items_data.len() as u32)?;
+
+ for data in &items_data {
+ Self::validate_create_item_args(&collection, data)?;
+ }
+ for data in &items_data {
+ Self::create_item_no_validation(&collection, owner.clone(), data.clone())?;
+ }
+
+ Ok(())
+ }
+
+ pub fn toggle_white_list_internal(
+ sender: &T::AccountId,
+ collection: &CollectionHandle<T>,
+ address: &T::AccountId,
+ whitelisted: bool,
+ ) -> DispatchResult {
+ Self::check_owner_or_admin_permissions(&collection, sender.clone())?;
+
+ if whitelisted {
+ <WhiteList<T>>::insert(collection.id, address, true);
+ } else {
+ <WhiteList<T>>::remove(collection.id, address);
+ }
+
+ Ok(())
+ }
fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::AccountId) -> DispatchResult {
let collection_id = collection.id;
runtime/src/chain_extension.rsdiffbeforeafterboth--- a/runtime/src/chain_extension.rs
+++ b/runtime/src/chain_extension.rs
@@ -19,6 +19,8 @@
pub use pallet_nft::*;
use nft_data_structs::*;
+use crate::Vec;
+
/// Create item parameters
#[derive(Debug, PartialEq, Encode, Decode)]
pub struct NFTExtCreateItem<E: Ext> {
@@ -36,13 +38,54 @@
pub amount: u128,
}
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtCreateMultipleItems<E: Ext> {
+ pub owner: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub data: Vec<CreateItemData>,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtApprove<E: Ext> {
+ pub spender: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub amount: u128,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtTransferFrom<E: Ext> {
+ pub owner: <E::T as SysConfig>::AccountId,
+ pub recipient: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub amount: u128,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtSetVariableMetaData {
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub data: Vec<u8>,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtToggleWhiteList<E: Ext> {
+ pub collection_id: u32,
+ pub address: <E::T as SysConfig>::AccountId,
+ pub whitelisted: bool,
+}
+
/// The chain Extension of NFT pallet
pub struct NFTExtension;
+pub type NftWeightInfoOf<C> = <C as pallet_nft::Config>::WeightInfo;
+
impl<C: Config + pallet_contracts::Config> ChainExtension<C> for NFTExtension {
fn call<E: Ext>(func_id: u32, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>
where
E: Ext<T = C>,
+ C: pallet_nft::Config,
<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
// The memory of the vm stores buf in scale-codec
@@ -50,37 +93,129 @@
0 => {
let mut env = env.buf_in_buf_out();
let input: NFTExtTransfer<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::transfer())?;
let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
- match pallet_nft::Module::<C>::transfer_internal(
- env.ext().caller().clone(),
+ pallet_nft::Module::<C>::transfer_internal(
+ env.ext().address().clone(),
input.recipient,
&collection,
input.token_id,
input.amount,
- ) {
- Ok(_) => Ok(RetVal::Converging(func_id)),
- _ => Err(DispatchError::Other("Transfer error"))
- }
+ )?;
+
+ Ok(RetVal::Converging(0))
},
1 => {
// Create Item
let mut env = env.buf_in_buf_out();
let input: NFTExtCreateItem<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::create_item(input.data.len()))?;
- match pallet_nft::Module::<C>::create_item_internal(
+ pallet_nft::Module::<C>::create_item_internal(
env.ext().address().clone(),
input.collection_id,
input.owner,
input.data,
- ) {
- Ok(_) => Ok(RetVal::Converging(func_id)),
- _ => Err(DispatchError::Other("CreateItem error"))
- }
+ )?;
+
+ Ok(RetVal::Converging(0))
},
+ 2 => {
+ // Create multiple items
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtCreateMultipleItems<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::create_item(
+ input.data.iter()
+ .map(|i| i.len())
+ .sum()
+ ))?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::create_multiple_items_internal(
+ env.ext().address().clone(),
+ &collection,
+ input.owner,
+ input.data,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 3 => {
+ // Approve
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtApprove<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::approve())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::approve_internal(
+ env.ext().address().clone(),
+ input.spender,
+ &collection,
+ input.item_id,
+ input.amount,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 4 => {
+ // Transfer from
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtTransferFrom<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::transfer_from())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::transfer_from_internal(
+ env.ext().address().clone(),
+ input.owner,
+ input.recipient,
+ &collection,
+ input.item_id,
+ input.amount
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 5 => {
+ // Set variable metadata
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtSetVariableMetaData = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::set_variable_meta_data())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::set_variable_meta_data_internal(
+ env.ext().address().clone(),
+ &collection,
+ input.item_id,
+ input.data,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 6 => {
+ // Toggle whitelist
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtToggleWhiteList<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::add_to_white_list())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::toggle_white_list_internal(
+ &env.ext().address().clone(),
+ &collection,
+ &input.address,
+ input.whitelisted,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ }
_ => {
- panic!("Passed unknown func_id to test chain extension: {}", func_id);
+ Err(DispatchError::Other("unknown chain_extension func_id"))
}
}
}
smart_contracs/transfer/Cargo.tomldiffbeforeafterboth--- a/smart_contracs/transfer/Cargo.toml
+++ b/smart_contracs/transfer/Cargo.toml
@@ -4,15 +4,17 @@
authors = ["[Greg Zaitsev] <[your_email]>"]
edition = "2018"
+[workspace]
+
[dependencies]
-ink_primitives = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_metadata = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false, features = ["derive"], optional = true }
-ink_env = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_storage = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_lang = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
+ink_primitives = { default-features = false }
+ink_metadata = { default-features = false, features = ["derive"], optional = true }
+ink_env = { default-features = false }
+ink_storage = { default-features = false }
+ink_lang = { default-features = false }
-scale = { package = "parity-scale-codec", version = "1.3", default-features = false, features = ["derive"] }
-scale-info = { version = "0.4.1", default-features = false, features = ["derive"], optional = true }
+scale = { package = "parity-scale-codec", version = "2.1.1", default-features = false, features = ["derive"] }
+scale-info = { version = "0.6.0", default-features = false, features = ["derive"] }
[lib]
name = "nft_transfer"
@@ -28,6 +30,7 @@
"ink_metadata/std",
"ink_env/std",
"ink_storage/std",
+ "ink_lang/std",
"ink_primitives/std",
"scale/std",
"scale-info/std",
smart_contracs/transfer/lib.rsdiffbeforeafterboth--- a/smart_contracs/transfer/lib.rs
+++ b/smart_contracs/transfer/lib.rs
@@ -1,4 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
+extern crate alloc;
+use alloc::vec::Vec;
use ink_lang as ink;
use ink_env::{Environment, DefaultEnvironment};
@@ -36,6 +38,24 @@
}
}
+#[derive(scale::Encode, scale::Decode, scale_info::TypeInfo)]
+pub enum CreateItemData {
+ Nft {
+ const_data: Vec<u8>,
+ variable_data: Vec<u8>,
+ },
+ Fungible {
+ value: u128,
+ },
+ ReFungible {
+ const_data: Vec<u8>,
+ variable_data: Vec<u8>,
+ pieces: u128,
+ },
+}
+
+type DefaultAccountId = <DefaultEnvironment as Environment>::AccountId;
+
#[ink::chain_extension]
pub trait NftChainExtension {
type ErrorCode = NftErrorCode;
@@ -43,11 +63,26 @@
/// Transfer one NFT token from sender
///
#[ink(extension = 0, returns_result = false)]
- fn transfer(recipient: <DefaultEnvironment as Environment>::AccountId, collection_id: u32, token_id: u32, amount: u128);
+ fn transfer(recipient: DefaultAccountId, collection_id: u32, token_id: u32, amount: u128);
+ #[ink(extension = 1, returns_result = false)]
+ fn create_item(owner: DefaultAccountId, collection_id: u32, data: CreateItemData);
+ #[ink(extension = 2, returns_result = false)]
+ fn create_multiple_items(owner: DefaultAccountId, collection_id: u32, data: Vec<CreateItemData>);
+ #[ink(extension = 3, returns_result = false)]
+ fn approve(spender: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
+ #[ink(extension = 4, returns_result = false)]
+ fn transfer_from(owner: DefaultAccountId, recipient: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
+ #[ink(extension = 5, returns_result = false)]
+ fn set_variable_meta_data(collection_id: u32, item_id: u32, data: Vec<u8>);
+ #[ink(extension = 6, returns_result = false)]
+ fn toggle_white_list(collection_id: u32, address: DefaultAccountId, whitelisted: bool);
}
-#[ink::contract(env = crate::NftEnvironment)]
+#[ink::contract(env = crate::NftEnvironment, dynamic_storage_allocator = true)]
mod nft_transfer {
+ use alloc::vec::Vec;
+ // use ink_storage::Vec;
+ use crate::CreateItemData;
#[ink(storage)]
pub struct NftTransfer {
@@ -69,6 +104,42 @@
.extension()
.transfer(recipient, collection_id, token_id, amount);
}
+ #[ink(message)]
+ pub fn create_item(&mut self, recipient: AccountId, collection_id: u32, data: CreateItemData) {
+ let _ = self.env()
+ .extension()
+ .create_item(recipient, collection_id, data);
+ }
+ #[ink(message)]
+ pub fn create_multiple_items(&mut self, owner: AccountId, collection_id: u32, data: Vec<CreateItemData>) {
+ let _ = self.env()
+ .extension()
+ .create_multiple_items(owner, collection_id, data);
+ }
+ #[ink(message)]
+ pub fn approve(&mut self, spender: AccountId, collection_id: u32, item_id: u32, amount: u128) {
+ let _ = self.env()
+ .extension()
+ .approve(spender, collection_id, item_id, amount);
+ }
+ #[ink(message)]
+ pub fn transfer_from(&mut self, owner: AccountId, recipient: AccountId, collection_id: u32, item_id: u32, amount: u128) {
+ let _ = self.env()
+ .extension()
+ .transfer_from(owner, recipient, collection_id, item_id, amount);
+ }
+ #[ink(message)]
+ pub fn set_variable_meta_data(&mut self, collection_id: u32, item_id: u32, data: Vec<u8>) {
+ let _ = self.env()
+ .extension()
+ .set_variable_meta_data(collection_id, item_id, data);
+ }
+ #[ink(message)]
+ pub fn toggle_white_list(&mut self, collection_id: u32, address: AccountId, whitelisted: bool) {
+ let _ = self.env()
+ .extension()
+ .toggle_white_list(collection_id, address, whitelisted);
+ }
}
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -16,9 +16,15 @@
} from "./util/contracthelpers";
import {
+ addToWhiteListExpectSuccess,
+ approveExpectSuccess,
createCollectionExpectSuccess,
createItemExpectSuccess,
- getGenericResult
+ enablePublicMintingExpectSuccess,
+ enableWhiteListExpectSuccess,
+ getGenericResult,
+ isWhitelisted,
+ transferFromExpectSuccess
} from "./util/helpers";
@@ -26,7 +32,7 @@
const expect = chai.expect;
const value = 0;
-const gasLimit = 3000n * 1000000n;
+const gasLimit = 9000n * 1000000n;
const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
describe('Contracts', () => {
@@ -53,8 +59,10 @@
expect(newContractInstance.address.toString()).to.equal(marketContractAddress);
});
});
+});
- it('Can transfer NFT using smart contract.', async () => {
+describe.only('Chain extensions', () => {
+ it('Transfer CE', async () => {
await usingApi(async api => {
const alice = privateKey("//Alice");
const bob = privateKey("//Bob");
@@ -63,6 +71,9 @@
const collectionId = await createCollectionExpectSuccess();
const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
const [contract, deployer] = await deployTransferContract(api);
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
+ await submitTransactionAsync(alice, changeAdminTx);
+
const tokenBefore: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();
// Transfer
@@ -77,4 +88,165 @@
expect(tokenAfter.Owner.toString()).to.be.equal(bob.address);
});
});
+
+ it('Mint CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await enableWhiteListExpectSuccess(alice, collectionId);
+ await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
+ await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+
+ const transferTx = contract.tx.createItem(value, gasLimit, bob.address, collectionId, { Nft: {const_data: '0x010203', variable_data: '0x020304' }});
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const tokensAfter: any = (await api.query.nft.nftItemList.entries(collectionId) as any).map((kv: any) => kv[1].toJSON());
+ expect(tokensAfter).to.be.deep.equal([
+ {
+ Owner: bob.address,
+ ConstData: '0x010203',
+ VariableData: '0x020304',
+ },
+ ]);
+ });
+ });
+
+ it('Bulk mint CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await enableWhiteListExpectSuccess(alice, collectionId);
+ await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
+ await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+
+ const transferTx = contract.tx.createMultipleItems(value, gasLimit, bob.address, collectionId, [
+ { Nft: { const_data: '0x010203', variable_data: '0x020304' } },
+ { Nft: { const_data: '0x010204', variable_data: '0x020305' } },
+ { Nft: { const_data: '0x010205', variable_data: '0x020306' } }
+ ]);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const tokensAfter: any = (await api.query.nft.nftItemList.entries(collectionId) as any)
+ .map((kv: any) => kv[1].toJSON())
+ .sort((a: any, b: any) => a.ConstData.localeCompare(b.ConstData));
+ expect(tokensAfter).to.be.deep.equal([
+ {
+ Owner: bob.address,
+ ConstData: '0x010203',
+ VariableData: '0x020304',
+ },
+ {
+ Owner: bob.address,
+ ConstData: '0x010204',
+ VariableData: '0x020305',
+ },
+ {
+ Owner: bob.address,
+ ConstData: '0x010205',
+ VariableData: '0x020306',
+ },
+ ]);
+ });
+ });
+
+ it('Approve CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address);
+
+ const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ await transferFromExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), charlie, 1, 'NFT');
+ });
+ });
+
+ it('TransferFrom CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);
+
+ const transferTx = contract.tx.transferFrom(value, gasLimit, bob.address, charlie.address, collectionId, tokenId, 1);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()
+ expect(token.Owner.toString()).to.be.equal(charlie.address);
+ });
+ });
+
+ it('SetVariableMetaData CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address);
+
+ const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()
+ expect(token.VariableData.toString()).to.be.equal('0x121314');
+ });
+ });
+
+ it('ToggleWhiteList CE', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract, deployer] = await deployTransferContract(api);
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+
+ {
+ const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, true);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isWhitelisted(collectionId, bob.address)).to.be.true;
+ }
+ {
+ const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, false);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+ }
+ });
+ });
});
tests/src/transfer_contract/metadata.jsondiffbeforeafterboth1{2 "metadataVersion": "0.1.0",3 "source": {4 "hash": "0xfbbc0729acefed9d99f93f6cbb751d12e317958fd0fe183f5781329b37f1bf6e",5 "language": "ink! 3.0.0-rc2",6 "compiler": "rustc 1.51.0-nightly"7 },8 "contract": {9 "name": "nft_transfer",10 "version": "0.1.0",11 "authors": [12 "[Greg Zaitsev] <[your_email]>"13 ]14 },15 "spec": {16 "constructors": [17 {18 "args": [],19 "docs": [20 "Default Constructor",21 "",22 "Constructors can delegate to other constructors."23 ],24 "name": [25 "default"26 ],27 "selector": "0x6a3712e2"28 }29 ],30 "docs": [],31 "events": [],32 "messages": [33 {34 "args": [35 {36 "name": "recipient",37 "type": {38 "displayName": [39 "AccountId"40 ],41 "type": 142 }43 },44 {45 "name": "collection_id",46 "type": {47 "displayName": [48 "u32"49 ],50 "type": 451 }52 },53 {54 "name": "token_id",55 "type": {56 "displayName": [57 "u32"58 ],59 "type": 460 }61 },62 {63 "name": "amount",64 "type": {65 "displayName": [66 "u128"67 ],68 "type": 569 }70 }71 ],72 "docs": [73 " Transfer one NFT token"74 ],75 "mutates": true,76 "name": [77 "transfer"78 ],79 "payable": false,80 "returnType": null,81 "selector": "0xfae3a09d"82 }83 ]84 },85 "storage": {86 "struct": {87 "fields": []88 }89 },90 "types": [91 {92 "def": {93 "composite": {94 "fields": [95 {96 "type": 297 }98 ]99 }100 },101 "path": [102 "ink_env",103 "types",104 "AccountId"105 ]106 },107 {108 "def": {109 "array": {110 "len": 32,111 "type": 3112 }113 }114 },115 {116 "def": {117 "primitive": "u8"118 }119 },120 {121 "def": {122 "primitive": "u32"123 }124 },125 {126 "def": {127 "primitive": "u128"128 }129 }130 ]131}1{2 "metadataVersion": "0.1.0",3 "source": {4 "hash": "0xc6c3f47adeafe86d1674ed72c7179605787842f2f05a2d7da0dbabf3c4fa1aa8",5 "language": "ink! 3.0.0-rc3",6 "compiler": "rustc 1.52.0-nightly"7 },8 "contract": {9 "name": "nft_transfer",10 "version": "0.1.0",11 "authors": [12 "[Greg Zaitsev] <[your_email]>"13 ]14 },15 "spec": {16 "constructors": [17 {18 "args": [],19 "docs": [20 "Default Constructor",21 "",22 "Constructors can delegate to other constructors."23 ],24 "name": [25 "default"26 ],27 "selector": "0xed4b9d1b"28 }29 ],30 "docs": [],31 "events": [],32 "messages": [33 {34 "args": [35 {36 "name": "recipient",37 "type": {38 "displayName": [39 "AccountId"40 ],41 "type": 142 }43 },44 {45 "name": "collection_id",46 "type": {47 "displayName": [48 "u32"49 ],50 "type": 451 }52 },53 {54 "name": "token_id",55 "type": {56 "displayName": [57 "u32"58 ],59 "type": 460 }61 },62 {63 "name": "amount",64 "type": {65 "displayName": [66 "u128"67 ],68 "type": 569 }70 }71 ],72 "docs": [73 " Transfer one NFT token"74 ],75 "mutates": true,76 "name": [77 "transfer"78 ],79 "payable": false,80 "returnType": null,81 "selector": "0x84a15da1"82 },83 {84 "args": [85 {86 "name": "recipient",87 "type": {88 "displayName": [89 "AccountId"90 ],91 "type": 192 }93 },94 {95 "name": "collection_id",96 "type": {97 "displayName": [98 "u32"99 ],100 "type": 4101 }102 },103 {104 "name": "data",105 "type": {106 "displayName": [107 "CreateItemData"108 ],109 "type": 6110 }111 }112 ],113 "docs": [],114 "mutates": true,115 "name": [116 "create_item"117 ],118 "payable": false,119 "returnType": null,120 "selector": "0xd7c3f083"121 },122 {123 "args": [124 {125 "name": "owner",126 "type": {127 "displayName": [128 "AccountId"129 ],130 "type": 1131 }132 },133 {134 "name": "collection_id",135 "type": {136 "displayName": [137 "u32"138 ],139 "type": 4140 }141 },142 {143 "name": "data",144 "type": {145 "displayName": [146 "Vec"147 ],148 "type": 8149 }150 }151 ],152 "docs": [],153 "mutates": true,154 "name": [155 "create_multiple_items"156 ],157 "payable": false,158 "returnType": null,159 "selector": "0x15f9a1eb"160 },161 {162 "args": [163 {164 "name": "spender",165 "type": {166 "displayName": [167 "AccountId"168 ],169 "type": 1170 }171 },172 {173 "name": "collection_id",174 "type": {175 "displayName": [176 "u32"177 ],178 "type": 4179 }180 },181 {182 "name": "item_id",183 "type": {184 "displayName": [185 "u32"186 ],187 "type": 4188 }189 },190 {191 "name": "amount",192 "type": {193 "displayName": [194 "u128"195 ],196 "type": 5197 }198 }199 ],200 "docs": [],201 "mutates": true,202 "name": [203 "approve"204 ],205 "payable": false,206 "returnType": null,207 "selector": "0x681266a0"208 },209 {210 "args": [211 {212 "name": "owner",213 "type": {214 "displayName": [215 "AccountId"216 ],217 "type": 1218 }219 },220 {221 "name": "recipient",222 "type": {223 "displayName": [224 "AccountId"225 ],226 "type": 1227 }228 },229 {230 "name": "collection_id",231 "type": {232 "displayName": [233 "u32"234 ],235 "type": 4236 }237 },238 {239 "name": "item_id",240 "type": {241 "displayName": [242 "u32"243 ],244 "type": 4245 }246 },247 {248 "name": "amount",249 "type": {250 "displayName": [251 "u128"252 ],253 "type": 5254 }255 }256 ],257 "docs": [],258 "mutates": true,259 "name": [260 "transfer_from"261 ],262 "payable": false,263 "returnType": null,264 "selector": "0x0b396f18"265 },266 {267 "args": [268 {269 "name": "collection_id",270 "type": {271 "displayName": [272 "u32"273 ],274 "type": 4275 }276 },277 {278 "name": "item_id",279 "type": {280 "displayName": [281 "u32"282 ],283 "type": 4284 }285 },286 {287 "name": "data",288 "type": {289 "displayName": [290 "Vec"291 ],292 "type": 7293 }294 }295 ],296 "docs": [],297 "mutates": true,298 "name": [299 "set_variable_meta_data"300 ],301 "payable": false,302 "returnType": null,303 "selector": "0xb0b26da2"304 },305 {306 "args": [307 {308 "name": "collection_id",309 "type": {310 "displayName": [311 "u32"312 ],313 "type": 4314 }315 },316 {317 "name": "address",318 "type": {319 "displayName": [320 "AccountId"321 ],322 "type": 1323 }324 },325 {326 "name": "whitelisted",327 "type": {328 "displayName": [329 "bool"330 ],331 "type": 9332 }333 }334 ],335 "docs": [],336 "mutates": true,337 "name": [338 "toggle_white_list"339 ],340 "payable": false,341 "returnType": null,342 "selector": "0x98574dac"343 }344 ]345 },346 "storage": {347 "struct": {348 "fields": []349 }350 },351 "types": [352 {353 "def": {354 "composite": {355 "fields": [356 {357 "type": 2,358 "typeName": "[u8; 32]"359 }360 ]361 }362 },363 "path": [364 "ink_env",365 "types",366 "AccountId"367 ]368 },369 {370 "def": {371 "array": {372 "len": 32,373 "type": 3374 }375 }376 },377 {378 "def": {379 "primitive": "u8"380 }381 },382 {383 "def": {384 "primitive": "u32"385 }386 },387 {388 "def": {389 "primitive": "u128"390 }391 },392 {393 "def": {394 "variant": {395 "variants": [396 {397 "fields": [398 {399 "name": "const_data",400 "type": 7,401 "typeName": "Vec<u8>"402 },403 {404 "name": "variable_data",405 "type": 7,406 "typeName": "Vec<u8>"407 }408 ],409 "name": "Nft"410 },411 {412 "fields": [413 {414 "name": "value",415 "type": 5,416 "typeName": "u128"417 }418 ],419 "name": "Fungible"420 },421 {422 "fields": [423 {424 "name": "const_data",425 "type": 7,426 "typeName": "Vec<u8>"427 },428 {429 "name": "variable_data",430 "type": 7,431 "typeName": "Vec<u8>"432 },433 {434 "name": "pieces",435 "type": 5,436 "typeName": "u128"437 }438 ],439 "name": "ReFungible"440 }441 ]442 }443 },444 "path": [445 "nft_transfer",446 "CreateItemData"447 ]448 },449 {450 "def": {451 "sequence": {452 "type": 3453 }454 }455 },456 {457 "def": {458 "sequence": {459 "type": 6460 }461 }462 },463 {464 "def": {465 "primitive": "bool"466 }467 }468 ]469}tests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -636,17 +636,19 @@
export async function
approveExpectSuccess(collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {
+ tokenId: number, owner: IKeyringPair, approved: IKeyringPair | string, amount: number | bigint = 1) {
+ if (typeof approved !== 'string')
+ approved = approved.address;
await usingApi(async (api: ApiPromise) => {
const allowanceBefore =
- await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;
- const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);
+ await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;
+ const approveNftTx = await api.tx.nft.approve(approved, collectionId, tokenId, amount);
const events = await submitTransactionAsync(owner, approveNftTx);
const result = getCreateItemResult(events);
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
const allowanceAfter =
- await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;
+ await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;
expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());
});
}
@@ -655,17 +657,19 @@
transferFromExpectSuccess(collectionId: number,
tokenId: number,
accountApproved: IKeyringPair,
- accountFrom: IKeyringPair,
+ accountFrom: IKeyringPair | string,
accountTo: IKeyringPair,
value: number | bigint = 1,
type: string = 'NFT') {
+ if (typeof accountFrom !== 'string')
+ accountFrom = accountFrom.address;
await usingApi(async (api: ApiPromise) => {
let balanceBefore = new BN(0);
if (type === 'Fungible') {
balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;
}
const transferFromTx = await api.tx.nft.transferFrom(
- accountFrom.address, accountTo.address, collectionId, tokenId, value);
+ accountFrom, accountTo.address, collectionId, tokenId, value);
const events = await submitTransactionAsync(accountApproved, transferFromTx);
const result = getCreateItemResult(events);
// tslint:disable-next-line:no-unused-expression
@@ -849,17 +853,13 @@
}
export async function createItemExpectSuccess(
- sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {
+ sender: IKeyringPair, collectionId: number, createMode: string, owner: string | AccountId = sender.address) {
let newItemId: number = 0;
await usingApi(async (api) => {
const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);
const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();
const AItemBalance = new BigNumber(Aitem.Value);
- if (owner === '') {
- owner = sender.address;
- }
-
let tx;
if (createMode === 'Fungible') {
const createData = {fungible: {value: 10}};
@@ -887,7 +887,7 @@
}
expect(collectionId).to.be.equal(result.collectionId);
expect(BItemCount).to.be.equal(result.itemId);
- expect(owner).to.be.equal(result.recipient);
+ expect(owner.toString()).to.be.equal(result.recipient);
newItemId = result.itemId;
});
return newItemId;
@@ -974,7 +974,7 @@
return whitelisted;
}
-export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {
+export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
await usingApi(async (api) => {
const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();