Skip to content

Commit

Permalink
feat: add solution for ex03
Browse files Browse the repository at this point in the history
  • Loading branch information
tdelabro committed Aug 21, 2022
1 parent 08aec00 commit b9fbd32
Showing 1 changed file with 83 additions and 0 deletions.
83 changes: 83 additions & 0 deletions exercises/ex03-nft/nft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,58 @@ pub mod pallet {
metadata: BoundedVec<u8, T::MaxLength>,
supply: u128,
) -> DispatchResult {
let origin = ensure_signed(origin)?;

ensure!(supply > 0, Error::<T>::NoSupply);

let id = Self::nonce();
let details = UniqueAssetDetails::new(origin.clone(), metadata, supply);
UniqueAsset::<T>::insert(id, details);
Account::<T>::insert(id, origin.clone(), supply);
Nonce::<T>::set(id.saturating_add(1));

Self::deposit_event(Event::<T>::Created {
creator: origin,
asset_id: id,
});

Ok(())
}

#[pallet::weight(0)]
pub fn burn(origin: OriginFor<T>, asset_id: UniqueAssetId, amount: u128) -> DispatchResult {
let origin = ensure_signed(origin)?;

ensure!(
Self::unique_asset(asset_id).is_some(),
Error::<T>::UnknownAssetId
);
Self::ensure_own_some(asset_id, origin.clone())?;

let mut total_supply = 0;

UniqueAsset::<T>::try_mutate(asset_id, |maybe_details| -> DispatchResult {
let details = maybe_details.as_mut().ok_or(Error::<T>::UnknownAssetId)?;

let mut burned_amount = 0;
Account::<T>::mutate(asset_id, origin.clone(), |balance| {
let old_balance = *balance;
*balance = balance.saturating_sub(amount);
burned_amount = old_balance - *balance;
});

details.supply -= burned_amount;
total_supply = details.supply;

Ok(())
})?;

Self::deposit_event(Event::<T>::Burned {
asset_id,
owner: origin,
total_supply,
});

Ok(())
}

Expand All @@ -109,7 +156,43 @@ pub mod pallet {
amount: u128,
to: T::AccountId,
) -> DispatchResult {
let origin = ensure_signed(origin)?;

ensure!(
Self::unique_asset(asset_id).is_some(),
Error::<T>::UnknownAssetId
);
Self::ensure_own_some(asset_id, origin.clone())?;

let mut transfered_amount = 0;
Account::<T>::mutate(asset_id, origin.clone(), |balance| {
let old_balance = *balance;
*balance = balance.saturating_sub(amount);
transfered_amount = old_balance - *balance;
});

Account::<T>::mutate(asset_id, to.clone(), |balance| {
*balance = balance.saturating_add(transfered_amount);
});

Self::deposit_event(Event::<T>::Transferred {
asset_id,
from: origin,
to,
amount: transfered_amount,
});

Ok(())
}
}
}

impl<T: Config> Pallet<T> {
fn ensure_own_some(asset_id: UniqueAssetId, account: T::AccountId) -> Result<(), Error<T>> {
let owned = Self::account(asset_id, account);

ensure!(owned > 0, Error::<T>::NotOwned);

Ok(())
}
}

0 comments on commit b9fbd32

Please sign in to comment.