Overview
This repo contains production-shaped Solidity contracts for the real-world-asset (RWA) workflows Unykorn actually ships against: construction draw escrow (Georgia statutory-form waiver evidence layer), ERC-3643-inspired permissioned security tokens, REIT NOI distribution, CMBS 3-tranche waterfalls, SREC tokens, and Chainlink oracle consumers.
The library exists because Unykorn Studio — the console that drives these contracts through an approval-per-step executor with hash-chained receipts — is the product. This library is the substrate. Real contracts to run through it. Real deployments to prove the audit chain works end to end.
🏢 Real Estate / Structured Finance
3 shipped families · 6 contracts
🏦 Private Credit / Institutional Lending
4 shipped families · Maple + Centrifuge (3)
💵 Tokenized Funds
2 shipped families · BUIDL-shape + ERC-4626 vault
🏠 Real Estate (Debt + Equity)
2 shipped families · Figure + RealT
🏛 Securities / Compliance
1 shipped family · 3 contracts
🌱 ESG / Climate / Sovereignty
2 shipped families · 1 design contract
🔗 Oracles / Cross-chain
3 shipped families · 1 design contract
See also: Ecosystem landscape — full Chainlink stack, tokenized private credit market leaders, and 20+ live TradFi–DeFi integrations mapped.
Status legend
SHIPPED Compiles clean under the pinned solc + vendored OZ. Deployable to Anvil via Unykorn Studio right now.
DESIGN CONTRACT Interface + integration shape is defined and the corresponding step kind exists in Studio's executor as an unwired branch — approve it in Studio and it fails loudly with a specific reason so the honest v0 behavior is preserved. Full implementation pending external dependency (e.g. Toucan bridge, BitGo Enterprise API, XRPL adapter subprocess).
Milestone-indexed construction draw escrow. Payment releases require inspector attestation of milestone completion, a signed EIP-712 waiver from the attestor (title company or draw administrator), matching waiver draw-number for replay protection, and sufficient net-of-retainage funds. Two-step timelocked attestor rotation. AIA G703 milestone-field mapping.
| Contracts | IWaiverAttestor (types) · MilestoneRegistry · DrawEscrow · LocalTestToken |
| Bytecode | DrawEscrow 6,642 bytes · MilestoneRegistry 3,181 bytes |
| Dependencies | @openzeppelin/contracts v5.0.2 (AccessControl · Pausable · ReentrancyGuard · SafeERC20 · EIP712 · SignatureChecker) |
| Reference deployment | M Helen Hotel LLC SPV (construction draws against $25M senior + $4.1M mezz) |
| Legal posture | On-chain contract EVIDENCES the waiver; does not constitute or replace the Georgia statutory-form waiver required under O.C.G.A. § 44-14-366. |
Legal: Georgia's statutory lien waiver requirement (O.C.G.A. § 44-14-366) prescribes specific form language. This contract stores a keccak256 hash of the executed statutory form and enforces payment-and-waiver coupling; it does not validate the form itself. Statutory conformity, current operative text, and nonpayment mechanics must be confirmed with Georgia counsel before any live draw.
Pull-based per-unit dividend distribution using the accumulator pattern (MasterChef-style). Sponsor deposits currency each period; investors claim their pro-rata share whenever they want. The token's _update hook settles per-holder debt on every transfer, so early or late claimers always get exactly their entitled share.
| Contracts | DistributionToken · REITDistributor |
| Bytecode | DistributionToken 4,386 bytes · REITDistributor 4,506 bytes |
| Pattern | Accumulator (accCurrencyPerUnit + per-holder debtCursor) |
| Why not ERC20Snapshot | OZ v5 removed ERC20Snapshot. Accumulator pattern is the standard replacement — same math, works with plain ERC-20. |
| Legal posture | REIT tax status (90% distribution rule, closely-held test, qualifying-asset composition) is an off-chain determination. Contract enforces distribution mechanics only. |
Senior / mezzanine / equity distribution waterfall. Every dollar of NOI or principal repayment first satisfies senior's accrued interest + principal, then mezz, then residual to equity. Per-tranche interest accrual by simple period-multiplied rate; investors pull their pro-rata share.
| Contract | CMBSWaterfall |
| Bytecode | 5,537 bytes |
| Default rates | Senior 700 bps (7%) · Mezz 1100 bps (11%) · Equity 0 (residual) |
| Contribution | recordContribution() for admin-registered off-chain funding, or fund() for on-chain push. |
| Legal posture | CMBS securitization involves REMIC / grantor-trust tax elections and offering-document disclosures this contract does not model. |
Institutional lending pool in the Maple Finance shape. Curated credit marketplace managed by a designated Pool Delegate (BlockTower / Room40 / AQRU-style professional credit officer) who underwrites individual borrowers, sets pool concentration limits, and posts first-loss capital to align incentives with lenders. Lender deposits gated by whitelist. Redemptions cooldown-protected to prevent runs on illiquid book.
| Contract | PoolDelegatePool |
| Roles | POOL_DELEGATE (originates loans, posts first-loss, marks defaults) · LP_WHITELIST (KYC-gated deposit access) · admin |
| Risk model (post-2022 restructuring) | Fixed-rate fixed-term loans (30–180 days typical) · overcollateralized 105–130% off-chain · Pool Delegate first-loss tranche absorbs defaults before LP write-down · per-borrower concentration cap |
| Redemption flow | requestRedemption() → cooldown elapses → executeRedemption() from idle balance |
| Reference market | Maple Finance — $4.6–$5B AUM · $2B active loans · $22B+ cumulative originations · targeting $100B annual by 2030 |
Structure note: Real Maple deployments layer additional infrastructure — off-chain collateral custody via a qualified custodian, borrower KYC via ACE + ERC-3643, auction-based liquidation of defaulted loans, tiered lender classes. This contract ships the core pool + first-loss + concentration-cap shape; production stacks these on top.
Short-tenor receivables pool. Originator funds an approved invoice at 80-90% of face value (advance rate); at maturity (30-90 days), the payer settles the full face value into the pool, which funds LP yield. Same shape Centrifuge Tinlake uses for supply-chain finance and invoice pools.
| Contract | InvoiceFactoringPool |
| Roles | ORIGINATOR (funds invoices, records repayments) · LP_WHITELIST (KYC-gated deposit access) |
| Advance rate | Configurable per invoice (80-90% typical). Discount from face becomes LP yield when payer settles. |
| Reference market | Centrifuge Tinlake — invoice financing pools + supply-chain finance |
| Playbook | Invoice Financing: B2B receivables factoring — full deal walkthrough from SPV formation through Stage-3 scale, published underwriting rules, per-invoice operating cycle |
Two-tranche pool with ongoing origination against a rolling loan book. The originator retains all or most of the junior tranche as first-loss skin-in-the-game; on-chain investors purchase the senior tranche at a fixed APY. Distinct from CMBSWaterfall (single securitization, 3 tranches) and PoolDelegatePool (single-tier, cooldown redemption). This is the classic Centrifuge shape.
| Contract | BridgeLoanTranchePool |
| Tranche stack | Senior — whitelist-gated, fixed APY (e.g. 700-900 bps), share = currency contribution, APY accrues on top · Junior — originator only, pro-rata against junior NAV, absorbs first loss |
| Sky protocol integration | Senior tranche token is designed to be freely transferable so it composes with Sky (formerly MakerDAO) — originator posts senior tranche as collateral to borrow USDS stablecoin against the real-world asset. Historically funded 85%+ of Centrifuge-originated loans. |
| Origination flow | originateLoan() draws from idle pool currency → borrower funded · repayLoan() settles principal + accrued interest, senior gets APY, junior receives residual via _juniorNav |
| Write-down flow | writeDownLoan() marks loan defaulted, reduces totalDeployed, increments totalWriteDowns. Junior NAV absorbs first via _juniorNav clamp to zero. |
| Reference market | Centrifuge active pools ~$430M + Janus Henderson JTRSY $880M |
Single-asset asset-backed loan for physical inventory sitting in a warehouse. UCC-1 lien hash pinned on-chain as evidentiary anchor (physical UCC-1 filing with the state remains the operative lien). Senior/junior tranche stack: senior investors get fixed rate + priority; junior tranche (typically originator or family office) absorbs first loss. Amortizing repayment with waterfall.
| Contract | InventoryFinancingSPV |
| Phases | Setup → Funding → Active → Repaid | Defaulted |
| Reference deal | $2M EV chargers in a Tennessee warehouse — 80% advance ($1.6M senior at 900 bps) + 20% junior tranche ($320K first-loss) + 18 month amortizing term. Full walkthrough in Deal Playbooks section below. |
| Off-chain enforcement | On default, physical repossession + auction proceeds through state court under UCC Article 9. Realistic 6-18 month enforcement timeline with 50-80% recovery expectation. Contract records defaulted state; recovery distributions happen off-chain then are recorded back. |
| Funding venue options | Centrifuge (senior tranche composable with Sky protocol for USDS borrow) · Maple (Pool Delegate underwrites) · Family office / private capital direct |
Legal: Contract stores UCC-1 filing hash + inventory attestation hash. Actual UCC-1 must be filed with the state's Secretary of State (Tennessee TDOC for a TN warehouse) to perfect the lien. On-chain hash proves the filing existed with that content at that time; it does not create the lien.
On-chain wrapper for a tokenized Treasury fund. Composable design: receiver eligibility via a PermissionedToken-shape gate, mint circuit breaker via ProofOfReserveConsumer, NAV-priced subscription/redemption with a T+N settlement queue. Same shape BlackRock BUIDL (Securitize transfer agent), Franklin Templeton BENJI, Ondo OUSG, and Circle USYC ship.
| Contract | TokenizedTreasury |
| Composes with | PermissionedToken (receiver eligibility) · ProofOfReserveConsumer (mint circuit breaker) |
| NAV pricing | Admin publishes daily NAV per share; subscriptions/redemptions price against that NAV with T+N settlement queue |
| Reference deployments | BUIDL ($500M+ AUM) · BENJI · OUSG · USYC |
Deposits stablecoin, allocator role rebalances between yield-bearing RWA shares (BUIDL / USYC / BENJI) while maintaining a minimum reserve ratio for instant redemptions. Reference shape: Maple Cash Management, Anchorage cash sweep.
| Contract | CashManagementVault |
| Roles | ALLOCATOR (rebalances into yield-bearing RWA shares) · admin |
| Reserve ratio | Configurable minimum stablecoin reserve (e.g. 10%) held in the vault at all times for instant redemptions. Allocator cannot deploy below the floor. |
Two orthogonal ways to put real estate on-chain — a claim on the loan's cash flow (debt) vs a claim on the property's economic upside (equity). Both shipped; pick the one that matches the deal.
Fungible ERC-20 claim on a single mortgage or HELOC. Servicer records monthly principal + interest payments received from the borrower; the accumulator pattern distributes to token holders pro-rata. Mortgage note hash + property deed hash + property address hash pinned on-chain as evidentiary anchors (physical note remains the operative legal instrument). Reference: Figure Technology Solutions — $18B+ tokenized HELOCs + mortgages on Provenance Blockchain.
| Contract | RealEstateDebtToken |
| Roles | ISSUER (mints shares during offering) · SERVICER (records monthly P+I payments, can declare default) · admin |
| Eligibility gate | Same PermissionedToken-shape claim-topic gate on every transfer. Default topics: [1=KYC, 2=accredited, 3=US-jurisdiction] for Reg D 506(c); drop topic 3 for Reg S non-US. |
| Amortization | Not computed on-chain — servicer's system of record produces principal/interest split per amortization schedule, then calls recordPayment(principalPortion, interestPortion) |
| Default flow | declareDefault() marks the loan defaulted, halts new payment recording. Outstanding principal is emitted for downstream recovery workflow (foreclosure, property sale, distribution of net proceeds). |
| Reference market | Figure Technology Solutions — $18-20B represented value, 56% of Q1 2026 tokenized loan volumes |
Legal: Mortgage-backed claims are securities under U.S. federal law. Regulation D 506(c) issuance requires accredited-investor verification (typically via a Securitize-registered transfer agent or equivalent). The physical mortgage note remains the operative legal instrument; the on-chain token is the settlement + cash-flow-distribution layer.
Fungible fractional equity in a single property held by a Delaware LLC SPV. Sponsor mints ERC-20 shares to eligible investors during offering; property manager deposits net rental income (after property tax, insurance, maintenance reserves) into the contract at operational cadence; accumulator pattern distributes to holders. On property sale, sponsor deposits sale proceeds and holders redeem tokens for pro-rata cash. Reference: RealT and Lofty — U.S. Midwest residential properties tokenized as SPV shares with daily USDC rental distribution.
| Contract | FractionalPropertyToken |
| Roles | SPONSOR (mints shares, records property sale) · PROPERTY_MANAGER (deposits net rental income at configured cadence) · admin |
| Distribution cadence | RealT: daily USDC · Lofty: weekly · larger commercial: monthly. Contract is agnostic — property manager chooses. |
| Sale-of-property flow | recordSale() sets salePoolPerShare and freezes rental deposits. Holders call redeemSaleShare() to burn their tokens and receive pending rental + pro-rata sale proceeds in one call. |
| Evidentiary hashes | propertyAddressHash (privacy — address itself not committed) · propertyDeedHash · spvFormationDocHash (Articles of Organization + Operating Agreement) |
| Reference market | RealT · Lofty — combined ~$100M+ property NAV, primarily Midwest single-family residential |
Legal: Fractional real estate SPV interests are securities in most jurisdictions. RealT's production model restricts to non-U.S. retail via Reg S; other issuers use Reg D 506(c) for U.S. accredited. The Delaware LLC formation, property title transfer, insurance, and ongoing tax filings (K-1s for U.S. LLC members) are the sponsor's off-chain responsibility.
Three-contract permissioned securities stack. Every transfer (including mint) checks the receiver is registered in the IdentityRegistry AND holds every claim topic required by the ClaimTopicsRegistry. Suitable for SPV equity, private-debt tranche tokens, and compliance-gated stablecoins.
| Contracts | IdentityRegistry · ClaimTopicsRegistry · PermissionedToken |
| Bytecode | 2,682 + 2,382 + 6,645 bytes |
| Simplified vs full T-REX | Production Tokeny T-REX has 6 contracts. We ship the 3 that matter for a single-issuer SPV. Add ModularCompliance when transfer rules need per-jurisdiction or per-investor-class logic. |
| Emergency controls | freezeTokens (per-address partial freeze) · forceTransfer (court-ordered, emits reason string) · pause |
| Legal posture | Securities-law obligations (Reg D / Reg S / private-placement filings) remain unchanged. Contract enforces transfer eligibility only. |
One-MWh Solar/Renewable Energy Credit. Mint requires an EIP-712 attestation signed by the registered generator's meter agent (utility, PJM-GATS agent, or on-site data logger). Vintage year + state encoded in the token ID so buyers can filter. Burn is retirement — emits a Retirement event with a reason string for the audit trail.
| Contract | SRECToken |
| Bytecode | 11,108 bytes |
| Token ID encoding | (vintageYear << 240) | (state >> 16) |
| Meter attestation | EIP-712 typed data (generatorId, vintageYear, state, mwhGenerated, nonce, issuedAt) signed by the attestor registered for that generator. Nonces are monotonic per generator. |
| Legal posture | Settlement / secondary-market layer, NOT a replacement for state-registry minting. Compliance-market SRECs (NJ, MA, DC, MD, DE, CT) still need PJM-GATS / NEPOOL-GIS / WREGIS serial numbers. |
Commodity RWA. 1 token = 1 troy oz LBMA-good-delivery gold (4 decimals). Mint gated by ProofOfReserveConsumer circuit breaker against LBMA-vault attestations. Redemption for physical: burn on-chain, physical shipment fulfilled off-chain by the reserve manager. Reference shape: Paxos PAXG.
| Contract | GoldBackedToken |
| Composes with | ProofOfReserveConsumer — feed must report reserves ≥ circulating supply × over-collateralization ratio before mint proceeds |
| Redemption flow | Holder calls requestRedemption(oz) → burns tokens → reserve manager fulfills physical shipment off-chain against redemption ticket |
| Reference deployments | PAXG (Paxos, LBMA vault attestations) · XAUT (Tether) |
Burn a tokenized Verra VCU (Toucan bridge on Polygon) or an issue-native Puro credit (ERC-3643) to retire it against a corporate ESG claim. LPS-1 provenance receipt anchored to Polygon 137 + Bitcoin OpenTimestamps.
| Studio step kind | retire_credit_onchain |
| Gate policy | IRREVERSIBLE — requires typing RETIRE_CREDIT_ONCHAIN at approval time regardless of user tier |
| External deps | Toucan-bridged Verra VCUs, Moss MCO2, or Puro-native ERC-3643 credits |
| Related | Companion to Carbon Portfolio Assessment capability in Studio (calls Unykorn Carbon engine for footprint + offset recommendation, then hands off to on-chain retirement) |
Reads a Chainlink Proof of Reserve feed and drives an automated circuit breaker over minting for a backed RWA token. If off-chain reserves fall below the on-chain circulating supply (adjusted for a configurable over-collateralization ratio), minting auto-pauses until reserves are restored. Same pattern 21.co, Backed, Bedrock, and Bancolombia use in production.
| Contract | ProofOfReserveConsumer |
| Integration | Issuer's mint path calls requireCanMint(currentSupply, mintAmount) before _mint. Reverts with InsufficientReserves if over-collateral threshold breached. |
| Safety checks | Feed staleness · negative-answer rejection · incomplete-round rejection · configurable over-collateralization bps |
| Live PoR users | 21.co (ARK 21Shares BTC ETF) · Backed · Bedrock · Wenia/Bancolombia |
ERC-20 that moves across chains via Chainlink CCIP burn-and-mint. Zero liquidity-pool risk — supply stays unified across every chain. Peer whitelist means only trusted deployments can trigger cross-chain mints. Programmable transfers can bundle tokens + data + instructions atomically (used by Swift+UBS, ANZ, HSBC+Ant Group pilots).
| Contract | CCIPBridgedToken |
| Mechanism | On source: burn locally + ccipSend. On destination: ccipReceive verifies peer + _mint. |
| Reach | 70+ CCIP-supported chains — Ethereum, Polygon, Arbitrum, Base, Avalanche, BNB, Optimism, and expanding |
| Institutional pilots | Swift + UBS · ANZ · SBI Digital + ADDX · HSBC + Ant Group |
Wrapper contract for Chainlink AggregatorV3 price feeds with staleness and heartbeat safety checks. RWA contracts (draw escrow, CMBS waterfall, REIT distributor) that need external prices for collateral valuation or NAV calculation read through this wrapper. If any safety check fails, the read reverts with a specific reason.
| Contract | RWAOracle |
| Bytecode | 3,386 bytes |
| Safety checks | NegativeAnswer · IncompleteRound (answeredInRound < roundId) · AnswerStale · HeartbeatMissed |
| Two entry points | priceFresh() — reverts on any safety violation (use for contracts that MOVE FUNDS). priceRaw() — no checks (use for read-only UI display). |
| Why | >90% of DeFi oracle exploits historically have been stale-price or incomplete-round attacks against contracts that used AggregatorV3.latestRoundData() directly with no safety wrapper. |
Multi-chain expansion. XRPL Hooks in C for XRPL-native lending flows (the pattern used by xrplloans.unykorn.org). Stellar SEP-based assets for cross-border settlement.
| Studio step kinds | deploy_xrpl_hook · deploy_stellar_asset (planned) |
| Adapter pattern | Subprocess bridges (Python for XRPL SDK, JS or Go for Stellar) — same shape Studio uses for the Carbon engine bridge. |
| Related infra | XRPL treasury: rsJ3PGGDH4vPpedjfVRe9YKTCf9BWu6TDC · Stellar treasury: GBJF54FBYPBVHR6Z3OKWWEMPF6QYPNH3RZZYX3E4V7AUMUWIEV7Z3DPX |
Build & test
Requires Foundry.
# Install OpenZeppelin dependencies (pinned)
forge install OpenZeppelin/openzeppelin-contracts@v5.0.2 --no-git
# Compile all contracts
forge build
# Run tests (when tests are added)
forge test -vv
# Deploy against a local Anvil
anvil --host 127.0.0.1 --port 8545 --chain-id 31337 &
forge script script/Deploy<Name>.s.sol --rpc-url http://127.0.0.1:8545 --broadcast
Determinism settings (frozen, in foundry.toml): solc 0.8.24 · optimizer 200 runs · evm_version paris · bytecode_hash ipfs. Same as Unykorn Studio's compile pipeline. Bytecode compiled here is byte-for-byte identical to what Studio produces via its self-hosted WASM worker.
Deal Playbooks
Concrete end-to-end walkthroughs of real deals against the contract library — legal structure, funding-venue selection, term sheet, constructor calls, week-by-week execution, and realistic default enforcement.
-
Inventory Financing: $2M EV chargers in a Tennessee warehouse
Delaware LLC formation → Centrifuge vs Maple funding venue comparison → senior/junior tranche stack ($1.6M senior at 900 bps + $320K junior first-loss) → 18-month amortizing term → constructor payload for InventoryFinancingSPV → UCC-1 filing checklist → month-by-month execution timeline → realistic 6-18 month enforcement path with 50-80% recovery expectation.
-
Invoice Financing: B2B receivables factoring — the easiest RWA to launch first
Delaware SPV + Receivables Purchase Agreement + UCC-1 → published underwriting rules (85% advance, 20% debtor concentration cap, 90 day max tenor, 5-day dispute repurchase) → three-stage funding funnel (anchor $250K-$1M → repeatable $1M-$10M → Sky/Centrifuge $10M+) → constructor payload for InvoiceFactoringPool → 6-step per-invoice operating cycle → dispute vs slow-pay vs write-off failure playbooks → realistic 6-7% net LP yield economics → graduation path to BridgeLoanTranchePool at ~$5M AUM.
More playbooks pending against CMBSWaterfall (M Helen Hotel refinance), RealEstateDebtToken (single-HELOC issuance), and PoolDelegatePool (curated credit onboarding).
Bringing it together: Unykorn Studio
Every contract family here has a companion template in Unykorn Studio. Studio drives the contracts through a per-step approval console with a SHA-256 hash-chained receipt written for every state transition — proposal, approval, execution, failure, source-modified, waiver-committed, attestation-received, draw-released, and every custom action per capability.
The chain is unbroken from "the operator asked for this" through "this exact bytecode was compiled from these exact sources" through "it deployed with these exact deal terms" through "this draw released against this waiver." Counsel can independently verify every claim by:
- Running
curl -s http://localhost:3200/api/receipts | jq .verification — returns { valid: true } if the chain is intact.
- Editing any past receipt in
.unykorn/receipts.jsonl and re-running — returns { valid: false, brokenAtSeq: N, reason: "content tampered" }.
- Reproducing a compile from the receipt's
inputHash + committed solc binary — byte-for-byte match.
- Reproducing a deploy's integrity check by hashing
maskImmutables(eth_getCode) against the compile receipt's deployedBytecodeSha256.
Videos
Explainer scripts and storyboards live in /videos. Record via OBS or Loom; publish to YouTube; embed below when links are live.
- 00 — Overview: what this library is and isn't (4 min)
- 01 — Draw Escrow: the M Helen use case (7 min)
- 02 — Permissioned Securities: ERC-3643 without T-REX complexity (6 min)
- 03 — Carbon Portfolio: subprocess bridge as abstraction test (5 min)
- 04 — The tamper beat: proving the ledger is not editable (3 min)
Audit posture
None of these contracts have been externally audited. Before any deployment holding real funds:
- External security audit (Trail of Bits, ConsenSys Diligence, OpenZeppelin, Sherlock, Code4rena — pick based on capability and budget).
- Static + dynamic analysis (Slither + Mythril + Foundry fuzz + invariant testing).
- Deployment through Unykorn Studio's
sign_external step (BitGo hand-off). Studio never holds testnet or mainnet keys.
- Verify on Etherscan / Sourcify —
metadata.bytecodeHash: ipfs makes verification straightforward.
- Bug bounty program (Immunefi or HackenProof), commensurate with TVL.
Every contract has been designed to be audit-friendly (single-purpose, minimal external calls, explicit custom errors, natspec) — but designed-to-be-audit-friendly is not the same as audited.