Smart Contracts Reference
RedCarpetHQ is powered by battle-tested smart contracts. This reference provides technical details for developers and advanced users.
Contract Architecture
Global Contracts (Single Instance)
Registry
Purpose: Central registry for all campaigns and system configurationAddress: [Deployed Address]
Key Functions:
campaigns(address token): Get campaign detailsgraduatedTime(address token): When token graduatedisGraduated(address token): Check graduation statusFEE_SAFE_ADDRESS(): Protocol treasury addressPROTOCOL_SAFE(): Protocol vault allocation addressStores:
Campaign
Purpose: Manages fundraising campaigns and token salesAddress: [Deployed Address]
Key Functions:
createCampaign(): Deploy new campaignpurchaseTokens(): Buy campaign tokensfinalizeCampaign(): Conclude successful campaigncancelCampaign(): Cancel and enable refundsextendCampaign(): Extend deadlineclaimRefund(): Get refund for failed/cancelled campaignEvents:
CampaignCreated: New campaign deployedTokensPurchased: Tokens boughtCampaignEnded: Campaign concludedRefunded: Refund claimedMarket
Purpose: Peer-to-peer token trading marketplaceAddress: [Deployed Address]
Key Functions:
createOffer(): Create buy/sell offerfillOffer(): Fill existing offercancelOffer(): Cancel your offeroffers(uint256 offerId): Get offer detailsOffer Types:
OFFER_BUY = 1: Buy tokens with USDCOFFER_SELL = 2: Sell tokens for USDCEvents:
OfferCreated: New offer postedOfferFilled: Offer executedOfferCancelled: Offer removedTradeExecuted: Trade completedFeeDistributor
Purpose: Central fee distribution (40/40/10/10 split)Address: [Deployed Address]
Distribution:
Key Functions:
distributeFees(): Process fee distributiondepositContestFees(): Send fees to ContestclaimProducerReward(): Producer claims 10%Events:
FeesReceived: Fees collectedFeesDistributed: Fees splitProducerRewardClaimed: Producer claimedContest
Purpose: 6-hour trading competition with volume trackingAddress: [Deployed Address]
Constants:
EPOCH_LENGTH = 6 hoursTHRESHOLD = 15,000 USDC: Minimum to qualifyFIRST_CLAIMER_BOUNTY_BPS = 100: 1% bountyKey Functions:
recordVolume(): Track trader volume (called by Market)depositFees(): Add prize poolfinalizeEpoch(): End epoch and calculate rewardsclaimReward(): Claim trading rewardsEvents:
Volume: Trade volume recordedQualified: Trader qualifiedEpochFinalized: Epoch endedRewardClaimed: Reward paidRiskOracle
Purpose: Real-time risk assessment for all tokensAddress: [Deployed Address]
Risk Tiers:
TIER_GREEN = 0: Healthy (50% CF, 60% LT)TIER_YELLOW = 1: Moderate (40% CF, 50% LT)TIER_RED = 2: High risk (30% CF, 40% LT)Key Functions:
assessRiskTier(): Calculate current tiergetRiskParameters(): Get tier parametersrecordTrade(): Track wash tradingtriggerCircuitBreaker(): Emergency pauseAssessment Factors:
HybridPriceOracle
Purpose: VWAP-based price feeds for all tokensAddress: [Deployed Address]
Key Functions:
updatePrice(): Record new trade (called by Market)getPrice(): Get current VWAPgetPriceAge(): Check stalenessisStale(): Check if price outdatedUpdate Mechanism:
DividendDistributor
Purpose: Revenue distribution to token holdersAddress: [Deployed Address]
Key Functions:
createDividendRound(): Start new distributionactivateRound(): Enable claims after snapshotclaimDividend(): Holder claims sharewhitelistDistributor(): Authorize distributorEvents:
DividendRoundCreated: New roundDividendRoundActivated: Claims enabledDividendClaimed: Holder claimedPer-Token Contracts
UnifiedVault (ERC4626)
Purpose: Single vault per token - lending, stability, insuranceDeployment: One per graduated token
ERC4626 Functions:
deposit(uint256 assets, address receiver): Deposit USDCwithdraw(uint256 assets, address receiver, address owner): Withdraw USDCredeem(uint256 shares, address receiver, address owner): Redeem sharestotalAssets(): Total USDC in vaultconvertToShares(uint256 assets): Calculate sharesconvertToAssets(uint256 shares): Calculate assetsLending Functions:
depositCollateral(uint256 amount): Deposit campaign tokenswithdrawCollateral(uint256 amount): Withdraw tokensborrow(uint256 amount): Borrow USDCrepay(uint256 amount): Repay loanliquidate(address borrower): Liquidate underwater positionState Variables:
lendingPool: 80% of depositsstabilityPool: 20% of depositsinsuranceFund: Funded by interesttotalBorrows: Total borrowed USDCborrowIndex: Interest accumulatorcollateralBalances: User collateralaccountBorrows: User debtEvents:
Deposit: USDC deposited (ERC4626)Withdraw: USDC withdrawn (ERC4626)CollateralDeposited: Tokens depositedBorrowed: USDC borrowedRepaid: Loan repaidLiquidated: Position liquidatedMinimumERC20 (Campaign Token)
Purpose: ERC20 token for each campaignDeployment: One per campaign
Standard ERC20:
transfer(): Send tokensapprove(): Approve spendertransferFrom(): Transfer on behalfbalanceOf(): Check balancetotalSupply(): Total token supplyAdditional Features:
snapshot(): Create balance snapshotmint(): Create tokens (campaign only)lockSupply(): Prevent further mintingEvents:
Transfer: Tokens movedApproval: Spending approvedSnapshot: Snapshot createdSupplyLocked: Minting disabledContract Interactions
Campaign Creation Flow
```
User → Campaign.createCampaign()
↓
Campaign → Clones.clone(tokenImplementation)
↓
Campaign → MinimumERC20.initialize()
↓
Campaign → Registry.registerCampaign()
↓
Event: CampaignCreated
Token Purchase Flow
``
User → USDC.approve(Campaign, amount)
↓
User → Campaign.purchaseTokens(token, amount)
↓
Campaign → USDC.transferFrom(user, Campaign, amount)
↓
Campaign → MinimumERC20.mint(user, tokens)
↓
Event: TokensPurchased
Campaign Finalization Flow
``
Creator → Campaign.finalizeCampaign(token)
↓
Campaign → Check: raised >= floor
↓
Campaign → USDC.transfer(fundsRecipient, raised)
↓
Campaign → MinimumERC20.lockSupply()
↓
Campaign → Registry.setGraduated(token)
↓
Campaign → LendingManager.deployVault(token)
↓
Event: CampaignEnded, SupplyLocked
Trading Flow
``
Seller → Token.approve(Market, amount)
↓
Seller → Market.createOffer(SELL, token, amount, price)
↓
Market → Token.transferFrom(seller, Market, amount)
↓
Event: OfferCreated
↓
Buyer → USDC.approve(Market, cost)
↓
Buyer → Market.fillOffer(offerId, amount)
↓
Market → USDC.transferFrom(buyer, Market, cost)
↓
Market → Calculate fee (2.5%)
↓
Market → FeeDistributor.distributeFees(token, fee)
↓
Market → Token.transfer(buyer, amount)
↓
Market → USDC.transfer(seller, cost - fee)
↓
Market → HybridPriceOracle.updatePrice(token, price, volume)
↓
Market → Contest.recordVolume(token, buyer, volume)
↓
Events: OfferFilled, TradeExecuted
Lending Flow
``
Lender → USDC.approve(Vault, amount)
↓
Lender → Vault.deposit(amount, lender)
↓
Vault → USDC.transferFrom(lender, Vault, amount)
↓
Vault → Split: 80% lending, 20% stability
↓
Vault → Mint shares to lender
↓
Event: Deposit
↓
Borrower → Token.approve(Vault, collateral)
↓
Borrower → Vault.depositCollateral(collateral)
↓
Vault → Token.transferFrom(borrower, Vault, collateral)
↓
Event: CollateralDeposited
↓
Borrower → Vault.borrow(amount)
↓
Vault → Check: collateral sufficient
↓
Vault → Accrue interest
↓
Vault → USDC.transfer(borrower, amount)
↓
Vault → Update totalBorrows
↓
Event: Borrowed
Liquidation Flow
``
Liquidator → Vault.liquidate(borrower)
↓
Vault → Check: collateral ratio < threshold
↓
Vault → Calculate debt + bonus
↓
Vault → Stability pool repays debt
↓
Vault → Seize collateral
↓
Vault → Distribute collateral to stability depositors
↓
Vault → Create sell offer on Market (auto-sell)
↓
Event: Liquidated
Dividend Flow
``
Producer → USDC.approve(DividendDistributor, amount)
↓
Producer → DividendDistributor.createDividendRound(token, amount)
↓
DividendDistributor → USDC.transferFrom(producer, contract, amount)
↓
Event: DividendRoundCreated
↓
Producer → Token.snapshot()
↓
Event: Snapshot
↓
Producer → DividendDistributor.activateRound(token, roundId)
↓
Event: DividendRoundActivated
↓
Holder → DividendDistributor.claimDividend(token, roundId)
↓
DividendDistributor → Calculate share
↓
DividendDistributor → USDC.transfer(holder, share)
↓
Event: DividendClaimed
Security Features
Access Control
Ownable Contracts:
Role-Based:
Reentrancy Protection
All state-changing functions use ReentrancyGuard:`solidity`
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
Pausable Contracts
Critical contracts can be paused:
`solidity
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
`
SafeERC20
All token transfers use OpenZeppelin's SafeERC20:
`solidity
using SafeERC20 for IERC20;
IERC20(token).safeTransfer(recipient, amount);
IERC20(token).safeTransferFrom(sender, recipient, amount);
`
Integer Overflow Protection
Solidity 0.8.20 has built-in overflow checks:
`solidity`
pragma solidity 0.8.20;
// Automatic overflow/underflow protection
Agentic Trading & Integrator Commission
For developers building trading interfaces, bots, or agentic trading agents, the platform exposes fee-aware functions that allow integrators to earn a commission on every trade they facilitate.
Integrator Commission (uiFeeFactor)
Integrators can earn a share of trading fees by routing orders through fee-aware functions. The commission is configurable per integrator address.
Commission Structure:
How It Works:
1. An integrator registers their commission rate (in basis points)
2. When a trader executes through the integrator's interface, the commission is calculated automatically
3. The integrator receives their share directly in USDC
4. The remaining fee follows the standard 40/40/10/10 distribution
Use Cases:
Batch Operations (MarketMulticall)
For high-frequency traders and bots, batch operations reduce gas costs and improve throughput:
Query Functions:
: Paginated list of open offers: Filtered offers by price: All buy offers for a token: All sell offers for a tokenBatch Execution:
: Fill multiple buy offers in one transaction: Fill multiple sell offers in one transaction: Cancel multiple of your own offersBenefits:
Gas Optimization
Efficient Storage
Packed Structs:
`solidity`
struct Offer {
uint256 offerId;
address token;
address paymentToken;
uint8 offerType; // Packed with status
uint8 status; // Same slot
// ... more fields
}
Immutable Variables:
`solidity`
IERC20 public immutable collateralToken;
Registry public immutable registry;
Batch Operations
Multiple Claims:
`solidity`
function claimMultipleDividends(
address[] calldata tokens,
uint256[] calldata roundIds
) external;
Gas Estimates
| Operation | Gas Cost | USD (50 gwei) |
|-----------|----------|---------------|
| Create Campaign | ~500,000 | $25 |
| Purchase Tokens | ~150,000 | $7.50 |
| Create Offer | ~200,000 | $10 |
| Fill Offer | ~200,000 | $10 |
| Deposit to Vault | ~180,000 | $9 |
| Borrow | ~250,000 | $12.50 |
| Repay | ~150,000 | $7.50 |
| Liquidate | ~300,000 | $15 |
| Claim Dividend | ~80,000 | $4 |
Estimates for Layer 2 networks. Actual costs may vary based on network conditions.
Contract Addresses
Current contract addresses are available on the platform dashboard and updated with each deployment.
Note: For security, addresses are not hard-coded in public documentation. Always verify the current deployment addresses on the official platform before interacting with contracts.
ABIs
Contract ABIs are available through the platform API or by querying verified contracts directly on a block explorer.
Integration
Web3.js
`javascript
const Web3 = require('web3');
const web3 = new Web3(RPC_URL); // Use platform-provided RPC
const campaignABI = [ / ABI from platform API / ];
const campaign = new web3.eth.Contract(campaignABI, CAMPAIGN_ADDRESS);
`
Ethers.js
`javascript
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider(RPC_URL); // Use platform-provided RPC
const campaignABI = [ / ABI from platform API / ];
const campaign = new ethers.Contract(CAMPAIGN_ADDRESS, campaignABI, provider);
``
Upgradability
Non-Upgradable Contracts
All core contracts are immutable (not upgradable):
Why?
Registry Updates
Registry can update:
Does NOT affect:
Next Steps: