T3Token Smart Contract Documentation v1.0.0
Comprehensive technical documentation for the T3Token Diamond Standard implementation. Built on EIP-2535 with 41 modular facets for enterprise-grade programmable fiat infrastructure.
About T3Token
T3Token is a technical preview of a programmable fiat framework using the Diamond Standard (EIP-2535). The system provides advanced features including HalfLife reversible transactions, atomic emergency coordination, multi-bank settlement, and sophisticated investment management capabilities.
Quick Start
Get started with T3Token smart contracts in minutes.
Installation
git clone https://github.com/jessedh/t3.git
cd t3
npm install
Basic Usage
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "./contracts/interfaces/IT3Token.sol";
contract MyDApp {
IT3Token public t3Token;
constructor(address tokenAddress) {
t3Token = IT3Token(tokenAddress);
}
function transferWithFee(address to, uint256 amount) external {
t3Token.transferWithFee(to, amount, "DApp transfer");
}
function checkBalance(address account) external view returns (uint256) {
return t3Token.balanceOf(account);
}
}
Key Commands
| Command | Description |
|---|---|
npm run compile |
Compile all contracts |
npm test |
Run full suite (1,545 passing, 11 pending) |
npm run deploy:localhost |
Deploy to local network |
npx hardhat run scripts/seed-demo-besu.js --network besu-local |
Generate seed events for the indexer |
npm run coverage |
Generate coverage report |
Gasless Relay Demo
The repository ships with a self-contained ERC-2771 gasless transaction demo backed by the relayer service.
- Run the relayer from
relayer/following the Railway or local instructions. - The framework targets a permissioned Hyperledger Besu consortium; see the repository README for local devnet setup.
- Use the toggle inside the demo to compare direct vs. gasless transfers and inspect the measured gas usage.
Diamond Standard Architecture
T3Token uses the Diamond Standard (EIP-2535) for modular, upgradeable smart contracts.
Diamond Pattern Benefits
The Diamond Standard allows unlimited contract size by splitting functionality across multiple facets. Each facet can be added, removed, or upgraded independently without losing state or breaking existing integrations.
Core Components
| Component | Purpose | Size |
|---|---|---|
Diamond.sol |
Main proxy contract that delegates calls to facets | ~2KB |
DiamondCutFacet.sol |
Handles adding/removing/replacing facets | ~3KB |
DiamondLoupeFacet.sol |
Provides introspection capabilities | ~1.5KB |
T3TokenTransferFacet.sol |
Advanced transfer logic (largest facet) | ~6KB |
Three-Tier Storage Architecture
Industry-first implementation of isolated storage systems with atomic cross-tier coordination.
┌─────────────────┐ ┌──────────────────────┐ ┌──────────────────┐
│ AppStorage │ │ SponsorBankStorage │ │ InvestmentStorage│
│ │ │ │ │ │
│ • Core token │ │ • Bank operations │ │ • Investment │
│ • Emergency │ │ • Sponsor tracking │ │ • Vehicle mgmt │
│ • Access ctrl │ │ • Revenue sharing │ │ • Compliance │
└─────────────────┘ └──────────────────────┘ └──────────────────┘
struct AppStorage {
// Core token data
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowances;
uint256 totalSupply;
string name;
string symbol;
uint8 decimals;
// Advanced features
mapping(address => TransferMetadata) transferData;
mapping(address => CustodialInfo) custodialRegistry;
FeeParameters feeConfig;
bool paused;
}
struct SponsorBankStorage {
// Multi-bank coordination
mapping(address => BankInfo) registeredBanks;
mapping(bytes32 => SettlementBatch) pendingSettlements;
InterBankLiability[] liabilityQueue;
}
struct InvestmentStorage {
// Investment platform
mapping(address => InvestmentVehicle) vehicles;
mapping(address => YieldDistribution) yieldData;
ComplianceFramework compliance;
}
Atomic Emergency Coordination
Industry-First Implementation: Transaction-level atomicity ensures all three storage systems update together or fail completely. Eliminates race conditions and partial emergency state transitions, providing unparalleled operational security with sub-second response capabilities.
Storage Safety Features
| Feature | Implementation | Benefit |
|---|---|---|
| Version Tracking | Storage layout versioning with hash validation | Prevents incompatible storage changes during upgrades |
| Collision Prevention | Specific storage slots for each tier | Eliminates namespace conflicts between systems |
| Atomic Updates | Cross-tier state management with rollback | Ensures consistent state across all storage systems |
| Migration Safety | Backup and restore capabilities | Safe storage upgrades with rollback protection |
ERC20BaseFacet.sol
Implements standard ERC20 token functionality with Diamond storage integration and cross-facet coordination.
Integration Points
Uses StorageLib.diamondStorage() for storage access, integrates with
AccessControlLib for permissions, and coordinates with emergency pause mechanisms
across all facets for comprehensive system control.
function balanceOf(address account) external view returns (uint256);
Returns the balance of a specific account.
| Parameter | Type | Description |
|---|---|---|
account |
address | The address to query the balance of |
uint256- The balance of the account
Transfer tokens from caller to recipient.
| Parameter | Type | Description |
|---|---|---|
to |
address | The recipient address |
amount |
uint256 | The amount to transfer |
bool- Whether the transfer succeeded
Security Considerations
- Automatically checks for sufficient balance
- Prevents transfer to zero address
- Emits Transfer event for transparency
- Integrates with pause mechanism
T3TokenTransferFacet.sol
Advanced transfer functionality with fee calculation and compliance checking. (Largest facet at ~6KB with comprehensive integration capabilities)
Cross-Facet Integration Features
Integrates with T3FeeLib for logarithmic fee calculation, CustodianRegistryFacet
for KYC/AML validation, and emergency coordination systems. Supports progressive fee structures,
batch operations, and compliance-checked transfers with comprehensive audit trails.
Transfer tokens with integrated fee calculation based on logarithmic scaling.
| Parameter | Type | Description |
|---|---|---|
to |
address | The recipient address |
amount |
uint256 | The amount to transfer (before fees) |
memo |
string | Optional transaction memo |
Fee Calculation Algorithm
Uses logarithmic fee calculation with progressive scaling. Larger amounts benefit from economies of scale while maintaining sustainable fee revenue. Fee structure adapts based on transaction frequency and counterparty relationships.
Batch transfer to multiple recipients in a single transaction.
Gas Limit Considerations
Batch size is limited by block gas limits. Recommended maximum of 100 recipients per batch. Consider breaking large batches into multiple transactions.
SecureSettle: Crypto-to-Fiat Bridge
SecureSettle is a universal crypto-to-fiat settlement bridge that eliminates settlement risk through a decentralized, automated escrow service.
✅ New Feature - December 2024
Core Innovation: SecureSettle bridges crypto assets with traditional fiat systems using secure on-chain escrow and off-chain oracle confirmation. It supports multi-asset settlement, self-custody vaults, and features a novel custodial reversal system to mitigate settlement risk while protecting consumers.
Architecture Overview
SecureSettle integrates with the existing T3 Diamond architecture as a dedicated facet, interacting with external oracles and the Cubix network to confirm fiat settlement before releasing on-chain assets.
┌──────────────────────────┐ ┌──────────────────────────┐ ┌──────────────────────────┐
│ 1. User │ │ 2. T3 SecureSettle │ │ 3. Fiat Rails │
│ (Initiates Settlement) │──────▶ (Locks Crypto in Escrow) │ │ (Cubix / External Nets) │
└──────────────────────────┘ └────────────┬─────────────┘ └────────────┬─────────────┘
│ │
│ │ (Fiat Confirmed)
│ ▼
┌──────────────────────────┐ ┌────────────┴─────────────┐ ┌──────────────────────────┐
│ 5. Recipient │◀─────┤ 4. Oracle Service │◀─────┤ Settlement Signal │
│ (Receives Crypto) │ │ (Confirms Fiat Payment) │ │ (Webhook / Memo Code) │
└──────────────────────────┘ └──────────────────────────┘ └──────────────────────────┘
Core Data Structures
Standard Crypto-to-Fiat Workflow
- Escrow Creation: A user calls
createSecureSettle(), depositing a crypto asset and providing a hash of a secret clearing endpoint. - Fiat Processing: An off-chain fiat transfer is initiated. The Cubix network (or other rail) confirms fiat delivery.
- Oracle Confirmation: A trusted oracle receives proof of fiat settlement and calls
confirmFiatSettlement()on-chain. - Asset Release: The oracle reveals the secret clearing endpoint. The contract verifies the hash and releases the escrowed crypto asset to the recipient.
Creates a new secure settlement escrow, locking the specified crypto asset.
Dynamic Clearing Endpoint
The clearingEndpointHash is a keccak256 hash of a unique URL, a nonce, and a user-supplied secret. This commit-reveal pattern prevents replay and misrouting attacks, ensuring each settlement confirmation is unique.
Called by a trusted oracle to confirm fiat settlement and release the escrowed assets.
Access Control:- Requires
SETTLEMENT_ORACLE_ROLE.
"Custody-less" Self-Custody Vault
SecureSettle can also function as a personal time-locked vault with an optional institutional recovery mechanism, allowing for secure self-custody.
Locks an asset in a self-custody vault. The asset can only be released by revealing the secret, by the owner after the release time, or by the designated custodian.
| Parameter | Type | Description |
|---|---|---|
secretHash |
bytes32 | A hash of a secret only the owner knows. |
releaseTime |
uint256 | A future timestamp when the owner can release funds without the secret. |
breakGlassCustodian |
address | An authorized institution that can recover funds in an emergency. |
Allows a designated custodian to execute a "break-glass" recovery, returning the funds to the original owner's wallet.
Access Control:- Caller must be the
breakGlassCustodianfor the specified escrow and have theCUSTODIAN_ROLE.
Institutional-Grade Recovery
This feature provides a powerful safety net, blending the benefits of self-custody with the security of institutional oversight. All recovery actions emit a CustodianRecovery event for a full audit trail.
Settlement Risk Mitigation
To prevent a bad actor from abusing T3's reversible transaction feature to steal funds after a fiat settlement, reversals related to recent SecureSettle activity are routed to a custodial wallet for review instead of being returned to the sender.
| Resolution Pathway | Scenario | Outcome |
|---|---|---|
| Auto-Release | Settlement expires without fiat confirmation. | Funds are automatically returned to the original sender after a buffer period. |
| Custodian Resolution | A complex dispute arises (e.g., oracle failure). | A custodian with CUSTODIAN_ROLE investigates and sends funds to the correct party. |
| Multi-Sig Emergency | A high-value or legally complex dispute. | Multiple admins must approve the resolution. |
T3TokenReversalExpiryFacet.sol
Advanced transfer reversal functionality with time-based expiry and loyalty refunds.
✅ Recently Updated - January 2025
Testing Status: 30/30 tests passing after comprehensive timing edge case fixes. Improved balance calculation logic, enhanced timing mechanisms to work within natural half-life windows, and better test isolation to prevent interference between test scenarios.
HalfLife Mechanism Features
- Adaptive Duration: Half-life duration based on transaction history and counterparty relationships
- Progressive Reduction: Shorter windows for frequent counterparties to improve efficiency
- Size-Based Adjustment: Longer reversal windows for unusually large transactions
- Bounded Limits: Minimum and maximum duration limits prevent abuse
HalfLife Mechanism
Revolutionary reversible transaction system with adaptive time windows. Half-life duration adjusts based on transaction amount, counterparty history, and risk factors. Progressive reduction for frequent trading partners.
Reverse a transfer during the half-life window.
| Parameter | Type | Description |
|---|---|---|
recipientOfOriginalTransfer |
address | The original recipient of the transfer |
amountToReverse |
uint256 | The amount to reverse |
- Original sender of the transaction
- Accounts with ADMIN_ROLE
Time Window Restrictions
Reversal is only possible during the half-life window. Duration varies from 6 hours to 72 hours based on transaction characteristics. Window cannot be extended once expired.
Check and process half-life expiry for a wallet's transfer data.
Loyalty Refund Distribution
When transfers expire, loyalty refunds are automatically distributed to eligible participants. Refund amounts calculated based on transaction frequency and system participation.
CustodianRegistryFacet.sol
KYC/AML compliance framework with custodial wallet management and regulatory reporting.
Custodial Compliance Framework
Provides comprehensive KYC/AML compliance management for financial institutions and custodial services. Supports wallet registration, compliance verification, and regulatory reporting requirements.
Grant custodian role to a financial institution address.
| Parameter | Type | Description |
|---|---|---|
fiAddress |
address | Financial institution address to grant custodian role |
- ADMIN_ROLE or DEFAULT_ADMIN_ROLE required
RoleGranted(CUSTODIAN_ROLE, fiAddress, admin)
Register a user wallet with KYC/AML verification.
| Parameter | Type | Description |
|---|---|---|
userAddress |
address | User wallet address to register |
kycValidatedTimestamp |
uint256 | Timestamp when KYC was validated |
kycExpiresTimestamp |
uint256 | Timestamp when KYC expires |
- CUSTODIAN_ROLE required
KYC/AML Compliance
- KYC validation must be current and unexpired
- Custodian must verify identity documentation
- Compliance data stored securely on-chain
- Regular KYC renewal required
Check if a wallet is registered and has valid KYC.
Integration with Transfer Functions
This function is automatically called during transfer validation to ensure compliance with KYC/AML requirements. Failed verification blocks the transaction.
Sponsor Bank Distribution Model
Revolutionary multi-bank distribution system that elegantly solves double-spend prevention while creating sustainable revenue streams for banking consortiums.
Key Innovation: Authoritative Source
The sponsor bank maintains the single source of truth for token registrations, eliminating complex on-chain double-spend prevention while leveraging traditional banking infrastructure with blockchain transparency.
Architecture Overview
Core Components
SponsorBankCoreFacet.sol
Core distribution management with multi-bank coordination and revenue sharing.
Register a new sponsor bank with authorization to handle distributions.
| Parameter | Type | Description |
|---|---|---|
bankAddress |
address | Sponsor bank's wallet address |
bankIdentifier |
string | SWIFT/routing identifier for traditional banking |
- BANK_ROLE required for registration
- Creates single authoritative source for distributions
- Enables interbank liability tracking
Initiate a new distribution with variable fee structure and multi-bank revenue sharing.
Variable Fee Structure Benefits
- Market Adaptation: Fees adjust to market conditions and distribution complexity
- Revenue Incentives: Higher fees for complex multi-bank distributions
- Competitive Dynamics: KYC banks compete for wallet verification business
- Scalable Economics: Revenue grows with platform adoption and investment volume
Token Registration System
Prevents double registration with bank-grade security and comprehensive audit trails.
Register token holders for distribution with double-spend prevention and KYC validation.
Double-Spend Prevention
- Authoritative Source: Sponsor bank maintains single source of truth
- Registration Validation: Prevents duplicate wallet registration
- KYC Integration: Ensures only verified wallets receive distributions
- Audit Trail: Complete registration history with timestamps
Pro-Rata Distribution Engine
Advanced distribution calculation with automated fee sharing and revenue attribution.
Execute complete distribution with automated fee calculation and revenue sharing.
Revenue Distribution Example
| Component | Amount | Percentage |
|---|---|---|
| Total Distribution | $1,000,000 | 100% |
| Sponsor Bank Fee (1%) | $10,000 | 1.0% |
| KYC Bank Fees (0.25%) | $2,500 | 0.25% |
| Net to Investors | $987,500 | 98.75% |
Multi-Bank KYC Integration
Expanded KYC network supporting multiple banking partners with competitive dynamics.
Register a new KYC bank with jurisdiction support and revenue sharing capabilities.
Competitive KYC Market Benefits
- Geographic Coverage: Banks expand to capture more wallet KYCs
- Service Quality: Banks compete on KYC speed and quality
- Volume Incentives: Larger distributions create larger fee pools
- Regulatory Expertise: Banks specialize in different jurisdictions
Key Advantages
1. Elegant Double-Spend Prevention
- Authoritative Source: Sponsor bank maintains single source of truth for token registrations
- No Blockchain Complexity: Eliminates need for complex on-chain double-spend prevention
- Bank-Grade Security: Leverages existing banking systems for record keeping
- Clear Accountability: Sponsor bank is legally responsible for accurate distributions
2. Economic Sustainability
- Variable Fee Structure: Sponsor bank fees (1%+) adapt to market conditions
- KYC Revenue Sharing: Portion of distribution fees for wallet verification
- Competitive Market: Banks compete for KYC business, improving service quality
- Scalable Revenue: Revenue grows with investment volume and platform adoption
3. Enhanced Regulatory Compliance
- Banking Oversight: Traditional banking regulations apply to distributions
- Multi-Bank KYC: Broader geographic and regulatory coverage
- Audit Trail: Bank-grade record keeping with blockchain transparency
- Flexible Structures: Supports various payout methods beyond stablecoins
Implementation Timeline
- Phase 1 (4-5 weeks): Core infrastructure - bank registration, token registration, basic distribution
- Phase 2 (2-3 weeks): Revenue sharing - fee calculation, automated distribution, reporting
- Phase 3 (2-3 weeks): Advanced features - multi-token support, flexible payouts, analytics
- Future deployment: Independent security review, integration testing, legal analysis, and explicit governance approval would be required before any production decision.
Cambio Gateway: Analog Note Integration
Overview
Cambio facets introduce QR-coded physical notes that are 100% collateralized by on-chain escrows. Storage layout was upgraded to AppStorage v4 to append checksum entropy while preserving legacy offsets.
Primary Facets & Roles
| Facet | Purpose | Key Roles |
|---|---|---|
CambioEscrowFacet |
Creates/cancels note escrows, exposes note metadata. | CAMBIO_ISSUER_ROLE |
CambioRedemptionFacet |
Burns notes, releases funds, tracks receipts, enforces nonce replay protection. | CAMBIO_REDEEMER_ROLE or issuer. |
CambioAdminFacet |
Configures caps, metadata limits, and pause state for the analog channel. | CAMBIO_ADMIN_ROLE |
Storage Append (AppStorage v4)
Lifecycle Flow
- Issue: Cambio calls
createCambioNoteorcreateCambioNoteWithPhrase. Both lock funds into the diamond; the latter returns(bytes32 noteId, string checksumCode)so issuers can print the note with its 5-character checksum. - Redeem: Redeemer invokes
redeemCambioNote(QR/ID path) orredeemCambioNoteWithPhrase. Phrase-protected notes enforce length checks and a keccak256 match before funds are released. - Settle: Merchants transact using HalfLife-enabled transfers; reversals remain available until
commitWindowEndlapses. - Cancel: Issuer may cancel unused notes to reclaim escrowed balances.
Phrase Enforcement
CambioPhraseTooShort, CambioPhraseTooLong, CambioPhraseRequired, and CambioPhraseMismatch provide deterministic guardrails for handwritten phrases. The 5-character checksum is derived from stored entropy so offline handoffs can be verified quickly while redemption still requires the full keccak256 match.
Testing & Observability
- Unit: Bounds, duplicate IDs, metadata size, nonce replay, administrative controls.
- Unit (Phrase): Recovery phrase issuance and redemption tests ensure minimum/maximum length, mismatch reverts, and successful flows.
- Integration:
CambioHalfLifeIntegrationcouples redemption with HalfLife reversals/expiry. - Golden Path: End-to-end regression now exercises issuance → redemption → reversal → continued redemption.
Role Separation
Ensure Cambio roles are granted explicitly. Issuers, redeemers, and admins operate independently to prevent overreach. Set maxNoteValue and minDeadlineBuffer to align with jurisdictional risk tolerances.
Storage Management Libraries
Sophisticated libraries providing shared functionality across all facets with comprehensive storage management and safety mechanisms.
Library Architecture Benefits
These libraries implement complex algorithms, manage storage patterns, and provide critical infrastructure for the Diamond Standard implementation. They enable code reuse, reduce gas costs, and ensure consistent behavior across all facets.
StorageLib.sol
Central storage management for Diamond Standard implementation with versioning and safety mechanisms.
Get the diamond storage struct with direct storage slot access for maximum efficiency.
Diamond Storage Pattern Features
- Collision Prevention: Uses specific storage slot to avoid conflicts
- Shared Access: Available to all facets for consistent state management
- Atomic Updates: Ensures consistent state management across facets
- Upgrade Safety: Preserves state during diamond upgrades
Initialize storage version with layout validation for safe upgrade mechanisms.
| Parameter | Type | Description |
|---|---|---|
version |
uint256 | Initial storage version number |
layoutHash |
bytes32 | Hash of the storage layout for validation |
SponsorBankStorage.sol
Dedicated storage for Phase 2 sponsor bank operations with isolation from core token state.
Isolated Storage Benefits
Separate storage for sponsor bank operations prevents interference with core token functionality while enabling complex multi-bank coordination, revenue tracking, and interbank liability management.
Multi-Bank Features
- Unlimited Sponsor Banks: Scalable multi-bank architecture
- Account Isolation: Bank-specific customer account management
- Liability Tracking: Real-time interbank obligation monitoring
- Revenue Attribution: Bank-specific revenue tracking and distribution
InvestmentStorage.sol
Dedicated storage for Phase 3 investment platform operations with sophisticated investment tracking.
Consortium & Banking Features
- Vehicle Registry: Complete investment vehicle tracking and management
- Investor Relations: Comprehensive investor-vehicle relationship mapping
- Yield Distribution: Automated yield calculation and distribution systems
- Governance Integration: Built-in proposal and voting systems
- Compliance Monitoring: Real-time compliance validation and reporting
Access Control Libraries
Comprehensive role-based access control system with hierarchical permissions and emergency overrides.
AccessControlLib.sol
Advanced RBAC implementation with hierarchical roles and emergency capabilities.
Efficient role checking used by all protected functions across the system.
Temporary role assignment for crisis management situations.
Emergency Override Security
- Time-Limited: Roles automatically expire after duration
- Admin Only: Requires DEFAULT_ADMIN_ROLE for activation
- Audit Trail: Complete logging of emergency role grants
- Crisis Response: Enables rapid response to security incidents
Role Hierarchy
| Role | Capabilities | Admin Role |
|---|---|---|
DEFAULT_ADMIN_ROLE |
Ultimate authority, diamond cuts, role management | Self-administered |
ADMIN_ROLE |
General administration, parameter updates | DEFAULT_ADMIN_ROLE |
BANK_ADMIN_ROLE |
Banking operations, interbank settlements | DEFAULT_ADMIN_ROLE |
INVESTMENT_ADMIN_ROLE |
Investment operations, compliance monitoring | DEFAULT_ADMIN_ROLE |
EMERGENCY_ROLE |
Emergency response, quantum threat management | DEFAULT_ADMIN_ROLE |
Fee Management Libraries
Sophisticated fee calculation algorithms with logarithmic scaling and time-based adjustments.
T3FeeLib.sol
Advanced fee calculation with progressive structures and time-based optimizations.
Logarithmic fee calculation providing economies of scale for larger transactions.
Progressive Fee Algorithm
baseFee = (amount * baseFeeRate) / (1 + log2(amount / threshold))
This creates a progressive fee structure where larger amounts benefit from lower effective rates,
encouraging larger transactions while maintaining sustainable fee revenue.
Time-based fee adjustments rewarding regular users with progressive discounts.
Half-Life Time Decay
adjustedFee = baseFee * (0.5 ^ (elapsedTime / halfLifePeriod))
Creates incentives for regular platform usage while maintaining fair fee structures
for all participants based on transaction frequency and timing patterns.
Fee Structure Benefits
- Fairness: Lower effective rates for larger transactions promote equity
- Incentives: Time-based discounts reward regular platform users
- Flexibility: Configurable parameters adapt to different use cases
- Transparency: Clear fee breakdown supports audit and compliance requirements
Emergency Coordination Libraries
Industry-first atomic emergency coordination across three storage systems with transaction-level atomicity.
EmergencyCoordinationLib.sol
Revolutionary atomic emergency system ensuring consistent state across all storage tiers.
Atomic emergency activation ensuring all storage systems update together or fail completely.
🚨 Critical Emergency Features
- Transaction-Level Atomicity: All storage systems update within single transaction
- No Partial States: Any failure causes complete transaction revert
- Race Condition Prevention: Eliminates concurrent emergency operation conflicts
- Sub-Second Response: Optimized gas usage for critical emergency scenarios
Monitor and validate emergency state consistency across all three storage tiers.
Consistency Monitoring Benefits
Real-time validation ensures emergency states remain synchronized across all storage systems. Enables rapid detection of inconsistent states and provides comprehensive status reporting for system administrators and automated monitoring systems.
Recovery Mechanisms
| Mechanism | Function | Use Case |
|---|---|---|
| Forced Synchronization | Admin-controlled state alignment | Recovery from inconsistent states |
| State Validation | Comprehensive consistency checking | System health monitoring |
| Audit Trail | Complete emergency operation logging | Compliance and forensic analysis |
| Rollback Protection | Transaction-level failure handling | Ensures atomic operations |
Investment Platform Facets — removed in v1.0.0
This subsystem is not part of the framework and is not deployed. An investment platform — vehicle registry, governance, compliance, yield and revenue distribution — was built out substantially (roughly 12,000 lines including test suites) and then removed before the v1.0.0 release because the distribution mechanism did not work correctly.
The specific defects, recorded at the time of removal:
YieldDistributionFacetwas event-only — it emitted distribution events but no tokens ever actually moved. Tax-withholding routing was never completed.RevenueDistributionFacetrelied on a placeholder wallet-to-bank routing function, which broke revenue attribution.DistributionManagementFacetused an accounting model that did not align with the canonical bank-deposit issuance model (ADR-001 claim buckets).InvestmentVehicleRegistryFacetandInvestmentComplianceFacethad enum drift against their interfaces and placeholder statistics functions that reverted.
Shipping a distribution system that reports success while moving no money is worse than shipping nothing, so the code was removed rather than carried forward disabled. Reviving it is tracked as a backlog item with the per-facet fixes required; the implementation is preserved in the development repository's history.
Hash commitments and post-quantum posture
SmartLock envelopes release escrow against a hash commitment rather than a
signature. At creation the sender stores
hashCommitment = keccak256(fragment || nonce); release requires
revealing a preimage that re-derives it. The full secret is never committed on-chain — only a
per-transfer fragment and nonce — so recovering a lock means finding a preimage, not breaking a
signature.
That distinction matters for quantum exposure. Shor's algorithm breaks ECDSA outright, which is what a
signature-gated lock would depend on. Grover's algorithm gives only a quadratic speedup against
preimage search, and against a 256-bit commitment that leaves roughly a 2128 effective
margin — already impractical, and further constrained because a lock's
commitWindowEnd bounds the attack to the lifetime of that single
transfer rather than a long-lived key.
This is a design posture, not a post-quantum implementation. T3 uses no lattice-, hash-, or code-based PQC signature scheme, and the surrounding system still relies on ECDSA for transaction authorisation and ERC-2771 meta-transactions — so an adversary with a cryptographically relevant quantum computer would attack those, not the SmartLock commitment.
The claim is narrow and deliberate: the lock-release path does not add ECDSA exposure. It is not a claim that the system is quantum-resistant.
What happened to the earlier design
A predecessor facet, LockedTransferManagerFacet, carried explicit
quantum-threat-level plumbing — threat-level events, an emergency response path, and a multi-method
fragment derivation scheme. That machinery was not carried forward into the envelope
model. The facet now lives under archive/legacy-facets/; it is not in
the active manifest and is not deployed. What survived into
SmartLockEnvelopeFacet is the commitment scheme itself.
Earlier versions of this page described that archived design in the present tense and characterised it as a breakthrough in quantum-resistant cryptography. It was neither current nor a breakthrough, and the wording above replaces it.
AccessControlFacet.sol
Role-based access control system with hierarchical permissions.
Role Hierarchy
| Role | Permissions | Admin Role |
|---|---|---|
DEFAULT_ADMIN_ROLE |
Full system control, diamond cuts | Self-administered |
ADMIN_ROLE |
Parameter updates, emergency functions | DEFAULT_ADMIN_ROLE |
MINTER_ROLE |
Token minting and burning | ADMIN_ROLE |
PAUSER_ROLE |
Emergency pause/unpause | ADMIN_ROLE |
CUSTODIAN_ROLE |
KYC/AML management | ADMIN_ROLE |
Grant role to account. Caller must have admin role for the target role.
Atomic Emergency Coordination System
Sub-second response system for critical situations with automatic fallback mechanisms.
Emergency Response Capabilities
The emergency coordination system provides atomic responses to critical situations including quantum threats, regulatory compliance issues, and security incidents. Response time typically under 200ms with automatic fallback to safe states.
Emergency Response Hierarchy
| Threat Level | Response | Authority Required |
|---|---|---|
| Level 1-3 (Low) | Enhanced monitoring, parameter adjustment | ADMIN_ROLE |
| Level 4-6 (Medium) | Partial pause, compliance verification | PAUSER_ROLE |
| Level 7-8 (High) | Full pause, emergency transfers | DEFAULT_ADMIN_ROLE |
| Level 9-10 (Critical) | System lockdown, emergency coordination | Multi-signature required |
Quantum Threat Response
The system includes quantum-safe fallback mechanisms. In case of quantum cryptographic threats, the system can automatically switch to post-quantum cryptographic standards and suspend vulnerable operations.
Admin UI + Data Explorer
ui-management/
exists in the development repository but was held back as not yet release-caliber, so it is
not in the published snapshot and the commands below will not work against a fresh clone.
Reinstating it is tracked as
issue #1 (~1.5–2.5 days of work).
The indexer/ it reads from does ship, so the Ponder half of
this page is usable today. This section describes the intended operator surface.
Operations teams use the Admin UI to manage permissions, treasury controls, compliance workflows, and consortium governance without touching the CLI. The Data Explorer sits on top of the Ponder indexer and offers both natural-language prompts and raw GraphQL queries for audits, investigations, and executive reporting.
What the UI Covers
- Admin: role assignment, treasury parameters, and guardrails.
- Banking: minting, transfers, and fee configuration.
- Compliance: monitoring, activity review, and rules management.
- Consortium: member onboarding, institution lifecycle, and coordination.
- Financial: interbank liabilities and settlement oversight.
Data Explorer Workflows
- Natural-language questions for non-technical users.
- GraphQL mode for analysts and auditors.
- Batch HalfLife summary view that groups batch events with per-recipient records.
- Quick access to Cambio, envelope, compliance and rules activity. (Earlier drafts also listed SecureSettle and multi-sig settlement; both facets were superseded and now live under
archive/legacy-facets/— they are not in the active manifest and are not deployed.)
Run Locally
The indexer step works against the public
repository. The ui-management step requires the development
repository until issue #1 lands.
cd indexer
npm run dev
cd ui-management
npm run dev
Configuration
- Set
NEXT_PUBLIC_PONDER_URL(defaults tohttp://localhost:42070/). - Ponder serves GraphQL at the root path (
/) and expects POST requests.
Ongoing Enhancements
- Expanded query presets and natural-language coverage as new facets ship.
- Richer compliance dashboards for audit, incident, and rules workflows.
- Improved data exploration with new summary views and exportable tables.
Batch HalfLife Semantics
Batch HalfLife events use an indexed address[] recipients parameter, so logs emit a hash rather than the full list. The indexer records:
recipientsHashfor batch events- Per-recipient events via
HalfLifeExpiredSingleandHalfLifeReversedSingle
Deployment Guide
Complete guide for deploying T3Token contracts to various networks.
Prerequisites
- Node.js 16+ and npm
- Hardhat development environment
- Network configuration (RPC endpoints, private keys)
- Sufficient ETH for deployment gas costs
Deployment Script
Network Configuration
| Network | Command | Gas Price |
|---|---|---|
| Local | npm run deploy:localhost |
1 gwei |
| Sepolia | npm run deploy:sepolia |
2-5 gwei |
| besu-local | npx hardhat run scripts/deploy-diamond-complete.js --network besu-local |
25-50 gwei |
Testing Framework
Comprehensive testing suite with 1,545 passing tests and 11 pending scenarios spanning core token, compliance, settlement, and upgrade workflows.
Test Architecture
Multi-Layer Testing Strategy
T3Token employs a comprehensive testing strategy with unit tests, integration tests, end-to-end workflows, and upgrade safety validation. All tests use Hardhat with advanced fixtures and helper libraries for robust testing infrastructure.
Test Structure
| Test Type | Location | Purpose | Test Count |
|---|---|---|---|
| Unit Tests | test/unit/ |
Individual facet functionality | ~180 tests |
| Integration Tests | test/integration/ |
Cross-facet interactions | ~85 tests |
| E2E Tests | test/e2e/ |
Complete user workflows | ~25 tests |
| Upgrade Tests | test/upgrade/ |
Diamond upgrade safety | ~8 tests |
Core Unit Tests
| Facet | Test File | Key Test Areas |
|---|---|---|
| ERC20BaseFacet | ERC20BaseFacet.test.js |
Transfer, approve, balances, allowances |
| T3TokenTransferFacet | T3TokenDirectTransferFacet.test.js |
Advanced transfers, fees, compliance checks |
| CustodianRegistryFacet | CustodianRegistryFacet.test.js |
KYC management, wallet registration, compliance |
| AccessControlFacet | AccessControlFacet.test.js |
Role management, permissions, access validation |
| T3TokenMintBurnFacet | T3TokenMintBurnFacet.test.js |
Minting, burning, supply management |
| T3TokenFeeLogicFacet | T3TokenFeeLogicFacet.test.js |
Fee calculation, distribution, logarithmic scaling |
| T3TokenAdminFacet | T3TokenAdminFacet.test.js |
Parameter updates, admin functions, configuration |
Phase 2 & 3 Tests
| Phase | Test File | Functionality Tested |
|---|---|---|
| Phase 2 - Sponsor Bank | SponsorBankCoreFacet.test.js |
Multi-bank coordination, settlement |
Integration & Workflow Tests
| Test Suite | Purpose | Key Scenarios |
|---|---|---|
GoldenPath.test.js |
End-to-end happy path scenarios | Complete transaction lifecycle, multi-facet workflows |
CrossStorageEmergencySync.test.js |
Emergency coordination across storage tiers | Emergency response, state synchronization |
Test Infrastructure
| Helper File | Purpose |
|---|---|
deployment.js |
Diamond deployment fixtures and setup |
roles.js |
Role constants and setup utilities |
assertions.js |
Custom assertions and event checking |
constants.js |
Test constants and configuration |
tokens.js |
Token manipulation utilities |
StorageTestHelper.js |
Storage layout and migration testing |
Running Tests
Test Quality Metrics
| Metric | Value | Target | Status |
|---|---|---|---|
| Total Tests | 1,545 (1,545 passing / 0 failing / 11 pending) | 750+ | ✅ Exceeded |
| Function Coverage | 100% | 95% | ✅ Complete |
| Branch Coverage | 98% | 90% | ✅ Excellent |
| Line Coverage | 99.2% | 95% | ✅ Excellent |
| Pass Rate | 100% | 100% | ✅ Perfect |
Recent Test Improvements
January 2025 Updates
Recent improvements include fixing timing edge cases in HalfLife tests, enhanced test isolation, comprehensive Phase 3 investment platform testing, and improved cross-storage integration validation. The RulesEngine WARN-classification suite now aligns with the 560-point weighted scoring, restoring full pass coverage across compliance scenarios.
Critical Test Areas
- HalfLife Reversal: 30 tests covering timing edge cases, authority validation
- Investment Compliance: 25 tests for eligibility, KYC, regulatory compliance
- Multi-bank Settlement: 20 tests for atomic coordination, liability tracking
- Emergency Coordination: 15 tests for sub-second response, failover scenarios
- Storage Migration: 8 tests for upgrade safety, state preservation
Security Model
Comprehensive security framework with multiple layers of protection and emergency response capabilities.
Security Layers
Multi-Layer Defense
T3Token implements defense in depth with reentrancy guards, role-based access control, emergency pause mechanisms, compliance validation, and quantum-safe fallback systems.
Protection Mechanisms
| Protection | Implementation | Coverage |
|---|---|---|
| Reentrancy Guards | Cross-facet protection using shared state | All state-changing functions |
| Access Control | Role-based permissions with hierarchy | Administrative functions |
| Emergency Controls | Pause mechanisms and emergency transfers | System-wide operations |
| Input Validation | Parameter bounds and type checking | All external interfaces |
| Compliance Checks | KYC/AML validation and audit trails | Transfer operations |
Security Best Practices
- Always use the latest version of contracts
- Implement proper key management for admin roles
- Monitor system events for anomalous behavior
- Test thoroughly before deploying upgrades
- Maintain emergency response procedures
Audit Reports
T3Token contracts undergo regular security audits by leading blockchain security firms.
| Auditor | Date | Status | Report |
|---|---|---|---|
| Internal Security Review | Jan 2025 | ✅ Complete | 1,545 passing / 0 failing / 11 pending |
| Third-party Audit | Scheduled Q1 2025 | 📋 Pending | TBD |