Skip to content

Commit

Permalink
feat: unsubscribe
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaumebogard committed Jul 26, 2022
1 parent dc7bfe2 commit 0c4ceb4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ frame-support = { default-features = false, git = "https://github.com/paritytech
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }
frame-benchmarking = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23", optional = true }



[features]
default = ["std"]
std = [
Expand Down
42 changes: 39 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,13 @@ pub mod pallet {
pub enum Event<T: Config> {
/// Subscription has been created
SubscriptionCreated(T::AccountId, T::AccountId, BalanceOf<T>, T::BlockNumber),
UnsubscriptionCreated(T::AccountId, T::AccountId),
}

#[pallet::error]
pub enum Error<T> {
/// Invalid subscription
InvalidSubscription,
UnknownUnsubscription,
}

#[pallet::hooks]
Expand Down Expand Up @@ -134,8 +135,8 @@ pub mod pallet {
next_block_number.saturating_inc();

<Subscriptions<T>>::mutate(next_block_number, |wrapped_current_subscriptions| {
if let Some(current_subscription) = wrapped_current_subscriptions {
current_subscription.push(new_subscription);
if let Some(current_subscriptions) = wrapped_current_subscriptions {
current_subscriptions.push(new_subscription);
} else {
*wrapped_current_subscriptions = Option::from(vec![new_subscription]);
}
Expand All @@ -144,5 +145,40 @@ pub mod pallet {
Self::deposit_event(Event::SubscriptionCreated(to, from, amount, frequency));
Ok(())
}

#[pallet::weight(1)]
pub fn unsubscribe(
origin: OriginFor<T>,
subscriber: T::AccountId,
subscription: Subscription<T::BlockNumber, BalanceOf<T>, T::AccountId>,
when: T::BlockNumber,
) -> DispatchResult {
ensure_signed(origin)?;

<Subscriptions<T>>::mutate(when, |wrapped_current_subscriptions| {
if let Some(current_subscriptions) = wrapped_current_subscriptions {
let old_subscriptions_len = current_subscriptions.len();

current_subscriptions.retain(|current_subscription| {
!(current_subscription.0 == subscription
&& current_subscription.1 == subscriber)
});

if old_subscriptions_len >= current_subscriptions.len() {
Err(Error::<T>::UnknownUnsubscription)
} else {
Ok(())
}
} else {
Err(Error::<T>::UnknownUnsubscription)
}
})?;

Self::deposit_event(Event::UnsubscriptionCreated(
subscription.beneficiary,
subscriber,
));
Ok(())
}
}
}

0 comments on commit 0c4ceb4

Please sign in to comment.