Skip to content

Smart contracts for the DecentraLabs project, including the diamond proxy, the multiple facets and the $LAB token

License

Notifications You must be signed in to change notification settings

DecentraLabsCom/Smart-Contracts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

214 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DecentraLabs Smart Contracts

A comprehensive blockchain-based solution for managing access to worldwide server-based simulations, laboratory equipment, and other Cyber-Physical Systems through a decentralized platform. Built on Ethereum using the Diamond proxy pattern for maximum upgradeability and modularity.

🌟 Overview

DecentraLabs provides a blockchain infrastructure for managing access, reservations, and payments to lab resources and services. The system enables:

  • Lab Providers to register and manage their laboratory equipment as NFTs
  • Users to discover, reserve, and access laboratory equipment worldwide
  • Administrators to oversee the platform and manage roles
  • Transparent payments using the native $LAB ERC20 token

πŸ—οΈ Architecture

This project implements a modular smart contract architecture using the EIP-2535 Diamond Standard, allowing for efficient upgrades and unlimited contract functionality.

Core Components

Diamond Proxy (Main Contract)
β”œβ”€β”€ DiamondCutFacet       (Upgrade management)
β”œβ”€β”€ DiamondLoupeFacet     (Introspection)
β”œβ”€β”€ OwnershipFacet        (Ownership management)
β”œβ”€β”€ DistributionFacet     (Tokenomics distribution and subsidies)
β”œβ”€β”€ IntentRegistryFacet   (EIP-712 intent registration and consumption)
β”œβ”€β”€ ProviderFacet         (Provider & institutional treasury management)
β”œβ”€β”€ LabFacet              (Lab/NFT management)
β”œβ”€β”€ StakingFacet          (Staking, slashing, and unstaking)
β”œβ”€β”€ Reservation Facets    (Booking & payments for labs)
└── LabERC20              (External: $LAB token)

✨ Key Features

1. Diamond Proxy Pattern (EIP-2535)

  • Unlimited contract size: Break through the 24KB Ethereum contract size limit
  • Upgradeable architecture: Add, replace, or remove functionality without redeploying
  • Gas efficient: Share storage across all facets
  • Modular design: Organize code into logical facets

2. Lab Management (LabFacet)

  • NFT-based labs: Each laboratory is represented as an ERC-721 token
  • Comprehensive metadata: URI, pricing, authentication endpoints, and access keys
  • Provider control: Lab owners can add, update, and delete their laboratories
  • Paginated queries: Efficient retrieval of lab listings
  • Transfer restrictions: Only lab providers can own lab NFTs

3. Reservation System (Reservation Facets)

  • Time-based booking: Reserve labs for specific time periods
  • Interval tree calendar: Efficient O(log n) calendar conflict detection
  • Multi-state workflow:
    • PENDING - User requests reservation
    • CONFIRMED - Admin confirms reservation
    • IN_USE - Reservation is active
    • COMPLETED - Reservation finished, ready for collection
    • COLLECTED - Provider claims payment after use
    • CANCELLED - Cancelled by user or provider
  • Automatic refunds: Failed or cancelled reservations are automatically refunded
  • Batch processing: Providers can claim multiple completed reservations in batches

4. $LAB Token (LabERC20)

  • ERC-20 compliant: Standard token interface
  • Supply cap: Maximum supply of 1,000,000 tokens (1M tokens with 6 decimals)
  • Burnable: Token holders can burn their tokens
  • Pausable: Emergency pause functionality for security incidents
  • Role-based minting: Only authorized contracts can mint new tokens
  • Initial distribution: New providers receive initial token allocation

5. Provider Management (ProviderFacet)

  • Role-based access control: Distinct roles for admins, providers, and institutions
  • Provider registry: Track provider information (name, email, country)
  • Institutional treasury: Manage token balances for institutional users
  • Automatic token grants: New providers receive initial $LAB tokens
  • Provider updates: Providers can update their information

