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).

🏢 Real Estate / Structured Finance

Draw Escrow (Georgia)

SHIPPED EVM

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.

ContractsIWaiverAttestor (types) · MilestoneRegistry · DrawEscrow · LocalTestToken
BytecodeDrawEscrow 6,642 bytes · MilestoneRegistry 3,181 bytes
Dependencies@openzeppelin/contracts v5.0.2 (AccessControl · Pausable · ReentrancyGuard · SafeERC20 · EIP712 · SignatureChecker)
Reference deploymentM Helen Hotel LLC SPV (construction draws against $25M senior + $4.1M mezz)
Legal postureOn-chain contract EVIDENCES the waiver; does not constitute or replace the Georgia statutory-form waiver required under O.C.G.A. § 44-14-366.

REIT NOI Distribution

SHIPPED EVM

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.

ContractsDistributionToken · REITDistributor
BytecodeDistributionToken 4,386 bytes · REITDistributor 4,506 bytes
PatternAccumulator (accCurrencyPerUnit + per-holder debtCursor)
Why not ERC20SnapshotOZ v5 removed ERC20Snapshot. Accumulator pattern is the standard replacement — same math, works with plain ERC-20.
Legal postureREIT tax status (90% distribution rule, closely-held test, qualifying-asset composition) is an off-chain determination. Contract enforces distribution mechanics only.

CMBS 3-Tranche Waterfall

SHIPPED EVM

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.

ContractCMBSWaterfall
Bytecode5,537 bytes
Default ratesSenior 700 bps (7%) · Mezz 1100 bps (11%) · Equity 0 (residual)
ContributionrecordContribution() for admin-registered off-chain funding, or fund() for on-chain push.
Legal postureCMBS securitization involves REMIC / grantor-trust tax elections and offering-document disclosures this contract does not model.

🏦 Private Credit / Institutional Lending

Pool Delegate Pool (Maple-style)

SHIPPED EVM

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.

ContractPoolDelegatePool
RolesPOOL_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 flowrequestRedemption() → cooldown elapses → executeRedemption() from idle balance
Reference marketMaple Finance — $4.6–$5B AUM · $2B active loans · $22B+ cumulative originations · targeting $100B annual by 2030

Invoice Factoring Pool (Centrifuge-shape)

SHIPPED EVM

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.

ContractInvoiceFactoringPool
RolesORIGINATOR (funds invoices, records repayments) · LP_WHITELIST (KYC-gated deposit access)
Advance rateConfigurable per invoice (80-90% typical). Discount from face becomes LP yield when payer settles.
Reference marketCentrifuge Tinlake — invoice financing pools + supply-chain finance
PlaybookInvoice Financing: B2B receivables factoring — full deal walkthrough from SPV formation through Stage-3 scale, published underwriting rules, per-invoice operating cycle

Bridge Loan Tranche Pool (Centrifuge Tinlake shape)

SHIPPED EVM Sky protocol composable

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.

ContractBridgeLoanTranchePool
Tranche stackSenior — 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 integrationSenior 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 floworiginateLoan() draws from idle pool currency → borrower funded · repayLoan() settles principal + accrued interest, senior gets APY, junior receives residual via _juniorNav
Write-down flowwriteDownLoan() marks loan defaulted, reduces totalDeployed, increments totalWriteDowns. Junior NAV absorbs first via _juniorNav clamp to zero.
Reference marketCentrifuge active pools ~$430M + Janus Henderson JTRSY $880M

Inventory Financing SPV

SHIPPED EVM Playbook: EV chargers

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.

ContractInventoryFinancingSPV
PhasesSetup → 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 enforcementOn 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 optionsCentrifuge (senior tranche composable with Sky protocol for USDS borrow) · Maple (Pool Delegate underwrites) · Family office / private capital direct

💵 Tokenized Funds

Tokenized Treasury / Money Market Fund

SHIPPED BUIDL / OUSG / USYC shape PoR-gated mint

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.

ContractTokenizedTreasury
Composes withPermissionedToken (receiver eligibility) · ProofOfReserveConsumer (mint circuit breaker)
NAV pricingAdmin publishes daily NAV per share; subscriptions/redemptions price against that NAV with T+N settlement queue
Reference deploymentsBUIDL ($500M+ AUM) · BENJI · OUSG · USYC

Cash Management Vault (ERC-4626)

SHIPPED ERC-4626

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.

ContractCashManagementVault
RolesALLOCATOR (rebalances into yield-bearing RWA shares) · admin
Reserve ratioConfigurable minimum stablecoin reserve (e.g. 10%) held in the vault at all times for instant redemptions. Allocator cannot deploy below the floor.

🏠 Real Estate (Debt + Equity)

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.

Tokenized Mortgage / HELOC (Figure-shape)

SHIPPED EVM Reg D 506(c) / Reg S

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.

ContractRealEstateDebtToken
RolesISSUER (mints shares during offering) · SERVICER (records monthly P+I payments, can declare default) · admin
Eligibility gateSame 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.
AmortizationNot computed on-chain — servicer's system of record produces principal/interest split per amortization schedule, then calls recordPayment(principalPortion, interestPortion)
Default flowdeclareDefault() marks the loan defaulted, halts new payment recording. Outstanding principal is emitted for downstream recovery workflow (foreclosure, property sale, distribution of net proceeds).
Reference marketFigure Technology Solutions — $18-20B represented value, 56% of Q1 2026 tokenized loan volumes

