Cadence smart contracts for the Trixy prediction market protocol on Flow blockchain.
Trixy is a decentralized prediction market platform that combines binary betting markets with DeFi yield protocols. Users can place bets on prediction markets while their staked assets earn yield through integration with protocols like Ankr, Increment, and Figment.
Defines common types and data structures used across the protocol:
- Enums:
MarketStatus,ProtocolType - Structs:
ProtocolStats- Statistics for staking protocolsUserPosition- User's position in a marketMarketInfo- Market metadataBinaryPosition- Binary prediction market position (YES/NO)PredictionMarketInfo- Prediction market details
Event definitions for the protocol:
MarketCreated- Emitted when a new market is createdBetPlaced- Emitted when a bet is placedMarketResolved- Emitted when a market is resolvedWinningsClaimed- Emitted when winnings are claimedYieldDeposited- Emitted when funds are deposited to yield protocolYieldWithdrawn- Emitted when funds are withdrawn from yield protocol
Staking-based prediction market implementation:
- Multi-option markets with staking protocol integration
- Supports Ankr, Increment, and Figment protocols
- APY-based yield generation
- Winner-takes-all with yield sharing
Binary (YES/NO) prediction market implementation:
- Simple binary outcome markets
- Integrated yield protocol support
- Proportional payout system
- Yield distribution to both winners and losers
Main protocol contract that manages:
- Market creation and lifecycle
- Market registry and lookup
- Admin functions
- Integration with both Market and PredictionMarket types
Price oracle and APY calculation contract:
- Real-time FLOW/USD price tracking
- APY calculation for staking protocols (Ankr, Increment, Figment)
- Dynamic APY adjustment based on FLOW price
- Yield projection and payout calculations
- Admin-controlled price updates (updated by cron service every 5 minutes)
- Protocol comparison and best APY finder
Protocol adapters implement IStakingProtocol interface:
AnkrAdapter.cdc- Ankr staking integrationIncrementAdapter.cdc- Increment protocol integrationFigmentAdapter.cdc- Figment staking integration
Standard interface for staking protocol adapters:
deposit()- Deposit funds to earn yieldwithdraw()- Withdraw fundsgetAPY()- Get current APYgetBalance()- Get deposited balance
- Account:
0x3564db973ae8bb36 - Contracts:
TrixyTypesTrixyEventsIStakingProtocolAnkrAdapterIncrementAdapterFigmentAdapterMarketTrixyProtocolPriceOracle
Query scripts for reading blockchain state:
get_market_info.cdc- Get detailed market informationget_protocol_apy.cdc- Get APY for a specific protocolget_protocol_apys.cdc- Get APYs for all protocols in a marketget_user_position.cdc- Get user's position in a marketget_leaderboard.cdc- Get platform leaderboardget_market_ids.cdc- List all market IDs (currently disabled)
get_flow_price.cdc- Get current FLOW/USD priceget_all_apys.cdc- Get APYs for all staking protocolsget_best_protocol.cdc- Get protocol with highest APY
create_staking_market.cdc- Create a new staking-based marketplace_bet.cdc- Place a bet on a market optionclaim_winnings.cdc- Claim winnings from a resolved marketresolve_market.cdc- Resolve a market (admin/creator only)
admin/remove_market_contract.cdc- Remove a market from the protocol
# Install Flow CLI
brew install flow-cli
# Verify installation
flow versionThe project uses flow.json for network and account configuration:
- Testnet contracts deployed to
0xe4a8713903104ee5 - Multiple test accounts configured
- Dependencies on Flow standard contracts (FungibleToken, FlowToken, etc.)
flow transactions send transactions/create_staking_market.cdc \
"Will ETH reach $5000 in 2025?" \
1735689600 \
'["YES", "NO"]' \
"increment" \
--network testnet \
--signer trixy-latest-accountflow transactions send transactions/place_bet.cdc \
0xe4a8713903104ee5 \
0 \
"YES" \
10.0 \
--network testnet \
--signer trixy-fresh-accountflow scripts execute scripts/get_market_info.cdc \
0xe4a8713903104ee5 \
0 \
--network testnetCheck code for errors:
flow cadence lint contracts/**/*.cdc scripts/*.cdc transactions/*.cdcTest contracts are in the tests/ directory:
unit_tests.cdc- Unit testsprediction_market_test.cdc- Prediction market testsHeistProtocol_test.cdc- Legacy protocol tests
cadence/
├── contracts/
│ ├── core/ # Core protocol contracts
│ │ ├── TrixyTypes.cdc
│ │ ├── TrixyEvents.cdc
│ │ ├── Market.cdc
│ │ └── PredictionMarket.cdc
│ ├── adapters/ # Protocol adapters
│ │ ├── AnkrAdapter.cdc
│ │ ├── IncrementAdapter.cdc
│ │ └── FigmentAdapter.cdc
│ ├── interfaces/ # Contract interfaces
│ │ └── IStakingProtocol.cdc
│ ├── helpers/ # Helper contracts
│ │ └── PriceOracle.cdc
│ └── TrixyProtocol.cdc # Main protocol contract
├── scripts/ # Query scripts
├── transactions/ # Transaction templates
├── tests/ # Test contracts
└── flow.json # Flow configuration
- Simple YES/NO outcomes
- Integrated yield generation during market duration
- Proportional payout based on winning side
- Both winners and losers receive yield share
- Multiple outcome options (up to 10)
- Protocol competition (Ankr, Increment, Figment)
- APY-based yield tracking
- Winner-takes-all with yield distribution
- Automated yield protocol deposits
- Real-time APY tracking
- Yield accumulation during market lifetime
- Fair yield distribution on resolution
Trixy Protocol now integrates FlowActions on testnet! ✅
The Market.cdc contract uses FlowActions Source and Sink connectors for composable DeFi operations:
FungibleTokenConnectors.VaultSource- Withdraws yield from vaultsFungibleTokenConnectors.VaultSink- Deposits funds to yield protocols
The protocol also maintains custom adapters for reference:
AnkrAdapter.cdc- Ankr stakingIncrementAdapter.cdc- Increment protocolFigmentAdapter.cdc- Figment staking
Markets use FlowActions connectors for yield vault operations:
-
Deposit Flow (
depositToYieldProtocol):// Use FlowActions Sink to deposit if let sink = self.yieldVaultSink { sink.depositCapacity(from: &funds) }
-
Withdrawal Flow (
withdrawAllYield):// Use FlowActions Source to withdraw if let source = self.yieldVaultSource { withdrawn <- source.withdrawAvailable(maxAmount: balance) }
-
Setup - Connectors are configured after market creation:
flow transactions send transactions/setup_flowactions_connectors.cdc \ 0xe4a8713903104ee5 \ 0 \ null \ --network testnet
✅ Composability - Markets can now plug into any DeFi protocol using FlowActions connectors ✅ Flexibility - Source/Sink pattern allows easy swapping of yield strategies ✅ Standardization - Uses Flow ecosystem's standard DeFi interface ✅ Fallback Support - Maintains backward compatibility with direct vault operations
Check FlowActions Status:
flow scripts execute scripts/get_flowactions_status.cdc \
0xe4a8713903104ee5 \
0 \
--network testnetSetup Connectors:
flow transactions send transactions/setup_flowactions_connectors.cdc \
0xe4a8713903104ee5 \
0 \
1000000.0 \
--network testnet \
--signer trixy-latest-accountPlanned integrations:
- Multi-Protocol Routing - Dynamic yield optimization
- AutoBalancer - Automated rebalancing across multiple yield protocols
Current Limitations:
- FlowActions is in beta - interfaces may change
- Connectors are optional - markets work without them
- Setup requires manual transaction after market creation
Resources:
- FlowActions: github.com/onflow/FlowActions
- Testnet deployments available at addresses like
0x4c2ff9dd03ab442f
The PriceOracle contract provides real-time FLOW price data and dynamic APY calculations for staking protocols. It's updated automatically every 5 minutes by a cron service (../cron-oracle).
- Real-time Price Updates: FLOW/USD price updated every 5 minutes from CoinGecko
- Dynamic APY Calculation: APY adjusts based on FLOW price movements
- Protocol Comparison: Compare APYs across Ankr, Increment, and Figment
- Yield Projections: Calculate expected yield and payouts
- Price History: All price updates stored in PostgreSQL database
CoinGecko API → Cron Service → PriceOracle Contract → Database
(Real price) (Every 5 min) (On-chain update) (PostgreSQL)
Get current FLOW price:
import PriceOracle from 0xe3f7e4d39675d8d3
access(all) fun main(): UFix64 {
return PriceOracle.getFlowPrice()
}Calculate protocol APY:
import PriceOracle from 0xe3f7e4d39675d8d3
access(all) fun main(protocol: String): UFix64 {
return PriceOracle.calculateAPY(protocol: protocol)
}Get best protocol:
import PriceOracle from 0xe3f7e4d39675d8d3
access(all) fun main(): String {
return PriceOracle.getBestProtocol()
}The automated price updater (cron-oracle) runs continuously:
- Fetches FLOW/USD price from CoinGecko API
- Updates PriceOracle contract on Flow blockchain
- Saves price history to PostgreSQL database
- Logs all operations
Deployment: See cron-oracle/README.md for setup instructions
The oracle dynamically adjusts APY based on FLOW price:
baseAPY = {
"ankr": 12.5%,
"increment": 15.3%,
"figment": 10.8%
}
priceImpact = 1.0 + (1.0 - flowPrice)
adjustedAPY = baseAPY * priceImpact
// Clamped between 5% and 50%Example:
- FLOW price = $0.28
- Increment base APY = 15.3%
- Price impact = 1.0 + (1.0 - 0.28) = 1.72
- Adjusted APY = 15.3% × 1.72 = 26.3%
PriceUpdated:
event PriceUpdated(
oldPrice: UFix64,
newPrice: UFix64,
updater: Address,
timestamp: UFix64
)APYCalculated:
event APYCalculated(
protocol: String,
apy: UFix64,
price: UFix64,
timestamp: UFix64
)Price history is stored in price_oracle table:
CREATE TABLE price_oracle (
id UUID PRIMARY KEY,
symbol VARCHAR(20) NOT NULL,
price_usd DECIMAL(20, 8) NOT NULL,
tx_hash TEXT,
block_number BIGINT,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);The backend indexer monitors these contracts:
- Indexes all events (MarketCreated, BetPlaced, PriceUpdated, etc.)
- Stores data in PostgreSQL for fast queries
- Provides REST API for frontend
- Syncs with PriceOracle for real-time APY data
See backend, indexer, and cron-oracle for implementation details.
MIT