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
62 changes: 62 additions & 0 deletions bindings/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,65 @@ export async function simulateBet(
};
}
}

// ─── Keeper Intent Errors & Helpers (Issue #370) ─────────────────

export class IntentAlreadyConsumedError extends XelmaError {
constructor() {
super("Keeper intent has already been consumed", 79, "IntentAlreadyConsumed");
this.name = "IntentAlreadyConsumedError";
}
}

export class IntentExpiredError extends XelmaError {
constructor() {
super("Keeper intent has expired", 80, "IntentExpired");
this.name = "IntentExpiredError";
}
}

export class IntentRevokedError extends XelmaError {
constructor() {
super("Keeper intent has been revoked by the user", 81, "IntentRevoked");
this.name = "IntentRevokedError";
}
}

export class IntentKeeperMismatchError extends XelmaError {
constructor() {
super("Caller address is not the keeper specified in the intent", 82, "IntentKeeperMismatch");
this.name = "IntentKeeperMismatchError";
}
}

export class IntentScopeMismatchError extends XelmaError {
constructor() {
super("Intent scope does not match the attempted operation", 83, "IntentScopeMismatch");
this.name = "IntentScopeMismatchError";
}
}

export class KeeperNotRegisteredError extends XelmaError {
constructor() {
super("Keeper is not on the authorized registration list", 84, "KeeperNotRegistered");
this.name = "KeeperNotRegisteredError";
}
}

export type KeeperScopeTag = "Resolve" | "Claim" | "CreateNext";

export interface KeeperIntentPayload {
user: string;
keeper: string;
scope: KeeperScopeTag;
nonce: bigint;
expiresAtLedger: number;
}

/**
* Builds intent summary metadata for off-chain keeper service indexing.
*/
export function formatKeeperIntentSummary(intent: KeeperIntentPayload): string {
return `Intent[user=${intent.user}, keeper=${intent.keeper}, scope=${intent.scope}, nonce=${intent.nonce}, expiresAt=${intent.expiresAtLedger}]`;
}

89 changes: 82 additions & 7 deletions contracts/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::common::{
};
use crate::errors::ContractError;
use crate::types::{
AttestationConfig, AttestationConfigKey, DataKey, DataKeyCore, DataKeyExt,
AttestationConfig, AttestationConfigKey, DataKey, DataKeyCore, DataKeyScoped,
DeviationConfig, DeviationConfigKey, DeviationReferenceMode, HbGateConfig, HbGateKey,
OracleHeartbeatRecord, OracleQuorumConfig, PolicyAction, ProtocolHealthStatus, Round,
RuntimeMode, PENDING_WINNINGS_EXPIRY_KEY, PendingWinningsUpdatedAtKey,
Expand Down Expand Up @@ -691,6 +691,81 @@ pub fn _save_hb_config(env: &Env, config: &HbGateConfig) {
);
}

pub fn _enforce_heartbeat_health(env: &Env, oracle: &Address) -> Result<(), ContractError> {
let config = _load_hb_config(env);
if config.override_armed {
let mut new_config = config.clone();
new_config.override_armed = false;
_save_hb_config(env, &new_config);
#[allow(deprecated)]
env.events().publish(
(symbol_short!("oracle"), Symbol::new(env, "hb_override")),
(oracle.clone(),),
);
return Ok(());
}

let heartbeat_key = DataKeyCore::OracleHeartbeat;
_extend_persistent_ttl(env, &heartbeat_key);
let record: OracleHeartbeatRecord = match env.storage().persistent().get(&heartbeat_key) {
Some(r) => r,
None => {
_emit_action_rejected(
env,
oracle,
symbol_short!("resolve"),
ContractError::OracleHeartbeatUnhealthy,
);
return Err(ContractError::OracleHeartbeatUnhealthy);
}
};

let threshold_key = DataKeyCore::OracleStaleThreshold;
_extend_persistent_ttl(env, &threshold_key);
let stale_threshold: u64 = env
.storage()
.persistent()
.get(&threshold_key)
.unwrap_or(DEFAULT_ORACLE_STALE_THRESHOLD);

let current_time = env.ledger().timestamp();
let is_fresh = current_time <= record.timestamp.saturating_add(stale_threshold);

match record.status {
0 => {
if is_fresh {
return Ok(());
}
}
1 => {
if is_fresh && !config.strict_mode {
return Ok(());
}
}
_ => {}
}

if (record.status == 0 || record.status == 1) && !config.strict_mode {
let within_grace = current_time
<= record
.timestamp
.saturating_add(stale_threshold)
.saturating_add(config.grace_seconds);

if within_grace {
return Ok(());
}
}

_emit_action_rejected(
env,
oracle,
symbol_short!("resolve"),
ContractError::OracleHeartbeatUnhealthy,
);
Err(ContractError::OracleHeartbeatUnhealthy)
}