Fractional Property Equity (RealT / Lofty-shape)

SHIPPED EVM Reg S / Reg D

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.

ContractFractionalPropertyToken
RolesSPONSOR (mints shares, records property sale) · PROPERTY_MANAGER (deposits net rental income at configured cadence) · admin
Distribution cadenceRealT: daily USDC · Lofty: weekly · larger commercial: monthly. Contract is agnostic — property manager chooses.
Sale-of-property flowrecordSale() 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 hashespropertyAddressHash (privacy — address itself not committed) · propertyDeedHash · spvFormationDocHash (Articles of Organization + Operating Agreement)
Reference marketRealT · Lofty — combined ~$100M+ property NAV, primarily Midwest single-family residential

🏛 Securities / Compliance

Permissioned Security Token

SHIPPED ERC-3643-inspired EVM

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.

ContractsIdentityRegistry · ClaimTopicsRegistry · PermissionedToken
Bytecode2,682 + 2,382 + 6,645 bytes
Simplified vs full T-REXProduction 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 controlsfreezeTokens (per-address partial freeze) · forceTransfer (court-ordered, emits reason string) · pause
Legal postureSecurities-law obligations (Reg D / Reg S / private-placement filings) remain unchanged. Contract enforces transfer eligibility only.

🌱 ESG / Climate / Sovereignty

SREC Token

SHIPPED ERC-1155 EVM

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.

ContractSRECToken
Bytecode11,108 bytes
Token ID encoding(vintageYear << 240) | (state >> 16)
Meter attestationEIP-712 typed data (generatorId, vintageYear, state, mwhGenerated, nonce, issuedAt) signed by the attestor registered for that generator. Nonces are monotonic per generator.
Legal postureSettlement / 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.

Gold-Backed Token (PAXG-shape)

SHIPPED Chainlink PoR

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.

ContractGoldBackedToken
Composes withProofOfReserveConsumer — feed must report reserves ≥ circulating supply × over-collateralization ratio before mint proceeds
Redemption flowHolder calls requestRedemption(oz) → burns tokens → reserve manager fulfills physical shipment off-chain against redemption ticket
Reference deploymentsPAXG (Paxos, LBMA vault attestations) · XAUT (Tether)

On-chain Carbon Retirement

DESIGN CONTRACT

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 kindretire_credit_onchain
Gate policyIRREVERSIBLE — requires typing RETIRE_CREDIT_ONCHAIN at approval time regardless of user tier
External depsToucan-bridged Verra VCUs, Moss MCO2, or Puro-native ERC-3643 credits
RelatedCompanion to Carbon Portfolio Assessment capability in Studio (calls Unykorn Carbon engine for footprint + offset recommendation, then hands off to on-chain retirement)

🔗 Oracles / Cross-chain

Proof of Reserve Consumer

SHIPPED Chainlink PoR EVM

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.

ContractProofOfReserveConsumer
IntegrationIssuer's mint path calls requireCanMint(currentSupply, mintAmount) before _mint. Reverts with InsufficientReserves if over-collateral threshold breached.
Safety checksFeed staleness · negative-answer rejection · incomplete-round rejection · configurable over-collateralization bps
Live PoR users21.co (ARK 21Shares BTC ETF) · Backed · Bedrock · Wenia/Bancolombia

CCIP Bridged Token

SHIPPED Chainlink CCIP Burn-and-Mint

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).

ContractCCIPBridgedToken
MechanismOn source: burn locally + ccipSend. On destination: ccipReceive verifies peer + _mint.
Reach70+ CCIP-supported chains — Ethereum, Polygon, Arbitrum, Base, Avalanche, BNB, Optimism, and expanding
Institutional pilotsSwift + UBS · ANZ · SBI Digital + ADDX · HSBC + Ant Group

XRPL Hooks + Stellar SEP Token

DESIGN CONTRACT

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 kindsdeploy_xrpl_hook · deploy_stellar_asset (planned)
Adapter patternSubprocess bridges (Python for XRPL SDK, JS or Go for Stellar) — same shape Studio uses for the Carbon engine bridge.
Related infraXRPL 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.

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:

  1. Running curl -s http://localhost:3200/api/receipts | jq .verification — returns { valid: true } if the chain is intact.
  2. Editing any past receipt in .unykorn/receipts.jsonl and re-running — returns { valid: false, brokenAtSeq: N, reason: "content tampered" }.
  3. Reproducing a compile from the receipt's inputHash + committed solc binary — byte-for-byte match.
  4. 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.

Audit posture

None of these contracts have been externally audited. Before any deployment holding real funds:

  1. External security audit (Trail of Bits, ConsenSys Diligence, OpenZeppelin, Sherlock, Code4rena — pick based on capability and budget).
  2. Static + dynamic analysis (Slither + Mythril + Foundry fuzz + invariant testing).
  3. Deployment through Unykorn Studio's sign_external step (BitGo hand-off). Studio never holds testnet or mainnet keys.
  4. Verify on Etherscan / Sourcify — metadata.bytecodeHash: ipfs makes verification straightforward.
  5. 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.