Skip to content
Closed
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
12 changes: 10 additions & 2 deletions contracts/stream_contract/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,11 @@ pub enum StreamError {
///
/// Returned by: `get_position_metadata`.
PositionNotFound = 49,
/// The stream has an arbiter configured, so the sender cannot cancel it
/// unilaterally. Open a dispute and let the arbiter resolve it instead.
///
/// Returned by: `cancel_stream`.
ArbiterConfigured = 50,
}

/// Type alias mapping `ContractError` to `StreamError` for off-chain testing and SDK callers.
Expand Down Expand Up @@ -364,6 +369,7 @@ impl TryFrom<u32> for StreamError {
47 => Ok(StreamError::DeadlineExpired),
48 => Ok(StreamError::InsufficientOutput),
49 => Ok(StreamError::PositionNotFound),
50 => Ok(StreamError::ArbiterConfigured),
_ => Err(()),
}
}
Expand Down Expand Up @@ -439,6 +445,7 @@ pub(crate) mod test_diagnostics {
StreamError::DeadlineExpired => "DeadlineExpired",
StreamError::InsufficientOutput => "InsufficientOutput",
StreamError::PositionNotFound => "PositionNotFound",
StreamError::ArbiterConfigured => "ArbiterConfigured",
}
}
}
Expand Down Expand Up @@ -510,7 +517,7 @@ pub(crate) mod test_diagnostics {
use std::string::ToString;

/// (variant, identifier, documented numeric code) for every variant.
const ALL_VARIANTS: [(StreamError, &str, u32); 49] = [
const ALL_VARIANTS: [(StreamError, &str, u32); 50] = [
(StreamError::InvalidAmount, "InvalidAmount", 1),
(StreamError::StreamNotFound, "StreamNotFound", 2),
(StreamError::Unauthorized, "Unauthorized", 3),
Expand Down Expand Up @@ -604,6 +611,7 @@ pub(crate) mod test_diagnostics {
(StreamError::DeadlineExpired, "DeadlineExpired", 47),
(StreamError::InsufficientOutput, "InsufficientOutput", 48),
(StreamError::PositionNotFound, "PositionNotFound", 49),
(StreamError::ArbiterConfigured, "ArbiterConfigured", 50),
];

#[test]
Expand Down Expand Up @@ -636,7 +644,7 @@ pub(crate) mod test_diagnostics {

// Unknown error codes must return Err(())
assert_eq!(ContractError::try_from(0), Err(()));
assert_eq!(ContractError::try_from(50), Err(()));
assert_eq!(ContractError::try_from(51), Err(()));
assert_eq!(ContractError::try_from(100), Err(()));
assert_eq!(ContractError::try_from(u32::MAX), Err(()));
}
Expand Down
63 changes: 63 additions & 0 deletions contracts/stream_contract/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,3 +944,66 @@ pub fn emit_stream_position_settled(env: &Env, event: StreamPositionSettledEvent
event,
);
}

/// Emitted when a stream's arbiter is configured, replaced, or cleared.
///
/// Topic: `("arbiter_updated", stream_id)`
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArbiterUpdatedEvent {
pub stream_id: u64,
pub sender: Address,
/// The newly configured arbiter, or `None` when the slot was cleared.
pub arbiter: Option<Address>,
pub timestamp: u64,
}

/// Emitted when a stream's yield opt-in flag is toggled.
///
/// Topic: `("yield_preference_updated", stream_id)`
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct YieldPreferenceUpdatedEvent {
pub stream_id: u64,
pub sender: Address,
pub yield_enabled: bool,
pub timestamp: u64,
}

/// Emits an `arbiter_updated` event indexed by `stream_id`.
///
/// # Event topic
/// `("arbiter_updated", stream_id: u64)`.
///
/// # Emission trigger
/// `set_stream_arbiter`, after the new arbiter (or `None`) has been persisted.
///
/// # Parameters
/// - `env` — the Soroban environment to publish into.
/// - `event` — the [`ArbiterUpdatedEvent`] payload: stream_id, sender, arbiter,
/// and timestamp.
pub fn emit_arbiter_updated(env: &Env, event: ArbiterUpdatedEvent) {
env.events().publish(
(Symbol::new(env, "arbiter_updated"), event.stream_id),
event,
);
}

/// Emits a `yield_preference_updated` event indexed by `stream_id`.
///
/// # Event topic
/// `("yield_preference_updated", stream_id: u64)`.
///
/// # Emission trigger
/// `set_stream_yield`, after the flag has been persisted.
///
/// # Parameters
/// - `env` — the Soroban environment to publish into.
/// - `event` — the [`YieldPreferenceUpdatedEvent`] payload: stream_id, sender,
/// the new flag value, and timestamp.
pub fn emit_yield_preference_updated(env: &Env, event: YieldPreferenceUpdatedEvent) {
env.events().publish(
(Symbol::new(env, "yield_preference_updated"), event.stream_id),
event,
);
}
113 changes: 110 additions & 3 deletions contracts/stream_contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,18 @@ use soroban_sdk::{

use errors::StreamError;
use events::{
emit_admin_transferred, emit_contract_upgraded, emit_cross_asset_withdrawal_executed,
emit_admin_transferred, emit_arbiter_updated, emit_contract_upgraded,
emit_cross_asset_withdrawal_executed, emit_yield_preference_updated,
emit_emergency_guardian_updated, emit_fee_collected, emit_fee_config_updated,
emit_hybrid_cliff_stream_created, emit_initialized, emit_protocol_fee_collected,
emit_protocol_pause_status, emit_protocol_paused, emit_state_migrated,
emit_step_vesting_stream_created, emit_stream_cancelled, emit_stream_closed,
emit_stream_completed, emit_stream_created, emit_stream_paused, emit_stream_position_created,
emit_stream_position_settled, emit_stream_position_updated, emit_stream_resumed,
emit_stream_topped_up, emit_tokens_withdrawn, AdminTransferredEvent,
AllowanceStreamCreatedEvent, ContractUpgradedEvent, CrossAssetWithdrawalExecutedEvent,
DisputeRequestedEvent, DisputeResolvedEvent, EmergencyGuardianUpdatedEvent, FeeCollectedEvent,
AllowanceStreamCreatedEvent, ArbiterUpdatedEvent, ContractUpgradedEvent,
CrossAssetWithdrawalExecutedEvent, DisputeRequestedEvent, DisputeResolvedEvent,
EmergencyGuardianUpdatedEvent, FeeCollectedEvent, YieldPreferenceUpdatedEvent,
FeeConfigUpdatedEvent, HybridCliffStreamCreatedEvent, InitializedEvent,
MilestoneConditionUnlockedEvent, ProtocolFeeCollectedEvent, ProtocolPauseStatusEvent,
RecipientTransferredEvent, StateMigratedEvent, StepVestingStreamCreatedEvent,
Expand Down Expand Up @@ -2185,6 +2187,13 @@ impl StreamContract {
Self::validate_stream_ownership(&stream, &sender)?;
Self::validate_stream_active(&stream)?;

// With an arbiter configured, cancellation is a two-party decision:
// the sender has to open a dispute and the arbiter has to approve it.
// Otherwise the arbiter slot would be decorative.
if stream.arbiter.is_some() {
return Err(StreamError::ArbiterConfigured);
}

let now = env.ledger().timestamp();
let accrued_amount = Self::calculate_claimable(&stream, now);

Expand Down Expand Up @@ -3155,6 +3164,104 @@ impl StreamContract {
Ok(())
}

/// Configure, replace, or clear the arbiter of a stream (sender action).
///
/// The arbiter is what makes the dispute path reachable: once set, the
/// sender can no longer cancel unilaterally (`cancel_stream` returns
/// [`StreamError::ArbiterConfigured`]) and must call `request_dispute`
/// instead, leaving `resolve_dispute` to the arbiter. Passing `None`
/// restores unilateral cancellation.
///
/// The arbiter can only change while no dispute is open, so a pending
/// dispute cannot be re-pointed at a different arbiter. Neither party to
/// the stream can arbitrate it.
///
/// A dispute already open on the stream freezes this slot until it is
/// resolved, so the sender cannot swap in a friendlier arbiter mid-dispute;
/// that attempt is rejected as unauthorised.
///
/// # Errors
/// - `StreamNotFound` — no stream exists with `stream_id`.
/// - `Unauthorized` — caller is not the stream's sender, or a dispute is
/// already open on this stream.
/// - `StreamInactive` — stream is inactive or cancelled.
/// - `InvalidAmount` — `arbiter` is the stream's sender or recipient.
pub fn set_stream_arbiter(
env: Env,
sender: Address,
stream_id: u64,
arbiter: Option<Address>,
) -> Result<(), StreamError> {
sender.require_auth();

let mut stream = load_stream(&env, stream_id)?;
Self::validate_stream_ownership(&stream, &sender)?;
Self::validate_stream_active(&stream)?;

if !matches!(stream.dispute_status, DisputeStatus::None) {
return Err(StreamError::Unauthorized);
}
if let Some(ref configured) = arbiter {
if *configured == stream.sender || *configured == stream.recipient {
return Err(StreamError::InvalidAmount);
}
}

stream.arbiter = arbiter.clone();
save_stream(&env, stream_id, &stream);

emit_arbiter_updated(
&env,
ArbiterUpdatedEvent {
stream_id,
sender,
arbiter,
timestamp: env.ledger().timestamp(),
},
);

Ok(())
}

/// Opt a stream in or out of yield generation (sender action).
///
/// `yield_enabled` is per-stream state that the sender controls; without
/// this entrypoint the flag could only ever be `false`. It records the
/// opt-in for a yield adapter to act on and deliberately stays independent
/// of the escrow accounting: nothing here moves tokens.
///
/// # Errors
/// - `StreamNotFound` — no stream exists with `stream_id`.
/// - `Unauthorized` — caller is not the stream's sender.
/// - `StreamInactive` — stream is inactive or cancelled.
pub fn set_stream_yield(
env: Env,
sender: Address,
stream_id: u64,
enabled: bool,
) -> Result<(), StreamError> {
sender.require_auth();

let mut stream = load_stream(&env, stream_id)?;
Self::validate_stream_ownership(&stream, &sender)?;
Self::validate_stream_active(&stream)?;

stream.yield_enabled = enabled;
save_stream(&env, stream_id, &stream);

emit_yield_preference_updated(
&env,
YieldPreferenceUpdatedEvent {
stream_id,
sender,
yield_enabled: enabled,
timestamp: env.ledger().timestamp(),
},
);

Ok(())
}

// ─── Internal Helpers ─────────────────────────────────────────────────────

/// Calculates the protocol fee and distributes it to configured recipients.
Expand Down
Loading
Loading