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
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,10 @@ pub enum StreamError {
///
/// Returned by: `get_position_metadata`.
PositionNotFound = 49,
/// The arbiter cannot be changed while a dispute is open. A sender who could
/// swap the arbiter mid-dispute could replace the decider with someone who
/// rules in their favour.
ArbiterLocked = 50,
}

/// Type alias mapping `ContractError` to `StreamError` for off-chain testing and SDK callers.
Expand Down Expand Up @@ -364,6 +368,7 @@ impl TryFrom<u32> for StreamError {
47 => Ok(StreamError::DeadlineExpired),
48 => Ok(StreamError::InsufficientOutput),
49 => Ok(StreamError::PositionNotFound),
50 => Ok(StreamError::ArbiterLocked),
_ => Err(()),
}
}
Expand Down Expand Up @@ -439,6 +444,7 @@ pub(crate) mod test_diagnostics {
StreamError::DeadlineExpired => "DeadlineExpired",
StreamError::InsufficientOutput => "InsufficientOutput",
StreamError::PositionNotFound => "PositionNotFound",
StreamError::ArbiterLocked => "ArbiterLocked",
}
}
}
Expand Down Expand Up @@ -510,7 +516,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 +610,7 @@ pub(crate) mod test_diagnostics {
(StreamError::DeadlineExpired, "DeadlineExpired", 47),
(StreamError::InsufficientOutput, "InsufficientOutput", 48),
(StreamError::PositionNotFound, "PositionNotFound", 49),
(StreamError::ArbiterLocked, "ArbiterLocked", 50),
];

#[test]
Expand Down Expand Up @@ -636,7 +643,8 @@ 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(()));
// 50 is now taken by ArbiterLocked, so probe the next free code.
assert_eq!(ContractError::try_from(51), Err(()));
assert_eq!(ContractError::try_from(100), Err(()));
assert_eq!(ContractError::try_from(u32::MAX), Err(()));
}
Expand Down
14 changes: 14 additions & 0 deletions contracts/stream_contract/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,20 @@ pub struct StreamRateModifiedEvent {
pub timestamp: u64,
}

/// Emitted when a stream's arbiter is set or replaced.
///
/// The arbiter is the only address that can resolve a cancellation dispute, so
/// who it is matters as much as the dispute itself. Emitting the change makes
/// "the arbiter was always that address" auditable.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StreamArbiterSetEvent {
pub stream_id: u64,
pub sender: Address,
pub arbiter: Option<Address>,
pub timestamp: u64,
}

/// Emitted when a cancellation dispute is initiated (for #1319).
///
/// Topic: `("dispute_requested", stream_id)`
Expand Down
65 changes: 63 additions & 2 deletions contracts/stream_contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ use events::{
FeeConfigUpdatedEvent, HybridCliffStreamCreatedEvent, InitializedEvent,
MilestoneConditionUnlockedEvent, ProtocolFeeCollectedEvent, ProtocolPauseStatusEvent,
RecipientTransferredEvent, StateMigratedEvent, StepVestingStreamCreatedEvent,
StreamCancelledEvent, StreamClosedEvent, StreamCompletedEvent, StreamCreatedEvent,
StreamPausedEvent, StreamPositionCreatedEvent, StreamPositionSettledEvent,
StreamArbiterSetEvent, StreamCancelledEvent, StreamClosedEvent, StreamCompletedEvent,
StreamCreatedEvent, StreamPausedEvent, StreamPositionCreatedEvent, StreamPositionSettledEvent,
StreamPositionUpdatedEvent, StreamRateModifiedEvent, StreamRefueledEvent, StreamResumedEvent,
StreamToppedUpEvent, TokensWithdrawnEvent,
};
Expand Down Expand Up @@ -2924,6 +2924,67 @@ impl StreamContract {
Ok(new_end_time)
}

