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
- Generated HTML Documentation
- How to Read Soroban Contract Docs
- ABI JSON (Contract Interface)
- TypeScript Bindings
The full reference documentation is generated from Rust doc comments (///) using cargo doc.
# 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.htmlGenerated 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/ |
Via npm script from repo root:
npm run docs:contractsThis runs cargo doc and copies the output to docs/contract-api/ for deployment.
Soroban contract documentation follows Rust conventions with additional Soroban-specific patterns:
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 addressResult<T, Error>— Functions returnOk(T)on success orErr(Error::Variant)on failurepub fn— Public entry points callable from off-chain
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 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`
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}`);
}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)
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.
# 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.wasmAfter 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.
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
Type-safe TypeScript bindings for the contracts are auto-generated from the compiled WASM artifacts (see issue #328).
npm run contracts:build-bindingsGenerated bindings are checked into the repository under:
frontend/src/contracts/
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();| 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 |
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_modewhile confidential mode is active will be rejected.
Owner → sep41_approve(spender, amount, expiration_ledger)
↓
allowance stored on-chain
↓
Spender → sep41_transfer_from(owner, recipient, amount)
↓
allowance decremented, balances updated
| 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 |
| 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) |
- Spend after
expiration_ledger— The allowance entry is deleted andApprovalExpired(#23) is returned. - Over-spend —
AllowanceExceeded(#22). The allowance is not modified. - Re-approve — Calling
sep41_approveagain 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).
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)
- Open a Discussion
- Check the FAQ for common issues
- Review ERROR_CODES.md for all error types