Payout flows in backend - fix Tremendous forex cards (#5001)

* wip: payouts flow api

* working

* Finish up flow migration

* vibe-coded frontend changes

* fix typos and vue

* fix: types

---------

Co-authored-by: Calum H. (IMB11) <contact@cal.engineer>
This commit is contained in:
aecsocket
2026-01-14 10:53:35 +00:00
committed by GitHub
parent 50a87ba933
commit d055dc68dc
17 changed files with 1224 additions and 873 deletions
+174
View File
@@ -0,0 +1,174 @@
//! Centralized place where payout rails are defined - their fees, minimum and
//! maximum withdraw amounts, and execution logic.
use eyre::eyre;
use modrinth_util::decimal::Decimal2dp;
use rust_decimal::Decimal;
use sqlx::PgTransaction;
use thiserror::Error;
pub mod mural;
pub mod paypal;
pub mod tremendous;
use crate::{
database::models::{DBPayoutId, DBUser},
models::payouts::{PayoutMethodRequest, Withdrawal},
queue::payouts::PayoutsQueue,
routes::ApiError,
util::{error::Context, gotenberg::GotenbergClient},
};
impl PayoutsQueue {
/// Begins a payout creation flow.
///
/// A payout creation flow is preparation for sending a user some amount of
/// money, but does not actually send the money until [`PayoutFlow::execute`]
/// is called. This allows callers to get information like the payout fee,
/// minimum, and maximum amounts for validation before actually sending the
/// payout.
pub async fn create_payout_flow(
&self,
withdrawal: Withdrawal,
) -> Result<PayoutFlow, ApiError> {
let get_method = async {
let method = self
.get_payout_methods()
.await
.wrap_internal_err("failed to fetch payout methods")?
.into_iter()
.find(|method| method.id == withdrawal.method_id)
.wrap_request_err("invalid payout method ID")?;
Ok::<_, ApiError>(method)
};
match withdrawal.method {
PayoutMethodRequest::PayPal => {
paypal::create(self, withdrawal.amount, false).await
}
PayoutMethodRequest::Venmo => {
paypal::create(self, withdrawal.amount, true).await
}
PayoutMethodRequest::MuralPay { method_details } => {
mural::create(self, withdrawal.amount, method_details).await
}
PayoutMethodRequest::Tremendous { method_details } => {
tremendous::create(
self,
withdrawal.amount,
method_details,
&get_method.await?,
)
.await
}
}
}
}
#[derive(Debug)]
pub struct PayoutFlow {
/// Net amount that the user receives after fees, in USD.
pub net_usd: Decimal2dp,
/// Total payout fee, in USD.
pub total_fee_usd: Decimal2dp,
/// Minimum payout amount, in USD.
pub min_amount_usd: Decimal2dp,
/// Maximum payout amount, in USD.
pub max_amount_usd: Decimal2dp,
/// Currency conversion rate from USD to the payout currency.
pub forex_usd_to_currency: Option<Decimal>,
inner: PayoutFlowInner,
}
#[derive(Debug)]
#[expect(clippy::large_enum_variant)]
enum PayoutFlowInner {
PayPal(paypal::PayPalFlow),
Mural(mural::MuralFlow),
Tremendous(tremendous::TremendousFlow),
}
struct ExecuteContext<'a> {
queue: &'a PayoutsQueue,
user: &'a DBUser,
payout_id: DBPayoutId,
transaction: PgTransaction<'a>,
gotenberg: &'a GotenbergClient,
}
#[derive(Debug)]
pub struct ReadyPayoutFlow {
inner: PayoutFlowInner,
}
#[derive(Debug, Error)]
pub enum ValidateError {
#[error("insufficient balance")]
InsufficientBalance,
#[error("withdraw amount below minimum")]
BelowMin,
#[error("withdraw amount above maximum")]
AboveMax,
}
impl PayoutFlow {
/// Checks that this payout can be sent if the recipient has the specified
/// balance.
pub fn validate(
self,
balance_usd: Decimal,
) -> Result<ReadyPayoutFlow, ValidateError> {
let gross_usd = self.net_usd + self.total_fee_usd;
if balance_usd < gross_usd {
return Err(ValidateError::InsufficientBalance);
}
if gross_usd < self.min_amount_usd {
return Err(ValidateError::BelowMin);
}
if gross_usd > self.max_amount_usd {
return Err(ValidateError::AboveMax);
}
Ok(ReadyPayoutFlow { inner: self.inner })
}
}
impl ReadyPayoutFlow {
/// Executes this payout.
pub async fn execute(
self,
queue: &PayoutsQueue,
user: &DBUser,
payout_id: DBPayoutId,
transaction: PgTransaction<'_>,
gotenberg: &GotenbergClient,
) -> Result<(), ApiError> {
let cx = ExecuteContext {
queue,
user,
payout_id,
transaction,
gotenberg,
};
match self.inner {
PayoutFlowInner::PayPal(flow) => paypal::execute(cx, flow).await,
PayoutFlowInner::Mural(flow) => mural::execute(cx, flow).await,
PayoutFlowInner::Tremendous(flow) => {
tremendous::execute(cx, flow).await
}
}
}
}
fn get_verified_email(user: &DBUser) -> Result<&str, ApiError> {
let email = user.email.as_ref().wrap_request_err(
"you must add an email to your account to withdraw",
)?;
if !user.email_verified {
return Err(ApiError::Request(eyre!(
"you must verify your email to withdraw"
)));
}
Ok(email)
}
@@ -0,0 +1,309 @@
use ariadne::ids::UserId;
use chrono::Utc;
use eyre::eyre;
use modrinth_util::decimal::Decimal2dp;
use muralpay::FiatAndRailCode;
use rust_decimal::{Decimal, RoundingStrategy, dec};
use tracing::error;
use crate::{
database::models::payout_item::DBPayout,
models::payouts::{
MuralPayDetails, PayoutMethodFee, PayoutMethodType, PayoutStatus,
},
queue::payouts::{
PayoutsQueue,
flow::{
ExecuteContext, PayoutFlow, PayoutFlowInner, get_verified_email,
},
mural::MuralPayoutRequest,
},
routes::ApiError,
util::error::Context,
};
pub const PLATFORM_FEE: PayoutMethodFee = PayoutMethodFee {
percentage: dec!(0.01),
min: Decimal::ZERO,
max: None,
};
// USDC has much lower fees.
pub const MIN_USD_BLOCKCHAIN: Decimal2dp = Decimal2dp::new_unchecked(dec!(0.1));
pub fn min_usd_fiat(fiat_and_rail_code: FiatAndRailCode) -> Decimal2dp {
match fiat_and_rail_code {
// Due to relatively low volume of Peru withdrawals, fees are higher,
// so we need to raise the minimum to cover these fees.
FiatAndRailCode::UsdPeru => Decimal2dp::new(dec!(10.0)),
_ => Decimal2dp::new(dec!(5.0)),
}
.unwrap()
}
pub const MAX_USD: Decimal2dp = Decimal2dp::new_unchecked(dec!(10_000.0));
#[derive(Debug)]
pub(super) struct MuralFlow {
net_usd: Decimal2dp,
method_fee_usd: Decimal2dp,
platform_fee_usd: Decimal2dp,
payout_details: MuralPayoutRequest,
recipient_info: muralpay::CreatePayoutRecipientInfo,
}
pub(super) async fn create(
queue: &PayoutsQueue,
amount: Decimal,
details: MuralPayDetails,
) -> Result<PayoutFlow, ApiError> {
let gross_usd =
Decimal2dp::new(amount).wrap_request_err("invalid amount")?;
let platform_fee_usd = Decimal2dp::rounded(
PLATFORM_FEE.compute_fee(gross_usd),
RoundingStrategy::AwayFromZero,
);
let mural = queue.muralpay.load();
let mural = mural
.as_ref()
.wrap_internal_err("Mural client not available")?;
let method_fee_usd;
let forex_usd_to_currency;
let min_amount_usd;
match &details.payout_details {
MuralPayoutRequest::Blockchain { .. } => {
method_fee_usd = Decimal2dp::ZERO;
forex_usd_to_currency = None;
min_amount_usd = MIN_USD_BLOCKCHAIN;
}
MuralPayoutRequest::Fiat {
fiat_and_rail_details,
..
} => {
let fiat_and_rail_code = fiat_and_rail_details.code();
let fees = mural
.client
.get_fees_for_token_amount(&[muralpay::TokenFeeRequest {
amount: muralpay::TokenAmount {
token_symbol: muralpay::USDC.into(),
token_amount: gross_usd.get(),
},
fiat_and_rail_code,
}])
.await
.wrap_internal_err("failed to request fees")?;
let fee = fees
.into_iter()
.next()
.wrap_internal_err("no fees returned")?;
match fee {
muralpay::TokenPayoutFee::Success {
exchange_rate,
fee_total,
..
} => {
method_fee_usd = Decimal2dp::rounded(
fee_total.token_amount,
RoundingStrategy::AwayFromZero,
);
forex_usd_to_currency = Some(exchange_rate);
min_amount_usd = min_usd_fiat(fiat_and_rail_code);
}
muralpay::TokenPayoutFee::Error { message, .. } => {
return Err(ApiError::Internal(eyre!(
"failed to compute fee: {message}"
)));
}
}
}
};
let total_fee_usd = method_fee_usd + platform_fee_usd;
let net_usd = gross_usd - total_fee_usd;
Ok(PayoutFlow {
net_usd,
total_fee_usd,
min_amount_usd,
max_amount_usd: MAX_USD,
forex_usd_to_currency,
inner: PayoutFlowInner::Mural(MuralFlow {
net_usd,
method_fee_usd,
platform_fee_usd,
payout_details: details.payout_details,
recipient_info: details.recipient_info,
}),
})
}
pub(super) async fn execute(
ExecuteContext {
queue,
user,
payout_id,
mut transaction,
gotenberg,
}: ExecuteContext<'_>,
MuralFlow {
net_usd,
method_fee_usd,
platform_fee_usd,
payout_details,
recipient_info,
}: MuralFlow,
) -> Result<(), ApiError> {
let user_email = get_verified_email(user)?;
let sent_to_method_usd = net_usd + method_fee_usd;
let total_fee_usd = method_fee_usd + platform_fee_usd;
let mural = queue.muralpay.load();
let mural = mural
.as_ref()
.wrap_internal_err("Mural client not available")?;
let payment_statement_doc = queue
.create_mural_payment_statement_doc(
payout_id,
net_usd,
total_fee_usd,
&recipient_info,
gotenberg,
)
.await?;
let user_id = UserId::from(user.id);
let method_id = match &payout_details {
MuralPayoutRequest::Blockchain { .. } => {
"blockchain-usdc-polygon".to_string()
}
MuralPayoutRequest::Fiat {
fiat_and_rail_details,
..
} => fiat_and_rail_details.code().to_string(),
};
let payout_details = match payout_details {
crate::queue::payouts::mural::MuralPayoutRequest::Fiat {
bank_name,
bank_account_owner,
fiat_and_rail_details,
} => muralpay::CreatePayoutDetails::Fiat {
bank_name,
bank_account_owner,
developer_fee: None,
fiat_and_rail_details,
},
crate::queue::payouts::mural::MuralPayoutRequest::Blockchain {
wallet_address,
} => {
muralpay::CreatePayoutDetails::Blockchain {
wallet_details: muralpay::WalletDetails {
// only Polygon chain is currently supported
blockchain: muralpay::Blockchain::Polygon,
wallet_address,
},
}
}
};
let payout = muralpay::CreatePayout {
amount: muralpay::TokenAmount {
token_amount: sent_to_method_usd.get(),
token_symbol: muralpay::USDC.into(),
},
payout_details,
recipient_info,
supporting_details: Some(muralpay::SupportingDetails {
supporting_document: Some(format!(
"data:application/pdf;base64,{}",
payment_statement_doc.body
)),
payout_purpose: Some(muralpay::PayoutPurpose::VendorPayment),
}),
};
let payout_request = mural
.client
.create_payout_request(
mural.source_account_id,
Some(format!("User {user_id}")),
&[payout],
)
.await
.map_err(|err| match err {
muralpay::MuralError::Api(err) => ApiError::Mural(Box::new(err)),
err => ApiError::Internal(
eyre!(err).wrap_err("failed to create payout request"),
),
})?;
// Once the Mural payout request has been created successfully,
// then we *must* commit *a* payout row into the DB, to link the Mural
// payout request to the `payout` row, and to subtract the user's balance.
// Even if we can't execute the payout afterwards.
// For this, we create a payout, try to execute it, and no matter what
// happens, insert the payout row.
// Otherwise if we don't put it into the DB, we've got a ghost Mural
// payout with no related database entry.
// However, this doesn't mean that the payout will definitely go through.
// For this, we need to execute it, and handle errors.
let mut payout = DBPayout {
id: payout_id,
user_id: user.id,
created: Utc::now(),
// after the payout has been successfully executed,
// we wait for Mural's confirmation that the funds have been delivered
// done in `SyncPayoutStatuses` background task
status: PayoutStatus::InTransit,
amount: net_usd.get(),
fee: Some(total_fee_usd.get()),
method: Some(PayoutMethodType::MuralPay),
method_id: Some(method_id),
method_address: Some(user_email.to_string()),
platform_id: Some(payout_request.id.to_string()),
};
// poor man's async try/catch block
let result = (async {
mural
.client
.execute_payout_request(payout_request.id)
.await
.wrap_internal_err("failed to execute payout request")?;
Ok::<_, ApiError>(())
})
.await;
if let Err(caught_err) = result {
payout.status = PayoutStatus::Failed;
// if execution fails, make sure to immediately cancel the payout request
// we don't want floating payout requests
if let Err(err) =
queue.cancel_mural_payout_request(payout_request.id).await
{
error!(
"Failed to cancel unexecuted payout request: {err:#}\noriginal error: {caught_err:#}"
);
}
}
payout
.insert(&mut transaction)
.await
.wrap_internal_err("failed to insert payout")?;
transaction
.commit()
.await
.wrap_internal_err("failed to commit transaction")?;
Ok(())
}
@@ -0,0 +1,233 @@
use chrono::Utc;
use modrinth_util::decimal::Decimal2dp;
use reqwest::Method;
use rust_decimal::{Decimal, RoundingStrategy, dec};
use serde::Deserialize;
use serde_json::json;
use tracing::error;
use crate::{
database::models::payout_item::DBPayout,
models::payouts::{PayoutMethodFee, PayoutMethodType, PayoutStatus},
queue::payouts::{
PayoutsQueue,
flow::{ExecuteContext, PayoutFlow, PayoutFlowInner},
},
routes::ApiError,
util::error::Context,
};
pub const FEE: PayoutMethodFee = PayoutMethodFee {
percentage: dec!(0.02),
min: dec!(0.25),
max: Some(dec!(1.0)),
};
pub const MIN_USD: Decimal2dp = Decimal2dp::new_unchecked(dec!(0.25));
pub const MAX_USD: Decimal2dp = Decimal2dp::new_unchecked(dec!(100_000.0));
#[derive(Debug)]
pub(super) struct PayPalFlow {
is_venmo: bool,
net_usd: Decimal2dp,
fee_usd: Decimal2dp,
}
pub(super) async fn create(
_queue: &PayoutsQueue,
amount: Decimal,
is_venmo: bool,
) -> Result<PayoutFlow, ApiError> {
let gross_usd =
Decimal2dp::new(amount).wrap_request_err("invalid amount")?;
let fee_usd = Decimal2dp::rounded(
FEE.compute_fee(amount),
RoundingStrategy::AwayFromZero,
);
let net_usd = gross_usd - fee_usd;
Ok(PayoutFlow {
net_usd,
total_fee_usd: fee_usd,
min_amount_usd: MIN_USD,
max_amount_usd: MAX_USD,
forex_usd_to_currency: None,
inner: PayoutFlowInner::PayPal(PayPalFlow {
is_venmo,
net_usd,
fee_usd,
}),
})
}
pub(super) async fn execute(
ExecuteContext {
queue,
user,
payout_id,
mut transaction,
gotenberg: _,
}: ExecuteContext<'_>,
PayPalFlow {
is_venmo,
net_usd,
fee_usd,
}: PayPalFlow,
) -> Result<(), ApiError> {
#[derive(Deserialize)]
struct PayPalLink {
href: String,
}
#[derive(Deserialize)]
struct PayoutsResponse {
pub links: Vec<PayPalLink>,
}
#[derive(Deserialize)]
struct PayoutItem {
pub payout_item_id: String,
}
#[derive(Deserialize)]
struct PayoutData {
pub items: Vec<PayoutItem>,
}
// keep the `method_id` code here since the big if block below is legacy code
// when we had paypal intl methods as well
let method_id = if is_venmo { "venmo" } else { "paypal_us" };
let (wallet, wallet_type, address, display_address) = if is_venmo {
if let Some(venmo) = &user.venmo_handle {
("Venmo", "user_handle", venmo.clone(), venmo)
} else {
return Err(ApiError::InvalidInput(
"Venmo address has not been set for account!".to_string(),
));
}
} else if let Some(paypal_id) = &user.paypal_id {
if let Some(paypal_country) = &user.paypal_country {
if paypal_country == "US" && method_id != "paypal_us" {
return Err(ApiError::InvalidInput(
"Please use the US PayPal transfer option!".to_string(),
));
} else if paypal_country != "US" && method_id == "paypal_us" {
return Err(ApiError::InvalidInput(
"Please use the International PayPal transfer option!"
.to_string(),
));
}
(
"PayPal",
"paypal_id",
paypal_id.clone(),
user.paypal_email.as_ref().unwrap_or(paypal_id),
)
} else {
return Err(ApiError::InvalidInput(
"Please re-link your PayPal account!".to_string(),
));
}
} else {
return Err(ApiError::InvalidInput(
"You have not linked a PayPal account!".to_string(),
));
};
let payout_req = json!({
"sender_batch_header": {
"sender_batch_id": format!("{}-payouts", Utc::now().to_rfc3339()),
"email_subject": "You have received a payment from Modrinth!",
"email_message": "Thank you for creating projects on Modrinth. Please claim this payment within 30 days.",
},
"items": [{
"amount": {
"currency": "USD",
"value": net_usd.to_string()
},
"receiver": address,
"note": "Payment from Modrinth creator monetization program",
"recipient_type": wallet_type,
"recipient_wallet": wallet,
"sender_item_id": crate::models::ids::PayoutId::from(payout_id),
}]
});
let res: PayoutsResponse = queue
.make_paypal_request(
Method::POST,
"payments/payouts",
Some(payout_req),
None,
None,
)
.await
.wrap_internal_err("failed to make payout request")?;
// by this point, we've made a monetary payout request to this user;
// no matter what we do, we *must* track this payout in the DB,
// even if the next steps fail, so that the user's balance is subtracted.
let mut payout = DBPayout {
id: payout_id,
user_id: user.id,
created: Utc::now(),
status: PayoutStatus::InTransit,
amount: net_usd.get(),
fee: Some(fee_usd.get()),
method: Some(if is_venmo {
PayoutMethodType::Venmo
} else {
PayoutMethodType::PayPal
}),
method_id: Some(method_id.to_string()),
method_address: Some(display_address.clone()),
platform_id: None, // attempt to populate this later
};
// poor man's async try/catch block
let result = (async {
let link = res
.links
.first()
.wrap_request_err("no PayPal links available")?;
let res = queue
.make_paypal_request::<(), PayoutData>(
Method::GET,
&link.href,
None,
None,
Some(true),
)
.await
.wrap_internal_err("failed to make PayPal link request")?;
let data = res.items.first().wrap_internal_err(
"no payout items returned from PayPal link request",
)?;
payout.platform_id = Some(data.payout_item_id.clone());
Ok::<_, ApiError>(())
})
.await;
if let Err(err) = result {
error!(
"Failed to get PayPal payout platform ID, will track this payout with no platform ID: {err:#}"
);
}
payout
.insert(&mut transaction)
.await
.wrap_internal_err("failed to insert payout")?;
transaction
.commit()
.await
.wrap_internal_err("failed to commit transaction")?;
Ok(())
}
@@ -0,0 +1,245 @@
use chrono::Utc;
use eyre::eyre;
use modrinth_util::decimal::Decimal2dp;
use reqwest::Method;
use rust_decimal::{Decimal, RoundingStrategy, dec};
use serde::Deserialize;
use serde_json::json;
use crate::{
database::models::payout_item::DBPayout,
models::payouts::{
PayoutMethod, PayoutMethodFee, PayoutMethodType, PayoutStatus,
TremendousCurrency, TremendousDetails, TremendousForexResponse,
},
queue::payouts::{
PayoutsQueue,
flow::{
ExecuteContext, PayoutFlow, PayoutFlowInner, get_verified_email,
},
},
routes::ApiError,
util::error::Context,
};
#[derive(Debug)]
pub(super) struct TremendousFlow {
value_denomination: Decimal,
value_currency_code: String,
net_usd: Decimal2dp,
total_fee_usd: Decimal2dp,
delivery_email: String,
method_id: String,
}
pub(super) async fn create(
queue: &PayoutsQueue,
amount: Decimal,
details: TremendousDetails,
method: &PayoutMethod,
) -> Result<PayoutFlow, ApiError> {
let forex: TremendousForexResponse = queue
.make_tremendous_request(Method::GET, "forex", None::<()>)
.await
.wrap_internal_err("failed to fetch Tremendous forex data")?;
let usd_to_currency_for = |currency_code: &str| {
forex
.forex
.get(currency_code)
.copied()
.wrap_internal_err_with(|| {
eyre!("no Tremendous forex rate for '{currency_code}'")
})
};
let category = method.category.as_ref().wrap_internal_err_with(|| {
eyre!("method '{}' should have a category", method.id)
})?;
let delivery_email = details.delivery_email;
let method_id = method.id.clone();
match category.as_str() {
"paypal" | "venmo" => {
let currency = details.currency.unwrap_or(TremendousCurrency::Usd);
let currency_code = currency.to_string();
let usd_to_currency = usd_to_currency_for(&currency_code)?;
let fee = PayoutMethodFee {
// If a user withdraws $10:
//
// amount charged by Tremendous = X * 1.04 = $10.00
//
// We have to solve for X here:
//
// X = $10.00 / 1.04
//
// So the percentage fee is `1 - (1 / 1.04)`
// Roughly 0.03846, not 0.04
percentage: dec!(1) - (dec!(1) / dec!(1.04)),
min: dec!(0.25),
max: None,
};
let gross_usd =
Decimal2dp::new(amount).wrap_request_err("invalid amount")?;
let total_fee_usd = Decimal2dp::rounded(
fee.compute_fee(amount),
RoundingStrategy::AwayFromZero,
);
let net_usd = gross_usd - total_fee_usd;
Ok(PayoutFlow {
net_usd,
total_fee_usd,
min_amount_usd: Decimal2dp::ZERO,
max_amount_usd: Decimal2dp::new(dec!(5000.0)).unwrap(),
forex_usd_to_currency: Some(usd_to_currency),
inner: PayoutFlowInner::Tremendous(TremendousFlow {
// In the Tremendous dashboard, we have configured it so that,
// if we make a $10 request for a premium method, *we* get
// charged an extra 4% - the user gets the full $10, and we get
// $10.40 subtracted from our Tremendous balance.
//
// To offset this, we (the platform) take the fees off before
// we send the request to Tremendous. Afterwards, the method
// (Tremendous) will take 0% off the top of our $10.
value_denomination: net_usd.get(),
value_currency_code: TremendousCurrency::Usd.to_string(),
net_usd,
total_fee_usd,
delivery_email,
method_id,
}),
})
}
_ => {
let currency_code =
if let Some(currency_code) = &method.currency_code {
currency_code.clone()
} else {
TremendousCurrency::Usd.to_string()
};
let usd_to_currency = usd_to_currency_for(&currency_code)?;
let currency_to_usd = dec!(1) / usd_to_currency;
// no fees
let net_usd = Decimal2dp::rounded(
amount * currency_to_usd,
RoundingStrategy::AwayFromZero,
);
Ok(PayoutFlow {
net_usd,
total_fee_usd: Decimal2dp::ZERO,
min_amount_usd: Decimal2dp::ZERO,
max_amount_usd: Decimal2dp::new(dec!(10_000.0)).unwrap(),
forex_usd_to_currency: Some(usd_to_currency),
inner: PayoutFlowInner::Tremendous(TremendousFlow {
// we have to use the exact `amount` here,
// since interval cards (e.g. PLN 70.00)
// require you to input that exact amount
value_denomination: amount,
value_currency_code: currency_code,
net_usd,
total_fee_usd: Decimal2dp::ZERO,
delivery_email,
method_id,
}),
})
}
}
}
pub(super) async fn execute(
ExecuteContext {
queue,
user,
payout_id,
mut transaction,
gotenberg: _,
}: ExecuteContext<'_>,
TremendousFlow {
value_denomination,
value_currency_code,
net_usd,
total_fee_usd,
delivery_email,
method_id,
}: TremendousFlow,
) -> Result<(), ApiError> {
#[derive(Debug, Deserialize)]
struct Reward {
pub id: String,
}
#[derive(Debug, Deserialize)]
struct Order {
pub rewards: Vec<Reward>,
}
#[derive(Debug, Deserialize)]
struct TremendousResponse {
pub order: Order,
}
let user_email = get_verified_email(user)?;
let order_req = json!({
"payment": {
"funding_source_id": "BALANCE",
},
"rewards": [{
"value": {
"denomination": value_denomination,
"currency_code": value_currency_code,
},
"delivery": {
"method": "EMAIL"
},
"recipient": {
"name": user.username,
"email": delivery_email
},
"products": [
method_id,
],
"campaign_id": dotenvy::var("TREMENDOUS_CAMPAIGN_ID")?,
}]
});
let order_res: TremendousResponse = queue
.make_tremendous_request(Method::POST, "orders", Some(order_req))
.await
.wrap_internal_err("failed to make Tremendous order request")?;
let platform_id = order_res
.order
.rewards
.first()
.map(|reward| reward.id.clone());
DBPayout {
id: payout_id,
user_id: user.id,
created: Utc::now(),
status: PayoutStatus::InTransit,
amount: net_usd.get(),
fee: Some(total_fee_usd.get()),
method: Some(PayoutMethodType::Tremendous),
method_id: Some(method_id),
method_address: Some(user_email.to_string()),
platform_id,
}
.insert(&mut transaction)
.await
.wrap_internal_err("failed to insert payout")?;
transaction
.commit()
.await
.wrap_internal_err("failed to commit transaction")?;
Ok(())
}