/// Set or replace the arbiter that resolves a cancellation dispute.
///
/// Until this existed the dispute subsystem was unreachable: every
/// constructor wrote `arbiter: None`, nothing ever changed it, and
/// `request_dispute` therefore always failed with `DisputeNotSupported`.
/// The tests reached into storage to inject an arbiter because no supported
/// path existed (#1897).
///
/// Only the stream's sender may name the arbiter, and only before a dispute
/// is open: swapping the decider mid-dispute would let a sender pick
/// someone who rules in their favour, so it is refused outright
/// (`ArbiterLocked`) rather than silently ignored.
///
/// Passing `None` detaches the arbiter, which makes the stream
/// non-disputable again.
///
/// # Errors
/// - `StreamNotFound` — no stream exists with `stream_id`.
/// - `Unauthorized` — the caller is not the stream's sender.
/// - `StreamInactive` — the stream has already ended.
/// - `ArbiterLocked` — a dispute is already open on this stream.
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 stream.dispute_status != DisputeStatus::None {
return Err(StreamError::ArbiterLocked);
}

// An arbiter that is the contract itself (or the stream's parties)
// would make "arbiter resolves" a no-op or a self-dealing shortcut.
if let Some(ref who) = arbiter {
if *who == env.current_contract_address() || *who == stream.sender {
return Err(StreamError::Unauthorized);
}
}

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

env.events().publish(
(Symbol::new(&env, "stream_arbiter_set"), stream_id),
StreamArbiterSetEvent {
stream_id,
sender,
arbiter,
timestamp: env.ledger().timestamp(),
},
);

Ok(())
}

// ─── Allowance-Based Streams (Feature #1318) ──────────────────────────────

/// Create a payment stream funded by allowance instead of upfront transfer.
Expand Down
78 changes: 78 additions & 0 deletions contracts/stream_contract/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8241,3 +8241,81 @@ fn test_withdraw_and_swap_rolls_back_when_the_router_fails() {
);
assert_eq!(token::Client::new(&env, &target).balance(&recipient), 0);
}

#[test]
fn test_coverage_set_stream_arbiter_makes_the_stream_disputable() {
let env = Env::default();
env.mock_all_auths();
let (token, _) = create_token(&env);
let client = create_contract(&env);
let sender = Address::generate(&env);
let recipient = Address::generate(&env);
let arbiter = Address::generate(&env);
mint(&env, &token, &sender, 1_000);

let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000);

// Before the arbiter is set there is nobody to resolve a dispute.
assert_eq!(
client.try_request_dispute(&sender, &id),
Err(Ok(StreamError::DisputeNotSupported))
);

client.set_stream_arbiter(&sender, &id, &Some(arbiter.clone()));
assert_eq!(client.get_stream(&id).unwrap().arbiter, Some(arbiter));

// The dispute path is now reachable through the public API alone.
client.request_dispute(&sender, &id);
assert_eq!(
client.get_stream(&id).unwrap().dispute_status,
DisputeStatus::Requested
);
}

#[test]
fn test_coverage_set_stream_arbiter_is_the_senders_call_only() {
let env = Env::default();
env.mock_all_auths();
let (token, _) = create_token(&env);
let client = create_contract(&env);
let sender = Address::generate(&env);
let recipient = Address::generate(&env);
mint(&env, &token, &sender, 1_000);

let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000);

assert_eq!(
client.try_set_stream_arbiter(&recipient, &id, &Some(Address::generate(&env))),
Err(Ok(StreamError::Unauthorized))
);
assert_eq!(
client.try_set_stream_arbiter(&sender, &id, &Some(sender.clone())),
Err(Ok(StreamError::Unauthorized))
);
// The contract itself can never be the arbiter.
assert_eq!(
client.try_set_stream_arbiter(&sender, &id, &Some(client.address.clone())),
Err(Ok(StreamError::Unauthorized))
);
}

#[test]
fn test_coverage_set_stream_arbiter_is_locked_once_a_dispute_is_open() {
let env = Env::default();
env.mock_all_auths();
let (token, _) = create_token(&env);
let client = create_contract(&env);
let sender = Address::generate(&env);
let recipient = Address::generate(&env);
mint(&env, &token, &sender, 1_000);

let id = client.create_stream(&sender, &recipient, &token, &1_000, &1_000);
client.set_stream_arbiter(&sender, &id, &Some(Address::generate(&env)));
client.request_dispute(&sender, &id);

// Swapping the decider mid-dispute would let the sender choose the verdict.
assert_eq!(
client.try_set_stream_arbiter(&sender, &id, &Some(Address::generate(&env))),
Err(Ok(StreamError::ArbiterLocked))
);
}
Loading