1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
// This file is part of GamePower Network.

// Copyright (C) 2021 GamePower Network.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_support::{
  decl_module, decl_storage, decl_error, decl_event, ensure,
  traits::{Currency, ExistenceRequirement, Get, ReservableCurrency},
};
use frame_system::{self as system, ensure_signed};
use sp_runtime::{
  DispatchResult, DispatchError, ModuleId, RuntimeDebug,
  traits::{AccountIdConversion, One},
};

#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_std::vec::Vec;
use sp_std::str;
use orml_nft::Pallet as AssetModule;
use gamepower_traits::*;
use gamepower_primitives::{ ListingId, ClaimId };

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[derive(Encode, Decode, Default, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
/// Listing data
pub struct Listing<ClassIdOf, TokenIdOf, AccountId, Balance> {
	/// Listing Id
	pub id: ListingId,
	/// Seller of the listing
	pub seller: AccountId,
	/// Asset - (class_id, token_id)
	pub asset: (ClassIdOf, TokenIdOf),
	/// Price of the asset listed
	pub price: Balance,
}

#[derive(Encode, Decode, Default, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
/// Claim data
pub struct Claim<ClassIdOf, TokenIdOf, AccountId> {
	/// account this claim is meant for
	pub receiver: AccountId,
	/// Asset - (class_id, token_id)
	pub asset: (ClassIdOf, TokenIdOf)
}

#[derive(Encode, Decode, Default, Clone, RuntimeDebug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
/// Order data
pub struct Order<ListingOf, AccountId, BlockNumber> {
	/// order listing
	pub listing: ListingOf,
	/// order buyer
	pub buyer: AccountId,
	/// genesis block
	pub block: BlockNumber,
}


/// The module configuration trait.
pub trait Config: system::Config + orml_nft::Config {
  type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;
  /// Wallet Transfer Handler
  type Transfer: OnTransferHandler<Self::AccountId, Self::ClassId, Self::TokenId>;
  /// Wallet Burn Handler
  type Burn: OnBurnHandler<Self::AccountId, Self::ClassId, Self::TokenId>;
  /// Wallet Claim Handler
  type Claim: OnClaimHandler<Self::AccountId, Self::ClassId, Self::TokenId>;
  /// Allow assets to be transferred through the wallet
  type AllowTransfer: Get<bool>;
  /// Allow assets to be burned from the wallet
  type AllowBurn: Get<bool>;
  /// Allow assets to be listed on the market
  type AllowEscrow: Get<bool>;
  /// Allow asset claiming
  type AllowClaim: Get<bool>;
  /// Currency type for reserve/unreserve balance
  type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;
  /// Wallet Module Id
  type ModuleId: Get<ModuleId>;
}

/// Class Id
pub type ClassIdOf<T> = <T as orml_nft::Config>::ClassId;
/// Token Id
pub type TokenIdOf<T> = <T as orml_nft::Config>::TokenId;
/// Listing Data
pub type ListingOf<T> = Listing<ClassIdOf<T>, TokenIdOf<T>, <T as system::Config>::AccountId, BalanceOf<T>>;
/// Claim Data
pub type ClaimOf<T> = Claim<ClassIdOf<T>, TokenIdOf<T>, <T as system::Config>::AccountId>;
/// Order Data
pub type OrderOf<T> = Order<ListingOf<T>, <T as system::Config>::AccountId, <T as system::Config>::BlockNumber>;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as system::Config>::AccountId>>::Balance;

decl_storage! {
  trait Store for Module<T: Config> as GamePowerWallet {

	/// Get a listing by the listing_id
	pub Listings get(fn listings):
		map hasher(twox_64_concat) ListingId => ListingOf<T>;
	/// Get all listings ids by an account
	pub ListingsByOwner get(fn listings_by_owner):
		map hasher(blake2_128_concat) T::AccountId => Vec<ListingId>;
	/// Get a vector of all listings. Used as a quick lookup.
	pub AllListings get(fn all_listings): Vec<(ClassIdOf<T>, TokenIdOf<T>)>;
	/// Get the next listing id
	pub NextListingId get(fn next_listing_id): ListingId;
	/// A fast and simple count of all current listings
	pub ListingCount: u64;
	/// A count of all orders made through the wallet
	pub OrderCount: u64;
	/// A history of orders for an asset
	pub OrderHistory get(fn order_history):
		map hasher(twox_64_concat) (ClassIdOf<T>, TokenIdOf<T>) => OrderOf<T>;
	/// Get one or more claims by AccountId or a single claim including the claim_id
	pub OpenClaims get(fn open_claims):
		double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) ClaimId => ClaimOf<T>;
	/// Get a vector of all claims. Used as a quick lookup.
	pub AllClaims get(fn all_claims): Vec<(ClassIdOf<T>, TokenIdOf<T>)>;
	/// Get the next claim id
	pub NextClaimId get(fn next_claim_id): ClaimId;
	/// Emotes used by the wallet
	pub Emotes get(fn emotes):
		double_map hasher(twox_64_concat) (ClassIdOf<T>, TokenIdOf<T>), hasher(twox_64_concat) T::AccountId => Vec<Vec<u8>>;
  }
}

decl_event!(
  pub enum Event<T>
  where
    <T as frame_system::Config>::AccountId,
    ClassId = ClassIdOf<T>,
    TokenId = TokenIdOf<T>,
    Balance = BalanceOf<T>,
  {
    /// Asset successfully transferred through the wallet [from, to, classId, tokenId]
    WalletAssetTransferred(AccountId, AccountId, ClassId, TokenId),
    /// Asset successfully burned through the wallet [owner, classId, tokenId]
    WalletAssetBurned(AccountId, ClassId, TokenId),
    /// Asset successfully listed through the wallet [owner, price, listingId,, classId, tokenId]
    WalletAssetListed(AccountId, Balance, ListingId, ClassId, TokenId),
    /// Asset successfully unlisted through the wallet [owner, listingId, classId, tokenId]
    WalletAssetUnlisted(AccountId, ListingId, ClassId, TokenId),
    /// Asset successfully purchased through the wallet [seller, buyer, classId, tokenId]
    WalletAssetPurchased(AccountId, AccountId, ClassId, TokenId),
    /// Asset successfully purchased through the wallet [receiver, classId, tokenId]
    WalletAssetClaimed(AccountId, ClassId, TokenId),
    /// Asset claim created [creator, receiver, classId, tokenId]
    WalletClaimCreated(AccountId, AccountId, ClassId, TokenId),
    /// Asset buy successful [seller, buyer, listingId, price]
    WalletAssetBuySuccess(AccountId, AccountId, ListingId, Balance),
	/// New Emote posted [poster, classId, tokenId, emote]
	WalletAssetEmotePosted(AccountId, ClassId, TokenId, Vec<u8>),
  }
);

decl_error! {
  pub enum Error for Module<T: Config> {
    /// Assets cannot be tranferred
    TransfersNotAllowed,
	/// An error occurred during transfer
	TransferCancelled,
	/// An error occurred during burn
	BurnCancelled,
    /// Assets cannot be burned
    BurningNotAllowed,
    /// Assets cannot be listed on the market
    EscrowNotAllowed,
    /// Asset locked in Escrow or Claims
    AssetLocked,
    /// Assets cannot be claimed
    ClaimingNotAllowed,
	/// An error occurred during claim
	ClaimCancelled,
    /// Asset not found
    AssetNotFound,
	/// Listing not found
    ListingNotFound,
	/// Listing not found
    UnlistingFailed,
    /// Claim not found
    ClaimNotFound,
    /// Claim creation failed
    ClaimCreateFailed,
    /// Maximum listings in Escrow
    NoAvailableListingId,
    /// Maximum claims made
    NoAvailableClaimId,
    /// Maximum orders in Escrow
    NoAvailableOrderId,
	/// Invalid Emote
	InvalidEmote,
    /// No Permission for this action
    NoPermission,
  }
}


decl_module! {
    pub struct Module<T: Config> for enum Call where origin: T::Origin {
    	type Error = Error<T>;

		fn deposit_event() = default;

		const AllowTransfer: bool = T::AllowTransfer::get();
		const AllowBurn: bool = T::AllowBurn::get();
		const AllowEscrow: bool = T::AllowEscrow::get();
		const AllowClaim: bool = T::AllowClaim::get();

	  	/// Transfer asset
		///
		/// - `to`: the token recipient
		/// - `asset`: (class_id, token_id)
		#[weight = 10_000]
		pub fn transfer(origin, to: T::AccountId, asset:(ClassIdOf<T>, TokenIdOf<T>)) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to transfer assets
			ensure!(T::AllowTransfer::get(), Error::<T>::TransfersNotAllowed);

			// Check that the sender owns this asset
			let check_ownership = Self::check_ownership(&sender, &asset)?;
			ensure!(check_ownership, Error::<T>::NoPermission);

			// Ensure that the asset is not locked in Escrow or Claims
			ensure!(!Self::is_locked(&asset), Error::<T>::AssetLocked);

			// Transfer the asset
			ensure!(T::Transfer::transfer(&sender, &to, asset).is_ok(), Error::<T>::TransferCancelled);

			Ok(())
		}

		/// Burn asset
		///
		/// - `asset`: (class_id, token_id)
		#[weight = 10_000]
		pub fn burn(origin, asset:(ClassIdOf<T>, TokenIdOf<T>)) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to burn assets
			ensure!(T::AllowBurn::get(), Error::<T>::BurningNotAllowed);

			// Check that the sender owns this asset
			let check_ownership = Self::check_ownership(&sender, &asset)?;
			ensure!(check_ownership, Error::<T>::NoPermission);

			// Ensure that the asset is not locked in Escrow or Claims
			ensure!(!Self::is_locked(&asset), Error::<T>::AssetLocked);

			// Burn the asset
			ensure!(T::Burn::burn(&sender, asset).is_ok(), Error::<T>::BurnCancelled);

			Ok(().into())
		}

		/// Send the asset to escrow to be listed on the market
		///
		/// - `asset`: (class_id, token_id)
		/// - `price`: price to sell the asset on the market
		#[weight = 10_000]
		pub fn list(origin, asset:(ClassIdOf<T>, TokenIdOf<T>), price: BalanceOf<T>) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to list assets
			ensure!(T::AllowEscrow::get(), Error::<T>::EscrowNotAllowed);

			// Check that the sender owns this asset
			let check_ownership = Self::check_ownership(&sender, &asset)?;
			ensure!(check_ownership, Error::<T>::NoPermission);

			// Ensure this asset isn't already listed
			ensure!(!Self::is_locked(&asset), Error::<T>::AssetLocked);

			// Escrow Account
			let escrow_account: T::AccountId = Self::get_escrow_account();

			// Transfer into escrow
			Self::do_transfer(&sender, &escrow_account, asset).ok();

			// Add the new listing id to storage
			let listing_id = NextListingId::try_mutate(|id| -> Result<ListingId, DispatchError> {
				let current_id = *id;
				*id = id.checked_add(One::one()).ok_or(Error::<T>::NoAvailableListingId)?;

				Ok(current_id)
			})?;

			// Create listing data
			let listing = Listing {
				id: listing_id,
				seller: sender.clone(),
				asset,
				price,
			};

			// Increment Listing count
			ListingCount::mutate(|id| -> Result<u64, DispatchError> {
				let current_count = *id;
				*id = id.checked_add(One::one()).ok_or(Error::<T>::NoAvailableListingId)?;

				Ok(current_count)
			}).ok();

			// Add listing to storage
			Listings::<T>::insert(listing_id, listing);

			// Add listing to owner
			// Get owner listing data
			let mut owner_data = ListingsByOwner::<T>::get(&sender);

			// Append the new listing id
			owner_data.push(listing_id);

			// Update owner listings
			ListingsByOwner::<T>::insert(&sender, owner_data);

			// Add asset to all listings
			AllListings::<T>::append(&asset);

			Self::deposit_event(RawEvent::WalletAssetListed(sender, price, listing_id, asset.0, asset.1));

			Ok(())
		}

		/// Remove the asset from escrow
		///
		/// - `listing_id`: id of the Listing
		#[weight = 10_000]
		pub fn unlist(origin, listing_id: ListingId) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to list assets
			ensure!(T::AllowEscrow::get(), Error::<T>::EscrowNotAllowed);

			// Get listing data
			let listing_data = Listings::<T>::get(listing_id);

			// Ensure the listing is in storage for this user
			ensure!(sender == listing_data.seller, Error::<T>::NoPermission);

			// Ensure listing was removed
			let is_unlisted = Self::do_unlist(&sender, listing_data.clone())?;
			ensure!(is_unlisted, Error::<T>::UnlistingFailed);

			Self::deposit_event(RawEvent::WalletAssetUnlisted(sender, listing_id, listing_data.asset.0, listing_data.asset.1));

			Ok(())
		}

		/// Buy the asset from the market
		///
		/// - `listing_id`: id of the Listing
		#[weight = 10_000]
		pub fn buy(origin, listing_id: ListingId) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to list assets
			ensure!(T::AllowEscrow::get(), Error::<T>::EscrowNotAllowed);

			// Ensure the listing is in storage
			ensure!(Listings::<T>::contains_key(listing_id), Error::<T>::ListingNotFound);

			// Get listing data
			let listing_data = Listings::<T>::take(listing_id);

			// Ensure listing was removed
			let is_unlisted = Self::do_unlist(&sender, listing_data.clone())?;
			ensure!(is_unlisted, Error::<T>::UnlistingFailed);

			// Transfer funds to seller
			<T as Config>::Currency::transfer(&sender, &listing_data.seller, listing_data.price, ExistenceRequirement::KeepAlive)?;

			// Increment Order count
			OrderCount::mutate(|id| -> Result<u64, DispatchError> {
				let current_count = *id;
				*id = id.checked_add(One::one()).ok_or(Error::<T>::NoAvailableOrderId)?;

				Ok(current_count)
			}).ok();

			// Get the current block for this order
			let block_number = <system::Module<T>>::block_number();

			// Create order data
			let order = Order {
				listing: listing_data.clone(),
				buyer: sender.clone(),
				block: block_number,
			};

			// Save order history
			OrderHistory::<T>::insert(order.listing.asset, order);

			Self::deposit_event(
				RawEvent::WalletAssetBuySuccess(
					listing_data.seller,
					sender,
					listing_data.id,
					listing_data.price
				)
			);

			Ok(())
		}

		/// Post an emote for the asset
		///
		/// - `asset`: (class_id, token_id)
		/// - `emote`: name of the emote to use
		#[weight = 10_000]
		pub fn emote(origin, asset:(ClassIdOf<T>, TokenIdOf<T>), emote: Vec<u8>) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Ensure this token exists
			ensure!(!AssetModule::<T>::tokens(asset.0, asset.1).is_none(), Error::<T>::AssetNotFound);

			// Convert the emote to a string
			let str_emote = str::from_utf8(&emote).unwrap();

			// Ensure this is a valid emote
			ensure!(!emojis::lookup(str_emote).is_none(), Error::<T>::InvalidEmote);

			// Get emoji
			let emoji = emojis::lookup(str_emote).unwrap().as_str().as_bytes().to_vec();

			// Get emotes data
			let mut emotes_data = Emotes::<T>::get(asset, &sender);

			// Append the new emoji
			emotes_data.push(emoji.clone());

			// Add emote to storage
			Emotes::<T>::insert(asset, &sender, emotes_data);

			Self::deposit_event(RawEvent::WalletAssetEmotePosted(sender, asset.0, asset.1, emoji));

			Ok(())
		}

		/// Claim an asset
		///
		/// - `claim_id`: id of the claim
		#[weight = 10_000]
		pub fn claim(origin, claim_id: ClaimId) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to claim assets
			ensure!(T::AllowClaim::get(), Error::<T>::ClaimingNotAllowed);

			// Ensure the claim is for this sender
			ensure!(OpenClaims::<T>::contains_key(&sender, claim_id), Error::<T>::ClaimNotFound);

			// Get claim data
			let claim_data = OpenClaims::<T>::get(&sender, claim_id);

			// Perform any domain related tasks to claiming
			ensure!(T::Claim::claim(&sender, claim_data.asset).is_ok(), Error::<T>::ClaimCancelled);

			// Claim Account
			let claim_account: T::AccountId = Self::get_claim_account();

			// Transfer asset into the reciever's account
			Self::do_transfer(&claim_account, &sender, claim_data.asset).ok();

			AllClaims::<T>::try_mutate(|asset_ids| -> DispatchResult {
				let asset_index = asset_ids.iter().position(|x| *x == claim_data.asset).unwrap();
				asset_ids.remove(asset_index);

				Ok(())
			})?;

			// Remove the open claim
			OpenClaims::<T>::remove(&sender, claim_id);

			Self::deposit_event(RawEvent::WalletAssetClaimed(sender, claim_data.asset.0, claim_data.asset.1));

			Ok(())
		}

		/// Create an asset claim for this account
		///
		/// - `receiver`: account to receive this asset
		/// - `asset`: (class_id, token_id)
		#[weight = 10_000]
		pub fn create_claim(origin, receiver: T::AccountId, asset:(ClassIdOf<T>, TokenIdOf<T>)) -> DispatchResult{

			let sender = ensure_signed(origin)?;

			// Check that the wallet has permission to claim assets
			ensure!(T::AllowClaim::get(), Error::<T>::ClaimingNotAllowed);

			// Check that the sender owns this asset
			let check_ownership = Self::check_ownership(&sender, &asset)?;
			ensure!(check_ownership, Error::<T>::NoPermission);

			// Ensure that the sender is the owner of this class
			let class_info = AssetModule::<T>::classes(asset.0).ok_or(Error::<T>::AssetNotFound)?;
			ensure!(sender == class_info.owner, Error::<T>::NoPermission);

			// Ensure the claim is created
			let claim_created = Self::do_create_claim(&sender, &receiver, asset)?;
			ensure!(claim_created, Error::<T>::ClaimCreateFailed);

			Self::deposit_event(RawEvent::WalletClaimCreated(sender, receiver, asset.0, asset.1));

			Ok(())
		}

    }
}

