Contract cafc5a34cc17c49f29c1aaeefe20520ac3d6336747a6eb125cdd85e082857cc4

← Back to Index 📥 Download WASM

Meta

rssdkver 22.0.8#f46e9e0610213bbb72285566f9dd960ff96d03d8
rsver 1.87.0

Instances

  • CC6UGDHEUEA6WAEULTNOOL3G34T5AWGAHJUGWNYNC3G7GRS3Y46JIP5Y

Interface

Initializes the P2P marketplace contract with essential configuration. This function can only be called once and sets up the foundational parameters.

Arguments

  • admin - The address that will have administrative privileges (pause, fees, disputes)
  • usdc_token_id - The contract address of the USDC token to be traded
  • fee_collector - The address that will receive trading fees

Security Considerations

  • Validates that USDC token address is a valid token contract
  • Uses persistent storage for critical configuration to survive upgrades
  • Prevents double initialization
  • Validates all addresses are non-zero

Returns

Result indicating success or failure of initialization

fn initialize(
    env: soroban_sdk::Env,
    admin: soroban_sdk::Address,
    usdc_token_id: soroban_sdk::Address,
    fee_collector: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Creates a new offer to sell USDC for KES with escrow protection. The seller must approve the contract to spend their USDC before calling this function.

Business Flow

  1. Validates seller authorization and input parameters
  2. Checks trading limits and seller doesn't have active offer
  3. Verifies seller has sufficient USDC balance and allowance
  4. Transfers USDC from seller to contract (escrow)
  5. Creates offer record and updates active offers mapping
  6. Emits event for transparency

Security Checks

  • Requires seller authorization
  • Validates amount ranges to prevent spam/large trades
  • Checks USDC balance and allowance before transfer
  • Uses safe transfer with error handling
  • Enforces one active offer per seller rule

Arguments

  • seller - The address creating the offer (must sign transaction)
  • usdc_amount - Amount of USDC to sell (with 6 decimals)
  • kes_amount - Amount of KES expected in return (off-chain settlement)

Returns

The unique ID of the created offer

Errors

  • ContractPaused: If tra
fn create_offer(
    env: soroban_sdk::Env,
    seller: soroban_sdk::Address,
    usdc_amount: i128,
    kes_amount: i128,
) -> Result

Initiates a trade by a buyer against an existing offer. This begins the escrow process where USDC is held while payment confirmation occurs.

Business Flow

  1. Validates buyer authorization and offer existence
  2. Prevents self-trading and checks offer is still active
  3. Ensures no existing active trade for the offer
  4. Creates trade record with initial status
  5. Emits event to notify participants

Security Features

  • Prevents buyers from trading with themselves
  • Validates offer is still active and available
  • Efficient lookup using active_offers mapping
  • Checks for existing active trades to prevent conflicts

Arguments

  • buyer - The address initiating the trade (must sign transaction)
  • offer_id - The ID of the offer to trade against

Returns

The unique ID of the created trade

Errors

  • ContractPaused: If trading is disabled
  • OfferNotFound: If offer doesn't exist or is no longer active
  • Unauthorized: If buyer tries to trade with themselves
  • TradeAlreadyInitiated: If offer already has an acti
fn initiate_trade(
    env: soroban_sdk::Env,
    buyer: soroban_sdk::Address,
    offer_id: u64,
) -> Result

Allows trade participants to confirm payment completion. Both buyer and seller must confirm before USDC is released.

Business Flow

  1. Validates participant authorization and trade existence
  2. Checks trade hasn't expired and is in correct status
  3. Records participant's payment confirmation
  4. If both parties confirm, automatically releases USDC
  5. Emits appropriate events for transparency

Security Features

  • Only trade participants can confirm
  • Prevents confirmation on expired trades
  • Validates trade is in correct status for confirmation
  • Automatic execution when both parties confirm

Arguments

  • trade_id - The ID of the trade to confirm payment for
  • participant - The address confirming (buyer or seller, must sign)

Errors

  • ContractPaused: If contract is paused
  • TradeNotFound: If trade doesn't exist
  • TradeExpired: If trade has exceeded time limit
  • InvalidTradeStatus: If trade is not in confirmable state
  • Unauthorized: If caller is not a trade participant
fn confirm_payment(
    env: soroban_sdk::Env,
    trade_id: u64,
    participant: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Allows trade participants to cancel an initiated trade. This returns the escrowed USDC to the seller.

Business Flow

  1. Validates participant authorization and trade state
  2. Ensures only initiated trades can be cancelled
  3. Returns escrowed USDC to seller
  4. Updates trade status and removes offer from active list
  5. Emits cancellation event

Security Features

  • Only trade participants can cancel
  • Only initiated trades can be cancelled
  • Safe transfer with error handling
  • Proper cleanup of offer state

Arguments

  • trade_id - The ID of the trade to cancel
  • participant - The address requesting cancellation (buyer or seller)

Errors

  • ContractPaused: If contract is paused
  • TradeNotFound: If trade doesn't exist
  • InvalidTradeStatus: If trade cannot be cancelled
  • Unauthorized: If caller is not a trade participant
  • TokenTransferFailed: If USDC return fails
fn cancel_trade(
    env: soroban_sdk::Env,
    trade_id: u64,
    participant: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Resolves expired trades by returning escrowed USDC to sellers. Anyone can call this function to clean up expired trades.

Business Logic

  • Trades have time limits to prevent indefinite escrow
  • Expired trades are automatically cancelled
  • USDC is returned to seller when trade expires
  • This prevents buyer griefing by not confirming payment

Public Access

  • Any address can call this function
  • Helps maintain marketplace hygiene
  • Incentivizes community participation in cleanup

Arguments

  • trade_id - The ID of the expired trade to resolve

Errors

  • ContractPaused: If contract is paused
  • TradeNotFound: If trade doesn't exist
  • TradeNotExpired: If trade hasn't actually expired
  • InvalidTradeStatus: If trade is not in expirable state
  • TokenTransferFailed: If USDC return fails
fn resolve_expired_trade(
    env: soroban_sdk::Env,
    trade_id: u64,
) -> Result<(), soroban_sdk::Error>

Allows sellers to cancel their offers and recover escrowed USDC. Offers can only be cancelled if no active trade exists.

Business Flow

  1. Validates seller authorization and offer ownership
  2. Checks no active trades exist for the offer
  3. Returns escrowed USDC to seller
  4. Removes offer from all mappings
  5. Emits cancellation event

Security Features

  • Only offer owner can cancel
  • Prevents cancellation if active trade exists
  • Safe transfer with error handling
  • Proper cleanup of all offer references

Arguments

  • seller - The address that created the offer (must sign)
  • offer_id - The ID of the offer to cancel

Errors

  • ContractPaused: If contract is paused
  • OfferNotFound: If offer doesn't exist
  • Unauthorized: If caller is not the offer owner
  • TradeAlreadyInitiated: If active trade exists for offer
  • TokenTransferFailed: If USDC return fails
fn cancel_offer(
    env: soroban_sdk::Env,
    seller: soroban_sdk::Address,
    offer_id: u64,
) -> Result<(), soroban_sdk::Error>

Emergency function to pause all trading activities. Only admin can pause the contract for security or maintenance.

Use Cases

  • Security incidents requiring immediate halt
  • Contract upgrades or maintenance
  • Regulatory compliance requirements
  • Market manipulation prevention

Admin Only

  • Requires admin authorization
  • Immediate effect on all trading functions
  • Does not affect existing trades, only new operations

Returns

Result indicating success or failure of pause operation

fn pause(env: soroban_sdk::Env) -> Result<(), soroban_sdk::Error>

Resumes trading activities after a pause. Only admin can unpause the contract.

Security Consideration

  • Admin should verify all issues are resolved before unpausing
  • Existing trades continue normally after unpause
  • New trading activities become available immediately

Returns

Result indicating success or failure of unpause operation

fn unpause(env: soroban_sdk::Env) -> Result<(), soroban_sdk::Error>

Raises a dispute for a trade when payment confirmation conflicts arise. This function allows trade participants to escalate issues that cannot be resolved through normal payment confirmation flow.

Business Logic

  • Either buyer or seller can raise a dispute
  • Disputes can be raised on initiated or payment-confirmed trades
  • Once disputed, trades require admin intervention to resolve
  • Prevents automatic trade completion until dispute is resolved

Security Features

  • Only trade participants can raise disputes
  • Validates trade exists and is in appropriate state
  • Prevents abuse by limiting who can dispute

Arguments

  • trade_id - The ID of the trade to dispute
  • caller - The address raising the dispute (buyer or seller)

Returns

Result indicating success or failure of dispute creation

Errors

  • TradeNotFound: If trade doesn't exist
  • Unauthorized: If caller is not a trade participant
  • InvalidTradeStatus: If trade is not in disputable state
fn raise_dispute(
    env: soroban_sdk::Env,
    trade_id: u64,
    caller: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Resolves a disputed trade with admin intervention. Only the admin can resolve disputes by choosing to release USDC to buyer or refund to seller.

Business Logic

  • Admin reviews dispute details off-chain
  • Admin decides whether buyer or seller is correct
  • USDC is transferred based on admin's resolution decision
  • Fees are still collected on successful trades (release to buyer)
  • No fees on refunds to seller

Admin Authority

  • Only admin can resolve disputes
  • Admin decisions are final and irreversible
  • Admin should have off-chain verification process

Arguments

  • trade_id - The ID of the disputed trade to resolve
  • resolution - The admin's decision (ReleaseToBuyer or RefundToSeller)

Returns

Result indicating success or failure of dispute resolution

Errors

  • Unauthorized: If caller is not the admin
  • TradeNotFound: If trade doesn't exist
  • InvalidTradeStatus: If trade is not in disputed state
  • TokenTransferFailed: If USDC transfer fails
fn resolve_dispute(
    env: soroban_sdk::Env,
    trade_id: u64,
    resolution: DisputeResolution,
) -> Result<(), soroban_sdk::Error>

Upgrades the contract to a new Wasm hash. This function can only be called by the contract admin.

Arguments

  • new_wasm_hash - The hash of the new contract Wasm to upgrade to.

Security

  • Requires admin authorization.
  • The new Wasm hash must be valid.
fn upgrade(
    env: soroban_sdk::Env,
    new_wasm_hash: soroban_sdk::BytesN<32>,
) -> Result<(), soroban_sdk::Error>

Updates the admin address to a new address. This is a critical security function that transfers administrative control.

Security Features

  • Requires current admin authorization
  • Requires new admin to sign transaction (prevents unauthorized transfers)
  • Emits event for transparency and audit trail
  • Immediate effect - new admin can perform admin functions right away

Use Cases

  • Transferring control to a new administrator
  • Moving to a multi-sig admin address
  • Emergency admin change for security reasons

Arguments

  • new_admin - The new admin address (must sign transaction)

Returns

Result indicating success or failure of admin update

Errors

  • Unauthorized: If caller is not current admin
fn update_admin(
    env: soroban_sdk::Env,
    new_admin: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Updates the fee collector address where trading fees are sent. This allows admin to change where marketplace fees are collected.

Business Logic

  • Fee collector receives a percentage of each completed trade
  • Can be set to treasury, DAO, or operational address
  • Takes effect immediately for new trades
  • Does not affect ongoing trades

Arguments

  • new_fee_collector - The new address to receive trading fees

Returns

Result indicating success or failure of fee collector update

Errors

  • Unauthorized: If caller is not admin
fn update_fee_collector(
    env: soroban_sdk::Env,
    new_fee_collector: soroban_sdk::Address,
) -> Result<(), soroban_sdk::Error>

Updates the trading fee rate charged on completed trades. Fee rate is specified in basis points (1/100th of a percent).

Fee Structure

  • Basis points: 1 = 0.01%, 100 = 1%, 1000 = 10%
  • Maximum allowed fee is 10% (1000 basis points)
  • Reasonable marketplace fees are typically 0.1% - 1%
  • Fees are only collected on successful trades

Arguments

  • new_fee_rate - New fee rate in basis points (max 1000 = 10%)

Returns

Result indicating success or failure of fee rate update

Errors

  • Unauthorized: If caller is not admin
  • InvalidAmount: If fee rate exceeds 10%
fn update_fee_rate(
    env: soroban_sdk::Env,
    new_fee_rate: u32,
) -> Result<(), soroban_sdk::Error>

Updates the minimum and maximum trade amounts for USDC trades. These limits help prevent spam trades and excessive exposure.

Business Logic

  • Minimum amount prevents spam with tiny trades
  • Maximum amount limits exposure per trade
  • Amounts are in USDC with 6 decimal places
  • Applies to new offers only, existing offers unchanged

Arguments

  • min_amount - Minimum USDC amount for trades (with 6 decimals)
  • max_amount - Maximum USDC amount for trades (with 6 decimals)

Returns

Result indicating success or failure of limits update

Errors

  • Unauthorized: If caller is not admin
  • InvalidAmount: If amounts are invalid or min > max
fn update_trade_limits(
    env: soroban_sdk::Env,
    min_amount: i128,
    max_amount: i128,
) -> Result<(), soroban_sdk::Error>

Updates the trade expiration time for new trades. This controls how long buyers have to confirm payment before trades expire.

Business Logic

  • Expired trades automatically return USDC to seller
  • Shorter times reduce seller risk but may rush buyers
  • Longer times give buyers more flexibility but increase seller risk
  • Typical values: 10 minutes to 24 hours

Arguments

  • expiration_seconds - New expiration time in seconds (60 to 86400)

Returns

Result indicating success or failure of expiration update

Errors

  • Unauthorized: If caller is not admin
  • InvalidAmount: If expiration is outside allowed range
fn update_trade_expiration(
    env: soroban_sdk::Env,
    expiration_seconds: u64,
) -> Result<(), soroban_sdk::Error>

Returns the current admin address.

Usage

  • Check who has administrative privileges
  • Verify admin address in UI applications
  • Audit administrative access

Returns

The address of the current contract administrator

fn get_admin(env: soroban_sdk::Env) -> soroban_sdk::Address

Returns the USDC token contract address.

Usage

  • Verify which token is used for trading
  • Set up token approvals in client applications
  • Validate contract configuration

Returns

The address of the USDC token contract

fn get_usdc_token_id(env: soroban_sdk::Env) -> soroban_sdk::Address

Returns the fee collector address.

Usage

  • See where trading fees are sent
  • Verify fee collection setup
  • Audit fee distribution

Returns

The address that receives trading fees

fn get_fee_collector(env: soroban_sdk::Env) -> soroban_sdk::Address

Returns the current trading fee rate in basis points.

Fee Calculation

  • Basis points: 25 = 0.25%, 100 = 1%
  • To calculate fee: (trade_amount * fee_rate) / 10000
  • Example: 1000 USDC trade with 25 basis points = 2.5 USDC fee

Returns

Current fee rate in basis points (e.g., 25 = 0.25%)

fn get_fee_rate(env: soroban_sdk::Env) -> u32

Returns the current minimum and maximum trade amounts.

Usage

  • Validate trade amounts before creating offers
  • Display trading limits in UI
  • Ensure compliance with platform rules

Returns

Tuple of (minimum_amount, maximum_amount) in USDC with 6 decimals

fn get_trade_limits(env: soroban_sdk::Env) -> (i128, i128)

Returns the current trade expiration time in seconds.

Usage

  • Calculate trade expiration times for UI
  • Inform users how long they have to confirm
  • Set appropriate timeout expectations

Returns

Trade expiration time in seconds

fn get_trade_expiration(env: soroban_sdk::Env) -> u64

Returns the next offer ID that will be assigned.

Usage

  • Predict offer IDs for client applications
  • Monitor marketplace growth and activity
  • Debug offer creation issues

Returns

The next available offer ID

fn get_next_offer_id(env: soroban_sdk::Env) -> u64

Returns the next trade ID that will be assigned.

Usage

  • Predict trade IDs for client applications
  • Monitor trading activity and volume
  • Debug trade creation issues

Returns

The next available trade ID

fn get_next_trade_id(env: soroban_sdk::Env) -> u64

Returns all offers in the marketplace. Warning: This function can be expensive for large datasets.

Performance Considerations

  • Returns ALL offers (including inactive ones)
  • Can consume significant gas for large datasets
  • Consider using pagination for production applications
  • Better to use get_offer for specific lookups

Returns

Map of all offers keyed by offer ID

fn get_offers(env: soroban_sdk::Env) -> soroban_sdk::Map

Returns a specific offer by its ID.

Usage

  • Get offer details for display
  • Validate offer exists before trading
  • Check offer parameters

Arguments

  • offer_id - The ID of the offer to retrieve

Returns

The offer if it exists, None otherwise

fn get_offer(env: soroban_sdk::Env, offer_id: u64) -> Option

Returns all trades in the marketplace. Warning: This function can be expensive for large datasets.

Performance Considerations

  • Returns ALL trades regardless of status
  • Can consume significant gas for large datasets
  • Consider using pagination for production applications
  • Better to use get_trade for specific lookups

Returns

Map of all trades keyed by trade ID

fn get_trades(env: soroban_sdk::Env) -> soroban_sdk::Map

Returns a specific trade by its ID.

Usage

  • Get trade details and status
  • Monitor trade progress
  • Validate trade exists before operations

Arguments

  • trade_id - The ID of the trade to retrieve

Returns

The trade if it exists, None otherwise

fn get_trade(env: soroban_sdk::Env, trade_id: u64) -> Option

Returns the mapping of sellers to their active offer IDs.

Usage

  • Check which sellers have active offers
  • Enforce one-offer-per-seller rule
  • Display active offers by seller

Returns

Map of seller addresses to their active offer IDs

fn get_active_offers(
    env: soroban_sdk::Env,
) -> soroban_sdk::Map

Returns the active offer ID for a specific seller.

Usage

  • Check if seller has an active offer
  • Get seller's current offer ID
  • Enforce business rules about multiple offers

Arguments

  • seller - The seller address to check

Returns

The seller's active offer ID if they have one, None otherwise

fn get_seller_active_offer(
    env: soroban_sdk::Env,
    seller: soroban_sdk::Address,
) -> Option

Returns whether the contract is currently paused.

Usage

  • Check if trading is allowed
  • Display maintenance status in UI
  • Validate operations before attempting

Returns

True if contract is paused, false if trading is active

fn is_paused(env: soroban_sdk::Env) -> bool

Returns comprehensive contract configuration and status. This is a convenience function that aggregates multiple config values.

Usage

  • Get all contract settings in one call
  • Display complete contract status
  • Validate configuration in client applications

Returns

Tuple containing: (admin, usdc_token, fee_collector, fee_rate, min_amount, max_amount, expiration, is_paused)

fn get_contract_info(
    env: soroban_sdk::Env,
) -> (
    soroban_sdk::Address,
    soroban_sdk::Address,
    soroban_sdk::Address,
    u32,
    i128,
    i128,
    u64,
    bool,
)

Imports

WebAssembly Text (WAT) ▶