Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions artifacts/stablecoin-idl.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,47 @@
}
]
},
{
"name": "deposit_collateral",
"accounts": [
{
"name": "owner",
"writable": false,
"signer": true,
"init": false
},
{
"name": "position",
"writable": true,
"signer": false,
"init": false
},
{
"name": "vault",
"writable": true,
"signer": false,
"init": false
},
{
"name": "user_holding",
"writable": true,
"signer": true,
"init": false
},
{
"name": "token_definition",
"writable": false,
"signer": false,
"init": false
}
],
"args": [
{
"name": "amount",
"type": "u128"
}
]
},
{
"name": "withdraw_collateral",
"accounts": [
Expand Down
62 changes: 58 additions & 4 deletions programs/integration_tests/tests/stablecoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ impl Balances {
200_000
}

fn collateral_extra_deposit() -> u128 {
100_000
}

fn stablecoin_supply_init() -> u128 {
1_000
}
Expand Down Expand Up @@ -247,7 +251,7 @@ fn assert_fungible_balance(state: &V03State, account_id: AccountId, expected_bal
}

#[test]
fn stablecoin_open_position_then_withdraw_collateral() {
fn stablecoin_open_position_deposit_then_withdraw_collateral() {
let mut state = state_for_stablecoin_tests();

// Open the position: deposit collateral from the user's holding into a fresh vault.
Expand Down Expand Up @@ -287,6 +291,52 @@ fn stablecoin_open_position_then_withdraw_collateral() {
Balances::user_holding_init() - Balances::collateral_deposit(),
);

// Deposit more collateral into the existing position.
let deposit = stablecoin_core::Instruction::DepositCollateral {
amount: Balances::collateral_extra_deposit(),
};
let message = public_transaction::Message::try_new(
Ids::stablecoin_program(),
vec![
Ids::owner(),
Ids::position(),
Ids::vault(),
Ids::user_holding(),
Ids::collateral_definition(),
],
vec![
current_nonce(&state, Ids::owner()),
current_nonce(&state, Ids::user_holding()),
],
deposit,
)
.unwrap();
let witness_set = public_transaction::WitnessSet::for_message(
&message,
&[&Keys::owner(), &Keys::user_holding()],
);
let tx = PublicTransaction::new(message, witness_set);
state
.transition_from_public_transaction(&tx, 0, 0)
.expect("deposit_collateral must succeed");

assert_position(
&state,
Balances::collateral_deposit() + Balances::collateral_extra_deposit(),
);
assert_fungible_balance(
&state,
Ids::vault(),
Balances::collateral_deposit() + Balances::collateral_extra_deposit(),
);
assert_fungible_balance(
&state,
Ids::user_holding(),
Balances::user_holding_init()
- Balances::collateral_deposit()
- Balances::collateral_extra_deposit(),
);

// Withdraw part of the collateral back to the same user holding.
let withdraw = stablecoin_core::Instruction::WithdrawCollateral {
amount: Balances::collateral_withdraw(),
Expand All @@ -311,17 +361,21 @@ fn stablecoin_open_position_then_withdraw_collateral() {

assert_position(
&state,
Balances::collateral_deposit() - Balances::collateral_withdraw(),
Balances::collateral_deposit() + Balances::collateral_extra_deposit()
- Balances::collateral_withdraw(),
);
assert_fungible_balance(
&state,
Ids::vault(),
Balances::collateral_deposit() - Balances::collateral_withdraw(),
Balances::collateral_deposit() + Balances::collateral_extra_deposit()
- Balances::collateral_withdraw(),
);
assert_fungible_balance(
&state,
Ids::user_holding(),
Balances::user_holding_init() - Balances::collateral_deposit()
Balances::user_holding_init()
- Balances::collateral_deposit()
- Balances::collateral_extra_deposit()
+ Balances::collateral_withdraw(),
);
}
Expand Down
44 changes: 36 additions & 8 deletions programs/stablecoin/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ use spel_framework_macros::account_type;
const POSITION_PDA_DOMAIN: [u8; 32] = [0; 32];
const POSITION_VAULT_PDA_DOMAIN: [u8; 32] = [1; 32];

pub const ERR_POSITION_ACCOUNT_ID_MISMATCH: &str =
"Position account ID does not match expected derivation";
pub const ERR_POSITION_VAULT_ACCOUNT_ID_MISMATCH: &str =
"Position vault account ID does not match expected derivation";

/// Stablecoin Program Instruction.
#[derive(Debug, Serialize, Deserialize)]
pub enum Instruction {
Expand All @@ -30,6 +35,25 @@ pub enum Instruction {
/// Amount of collateral tokens to deposit into the position vault.
collateral_amount: u128,
},
/// Deposit additional collateral tokens into an existing position vault.
///
/// Required accounts (5):
/// - Owner account (authorized; binds caller-as-owner via position PDA re-derivation)
/// - Position account (initialized, owned by `self_program_id`)
/// - Position vault token holding (address must match
/// `compute_position_vault_pda(self_program_id, position_id)`)
/// - User's source token holding for the collateral (authorized, initialized, owned by the
/// same Token Program as the token definition, with `TokenHolding.definition_id ==
/// Position.collateral_definition_id`)
/// - Token definition account for the collateral (matches `Position.collateral_definition_id`;
/// must be fungible, and its `program_owner` determines the Token Program used by the
/// chained `Transfer` call)
///
/// No collateralization check is needed because this instruction never increases debt.
DepositCollateral {
/// Amount of collateral tokens to deposit into the position vault.
amount: u128,
},
/// Withdraw `amount` collateral tokens from a position back to a user-controlled holding.
///
/// Required accounts (4):
Expand Down Expand Up @@ -186,10 +210,12 @@ pub fn verify_position_and_get_seed(
) -> PdaSeed {
let seed = compute_position_pda_seed(owner.account_id, collateral_definition_id);
let expected_id = AccountId::for_public_pda(&stablecoin_program_id, &seed);
assert_eq!(
position.account_id, expected_id,
"Position account ID does not match expected derivation"
);
if position.account_id != expected_id {
panic!(
"{ERR_POSITION_ACCOUNT_ID_MISMATCH}: provided {}, expected {}",
position.account_id, expected_id
);
}
seed
}

Expand All @@ -206,9 +232,11 @@ pub fn verify_position_vault_and_get_seed(
) -> PdaSeed {
let seed = compute_position_vault_pda_seed(position_id);
let expected_id = AccountId::for_public_pda(&stablecoin_program_id, &seed);
assert_eq!(
vault.account_id, expected_id,
"Position vault account ID does not match expected derivation"
);
if vault.account_id != expected_id {
panic!(
"{ERR_POSITION_VAULT_ACCOUNT_ID_MISMATCH}: provided {}, expected {}",
vault.account_id, expected_id
);
}
seed
}
37 changes: 37 additions & 0 deletions programs/stablecoin/methods/guest/src/bin/stablecoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,43 @@ mod stablecoin {
))
}

/// Deposit additional collateral tokens into an existing position vault.
///
/// # Errors
/// Returns the host program's panic-converted error if any precondition
/// fails (see
/// [`stablecoin_program::deposit_collateral::deposit_collateral`] for the
/// full list).
#[instruction]
pub fn deposit_collateral(
ctx: ProgramContext,
#[account(signer)]
owner: AccountWithMetadata,
#[account(mut)]
position: AccountWithMetadata,
#[account(mut)]
vault: AccountWithMetadata,
#[account(mut, signer)]
user_holding: AccountWithMetadata,
token_definition: AccountWithMetadata,
amount: u128,
) -> SpelResult {
let (post_states, chained_calls) =
stablecoin_program::deposit_collateral::deposit_collateral(
owner,
position,
vault,
user_holding,
token_definition,
ctx.self_program_id,
amount,
);
Ok(spel_framework::SpelOutput::execute(
post_states,
chained_calls,
))
}

/// Withdraw `amount` collateral tokens from an existing position back to a
/// user-controlled holding.
///
Expand Down
Loading
Loading