Skip to content

Commit

Permalink
++
Browse files Browse the repository at this point in the history
  • Loading branch information
bitdivine committed Sep 9, 2024
1 parent 5a7a781 commit 28caa59
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/guard/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ ic-cdk = "0.15.0"
ic-papi-api = { workspace = true }
candid = { workspace = true }
cycles-ledger-client = { workspace = true }
serde_bytes = { workspace = true }
39 changes: 31 additions & 8 deletions src/guard/src/guards/icrc2_cycles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,49 @@ use ic_papi_api::{Account, Icrc2Payer};

pub struct Icrc2CyclesPaymentGuard {
/// The payer
pub payer: Icrc2Payer,
pub payer_account: Account,
/// The spender, if different from the payer.
pub spender_subaccount: Option<serde_bytes::ByteBuf>,
/// The ICRC-2 time, if applicable.
pub created_at_time: Option<u64>,
/// The ledger to withdraw the cycles from.
pub ledger_canister_id: Principal,
/// Own canister ID
pub own_canister_id: Principal,
}
impl Icrc2CyclesPaymentGuard {
pub fn default_account() -> Account {
Account {
owner: ic_cdk::caller(),
subaccount: None,
}
}
pub fn default_cycles_ledger() -> Principal {
Principal::from_text(
option_env!("DFX_CYCLES_LEDGER_CANISTER_ID").unwrap_or("um5iw-rqaaa-aaaaq-qaaba-cai"),
)
.expect("Failed to parse cycles ledger canister ID")
}
pub fn new(own_canister_id: Principal) -> Self {
Self {
payer_account: Self::default_account(),
ledger_canister_id: Self::default_cycles_ledger(),
own_canister_id,
created_at_time: None,
spender_subaccount: None,
}
}
}

impl PaymentGuard for Icrc2CyclesPaymentGuard {
async fn deduct(&self, fee: u64) -> Result<(), PaymentError> {
let account = self.payer.account.clone().unwrap_or_else(|| Account {
owner: ic_cdk::caller(),
subaccount: None,
});
cycles_ledger_client::Service(self.ledger_canister_id)
.withdraw_from(&WithdrawFromArgs {
to: self.own_canister_id.clone(),
amount: Nat::from(fee),
from: account,
spender_subaccount: self.payer.spender_subaccount.clone(),
created_at_time: self.payer.created_at_time,
from: self.payer_account.clone(),
spender_subaccount: self.spender_subaccount.clone(),
created_at_time: self.created_at_time,
})
.await
.map_err(|(rejection_code, string)| {
Expand Down

0 comments on commit 28caa59

Please sign in to comment.