Skip to content

Commit

Permalink
Expire old BTC Miami referral codes (#6053)
Browse files Browse the repository at this point in the history
  • Loading branch information
hpeebles authored Jul 18, 2024
1 parent b927766 commit 9ed6706
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 197 deletions.
4 changes: 4 additions & 0 deletions backend/canisters/local_user_index/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [unreleased]

### Changed

- Expire old BTC Miami referral codes ([#6053](https://github.com/open-chat-labs/open-chat/pull/6053))

## [[2.0.1241](https://github.com/open-chat-labs/open-chat/releases/tag/v2.0.1241-local_user_index)] - 2024-07-17

### Added
Expand Down

This file was deleted.

2 changes: 0 additions & 2 deletions backend/canisters/local_user_index/impl/src/jobs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use crate::RuntimeState;

pub mod delete_users;
pub mod make_btc_miami_payments;
pub mod sync_events_to_user_canisters;
pub mod sync_events_to_user_index_canister;
pub mod topup_canister_pool;
pub mod upgrade_canisters;

pub(crate) fn start(state: &RuntimeState) {
delete_users::start_job_if_required(state, None);
make_btc_miami_payments::start_job_if_required(state);
sync_events_to_user_canisters::start_job_if_required(state);
sync_events_to_user_index_canister::start_job_if_required(state);
topup_canister_pool::start_job_if_required(state);
Expand Down
8 changes: 3 additions & 5 deletions backend/canisters/local_user_index/impl/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::model::btc_miami_payments_queue::BtcMiamiPaymentsQueue;
use crate::model::referral_codes::{ReferralCodes, ReferralTypeMetrics};
use crate::timer_job_types::TimerJob;
use candid::Principal;
Expand Down Expand Up @@ -165,14 +164,15 @@ impl RuntimeState {
}

pub fn metrics(&self) -> Metrics {
let now = self.env.now();
let canister_upgrades_metrics = self.data.canisters_requiring_upgrade.metrics();
let event_store_client_info = self.data.event_store_client.info();
let event_relay_canister_id = event_store_client_info.event_store_canister_id;

Metrics {
heap_memory_used: utils::memory::heap(),
stable_memory_used: utils::memory::stable(),
now: self.env.now(),
now,
cycles_balance: self.env.cycles_balance(),
wasm_version: WASM_VERSION.with_borrow(|v| **v),
git_commit_id: utils::git::git_commit_id().to_string(),
Expand All @@ -189,7 +189,7 @@ impl RuntimeState {
user_upgrade_concurrency: self.data.user_upgrade_concurrency,
user_events_queue_length: self.data.user_event_sync_queue.len(),
users_to_delete_queue_length: self.data.users_to_delete_queue.len(),
referral_codes: self.data.referral_codes.metrics(),
referral_codes: self.data.referral_codes.metrics(now),
event_store_client_info,
canister_ids: CanisterIds {
user_index: self.data.user_index_canister_id,
Expand Down Expand Up @@ -230,7 +230,6 @@ struct Data {
pub platform_moderators_group: Option<ChatId>,
pub referral_codes: ReferralCodes,
pub timer_jobs: TimerJobs<TimerJob>,
pub btc_miami_payments_queue: BtcMiamiPaymentsQueue,
pub rng_seed: [u8; 32],
pub video_call_operators: Vec<Principal>,
pub oc_secret_key_der: Option<Vec<u8>>,
Expand Down Expand Up @@ -292,7 +291,6 @@ impl Data {
platform_moderators_group: None,
referral_codes: ReferralCodes::default(),
timer_jobs: TimerJobs::default(),
btc_miami_payments_queue: BtcMiamiPaymentsQueue::default(),
rng_seed: [0; 32],
video_call_operators,
oc_secret_key_der,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::lifecycle::{init_env, init_state};
use crate::memory::get_upgrades_memory;
use crate::Data;
use crate::{mutate_state, Data};
use canister_logger::LogEntry;
use canister_tracing_macros::trace;
use ic_cdk::post_upgrade;
use local_user_index_canister::post_upgrade::Args;
use stable_memory::get_reader;
use std::time::Duration;
use tracing::info;
use utils::cycles::init_cycles_dispenser_client;

Expand All @@ -24,4 +25,10 @@ fn post_upgrade(args: Args) {
init_state(env, data, args.wasm_version);

info!(version = %args.wasm_version, "Post-upgrade complete");

ic_cdk_timers::set_timer(Duration::from_secs(600), || {
mutate_state(|state| {
state.data.referral_codes.set_expired(state.env.now());
});
});
}

This file was deleted.

1 change: 0 additions & 1 deletion backend/canisters/local_user_index/impl/src/model/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub mod btc_miami_payments_queue;
pub mod global_user_map;
pub mod local_user_map;
pub mod referral_codes;
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ pub struct ReferralCodes {
codes: HashMap<String, ReferralCodeDetails>,
}

impl ReferralCodes {
pub fn set_expired(&mut self, now: TimestampMillis) {
for code in self.codes.values_mut() {
code.expiry = Some(now);
}
}
}

#[derive(Serialize, Deserialize)]
pub struct ReferralCodeDetails {
referral_type: ReferralType,
Expand All @@ -40,6 +48,7 @@ pub struct ReferralCodeClaim {
#[derive(Serialize, Debug, Default)]
pub struct ReferralTypeMetrics {
pub claimed: usize,
pub expired: usize,
pub total: usize,
}

Expand Down Expand Up @@ -71,6 +80,7 @@ impl ReferralCodes {
}
}

#[allow(dead_code)]
pub fn claim(&mut self, code: String, user_id: UserId, now: TimestampMillis) -> bool {
match self.codes.entry(code) {
Entry::Occupied(mut e) => {
Expand Down Expand Up @@ -107,14 +117,16 @@ impl ReferralCodes {
}
}

pub fn metrics(&self) -> HashMap<ReferralType, ReferralTypeMetrics> {
pub fn metrics(&self, now: TimestampMillis) -> HashMap<ReferralType, ReferralTypeMetrics> {
let mut metrics = HashMap::new();

for details in self.codes.values() {
let ms: &mut ReferralTypeMetrics = metrics.entry(details.referral_type).or_default();
ms.total += 1;
if details.claimed.is_some() {
ms.claimed += 1;
} else if details.expiry.is_some_and(|ts| ts < now) {
ms.expired += 1;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::model::btc_miami_payments_queue::PendingPayment;
use crate::model::referral_codes::{ReferralCode, ReferralCodeError};
use crate::timer_job_types::{AddUserToSatoshiDice, TimerJob};
use crate::{mutate_state, RuntimeState, USER_CANISTER_INITIAL_CYCLES_BALANCE};
use candid::Principal;
use canister_tracing_macros::trace;
Expand All @@ -10,7 +8,7 @@ use local_user_index_canister::register_user::{Response::*, *};
use types::{BuildVersion, CanisterId, CanisterWasm, Cycles, MessageContentInitial, TextContent, UserId};
use user_canister::init::Args as InitUserCanisterArgs;
use user_canister::{Event as UserEvent, ReferredUserRegistered};
use user_index_canister::{Event as UserIndexEvent, JoinUserToGroup, UserRegistered};
use user_index_canister::{Event as UserIndexEvent, UserRegistered};
use utils::canister;
use utils::canister::CreateAndInstallError;
use utils::consts::{min_cycles_balance, CREATE_CANISTER_CYCLES_FEE};
Expand Down Expand Up @@ -212,35 +210,7 @@ fn commit(
);
}
}
Some(ReferralCode::BtcMiami(code)) => {
let test_mode = state.data.test_mode;

// This referral code can only be used once so claim it
state.data.referral_codes.claim(code, user_id, now);

state.data.btc_miami_payments_queue.push(PendingPayment {
amount: if test_mode { 50 } else { 50_000 }, // Approx $14
timestamp: state.env.now_nanos(),
recipient: user_id.into(),
});
crate::jobs::make_btc_miami_payments::start_job_if_required(state);

let btc_miami_group =
Principal::from_text(if test_mode { "ueyan-5iaaa-aaaaf-bifxa-cai" } else { "pbo6v-oiaaa-aaaar-ams6q-cai" })
.unwrap()
.into();

state.push_event_to_user_index(UserIndexEvent::JoinUserToGroup(Box::new(JoinUserToGroup {
user_id,
chat_id: btc_miami_group,
})));
state.data.timer_jobs.enqueue_job(
TimerJob::AddUserToSatoshiDice(AddUserToSatoshiDice { user_id, attempt: 0 }),
now,
now,
)
}
None => {}
Some(ReferralCode::BtcMiami(_)) | None => {}
}
}

Expand Down

0 comments on commit 9ed6706

Please sign in to comment.