Skip to content
Merged
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
17 changes: 17 additions & 0 deletions scripts/verify.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,23 @@
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SMARTCONTRACT_DIR="${SCRIPT_DIR}/../smartcontract"

# ---------------------------------------------------------------------------
# Static analysis: run cargo clippy on the smart contract
# ---------------------------------------------------------------------------
echo "============================================"
echo "Running cargo clippy on smartcontract"
echo "============================================"

if ! command -v cargo &>/dev/null; then
echo "ERROR: cargo not found. Install Rust toolchain to run clippy."
exit 1
fi

(cd "${SMARTCONTRACT_DIR}" && cargo clippy -- -D warnings)
echo " PASS cargo clippy passed"
echo ""
CONFIG_FILE="${SCRIPT_DIR}/config/testnet.env"
CONTRACT_ID=""

Expand Down
13 changes: 12 additions & 1 deletion smartcontract/src/htlc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::crypto;
use crate::error::Error;
use crate::storage;
use crate::types::{HTLCStatus, HashAlgorithm, OptMultiSig, HTLC};
use soroban_sdk::{Address, Bytes, BytesN, Env};
use soroban_sdk::{symbol_short, Address, Bytes, BytesN, Env};

/// Creates a new HTLC using SHA256 as the hash algorithm (default, Bitcoin-compatible).
pub fn create_htlc(
Expand Down Expand Up @@ -34,6 +34,7 @@ pub fn create_htlc(
///
/// Callers that need Ethereum-compatible swaps should pass `HashAlgorithm::Keccak256`.
/// The `claim_htlc` call for this HTLC must use the same algorithm.
#[allow(clippy::too_many_arguments)]
pub fn create_htlc_with_algorithm(
env: &Env,
sender: &Address,
Expand Down Expand Up @@ -108,6 +109,11 @@ pub fn claim_htlc(env: &Env, htlc_id: u64, secret: Bytes) -> Result<(), Error> {
htlc.secret = Some(secret);
storage::write_htlc(env, htlc_id, &htlc);

env.events().publish(
(symbol_short!("htlc"), symbol_short!("claimed")),
(htlc_id, htlc.receiver),
);

Ok(())
}

Expand Down Expand Up @@ -137,6 +143,11 @@ pub fn refund_htlc(env: &Env, htlc_id: u64, sender: &Address) -> Result<(), Erro
htlc.status = HTLCStatus::Refunded;
storage::write_htlc(env, htlc_id, &htlc);

env.events().publish(
(symbol_short!("htlc"), symbol_short!("refunded")),
(htlc_id, htlc.sender),
);

Ok(())
}

Expand Down
31 changes: 16 additions & 15 deletions smartcontract/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![no_std]
#![allow(clippy::too_many_arguments)]

mod crypto;
mod error;
Expand All @@ -16,8 +17,8 @@ use soroban_sdk::{contract, contractimpl, Address, Bytes, BytesN, Env, String, V

use crate::error::Error;
use crate::types::{
AdvancedOrderType, Chain, ChainProof, CrossChainSwap, GovernanceConfig, GovernanceProposal,
HTLCStatus, HashAlgorithm, LiquidityPool, LiquidityPosition, OrderExecutionCondition,
AdvancedOrderConfig, Chain, ChainProof, CrossChainSwap, GovernanceConfig, GovernanceProposal,
HTLCStatus, HashAlgorithm, LiquidityPool, LiquidityPosition, OptMultiSig, OptOrderExecution,
ReferralRecord, StorageMetrics, SwapOrder, VoteChoice, HTLC,
};

Expand Down Expand Up @@ -206,9 +207,12 @@ impl ChainBridge {
storage::get_storage_metrics(&env)
}

/// Cleanup expired HTLCs
pub fn cleanup_expired_htlcs(env: Env) -> u64 {
storage::cleanup_expired_htlcs(&env)
/// Cleanup expired HTLCs.
///
/// `limit` caps how many entries are removed per call; pass `0` to use the
/// default batch size. Returns the number of HTLCs actually cleaned up.
pub fn cleanup_expired_htlcs(env: Env, limit: u32) -> u64 {
storage::cleanup_expired_htlcs(&env, limit)
}

/// Mark HTLC for cleanup
Expand Down Expand Up @@ -276,12 +280,11 @@ impl ChainBridge {
to_amount,
expiry,
min_fill_amount,
AdvancedOrderType::Market,
None,
crate::types::AdvancedOrderType::Market,
OptOrderExecution::None,
)
}

#[allow(clippy::too_many_arguments)]
pub fn create_advanced_order(
env: Env,
creator: Address,
Expand All @@ -292,9 +295,7 @@ impl ChainBridge {
from_amount: i128,
to_amount: i128,
expiry: u64,
min_fill_amount: i128,
order_type: AdvancedOrderType,
execution: Option<OrderExecutionCondition>,
config: AdvancedOrderConfig,
) -> Result<u64, Error> {
creator.require_auth();
order::create_advanced_order(
Expand All @@ -307,9 +308,9 @@ impl ChainBridge {
from_amount,
to_amount,
expiry,
min_fill_amount,
order_type,
execution,
config.min_fill_amount,
config.order_type,
config.execution,
)
}

Expand Down Expand Up @@ -344,7 +345,7 @@ impl ChainBridge {
order_id: u64,
to_amount: i128,
expiry: u64,
execution: Option<OrderExecutionCondition>,
execution: OptOrderExecution,
) -> Result<(), Error> {
creator.require_auth();
order::amend_order(&env, &creator, order_id, to_amount, expiry, execution)
Expand Down
10 changes: 5 additions & 5 deletions smartcontract/src/order.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::error::Error;
use crate::storage;
use crate::types::{AdvancedOrderType, Chain, OrderExecutionCondition, SwapOrder, SwapStatus};
use crate::types::{AdvancedOrderType, Chain, OptOrderExecution, SwapOrder, SwapStatus};
use soroban_sdk::{Address, Env, String};

#[allow(clippy::too_many_arguments)]
Expand Down Expand Up @@ -32,7 +32,7 @@ pub fn create_order(
expiry,
from_amount,
AdvancedOrderType::Market,
None,
OptOrderExecution::None,
)
}

Expand All @@ -57,7 +57,7 @@ pub fn create_order_with_min_fill(
expiry: u64,
min_fill_amount: i128,
order_type: AdvancedOrderType,
execution: Option<OrderExecutionCondition>,
execution: OptOrderExecution,
) -> Result<u64, Error> {
if storage::is_paused(env) {
return Err(Error::Paused);
Expand Down Expand Up @@ -115,7 +115,7 @@ pub fn create_advanced_order(
expiry: u64,
min_fill_amount: i128,
order_type: AdvancedOrderType,
execution: Option<OrderExecutionCondition>,
execution: OptOrderExecution,
) -> Result<u64, Error> {
create_order_with_min_fill(
env,
Expand Down Expand Up @@ -258,7 +258,7 @@ pub fn amend_order(
order_id: u64,
to_amount: i128,
expiry: u64,
execution: Option<OrderExecutionCondition>,
execution: OptOrderExecution,
) -> Result<(), Error> {
let mut order = storage::read_order(env, order_id).ok_or(Error::OrderNotFound)?;
if order.creator != *creator {
Expand Down
49 changes: 41 additions & 8 deletions smartcontract/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ pub enum DataKey {
Swap(u64),
SupportedChain(u32),
ExpiredHTLCs,
/// Read pointer: the next queue index to process in cleanup_expired_htlcs.
ExpiredHTLCHead,
ExpiredHTLCQueue(u64),
StorageMetrics,
Paused,
Expand Down Expand Up @@ -149,6 +151,7 @@ pub fn write_proposal_vote(env: &Env, proposal_id: u64, voter: &Address, voted:
.set(&DataKey::ProposalVote(proposal_id, voter.clone()), &voted);
}

#[allow(dead_code)]
pub fn read_delegation(env: &Env, delegator: &Address) -> Option<DelegationRecord> {
env.storage()
.persistent()
Expand Down Expand Up @@ -374,6 +377,7 @@ pub fn get_orders_by_chain_pair(env: &Env, from: &Chain, to: &Chain) -> Vec<u64>
// Expired HTLC cleanup queue
// =============================================================================

/// Append an HTLC id to the expired-cleanup queue.
pub fn add_expired_htlc(env: &Env, htlc_id: u64) {
let counter = get_expired_htlc_counter(env);
env.storage()
Expand All @@ -382,6 +386,7 @@ pub fn add_expired_htlc(env: &Env, htlc_id: u64) {
set_expired_htlc_counter(env, counter + 1);
}

/// Write pointer: total number of entries ever enqueued.
pub fn get_expired_htlc_counter(env: &Env) -> u64 {
env.storage()
.instance()
Expand All @@ -393,6 +398,20 @@ pub fn set_expired_htlc_counter(env: &Env, count: u64) {
env.storage().instance().set(&DataKey::ExpiredHTLCs, &count);
}

/// Read pointer: the next queue index to process in cleanup_expired_htlcs.
pub fn get_expired_htlc_head(env: &Env) -> u64 {
env.storage()
.instance()
.get(&DataKey::ExpiredHTLCHead)
.unwrap_or(0)
}

fn set_expired_htlc_head(env: &Env, head: u64) {
env.storage()
.instance()
.set(&DataKey::ExpiredHTLCHead, &head);
}

pub fn get_expired_htlc(env: &Env, index: u64) -> Option<u64> {
env.storage()
.instance()
Expand All @@ -405,17 +424,32 @@ pub fn remove_expired_htlc(env: &Env, index: u64) {
.remove(&DataKey::ExpiredHTLCQueue(index));
}

pub fn cleanup_expired_htlcs(env: &Env) -> u64 {
let counter = get_expired_htlc_counter(env);
let mut cleaned = 0u64;
/// Process expired HTLCs from the cleanup queue.
///
/// Uses a persistent read pointer so successive calls resume where the
/// previous call left off, enabling partial cleanup over multiple calls.
/// `limit` caps how many entries are removed per call; pass `0` to use the
/// default batch size (`CLEANUP_BATCH_SIZE`). Returns the number of HTLCs
/// actually removed.
pub fn cleanup_expired_htlcs(env: &Env, limit: u32) -> u64 {
let write_counter = get_expired_htlc_counter(env);
let head = get_expired_htlc_head(env);

if head >= write_counter {
return 0;
}

let batch_end = if counter > CLEANUP_BATCH_SIZE {
let effective_limit = if limit == 0 {
CLEANUP_BATCH_SIZE
} else {
counter
limit as u64
};

for i in 0..batch_end {
let pending = write_counter - head;
let batch_size = pending.min(effective_limit);
let mut cleaned = 0u64;

for i in head..head + batch_size {
if let Some(htlc_id) = get_expired_htlc(env, i) {
remove_htlc(env, htlc_id);
remove_expired_htlc(env, i);
Expand All @@ -424,8 +458,7 @@ pub fn cleanup_expired_htlcs(env: &Env) -> u64 {
}

if cleaned > 0 {
let remaining = counter.saturating_sub(cleaned);
set_expired_htlc_counter(env, remaining);
set_expired_htlc_head(env, head + cleaned);
}

cleaned
Expand Down
Loading
Loading