6. Advanced Calendar Management

  • Red-Black Tree: Self-balancing binary search tree for O(log n) operations
  • Rival interval management: Prevents overlapping reservations
  • Efficient lookups: Fast availability checking and booking confirmation
  • Space efficient: Optimized storage using interval compression

7. Security Features

  • Access control: OpenZeppelin's AccessControlUpgradeable
  • Input validation: Comprehensive parameter checking
  • Reentrancy protection: Safe token transfer patterns
  • Emergency controls: Pausable token for critical situations
  • Immutable ownership: Diamond ownership can be transferred but not renounced

πŸ“‹ Smart Contract Details

Diamond.sol

The main entry point implementing the EIP-2535 Diamond proxy pattern. Delegates all function calls to the appropriate facet using delegatecall.

Facets

DiamondCutFacet

Manages the upgrade mechanism allowing addition, replacement, and removal of facet functions.

DiamondLoupeFacet

Provides introspection into the Diamond's structure, allowing queries about available functions and their corresponding facets.

OwnershipFacet

Manages the Diamond contract ownership following EIP-173.

DistributionFacet

Handles initial tokenomics distribution and controlled subsidies:

  • One-time mint of treasury, subsidies, and ecosystem funds
  • Admin-controlled top-ups with caps
  • Timelock and vesting for large distributions
  • Emergency pause for distribution controls

IntentRegistryFacet

Manages EIP-712 based intent system for gasless operations:

  • Intent registration with admin approval
  • Secure execution of signed intents
  • Nonce-based replay protection
  • Support for reservation and provider actions

ProviderFacet

Manages lab providers, roles, and institutional treasuries:

  • Add/remove providers and institutions
  • Institutional treasury management for SAML users
  • Role-based access control (admin, provider, institution)
  • Automatic token grants for new providers

LabFacet

Implements ERC-721 for laboratory NFTs with additional features:

  • Add/update/delete labs
  • Set token URIs and metadata
  • Paginated lab queries
  • Provider-only transfer restrictions
  • Staking requirements for listing labs

Sub-facets:

  • LabAdminFacet: Admin operations for lab management (minting, burning)
  • LabIntentFacet: Lab operations via intent system
  • LabQueryFacet: Read-only queries for lab data
  • LabReputationFacet: Reputation-based lab features

StakingFacet

Implements provider staking mechanism for quality assurance:

  • Token staking requirements for providers
  • Slashing for misconduct with timelock recovery
  • Unstaking with lock periods
  • Reputation-based mechanisms

Reservation Facets

Handles the complete reservation lifecycle for labs:

  • Reservation requests and admin confirmations
  • Calendar conflict detection using interval trees
  • Multi-state workflow (PENDING β†’ CONFIRMED β†’ IN_USE β†’ COMPLETED β†’ COLLECTED)
  • Automatic refunds and batch fund collection
  • Support for institutional and wallet reservations

Sub-facets:

  • WalletReservationReleaseFacet: Releases expired reservations paid from user wallets
  • WalletReservationCoreFacet: Core reservation request flow for wallet users
  • WalletReservationConfirmationFacet: Confirms wallet reservation requests
  • ReservationDenialFacet: Denies reservation requests (wallet + institutional)
  • WalletReservationCancellationFacet: Cancellation logic for wallet reservations
  • WalletPayoutFacet: Provider payout collection for wallet reservations
  • InstitutionalReservationFacet: Releases expired institutional reservations
  • InstitutionalReservationRequestFacet: Entry point for institutional reservation requests
  • InstitutionalReservationRequestValidationFacet: Validates institutional reservation requests
  • InstitutionalReservationRequestCreationFacet: Creates institutional reservation records
  • InstitutionalReservationConfirmationFacet: Confirms institutional reservation requests
  • InstitutionalReservationCancellationFacet: Cancellation logic for institutional reservations
  • InstitutionalReservationQueryFacet: Read-only queries for institutional reservations
  • InstitutionalTreasuryFacet: Institutional treasury balances and transfers
  • InstitutionalOrgRegistryFacet: Institutional organization registry
  • InstitutionFacet: Institution role and organization management
  • ReservationIntentFacet: Intent-based institutional reservation actions
  • ReservationCheckInFacet: Check-in functionality for completed reservations

