diff --git a/primitives/src/campaign.rs b/primitives/src/campaign.rs index b2f2fdcc5..eb1298e86 100644 --- a/primitives/src/campaign.rs +++ b/primitives/src/campaign.rs @@ -40,7 +40,7 @@ mod campaign_id { write!(f, "CampaignId({})", self) } } - + impl CampaignId { /// Generates randomly a `CampaignId` using `Uuid::new_v4().to_simple()` pub fn new() -> Self { diff --git a/sentry/src/routes/channel.rs b/sentry/src/routes/channel.rs index 0a86aa38f..c66a7ffc5 100644 --- a/sentry/src/routes/channel.rs +++ b/sentry/src/routes/channel.rs @@ -307,22 +307,47 @@ pub async fn add_spender_leaf( let channel = req .extensions() .get::>() - .ok_or(ResponseError::NotFound)? - .context; + .ok_or(ResponseError::NotFound)?; update_accounting( app.pool.clone(), - channel.id(), + channel.context.id(), spender, Side::Spender, UnifiedNum::from_u64(0), ) .await?; - // TODO: Replace with SpenderResponse - Ok(success_response(serde_json::to_string(&SuccessResponse { - success: true, - })?)) + let latest_spendable = + fetch_spendable(app.pool.clone(), &spender, &channel.context.id()).await?; + + let latest_spendable = match latest_spendable { + Some(spendable) => spendable, + None => { + create_or_update_spendable_document(&app.adapter, app.pool.clone(), &channel, spender) + .await? + } + }; + + let new_state = + match get_corresponding_new_state(&app.pool, &app.logger, &channel.context).await? { + Some(new_state) => new_state, + None => return spender_response_without_leaf(latest_spendable.deposit.total), + }; + + let total_spent = new_state + .balances + .spenders + .get(&spender) + .map(|spent| spent.to_owned()); + + let res = SpenderResponse { + spender: Spender { + total_deposited: latest_spendable.deposit.total, + total_spent, + }, + }; + Ok(success_response(serde_json::to_string(&res)?)) } async fn get_corresponding_new_state( @@ -902,12 +927,21 @@ mod test { #[tokio::test] async fn adds_and_retrieves_spender_leaf() { let app = setup_dummy_app().await; + let channel_context = app .config .find_chain_of(DUMMY_CAMPAIGN.channel.token) .expect("Dummy channel Token should be present in config!") .with(DUMMY_CAMPAIGN.channel); + let deposit = AdapterDeposit { + total: BigNum::from_str("100000000000000000000").expect("should convert"), // 100 DAI + still_on_create2: BigNum::from_str("1000000000000000000").expect("should convert"), // 1 DAI + }; + app.adapter + .client + .add_deposit_call(channel_context.context.id(), *CREATOR, deposit.clone()); + insert_channel(&app.pool, channel_context.context) .await .expect("should insert channel");