/// Records an oracle heartbeat (oracle only).
pub fn update_oracle_heartbeat(env: Env, status: u32) -> Result<(), ContractError> {
_require_supported_schema(&env)?;
Expand Down Expand Up @@ -1000,11 +1075,11 @@ pub fn _is_ttl_touch_allowed(key: &DataKeyCore) -> bool {
| DataKeyCore::MigratedToV3
| DataKeyCore::ArchiveRetention
| DataKeyCore::RoundTemplate
| DataKeyCore::Ext(DataKeyExt::LeaderboardWins)
| DataKeyCore::Ext(DataKeyExt::LeaderboardStreak)
| DataKeyCore::Ext(DataKeyExt::SeasonId)
| DataKeyCore::Ext(DataKeyExt::SeasonLeaderboardWins)
| DataKeyCore::Ext(DataKeyExt::SeasonLeaderboardStreak)
| DataKeyCore::LeaderboardWins
| DataKeyCore::LeaderboardStreak
| DataKeyCore::SeasonId
| DataKeyCore::SeasonLeaderboardWins
| DataKeyCore::SeasonLeaderboardStreak
| DataKeyCore::LastRoundId
| DataKeyCore::OracleRotationProposal
| DataKeyCore::MintLimitConfig
Expand Down Expand Up @@ -1207,7 +1282,7 @@ pub fn reclaim_expired_pending_winnings(env: Env, user: Address) -> Result<i128,
}

// Read pending winnings.
let pending_key = DataKey::PendingWinnings(user.clone());
let pending_key = DataKeyScoped::PendingWinnings(user.clone());
let pending: i128 = env.storage().persistent().get(&pending_key).unwrap_or(0);
if pending == 0 {
_emit_action_rejected(
Expand Down
12 changes: 4 additions & 8 deletions contracts/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ extern crate alloc;
use alloc::vec::Vec as StdVec;
use crate::errors::ContractError;
use crate::types::{
ConfigChangeKind, ConfigChangePayload, DataKey, PendingWinningsUpdatedAtKey, Round, RoundPhase,
ConfigChangeKind, ConfigChangePayload, DataKey, DataKeyCore, DataKeyScoped,
PendingWinningsUpdatedAtKey, Round, RoundPhase,
};
use soroban_sdk::{symbol_short, Address, Env, IntoVal, Symbol, Val, Vec};

pub const DEFAULT_PENDING_WINNINGS_EXPIRY: u32 = 0; // 0 = disabled
pub const MIN_PENDING_WINNINGS_EXPIRY: u32 = 128; // ~10 min at 5s ledgers
pub const MAX_PENDING_WINNINGS_EXPIRY: u32 = 1_000_000; // ~58 days
use crate::types::{ConfigChangeKind, ConfigChangePayload, DataKeyCore, DataKeyScoped, Round, RoundPhase};
use soroban_sdk::{symbol_short, Address, Env, IntoVal, Symbol, Val, Vec};
pub const DEFAULT_GOV_PROPOSAL_TTL_LEDGERS: u32 = 17280; // ~24h at 5s ledgers

// ─── DataKey overflow workaround (DataKey has 51 variants, XDR limit is 50) ──
// Moved out of DataKey to get under the limit.
Expand Down Expand Up @@ -103,10 +103,7 @@ pub const MIN_TWAP_WINDOW_SAMPLES: u32 = 2;
/// Maximum trailing samples configurable — bounds the ring buffer's storage cost.
pub const MAX_TWAP_WINDOW_SAMPLES: u32 = 64;

/// Bumps/extends the TTL of the given persistent storage key if its remaining TTL
/// is less than the threshold. Enforces rent policy (Issue #142).
pub fn _extend_persistent_ttl<K: IntoVal<Env, Val>>(env: &Env, key: &K) {
pub fn _extend_persistent_ttl<T: IntoVal<Env, Val>>(env: &Env, key: &T) {
if env.storage().persistent().has(key) {
env.storage()
.persistent()
Expand Down Expand Up @@ -152,8 +149,7 @@ pub fn payout_mul(a: i128, b: i128) -> Result<i128, ContractError> {

/// Accumulates `amount` into a user's pending winnings, enforcing the cap if set (Issue #120).
pub fn _accumulate_pending(env: &Env, user: Address, amount: i128) -> Result<(), ContractError> {
let key = DataKey::PendingWinnings(user.clone());
let key = DataKeyScoped::PendingWinnings(user);
let key = DataKeyScoped::PendingWinnings(user.clone());
let existing: i128 = env.storage().persistent().get(&key).unwrap_or(0);
let new_pending = payout_add(existing, amount)?;

Expand Down
41 changes: 27 additions & 14 deletions contracts/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
// SPDX-License-Identifier: MIT
use crate::admin::{_ensure_normal_mode, _ensure_not_paused, _require_supported_schema};
use crate::common::{
_emit_action_rejected, _emit_config_updated, _extend_persistent_ttl, _set_balance, balance,
payout_add, BPS_DENOMINATOR, CONFIG_TIMELOCK_LEDGERS, DEFAULT_ARCHIVE_RETENTION,
DEFAULT_BET_WINDOW_LEDGERS, DEFAULT_CLOSE_BUFFER_LEDGERS, DEFAULT_MAX_PRECISION_PARTICIPANTS,
DEFAULT_ORACLE_STALE_THRESHOLD, DEFAULT_ORACLE_TIMESTAMP_SKEW, DEFAULT_RUN_WINDOW_LEDGERS,
MAX_ARCHIVE_RETENTION, MAX_BET_WINDOW_LEDGERS, MAX_CLOSE_BUFFER_LEDGERS, MAX_MIN_PARTICIPANTS,
MAX_ORACLE_DEVIATION_BPS, MAX_ORACLE_STALE_THRESHOLD, MAX_ORACLE_TIMESTAMP_SKEW,
MAX_PRECISION_PARTICIPANTS_LIMIT, MAX_PROTOCOL_FEE_BPS, MAX_RUN_WINDOW_LEDGERS,
MAX_START_PRICE, MIN_ARCHIVE_RETENTION, MIN_CAP_VALUE, MIN_ORACLE_STALE_THRESHOLD,
MIN_ORACLE_TIMESTAMP_SKEW, MIN_START_PRICE,
_emit_action_rejected, _emit_config_updated, _extend_persistent_ttl, _extend_ttl_symbol,
_set_balance, balance, payout_add, BPS_DENOMINATOR, CONFIG_TIMELOCK_LEDGERS,
DEFAULT_ARCHIVE_RETENTION, DEFAULT_BET_WINDOW_LEDGERS, DEFAULT_CLOSE_BUFFER_LEDGERS,
DEFAULT_DISPUTE_LEDGERS, DEFAULT_MAX_PRECISION_PARTICIPANTS, DEFAULT_ORACLE_STALE_THRESHOLD,
DEFAULT_PENDING_WINNINGS_EXPIRY, DEFAULT_RUN_WINDOW_LEDGERS, MAX_ARCHIVE_RETENTION,
MAX_BET_WINDOW_LEDGERS, MAX_CLOSE_BUFFER_LEDGERS, MAX_DISPUTE_LEDGERS, MAX_MIN_PARTICIPANTS,
MAX_ORACLE_DEVIATION_BPS, MAX_ORACLE_STALE_THRESHOLD, MAX_PENDING_WINNINGS_EXPIRY,
MAX_PRECISION_PARTICIPANTS_LIMIT, MAX_PROTOCOL_FEE_BPS, MAX_RUN_WINDOW_LEDGERS,
MAX_START_PRICE, MIN_ARCHIVE_RETENTION, MIN_CAP_VALUE, MIN_ORACLE_STALE_THRESHOLD,
DEFAULT_ORACLE_TIMESTAMP_SKEW, DEFAULT_PENDING_WINNINGS_EXPIRY, DEFAULT_RUN_WINDOW_LEDGERS,
MAX_ARCHIVE_RETENTION, MAX_BET_WINDOW_LEDGERS, MAX_CLOSE_BUFFER_LEDGERS, MAX_DISPUTE_LEDGERS,
MAX_MIN_PARTICIPANTS, MAX_ORACLE_DEVIATION_BPS, MAX_ORACLE_STALE_THRESHOLD,
MAX_ORACLE_TIMESTAMP_SKEW, MAX_PENDING_WINNINGS_EXPIRY, MAX_PRECISION_PARTICIPANTS_LIMIT,
MAX_PROTOCOL_FEE_BPS, MAX_RUN_WINDOW_LEDGERS, MAX_START_PRICE, MIN_ARCHIVE_RETENTION,
MIN_CAP_VALUE, MIN_ORACLE_STALE_THRESHOLD, MIN_ORACLE_TIMESTAMP_SKEW,
MIN_PENDING_WINNINGS_EXPIRY, MIN_START_PRICE,
};
use crate::errors::ContractError;
Expand Down Expand Up @@ -847,6 +839,7 @@ pub fn set_early_cashout_bps(env: Env, bps: Option<u32>) -> Result<(), ContractE
}

let key = DataKeyCore::EarlyCashoutBps;
let old_bps: Option<u32> = env.storage().persistent().get(&key);
if let Some(v) = bps {
env.storage().persistent().set(&key, &v);
_extend_persistent_ttl(&env, &key);
Expand Down Expand Up @@ -1272,6 +1265,9 @@ pub fn _current_config_payload(env: &Env, kind: &ConfigChangeKind) -> ConfigChan
.unwrap_or(DEFAULT_DISPUTE_LEDGERS),
),
ConfigChangeKind::FeeModel => ConfigChangePayload::FeeModel(_read_fee_model(env)),
ConfigChangeKind::EarlyCashoutBps => {
ConfigChangePayload::EarlyCashoutBps(get_early_cashout_bps(env.clone()))
}
}
}

Expand Down Expand Up @@ -1413,6 +1409,8 @@ pub fn _apply_config_payload(
) => {
_validate_oracle_timestamp_skew(*seconds)?;
env.storage().instance().set(&symbol_short!("otskew"), seconds);
}
(
ConfigChangeKind::PendingWinningsExpiry,
ConfigChangePayload::PendingWinningsExpiry(ledgers),
) => {
Expand Down Expand Up @@ -1517,6 +1515,21 @@ pub fn _apply_config_payload(
env.storage().persistent().set(&key, max);
_extend_persistent_ttl(env, &key);
}
(ConfigChangeKind::EarlyCashoutBps, ConfigChangePayload::EarlyCashoutBps(bps)) => {
if let Some(b) = bps {
if i128::from(*b) > crate::common::BPS_DENOMINATOR {
return Err(ContractError::InvalidProtocolFeeBps);
}
}
let key = DataKeyCore::EarlyCashoutBps;
if let Some(v) = bps {
env.storage().persistent().set(&key, v);
_extend_persistent_ttl(env, &key);
} else {
env.storage().persistent().remove(&key);
}
}
_ => return Err(ContractError::UnsupportedSchemaVersion),
}
_emit_config_updated(env, kind.clone(), old_value, payload.clone());
Ok(())
Expand Down
Loading