// Module Implementation
impl<T: Config> Module<T> {
	fn check_ownership(
    	owner: &T::AccountId,
    	asset: &(ClassIdOf<T>, TokenIdOf<T>)
	) -> Result<bool, DispatchError> {
    	return Ok(AssetModule::<T>::is_owner(&owner, *asset));
  	}

  	fn do_transfer(
    	from: &T::AccountId,
    	to: &T::AccountId,
    	asset: (ClassIdOf<T>, TokenIdOf<T>)
	) -> Result<bool, DispatchError> {
    	AssetModule::<T>::transfer(&from, &to, asset).ok();
    	return Ok(true)
  	}

	fn is_listed(asset: &(ClassIdOf<T>, TokenIdOf<T>)) -> bool {
		return Self::all_listings().contains(asset);
	}

	fn is_claiming(asset: &(ClassIdOf<T>, TokenIdOf<T>)) -> bool {
		return Self::all_claims().contains(asset)
	}

	fn get_claim_account() -> T::AccountId {
		return T::ModuleId::get().into_sub_account(100u32)
	}

	fn get_escrow_account() -> T::AccountId {
		return T::ModuleId::get().into_account()
	}

	pub fn is_locked(asset: &(ClassIdOf<T>, TokenIdOf<T>)) -> bool {
		return Self::is_listed(&asset) || Self::is_claiming(&asset)
	}

