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
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;

#[cfg(test)]
mod mock;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
mod tests;

#[frame_support::pallet]
pub mod pallet {
	use admeta_common::{AdData, AdPreference, TargetTag};
	use codec::{Decode, Encode, MaxEncodedLen};
	use frame_support::{
		dispatch::DispatchResult,
		pallet_prelude::*,
		traits::{BalanceStatus, Currency, OnUnbalanced, Randomness, ReservableCurrency},
	};
	use frame_system::pallet_prelude::*;
	use scale_info::TypeInfo;
	use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, Saturating};
	use sp_std::prelude::*;

	pub type BlockNumberOf<T> = <T as frame_system::Config>::BlockNumber;
	pub type BalanceOf<T> =
		<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
	pub type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
		<T as frame_system::Config>::AccountId,
	>>::NegativeImbalance;

	pub type GeneralData<T> = BoundedVec<u8, <T as Config>::MaxAdDataLength>;

	/// This defines impression ads, which pays by CPI
	#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
	#[scale_info(skip_type_params(T))]
	pub struct ImpressionAd<T: Config> {
		/// The account who proposed this ad
		pub proposer: T::AccountId,
		/// The URL where this ad's metadata stores
		pub metadata: GeneralData<T>,
		/// The target URL where it redirects to when user clicks this ad
		pub target: GeneralData<T>,
		/// The title of this ad
		pub title: GeneralData<T>,
		/// The bond reserved for this ad
		pub bond: BalanceOf<T>,
		/// The cost per impression (CPI)
		pub cpi: BalanceOf<T>,
		/// The total number of impressions in this ad
		pub amount: u32,
		/// The end block of this ad
		pub end_block: BlockNumberOf<T>,
		/// The preference of target group
		pub preference: AdPreference,
		/// The approval status
		pub approved: bool,
	}

	// TODO ClickAd, ActionAd will be implemented

	#[pallet::config]
	pub trait Config: frame_system::Config {
		type AdIndex: Parameter
			+ MaybeSerializeDeserialize
			+ Bounded
			+ AtLeast32BitUnsigned
			+ Copy
			+ MaxEncodedLen
			+ Default;

		/// Origin from which approvals must come.
		type ApproveOrigin: EnsureOrigin<Self::RuntimeOrigin>;

		/// Origin from which rejections must come.
		type RejectOrigin: EnsureOrigin<Self::RuntimeOrigin>;

		/// Handler for the unbalanced decrease when slashing for a rejected proposal.
		type OnSlash: OnUnbalanced<NegativeImbalanceOf<Self>>;

		/// Because this pallet emits events, it depends on the runtime's definition of an event.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// Currency for balance reserving and unreserving operations
		type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;

		type Randomness: Randomness<Self::Hash, Self::BlockNumber>;

		/// Maximum acceptable Ad metadata length
		#[pallet::constant]
		type MaxAdDataLength: Get<u32>;

		/// Maximum num of tags per Ad
		#[pallet::constant]
		type MaxAdTags: Get<u32>;

		/// The base deposit amount of an ad proposal
		#[pallet::constant]
		type AdDepositBase: Get<BalanceOf<Self>>;

		/// The deposit amount per byte of an ad's metadata
		#[pallet::constant]
		type AdDepositPerByte: Get<BalanceOf<Self>>;
	}

	#[pallet::pallet]
	#[pallet::generate_store(pub(super) trait Store)]
	pub struct Pallet<T>(_);

	/// Number of ad proposals that have been made.
	#[pallet::storage]
	#[pallet::getter(fn ad_count)]
	pub type AdCount<T: Config> = StorageValue<_, T::AdIndex, OptionQuery>;

	#[pallet::storage]
	#[pallet::getter(fn impression_ads)]
	// TODO Optimize the storage usage, as hashmap is not the optimal and scalable solution
	/// Impression ads storage
	pub type ImpressionAds<T: Config> = StorageDoubleMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		Blake2_128Concat,
		T::AdIndex,
		ImpressionAd<T>,
		OptionQuery,
	>;

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// New advertising proposal created
		NewAdProposal(T::AccountId, T::AdIndex),

		/// Ad proposal approved
		AdProposalApproved(T::AccountId, T::AdIndex),

		/// Ad proposal rejected
		AdProposalRejected(T::AccountId, T::AdIndex),

		/// New user added
		NewUserAdded(T::AccountId),

		/// Ad display enabled/disabled by users
		UserSetAdDisplay(T::AccountId, bool),

		/// Ad reward claimed
		RewardClaimed(T::AccountId, T::AdIndex),

		/// Ad reward not claimed
		RewardNotClaimed(T::AccountId, T::AdIndex),
	}

	#[pallet::error]
	pub enum Error<T> {
		AdDoesNotExist,
		AdCountOverflow,
		InvalidAdPreference,
		InsufficientProposalBalance,
		InvalidAdIndex,
		UserAlreadyExists,
		UserDoesNotExist,
		AdNotForThisUser,
		AdPaymentError,
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Create an ad proposal.
		///
		/// The dispatch origin for this call must be `Signed` by the proposer.
		/// - 'ad_url': The URL which links to the ad metadata(usually an image stored on IPFS)
		/// - 'target_url': The jump link of this ad proposal
		/// - 'title': Title of this ad
		/// - 'cpi': Cost per impression of this ad
		/// - 'amount': The total duplications of this ad
		/// - 'end_block': The expiration time of this ad in Block height
		/// - 'ad_preference': The preferred target group of this ad
		#[pallet::weight(10_000)]
		pub fn propose_ad(
			origin: OriginFor<T>,
			ad_url: GeneralData<T>,
			target_url: GeneralData<T>,
			title: GeneralData<T>,
			cpi: BalanceOf<T>,
			amount: u32,
			end_block: BlockNumberOf<T>,
			ad_preference: AdPreference,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			Self::create_proposal(
				who,
				ad_url,
				target_url,
				title,
				cpi,
				amount,
				end_block,
				ad_preference,
			)?;

			Ok(())
		}
		/// Approve an ad proposal.
		///
		/// The dispatch origin for this call must be `Signed` by the ApproveOrigin.
		#[pallet::weight(10_000)]
		pub fn approve_ad(
			origin: OriginFor<T>,
			proposer: T::AccountId,
			ad_index: T::AdIndex,
		) -> DispatchResult {
			T::ApproveOrigin::ensure_origin(origin)?;

			// Set approved to true
			ImpressionAds::<T>::mutate(proposer.clone(), ad_index, |ad_op| {
				if let Some(ad) = ad_op {
					ad.approved = true;
					Self::deposit_event(Event::AdProposalApproved(proposer, ad_index));
					Ok(())
				} else {
					Err(Error::<T>::InvalidAdIndex)
				}
			})?;

			Ok(())
		}
		/// Reject an ad proposal.
		///
		/// The dispatch origin for this call must be `Signed` by the RejectOrigin.
		#[pallet::weight(10_000)]
		pub fn reject_ad(
			origin: OriginFor<T>,
			proposer: T::AccountId,
			ad_index: T::AdIndex,
		) -> DispatchResult {
			T::RejectOrigin::ensure_origin(origin)?;

			// Slash the bond and unreserve the ad payment
			let ad = Self::impression_ads(&proposer, ad_index).ok_or(Error::<T>::InvalidAdIndex)?;
			let imbalance = T::Currency::slash_reserved(&ad.proposer, ad.bond).0;
			T::OnSlash::on_unbalanced(imbalance);
			let ad_cost = ad.cpi * ad.amount.into();
			T::Currency::unreserve(&ad.proposer, ad_cost);
			// Remove this proposal
			ImpressionAds::<T>::remove(&proposer, ad_index);
			Self::deposit_event(Event::AdProposalRejected(proposer, ad_index));

			Ok(())
		}
	}

	impl<T: Config> AdData<T::BlockNumber, T::AdIndex, T::AccountId> for Pallet<T> {
		fn match_ad_for_user(
			age: u8,
			tag: TargetTag,
			block_number: T::BlockNumber,
		) -> Vec<(T::AccountId, T::AdIndex)> {
			let mut matched_vec = Vec::new();
			for ad in ImpressionAds::<T>::iter() {
				if ad.2.preference.age.is_in_range(age) &&
					ad.2.preference.tags.contains(&tag) &&
					ad.2.amount > 0 && ad.2.approved &&
					ad.2.end_block >= block_number
				{
					// Decrease the total amount of this ad by 1
					ImpressionAds::<T>::mutate(&ad.0, &ad.1, |ad_op| {
						if let Some(ad) = ad_op {
							ad.amount -= 1;
						}
					});
					matched_vec.push((ad.0, ad.1));
				}
			}
			matched_vec
		}

		fn claim_reward_for_user(
			proposer: T::AccountId,
			ad_index: T::AdIndex,
			user: T::AccountId,
		) -> DispatchResult {
			if let Some(ad) = Self::impression_ads(proposer, ad_index) {
				let ad_proposer = ad.proposer;
				T::Currency::repatriate_reserved(&ad_proposer, &user, ad.cpi, BalanceStatus::Free)
					.map_err(|_| Error::<T>::AdPaymentError)?;
				Ok(())
			} else {
				Err(Error::<T>::AdDoesNotExist)?
			}
		}
	}

	impl<T: Config> Pallet<T> {
		/// Calculate the next ad index
		fn next_ad_id() -> Result<T::AdIndex, Error<T>> {
			match Self::ad_count() {
				Some(id) => {
					// Ensure id won't overflow
					ensure!(id < T::AdIndex::max_value(), Error::<T>::AdCountOverflow);
					Ok(id.saturating_add(T::AdIndex::from(1u8)))
				},
				// Start count from 1
				None => Ok(T::AdIndex::min_value().saturating_add(T::AdIndex::from(1u8))),
			}
		}
		/// Create an ad proposal
		fn create_proposal(
			who: T::AccountId,
			ad_url: GeneralData<T>,
			target_url: GeneralData<T>,
			title: GeneralData<T>,
			cpi: BalanceOf<T>,
			amount: u32,
			end_block: BlockNumberOf<T>,
			ad_preference: AdPreference,
		) -> Result<(), Error<T>> {
			ensure!(ad_preference.age.self_check(), Error::<T>::InvalidAdPreference);

			let ad_index = Self::next_ad_id()?;

			let bond =
				T::AdDepositBase::get() + T::AdDepositPerByte::get() * (ad_url.len() as u32).into();

			let ad_cost = cpi * amount.into();

			T::Currency::reserve(&who, bond + ad_cost)
				.map_err(|_| Error::<T>::InsufficientProposalBalance)?;

			let ad = ImpressionAd::<T> {
				proposer: who.clone(),
				metadata: ad_url,
				target: target_url,
				title,
				bond,
				cpi,
				amount,
				end_block,
				preference: ad_preference,
				approved: false,
			};

			ImpressionAds::<T>::insert(&who, ad_index, ad);
			AdCount::<T>::put(ad_index);

			Self::deposit_event(Event::NewAdProposal(who, ad_index));

			Ok(())
		}
	}
}