Skip to content

Latest commit

 

History

History
359 lines (260 loc) · 14.7 KB

CONTRACTS_API.md

File metadata and controls

359 lines (260 loc) · 14.7 KB

Trivela Smart Contract API Reference

Status: Generated from source code doc comments using cargo doc.

The Trivela platform consists of two Soroban smart contracts deployed on Stellar:

  • Campaign Contract — On-chain campaign configuration, participant registration, and eligibility
  • Rewards Contract — On-chain points, rewards, tiered distribution, and vesting

Table of Contents


Generated HTML Documentation

The full reference documentation is generated from Rust doc comments (///) using cargo doc.

Viewing Locally

# Generate docs for both contract crates
cargo doc --package trivela-campaign-contract --package trivela-rewards-contract --no-deps

# Open in browser
open target/doc/trivela_campaign_contract/index.html
open target/doc/trivela_rewards_contract/index.html

Viewing Online

Generated docs are deployed to GitHub Pages on every push to main:

Contract URL
Campaign https://finessestudiolab.github.io/Trivela/contract-api/trivela_campaign_contract/
Rewards https://finessestudiolab.github.io/Trivela/contract-api/trivela_rewards_contract/

Regenerating Documentation

Via npm script from repo root:

npm run docs:contracts

This runs cargo doc and copies the output to docs/contract-api/ for deployment.


How to Read Soroban Contract Docs

Soroban contract documentation follows Rust conventions with additional Soroban-specific patterns:

Public Functions (#[contractimpl])

All public contract entry points are defined inside #[contractimpl] blocks. These are the functions you can call from off-chain code.

Example from Campaign contract:

/// Register a participant.
///
/// `leaf`  – the 32-byte leaf value committed in the Merkle tree for this
///           participant.  Must be `sha256(address_xdr_bytes)` for the
///           caller's address, computed by off-chain tooling.
///
/// `proof` – ordered list of sibling hashes for the Merkle path from
///           `leaf` to the stored root.  Pass an empty `Vec` when no root
///           is configured.
///
/// Returns `true` on first registration, `false` if already registered.
pub fn register(
    env: Env,
    participant: Address,
    leaf: BytesN<32>,
    proof: Vec<BytesN<32>>,
) -> Result<bool, Error>

Key things to look for:

  • env: Env — The Soroban environment context (always the first parameter)
  • Address — A Stellar account or contract address
  • Result<T, Error> — Functions return Ok(T) on success or Err(Error::Variant) on failure
  • pub fn — Public entry points callable from off-chain

Error Types (#[contracterror])

Each contract defines an Error enum with numeric error codes:

#[contracterror]
#[repr(u32)]
pub enum Error {
    Unauthorized = 100,
    OutsideTimeWindow = 101,
    // ...
}

Error codes are unique within each contract. See ERROR_CODES.md for the full list.

Events

Events are documented in the module-level doc comment at the top of each lib.rs file. Each event has:

  • Topics — Indexed event identifiers (used for filtering)
  • Data — The event payload

Example from Rewards contract:

// Events:
// - `credit`: topics `(credit, user)`, data `amount: u64`
// - `claim`: topics `(claim, user)`, data `amount: u64`

Campaign state-change event (st_chng)

Every call to set_active emits a st_chng event in addition to the existing active event. Indexers should subscribe to st_chng to track campaign lifecycle without polling.

Field Type Description
topics (st_chng,) Single-element tuple used for filtering
data (CampaignState, CampaignState) (old_state, new_state)

CampaignState values:

Variant Meaning
Created Contract deployed; set_active has never been called
Active set_active(true) — campaign is accepting registrations
Paused set_active(false) called before the configured end_time
Ended set_active(false) called on or after the configured end_time

Subscribing from an indexer (JavaScript example):

const events = await server.getEvents({
  startLedger,
  filters: [{
    type: 'contract',
    contractIds: [CAMPAIGN_CONTRACT_ID],
    topics: [['st_chng']],
  }],
});

for (const event of events.events) {
  const [oldState, newState] = scValToNative(event.value);
  console.log(`Campaign transitioned: ${oldState} → ${newState}`);
}

Storage Layout

Key-value storage keys are documented as constants in the source code:

const ADMIN: Symbol = symbol_short!("admin");
const BALANCE: Symbol = symbol_short!("balance");
const PARTICIPANT: Symbol = symbol_short!("partic");

Storage uses two tiers:

  • Instance storage — Shared across all users (admin, config, total counts)
  • Persistent storage — Per-user data (participant records)

ABI JSON (Contract Interface)

The contract ABI (Application Binary Interface) is a JSON file generated by the Stellar CLI. It describes all public functions, their parameters, and return types in a machine-readable format.

Generating ABI JSON

# Generate ABI for the campaign contract
stellar contract build --manifest-path contracts/campaign/Cargo.toml
# Output: target/wasm32-unknown-unknown/release/trivela_campaign_contract.wasm

# Extract ABI from WASM
stellar contract inspect --wasm target/wasm32-unknown-unknown/release/trivela_campaign_contract.wasm

Where to Find ABI Files

After building, ABI information can be extracted from the compiled WASM files:

target/wasm32-unknown-unknown/release/*.wasm

The Stellar CLI embeds contract spec metadata directly in the WASM binary during compilation. Use stellar contract inspect to view the JSON representation.

Using ABI JSON

ABI JSON is used by:

  • Frontend integrations — Generate SDKs and type-safe clients
  • Indexers — Parse contract events and operations
  • Testing tools — Generate test harnesses automatically

TypeScript Bindings

Type-safe TypeScript bindings for the contracts are auto-generated from the compiled WASM artifacts (see issue #328).

Regenerating Bindings

npm run contracts:build-bindings

Location

Generated bindings are checked into the repository under:

frontend/src/contracts/

Usage Example

import { CampaignContract } from '../contracts/campaign.js';

const contract = new CampaignContract({
  contractId: 'C...',
  rpcUrl: 'https://soroban-testnet.stellar.org',
  networkPassphrase: 'Test SDF Network ; September 2015',
});

const isActive = await contract.is_active();
const participantCount = await contract.get_participant_count();

Contract Overview

Aspect Campaign Contract Rewards Contract
Source contracts/campaign/src/lib.rs contracts/rewards/src/lib.rs
Package trivela-campaign-contract trivela-rewards-contract
Functions initialize, register, deregister, set_window, set_active, set_max_cap, set_merkle_root, migrate, admin rotation initialize, credit, claim, batch_credit, credit_vested, claim_vested, set_tiers, credit_by_rank, snapshot, admin rotation
Events register, active, window, maxcap, merkle, aproposed, aaccepted, deregister credit, claim, transfer, paused, mxcredit, multset, ratlset, snapshot, vcredit, vclaim, aproposed, aaccepted
Errors Unauthorized, OutsideTimeWindow, CapReached, CampaignInactive, NotInAllowlist, UnsupportedMigration, InvalidAdminNonce, InvalidWindow, NoPendingAdmin Overflow, InsufficientBalance, Unauthorized, ContractPaused, CreditLimitExceeded, UnsupportedMigration, InvalidMultiplier, RateLimitExceeded, VestingNotFound, NoPendingAdmin

SEP-41 Token Interface (Rewards Contract)

When token_mode is enabled via set_token_mode(admin, true), the rewards contract exposes a SEP-41-compliant token interface. SEP-41 is the Soroban token standard (analogous to ERC-20).

Mutual exclusivity note: SEP-41 token mode and confidential balance mode (NEW-003) are mutually exclusive. Enabling token_mode while confidential mode is active will be rejected.

Allowance / Approve / Transfer-From Flow

Owner → sep41_approve(spender, amount, expiration_ledger)
                        ↓
                allowance stored on-chain
                        ↓
Spender → sep41_transfer_from(owner, recipient, amount)
                        ↓
          allowance decremented, balances updated

Functions

Function Auth required Description
sep41_balance(id) none Returns token balance (as i128)
sep41_transfer(from, to, amount) from Direct transfer
sep41_transfer_from(spender, from, to, amount) spender Delegated transfer using allowance
sep41_approve(from, spender, amount, expiration_ledger) from Grant allowance; expiration_ledger = 0 means non-expiring
sep41_allowance(owner, spender) none Read current allowance
sep41_burn(from, amount) from Burn tokens from own balance
sep41_burn_from(spender, from, amount) spender Burn from another's balance using allowance
sep41_decimals() none Token decimal places
sep41_name() none Token name
sep41_symbol() none Token ticker symbol

Error Codes (SEP-41 specific)

Code Name Cause
21 TokenModeNotEnabled Called a SEP-41 function without enabling token mode
22 AllowanceExceeded transfer_from/burn_from amount > current allowance
23 ApprovalExpired expiration_ledger has passed
24 InvalidExpiration expiration_ledger is in the past (must be > current ledger)

Edge Cases

  • Spend after expiration_ledger — The allowance entry is deleted and ApprovalExpired (#23) is returned.
  • Over-spend — AllowanceExceeded (#22). The allowance is not modified.
  • Re-approve — Calling sep41_approve again replaces the previous amount and expiry (not additive). This is per-spec.
  • Allowance to self — Permitted by the contract; no special restriction.
  • Zero amount approve — Permitted; effectively revokes the allowance (amount stored as 0).

TypeScript Usage

import { Client as RewardsClient } from './contracts/rewards';

const client = new RewardsClient({
  rpcUrl,
  networkPassphrase,
  contractId,
  publicKey,
  signTransaction,
});

// Grant allowance
await (
  await client.sep41_approve({ from, spender, amount: 1000n, expiration_ledger: 0 })
).signAndSend();

// Check allowance
const allowance = await (await client.sep41_allowance({ owner: from, spender })).simulate();

// Spend on behalf of `from`
await (await client.sep41_transfer_from({ spender, from, to, amount: 500n })).signAndSend();

Frontend helpers are also available in frontend/src/stellar.js:

  • submitApproveTransaction(walletAddress, spender, amount, expirationLedger)
  • fetchAllowance(owner, spender)
  • submitTransferFromTransaction(spenderAddress, from, to, amount)
  • submitBurnFromTransaction(spenderAddress, from, amount)

Questions?