External Contracts

LabERC20

The native platform token with:

  • 6 decimal precision
  • 1,000,000 token supply cap
  • Minter role (granted to Diamond)
  • Pauser role (for emergencies)
  • Burnable tokens

Libraries

LibDiamond

Core Diamond Standard implementation managing facet storage and function selectors.

LibAppStorage

Diamond Storage pattern implementation providing shared storage across all facets.

LibAccessControlEnumerable

Enhanced access control with role enumeration capabilities.

LibInstitutionalOrg

Manages institutional organizations and SAML-based user associations.

LibIntent

Handles EIP-712 intent validation and execution logic.

LibReputation

Implements provider reputation system with check-in rewards and penalties.

LibRevenue

Manages revenue sharing and distribution calculations.

LibTracking

Provides tracking and analytics for reservations and usage.

RivalIntervalTreeLibrary

Red-Black tree implementation for efficient calendar management and conflict detection.

πŸ”§ Technical Standards

This solution is built upon the following Ethereum standards and implementations:

  1. EIP-2535 Diamonds - Diamond-1-Hardhat Implementation by Nick Mudge
    https://github.com/mudgen/diamond-1-hardhat

  2. ERC-809 - Rental NFT implementation concept by Greg Taschuk
    https://github.com/gtaschuk/erc809

  3. EIP-721 - NFT standard with OpenZeppelin upgradeable contracts
    https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable

  4. EIP-2612 - Token permits (via OpenZeppelin ERC20)

  5. EIP-173 - Contract ownership standard

πŸ“Š Data Structures

Provider Structure

struct ProviderBase {
    string name;
    string email;
    string country;
    string authURI;
}

struct Provider {
    address account;
    ProviderBase base;
}

Lab Structure

struct LabBase {
    string uri;
    uint96 price;
    string accessURI;
    string accessKey;
    uint32 createdAt;
}

struct Lab {
    uint labId;
    LabBase base;
}

Reservation Structure

struct Reservation {
    uint256 labId;
    address renter;
    uint96 price;
    address labProvider;
    uint8 status;  // 0=PENDING, 1=CONFIRMED, 2=IN_USE, 3=COMPLETED, 4=COLLECTED, 5=CANCELLED
    uint32 start;
    uint32 end;
    string puc;  // schacPersonalUniqueCode for institutional
    uint64 requestPeriodStart;
    uint64 requestPeriodDuration;
    address payerInstitution;
    address collectorInstitution;
    uint96 providerShare;
    uint96 projectTreasuryShare;
    uint96 subsidiesShare;
    uint96 governanceShare;
}

Pending Slash Structure

struct PendingSlash {
    uint256 amount;
    uint256 executeAfter;
    string reason;
}

Intent Meta Structure

struct IntentMeta {
    bytes32 requestId;
    address signer;
    address executor;
    uint8 action;
    bytes32 payloadHash;
    uint256 nonce;
    uint64 requestedAt;
    uint64 expiresAt;
    IntentState state;
}

πŸ“ License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE.txt file for details.

Portions of the code are also licensed under:

  • MIT License (Diamond implementation)
  • GPL-2.0-or-later (Custom facets)

πŸ‘₯ Authors

πŸ™ Acknowledgments

  • Nick Mudgen for the Diamond Standard implementation
  • OpenZeppelin team for secure, audited contract libraries
  • Greg Taschuk for the Rental NFT concept
  • BokkyPooBah for the Red-Black Tree library foundation

πŸ“š Additional Resources

About

Smart contracts for the DecentraLabs project, including the diamond proxy, the multiple facets and the $LAB token

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •