-
Notifications
You must be signed in to change notification settings - Fork 0
DO NOT MERGE: PAPI wrapper canister #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
AntonioVentilii
wants to merge
1
commit into
main
Choose a base branch
from
feat/PAPI-wrapper-canister
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| [package] | ||
| name = "ic-papi-wrapper" | ||
| version = "0.0.1" | ||
|
|
||
| [dependencies] | ||
| lazy_static = { workspace = true } | ||
| candid = { workspace = true } | ||
| ic-cdk = { workspace = true } | ||
| ic-papi-api = { workspace = true } | ||
| ic-papi-guard = { workspace = true } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| //! Public, stateless API for payment-wrapped proxy calls. | ||
| //! | ||
| //! You choose *how* to pass arguments: | ||
| //! - `call0` : target takes no args → we send `()` | ||
| //! - `call_blob`: you provide a Candid-encoded arg blob | ||
| //! - `call_text`: you provide Candid text like `("(42, \"hi\")")` | ||
| //! | ||
| //! In all cases you also pass: | ||
| //! - `fee_amount` (u128, in the unit implied by your `PaymentType` variant) | ||
| //! - `payment` (which variant determines cycles vs token, patron vs caller) | ||
| //! - optional `cycles_to_forward` (for targets that expect cycles) | ||
|
|
||
| use candid::{Encode, Principal}; | ||
| use ic_cdk::update; | ||
| use ic_papi_api::PaymentType; | ||
|
|
||
| use crate::domain::BridgeError; | ||
| use crate::payments::PAYMENT_GUARD; | ||
| use crate::util::cycles::forward_raw; | ||
|
|
||
| fn map_guard_err<E: core::fmt::Debug>(e: E) -> String { | ||
| BridgeError::GuardError(format!("{e:?}")).to_string() | ||
| } | ||
|
|
||
| /// Proxies a call to a target method that takes **no arguments** (`()`), after charging a fee. | ||
| /// | ||
| /// # Arguments | ||
| /// - `target`: Target canister principal. | ||
| /// - `method`: Exact method name on the target. | ||
| /// - `fee_amount`: Amount to charge via `PAYMENT_GUARD`. | ||
| /// - `payment`: Payment type to use. If `None`, defaults to `AttachedCycles`. | ||
| /// - `cycles_to_forward`: Optional cycles to attach to the target call. | ||
| /// | ||
| /// # Returns | ||
| /// Raw Candid reply blob from the target (decode on the client). | ||
| #[update] | ||
| pub async fn call0( | ||
| target: Principal, | ||
| method: String, | ||
| fee_amount: u128, | ||
| payment: Option<PaymentType>, | ||
| cycles_to_forward: Option<u128>, | ||
| ) -> Result<Vec<u8>, String> { | ||
| let p = payment.unwrap_or(PaymentType::AttachedCycles); | ||
| PAYMENT_GUARD.deduct(p, fee_amount).await.map_err(map_guard_err)?; | ||
|
|
||
| let args = Encode!().map_err(|e| BridgeError::Candid(e.to_string()).to_string())?; | ||
|
|
||
| let cycles = cycles_to_forward.unwrap_or(0); | ||
|
|
||
| forward_raw(target, &method, args, cycles) | ||
| .await | ||
| .map_err(|e| BridgeError::TargetRejected(e).to_string()) | ||
| } | ||
|
|
||
| /// Proxies a call using a **Candid-encoded argument blob**, after charging a fee. | ||
| /// | ||
| /// Use this when your client already encoded args with `IDL.encode` (agent-js) | ||
| /// or `candid::Encode!` (Rust). | ||
| /// | ||
| /// # Arguments | ||
| /// - `args_blob`: The exact Candid byte payload to forward to the target. | ||
| #[update] | ||
| pub async fn call_blob( | ||
| target: Principal, | ||
| method: String, | ||
| args_blob: Vec<u8>, | ||
| fee_amount: u128, | ||
| payment: Option<PaymentType>, | ||
| cycles_to_forward: Option<u128>, | ||
| ) -> Result<Vec<u8>, String> { | ||
| // 1) charge fee | ||
| let p = payment.unwrap_or(PaymentType::AttachedCycles); | ||
| PAYMENT_GUARD.deduct(p, fee_amount).await.map_err(map_guard_err)?; | ||
|
|
||
| // 2) forward as-is | ||
| let cycles = cycles_to_forward.unwrap_or(0); | ||
| forward_raw(target, &method, args_blob, cycles) | ||
| .await | ||
| .map_err(|e| BridgeError::TargetRejected(e).to_string()) | ||
| } | ||
|
|
||
| /// Proxies a call using **Candid text** (e.g., `"(\"hello\", 42, opt null)"`), after charging a fee. | ||
| /// | ||
| /// This is convenient when you want to pass args “like in a .did example” without | ||
| /// writing encoding code on the client. | ||
| /// | ||
| /// # Arguments | ||
| /// - `args_text`: A string containing Candid values for the target method’s parameter list. | ||
| #[update] | ||
| pub async fn call_text( | ||
| target: Principal, | ||
| method: String, | ||
| args_text: String, | ||
| fee_amount: u128, | ||
| payment: Option<PaymentType>, | ||
| cycles_to_forward: Option<u128>, | ||
| ) -> Result<Vec<u8>, String> { | ||
| use candid::parser::value::IDLArgs; | ||
|
|
||
| // 1) charge fee | ||
| let p = payment.unwrap_or(PaymentType::AttachedCycles); | ||
| PAYMENT_GUARD.deduct(p, fee_amount).await.map_err(map_guard_err)?; | ||
|
|
||
| // 2) parse candid text -> blob | ||
| let idl_args = IDLArgs::from_str(&args_text) | ||
| .map_err(|e| BridgeError::Candid(e.to_string()).to_string())?; | ||
| let args_blob = idl_args | ||
| .to_bytes() | ||
| .map_err(|e| BridgeError::Candid(e.to_string()).to_string())?; | ||
|
|
||
| // 3) forward | ||
| let cycles = cycles_to_forward.unwrap_or(0); | ||
| forward_raw(target, &method, args_blob, cycles) | ||
| .await | ||
| .map_err(|e| BridgeError::TargetRejected(e).to_string()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| pub mod call; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
|
|
||
| /// Errors returned by the bridge canister. | ||
| /// | ||
| /// Kept small because the canister is stateless; pricing/governance are pushed to the caller. | ||
| #[derive(Debug)] | ||
| pub enum BridgeError { | ||
| /// Candid encoding/decoding failed. | ||
| Candid(String), | ||
| /// Target canister rejected the proxied call. | ||
| TargetRejected(String), | ||
| /// Fee deduction failed (insufficient cycles/allowance/etc.). | ||
| GuardError(String), | ||
| } | ||
|
|
||
| impl ToString for BridgeError { | ||
| fn to_string(&self) -> String { | ||
| use BridgeError::*; | ||
| match self { | ||
| Candid(e) => format!("Candid: {e}"), | ||
| TargetRejected(e) => format!("TargetRejected: {e}"), | ||
| GuardError(e) => format!("GuardError: {e}"), | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| pub mod errors; | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| use candid::Principal; | ||
| use ic_papi_guard::guards::any::VendorPaymentConfig; | ||
|
|
||
| #[derive(Debug, CandidType, Deserialize, Clone, Eq, PartialEq)] | ||
| pub enum FeeDenom { | ||
| Cycles, | ||
| Icrc2 { ledger: Principal }, | ||
| } | ||
|
|
||
| #[derive(Debug, CandidType, Deserialize, Clone, Eq, PartialEq)] | ||
| pub struct FeeSpec { | ||
| pub amount: u128, | ||
| pub denom: FeeDenom, | ||
| } | ||
|
|
||
| #[derive(Debug, CandidType, Deserialize, Clone, Eq, PartialEq)] | ||
| pub struct MethodConfig { | ||
| pub fee: FeeSpec, | ||
| pub supported: Vec<VendorPaymentConfig>, | ||
| pub forward_cycles: Option<u128>, | ||
| } | ||
|
|
||
| #[derive(Debug, CandidType, Deserialize, Clone, Eq, PartialEq)] | ||
| pub struct MethodKey { | ||
| pub target: Principal, | ||
| pub method: String, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| pub mod api; | ||
| pub mod domain; | ||
| pub mod payments; | ||
| mod util; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| use candid::Principal; | ||
| use ic_papi_guard::guards::any::{PaymentGuard, VendorPaymentConfig}; | ||
| use lazy_static::lazy_static; | ||
|
|
||
| /// Return the ICRC-2 ledger principal used when the *payment type* is token-based. | ||
| /// | ||
| /// Replace this with your real ledger principal. | ||
| fn payment_ledger() -> Principal { | ||
| Principal::from_text("aaaaa-aa").unwrap() // TODO: set real ledger | ||
| } | ||
|
|
||
| /// Shared guard accepting multiple payment modes. | ||
| /// | ||
| /// The *caller* selects the mode by passing an appropriate `PaymentType` variant. | ||
| /// The fee *amount* is provided per call. | ||
| lazy_static! { | ||
| pub static ref PAYMENT_GUARD: PaymentGuard<5> = PaymentGuard { | ||
| supported: [ | ||
| VendorPaymentConfig::AttachedCycles, | ||
| VendorPaymentConfig::CallerPaysIcrc2Cycles, | ||
| VendorPaymentConfig::PatronPaysIcrc2Cycles, | ||
| VendorPaymentConfig::CallerPaysIcrc2Tokens { ledger: payment_ledger() }, | ||
| VendorPaymentConfig::PatronPaysIcrc2Tokens { ledger: payment_ledger() }, | ||
| ], | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| pub mod guard_config; | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| use candid::Principal; | ||
| use ic_cdk::api::call::{call_raw, call_raw128}; | ||
|
|
||
| /// Forwards a raw candid call to the target canister, optionally attaching cycles. | ||
| /// | ||
| /// # Errors | ||
| /// Returns a string with reject code/message if the target rejects. | ||
| pub async fn forward_raw( | ||
| target: Principal, | ||
| method: &str, | ||
| args: Vec<u8>, | ||
| cycles: u128, | ||
| ) -> Result<Vec<u8>, String> { | ||
| if cycles > 0 { | ||
| call_raw128(target, method, args, cycles) | ||
| .await | ||
| .map_err(|(code, msg)| format!("{code:?} {msg}")) | ||
| } else { | ||
| call_raw(target, method, args, 0) | ||
| .await | ||
| .map_err(|(code, msg)| format!("{code:?} {msg}")) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The caller may have to provide more type information than they are used to. Normally dfx will use the target canister's candid file to convert to the correct types; without that information it will guess more simply and won't always get this conversion right.