	fn do_unlist(sender: &T::AccountId, listing_data: ListingOf<T>) -> Result<bool, DispatchError> {
		//Escrow Account
		let escrow_account: T::AccountId = Self::get_escrow_account();

		// Transfer out of escrow
		Self::do_transfer(&escrow_account, &sender, listing_data.asset).ok();

		// Decrease Listing count
		ListingCount::mutate(|id| -> Result<u64, DispatchError> {
			let current_count = *id;
			*id = id.checked_sub(One::one()).ok_or(Error::<T>::NoAvailableListingId)?;

			Ok(current_count)
		}).ok();

		// Remove the asset from all listings
		AllListings::<T>::try_mutate(|asset_ids| -> DispatchResult {
			let asset_index = asset_ids.iter().position(|x| *x == listing_data.asset).unwrap();
			asset_ids.remove(asset_index);

			Ok(())
		})?;

		// remove the listing
		Listings::<T>::remove(listing_data.id);

		// Remove listing from owner
		// Get owner listing data
		let mut owner_data = ListingsByOwner::<T>::get(listing_data.clone().seller);

		// Remove the old listing id
		owner_data.retain(|&x| x != listing_data.id);

		// Update owner listings
		ListingsByOwner::<T>::insert(listing_data.clone().seller, owner_data);

		Ok(true)
	}

	fn do_create_claim(
		owner: &T::AccountId,
		receiver: &T::AccountId,
		asset: (ClassIdOf<T>, TokenIdOf<T>)
	) -> Result<bool, DispatchError> {
		// Get claim account
		let claim_account: T::AccountId = Self::get_claim_account();

		// Transfer asset into the claim account
		Self::do_transfer(&owner, &claim_account, asset).ok();

		// Create claim data
		let claim = Claim {
		receiver: receiver.clone(),
		asset,
		};

		// Add the new claim id to storage
		let claim_id = NextClaimId::try_mutate(|id| -> Result<ClaimId, DispatchError> {
		let current_id = *id;
		*id = id.checked_add(One::one()).ok_or(Error::<T>::NoAvailableClaimId)?;

		Ok(current_id)
		})?;

		// Add claim to storage
		OpenClaims::<T>::insert(receiver, claim_id, claim);
		AllClaims::<T>::append(&asset);

		Ok(true)
	}
}

// Implement OnTransferHandler
impl<T: Config> OnTransferHandler<T::AccountId, T::ClassId, T::TokenId> for Module<T> {
	fn transfer(from: &T::AccountId, to: &T::AccountId, asset: (T::ClassId, T::TokenId)) -> DispatchResult {
		Self::do_transfer(&from, &to, asset)?;
		Module::<T>::deposit_event(RawEvent::WalletAssetTransferred(from.clone(), to.clone(), asset.0, asset.1));
		Ok(())
	}
}

// Implement OnBurnHandler
impl<T: Config> OnBurnHandler<T::AccountId, T::ClassId, T::TokenId> for Module<T> {
	fn burn(owner: &T::AccountId, asset: (T::ClassId, T::TokenId)) -> DispatchResult {
		AssetModule::<T>::burn(&owner, asset)?;
		Module::<T>::deposit_event(RawEvent::WalletAssetBurned(owner.clone(), asset.0, asset.1));
		Ok(())
	}
}

// Implement OnClaimHandler
impl<T: Config> OnClaimHandler<T::AccountId, T::ClassId, T::TokenId> for Module<T> {
	fn claim(_owner: &T::AccountId, _asset: (T::ClassId, T::TokenId)) -> DispatchResult {
		Ok(())
	}
}