Skip to main content

Technical Documentation

MarsBase Community Deals Platform

1. Executive Summary

1.1 High-Level Overview

The MarsBase Community Deals Platform is a holistic solution for creating, managing, and investing in diverse asset offerings—ranging from equity and debt instruments to real estate and tokenized securities. By combining blockchain-based security tokens, robust compliance features, and a user-friendly web application, the platform provides a seamless experience for issuers, investors, and regulatory stakeholders.

Key features include:

  • Flexible Deal Creation: An intuitive wizard for setting up new offerings, complete with required documentation, key terms, and FAQs.
  • Compliance Integration: Real-time KYC/AML checks, accreditation verification, and multi-regulation support.
  • On-Chain Engagement: Automated token minting, distribution, and vesting schedules powered by smart contracts like TokenSale and P2PEscrow.
  • Secondary Market: Investors can trade their positions via peer-to-peer escrow or an on-chain order book, ensuring liquidity and ongoing compliance checks.

By integrating best-in-class security, transparent workflows, and role-based oversight, the platform aims to become the go-to environment for compliant global investments.

1.2 Core Objectives and Value Propositions

  1. Regulatory Compliance at Scale

    • The platform streamlines compliance workflows (broker/transfer agent approvals, KYC/AML) so issuers can focus on fundraising without worrying about legal complexities.
    • Multiple jurisdictional presets (e.g., Reg D, Reg S) enable a single offering to address various investor types in different markets.
  2. Secure & Efficient On-Chain Operations

    • Investors can buy tokens with stablecoins or ETH (via the TokenSale contract), receiving immediate confirmations or refunds if softcaps aren’t met.
    • The Core ERC-20 standard is extended with snapshot and compliance modules, supporting dividend distribution, governance voting, and restricted transfers.
  3. End-to-End Investment Lifecycle

    • From offering creation and investor onboarding to post-sale distributions and secondary trades, every step is orchestrated in one platform.
    • Deal creators can automatically generate offering memoranda and subscription agreements, while the platform manages digital signatures and locked tokens.
  4. Role-Based Oversight & Transparency

    • Issuers, brokers, transfer agents, and admins each have dedicated dashboards, with real-time notifications and distinct permissions.
    • Detailed activity logs, on-chain transaction records, and KYC data form an auditable trail for regulators and auditors.
  5. Scalability & Future Readiness

    • Multi-tenant architecture allows multiple deals or parallel offerings, each with its own brand, compliance rules, and user sets.
    • Planned expansions (DeFi integrations, advanced analytics) ensure the platform can evolve alongside emerging digital asset trends.

1.3 Architecture in Brief

Technically, the platform combines:

  • Frontend: Next.js (React + TypeScript) for a responsive user interface, leveraging Zod for client-side validations.
  • Backend: Node.js-based Next.js API routes (Express-style) that handle compliance logic, user authentication, role checks, and data orchestration with the database.
  • Database & Storage:
    • PostgreSQL hosts relational data (deals, users, compliance statuses).
    • IPFS + Cloudflare R2 manage large document files, ensuring secure distributed storage and optional geo restrictions.
  • Smart Contracts:
    • TokenSale: Manages token minting, on-chain payments, refunds, and lockups.
    • P2PEscrow: Facilitates secondary market trades with whitelisting and escrow logic.
    • Core ERC-20 extended with compliance modules, enabling restricted transfers, snapshots, and governance.
  • Compliance & Oversight: KYC providers like Sumsub/ShuftiPro perform identity checks off-chain, while broker/transfer agents sign off on deals and trades.
  • Security: End-to-end encryption, multi-factor auth, MPC wallets, periodic security audits, and thorough logging to ensure the system meets advanced regulatory standards.

2. System Architecture & Technology Stack

2.1 Overall Architecture Diagram

At a high level, the MarsBase Community Deals Platform uses a multi-layered architecture:

                +----------------------+
| Frontend UI |
| (Next.js & React) |
+----------+-----------+
|
| (HTTPS API calls)
v
+---------------------------------------------------+
| Next.js API (Backend) |
| (Node.js, Express-style middleware, role checks) |
+----------+----------+-----------------------------+
| |
|(Queries) | (KYC/AML APIs, Blockchain)
v v
+----------------------+ +---------------------------------+
| PostgreSQL Database | | External Integrations (KYC, etc.)|
| (Deals, KYC status, | | Sumsub, ShuftiPro, EVM Chains |
| Users, Apps, Logs) | | for TokenSale/P2PEscrow calls |
+----------------------+ +--------------+-------------------+
|
v
+-----------------------------+
| IPFS + Cloudflare R2 (Docs) |
| (doc storage & distribution)|
+-----------------------------+
  1. Frontend: Built with Next.js (React + TypeScript) for a user-friendly interface and server-side rendering.
  2. Backend: Next.js API routes provide REST-like endpoints, hosting compliance logic, user auth, role checks, etc.
  3. Database: PostgreSQL for relational data (user profiles, deals, compliance statuses).
  4. Storage: Large file storage & distribution via IPFS (for immutability) + Cloudflare R2 (S3-like).
  5. Integrations: KYC/AML providers (Sumsub, ShuftiPro), external blockchain networks for TokenSale & escrow.

2.2 Frontend (Next.js, React, TypeScript)

  1. Next.js

    • Combines server-side rendering (SSR) for SEO and client-side React.
    • Offers API routes co-located with the UI code, simplifying deployments.
  2. React + TypeScript

    • Strong typing to reduce runtime errors and enhance maintainability.
    • A variety of Zod-based forms for wizard steps (deal creation, payment configuration).
    • Components library (e.g., shadcn/ui or similar) for consistent styling.
  3. Key Advantages

    • Hot Reload & streamlined developer experience.
    • Scalable Routing structure that easily separates admin, issuer, investor UIs.
    • SSR or static generation can improve performance for deal listing pages.

2.3 Backend (Next.js API, Node.js, Express-Style Middleware)

  1. API Routes in Next.js

    • Organized by feature (e.g. /api/auth/*, /api/deals/*, /api/p2p-trades/*).
    • Business logic: from route handlers, we call specialized services (e.g. dealService, complianceService).
  2. Middleware

    • Auth & role checks using JWT or session tokens.
    • KYC checks triggered on sensitive endpoints (e.g. purchase calls).
  3. Node.js runtime

    • Asynchronous I/O for concurrency with minimal overhead.
    • Built-in tools for TLS or bridging to external microservices if needed.
  4. Reusability & Plug-Ins

    • Express-like architecture, allowing easy integration with third-party libraries (e.g. Morgan for logs, Helmet for security headers).

2.4 Database Layer (PostgreSQL, R2/IPFS for Documents)

  1. PostgreSQL

    • Stores deals, user profiles, compliance states, KYC statuses, applications, P2P trades, and activity logs.
    • Powerful relational queries, ACID transactions for consistent updates on deals/investments.
  2. IPFS + Cloudflare R2

    • IPFS: Decentralized, immutable storage for official documents or minted tokens metadata.
    • Cloudflare R2: S3-compatible. Offers global distribution and cost efficiency.
    • Enforced geolocation rules or restricted regions for certain docs if local regulations require.
  3. Schema

    • Typical tables: users, deals, p2p_trades, tokensale_records, applications, kyc_data, activity_logs, etc.
    • JSONB columns for flexible data (metadata, disclaimers, dynamic fields).

2.5 Containerization & Deployment (Docker, CI/CD)

  1. Docker Containers

    • The entire Next.js app (UI + API) runs in a single container or separate containers (if needed for horizontal scaling).
    • A separate container for PostgreSQL or a managed DB service, plus a possible container for IPFS node.
  2. CI/CD

    • Automated pipeline (GitHub Actions, GitLab CI, or Jenkins).
    • Steps: Linting, tests (unit/integration), building Docker images, pushing to registry, deploying to staging, then production.
  3. Orchestrations

    • Kubernetes (K8s) or Docker Swarm if needed for advanced scaling.
    • Health checks & auto-rollbacks for safe updates.

2.6 Key Integrations (KYC/AML Providers, External APIs)

  1. Sumsub / ShuftiPro (KYC/AML)

    • The platform calls their APIs after a user uploads identity docs.
    • The user’s compliance “status” is stored in kyc_data.
    • Hook-based or polling approach to confirm if a user is “approved” before they can invest.
  2. Blockchain Networks

    • Ethereum, Polygon, or any EVM chain for deploying the TokenSale, P2PEscrow, and custom ERC-20 token contracts.
    • The platform listens for events (purchase, escrow executed, token transfers, minting) via webhooks or direct calls.
    • Monitors custom ERC-20 token events for dividend distributions, ownership changes, and compliance updates.
    • Gas management ensures transactions from the platform remain feasible.
  3. Email / Notification APIs

    • The platform uses Resend for system emails (like deal approvals, user confirmations).
    • Real-time messaging or Telegram bots for certain user segments.

3. Security & Data Protection

Ensuring a secure, compliant, and resilient environment is critical for the MarsBase Community Deals Platform. This chapter outlines the authentication mechanisms (JWT, MPC wallets), encryption standards, the role of Zod in data validation, our RBAC approach, audit logging, and how we handle backup & disaster recovery (DR).


3.1 Authentication (JWT, MPC Wallet Integration)

3.1.1 JWT-Based Auth

  1. Short-Lived Access Tokens

    • The platform issues JSON Web Tokens (JWTs) upon successful login.
    • These tokens have a 60-minute lifespan to mitigate the impact of token compromise.
    • A refresh token or re-login flow re-issues access tokens as needed.
  2. Secure Storage

    • JWTs are commonly stored in HTTP-only cookies, preventing access by JavaScript and limiting XSS vulnerability.
    • Alternatively, local storage can be used, but with additional security measures (CSRF tokens, domain scoping).
  3. Claim Structure

    • Standard claims: sub (user ID), iss (issuer), exp (expiration time).
    • Additional claims: user roles, compliance status, or tenant ID for multi-tenant systems.

3.1.2 MPC Wallets

  1. Multi-Party Computation

    • For advanced scenarios, the platform supports an MPC-based approach where private key shares are split between the user and the server.
    • This ensures neither party can sign alone, adding a layer of protection against key theft.
  2. Use Cases

    • High-value deals: ensures no single point of failure for on-chain transactions.
    • Organizational accounts: multiple signers can collectively authorize on-chain actions (like minted tokens or big trade approvals).
  3. Implementation Details

    • The platform uses thirdweb for MPC wallets and blockchain integration.
    • The platform can "partial-sign" transactions if compliance checks pass, while the user holds the final share.

3.2 Encryption (Data at Rest & In Transit)

3.2.1 Data in Transit

  1. TLS Everywhere

    • All external communication occurs over HTTPS with TLS 1.2+ (or TLS 1.3).
    • This includes calls from the user’s browser to the Next.js server and from the server to external services (KYC providers, blockchain nodes).
  2. SSH & Secure Channels

    • Internal connections (like DB queries) are within a secure VPC or TLS-enabled if external.
    • Admin or DevOps access is restricted to SSH with key-based auth or VPN gating.

3.2.2 Data at Rest

  1. Database Encryption

    • PostgreSQL may be encrypted at the disk level (full disk encryption).
    • Critical fields (KYC info) are encrypted at the column or table-level.
  2. Document Storage

    • Files uploaded to Cloudflare R2 can be encrypted server-side or client-side.
    • IPFS node can store partial or fully encrypted files, with the decryption key only known to authorized roles in the platform.
  3. Key Management

    • Secrets for TLS certificates, JWT signing, or encryption keys are managed via secure vault solutions (e.g., HashiCorp Vault, AWS KMS).

3.3 Zod Validation & Business Logic Enforcement

3.3.1 Zod for Type-Safe Schemas

  1. Form & API Validation

    • Zod is used to define exact data schemas (e.g., user input for deal creation or investment steps).
    • If data fails validation, the request is rejected early, preventing malformed or malicious payloads from reaching deeper logic.
  2. Wizard Steps

    • In multi-step forms (e.g., Deal Wizard), each step has its own Zod schema.
    • The platform merges the validated partial results into a final deal object.
  3. Client & Server

    • Client side: offers immediate feedback.
    • Server side: re-validates to ensure no tampering occurred in transit.

3.3.2 Enforcement in Business Logic

  1. Express-Style Middleware

    • Each Next.js API route can parse the body, run Zod validations, then call the associated service only if passing.
    • Minimizes duplication, ensures consistent data shape across all layers.
  2. Consistency for Audits

    • By guaranteeing structured data, we reduce error rates and simplify compliance checks or audits.

3.4 Role-Based Access Control

3.4.1 Role Hierarchy

Common roles in the platform include:

  • Investor: Can browse deals, invest if KYC/AML is cleared.
  • Issuer: Creates or manages deals, sees investor applications, may require broker approval for final publish.
  • Broker: Approves deals (if regulation demands). Can comment or request changes.
  • Transfer Agent: Oversees secondary trades, enforces restricted ownership changes.
  • Admin/Super Admin: Full system-level privileges to manage tenants, user roles, and advanced configurations.

3.4.2 Implementation

  1. RBAC Tables

    • A typical table: tenant_user_roles storing arrays of roles (ARRAY['issuer','broker']).
    • API routes or front-end checks if the user’s role array contains the required role.
  2. Granular Permissions

    • Some sub-roles or specialized permissions might revolve around advanced compliance tasks, e.g., marking an investor as “accredited” or finalizing a distribution event.
  3. Integration with JWT Claims

    • For role and permission verification, the platform directly queries database fields rather than storing role information in tokens.
    • This ensures up-to-date access control by always checking the current database state.

3.5 Activity Logging & Audit Trails

3.5.1 Log Structure

  1. activity_logs Table

    • Key columns: id, user_id, tenant_id, entity_type, entity_id, action, metadata (JSONB), created_at.
    • action might be “deal_created”, “broker_approved”, “transfer_executed”, etc.
  2. Front-End & API Integration

    • Each critical route or UI action triggers a logging function.
    • If on-chain events happen, the platform captures the transaction hash and relevant metadata in activity_logs.

3.5.2 Use Cases

  • Regulatory: Auditors can see the entire chain of who did what and when.
  • Debugging: Admin can pinpoint anomalies or user complaints about a trade.
  • Analytics: Summaries on how many deals were created, how many trades, etc.

3.6 Backup & Disaster Recovery Strategies

3.6.1 Database Backups

  1. Automated Snapshots

    • Nightly or hourly logical backups of PostgreSQL.
    • Retain multiple restore points (e.g., up to 7–30 days).
    • Optionally, a point-in-time recovery setup if we use WAL (Write-Ahead Log) archiving.
  2. Off-Site Storage

    • Encrypted backups saved to separate cloud regions or a second service.
    • Minimizes the risk of losing data to a single data center outage.

3.6.2 Document Redundancy

  • Cloudflare R2 already has redundancy across multiple availability zones.
  • IPFS can be pinned on multiple nodes for additional fault tolerance.
  • Admin can replicate critical docs to local or other third-party storages if needed.

3.6.3 Disaster Recovery

  1. RPO & RTO

    • Recovery Point Objective (RPO): e.g., max 1 hour of data loss in worst case.
    • Recovery Time Objective (RTO): e.g., the system can be restored within 2 hours.
  2. Failover

    • If the main hosting environment fails, an auto-deployment or backup environment can spin up from the latest DB snapshots + container images.
    • DNS or environment variables are updated to route traffic to the DR site.

4. Compliance Framework

The MarsBase Community Deals Platform is built to accommodate a wide range of regulatory requirements, ensuring that every step—from user onboarding to deal creation and secondary trading—adheres to jurisdictional rules. This chapter outlines the KYC/AML integrations, accredited investor checks, broker/transfer agent approvals, multi-regulation support, and data privacy considerations like GDPR.


4.1 KYC/AML Integration (Sumsub, ShuftiPro)

4.1.1 Overview

  • Providers: The platform integrates with third-party providers such as Sumsub or ShuftiPro, each offering automated checks for:
    1. Identity verification (ID documents, selfie matching)
    2. Address verification
    3. Sanctions and PEP (Politically Exposed Persons) screening

4.1.2 Workflow

  1. User Onboarding: When a new investor or issuer registers, they’re prompted to complete KYC.
  2. Provider Redirect: The user may be redirected to Sumsub/ShuftiPro’s hosted flow or asked to upload docs directly.
  3. Result Handling: The platform periodically checks (webhook or polling) for “approved,” “rejected,” or “needs more info.”
  4. Local Storage: The user’s KYC status is stored in the DB (e.g., kyc_data table) with details like provider, risk_score, or final outcome.

4.1.3 Risk & Sanction Alerts

  • If a user is flagged as high-risk or found in sanctions lists, an alert triggers for the admin/broker, potentially locking the account or restricting investment.
  • Manual overrides: Admin or compliance officers can override certain rejections if they have additional proof or context.

4.2 Accredited Investor Checks & Self-Accreditation

4.2.1 Accredited Investor Requirements

  • Many jurisdictions (e.g., US Reg D 506(c)) require that certain deals be accessible only to accredited or sophisticated investors.
  • Accreditation typically involves checking:
    • Annual income threshold
    • Net worth threshold
    • Professional/Institutional investor status

4.2.2 Self-Accreditation Flow

  1. User Disclosure: The investor declares they meet the accredited criteria.
  2. Document Upload: They provide bank statements, W-2 forms, or an accountant’s letter.
  3. Compliance Review: The system notifies an admin or an automated service to confirm authenticity.
  4. Approval: If valid, the user’s profile now carries an “accredited” flag, enabling them to invest in certain deals.

4.2.3 Renewals & Expirations

  • Some regulations require annual re-check of accreditation.
  • The platform can remind the user or automatically degrade their status to “unverified” if out of date.

4.3 Broker & Transfer Agent Approval Mechanisms

4.3.1 Broker Approval

  1. When: If a deal’s regulation demands broker sign-off (e.g., certain US or EU frameworks).
  2. Workflow:
    • Issuer finalizes deal → The platform marks the deal as “pending_broker_approval.”
    • Broker logs in, reviews docs & disclaimers → Approves or rejects with notes.
    • If approved, deal transitions to “active.” If rejected, it returns to “draft” or “changes_requested.”

4.3.2 Transfer Agent Oversight

  1. Secondary Market: The transfer agent checks if a buyer meets KYC/AML and is allowed under the chosen regulation.
  2. Ownership Tracking: The agent or the system maintains a ledger or on-chain record of share ownership.
  3. Lockup & Restricted Transfers: The platform automatically enforces restricted resale periods and accredited-only transfer rules, rejecting non-compliant P2P trades without requiring manual intervention.

4.4 Multiple Regulation Selection (e.g., Reg D 506(c), Reg S)

4.4.1 Purpose

  • Allows an issuer to combine multiple frameworks in a single offering, e.g. Reg D for US accredited investors + Reg S for non-US investors.

4.4.2 Implementation

  1. Deal Wizard: Issuer selects multiple regs from a preset list.
  2. Platform: Based on user nationality & accreditation, the system routes them to the relevant disclaimers and docs.
  3. Compliance Tagging: The user’s investment is flagged under a specific regulation path.

4.4.3 Documentation & Disclaimers

  • Each regulation has unique disclaimers or disclaimers, risk statements, etc. for:
    • US: Reg D, CF, A+
    • EU: Prospectus Regulation, MiFID II
    • UK: FCA guidelines
    • APAC: MAS (Singapore), SFC (HK)

4.4.4 Automatic Warnings & Blocks

  • If a user’s nationality is from a restricted country, the platform can display “not available” or require them to choose a different regulation path.
  • IP checks or address-based checks can block unauthorized regions, though user-provided KYC data is more reliable.

4.5 Regulatory Presets & Country-Based Disclaimers

4.5.1 Preset Library

  • The platform ships with a library of disclaimers, disclaimers, risk statements, etc. for:
    • US: Reg D, CF, A+
    • EU: Prospectus Regulation, MiFID II
    • UK: FCA guidelines
    • APAC: MAS (Singapore), SFC (HK)

4.5.2 Template Generation

  • If the issuer doesn’t have custom docs, the platform can auto-generate from template libraries.
  • Fields like deal name, issuer name, target raise are auto-filled.
  • The user can preview or edit placeholders (like risk statements, disclaimers).

4.5.3 Document Storage

  • All final docs are stored in IPFS + Cloudflare R2.
  • Some required docs might be flagged for e-signing or mandatory investor acceptance.

4.6 GDPR & Other Data Privacy Considerations

4.6.1 Data Minimization & Retention

  • GDPR: The system only stores data strictly needed for compliance.
  • KYC docs can be pseudonymized or removed after a certain retention period if regulations allow.

4.6.2 Right to Erasure

  • A user from the EU can request data deletion. The platform must remove non-essential data while still retaining required regulatory info (like investment records or suspicious activity logs).
  • If the platform collects marketing consent (like a newsletter opt-in), it ensures separate, explicit user consent.
  • Cookie usage or local storage disclaimers are also provided.

5. Deal Creation & Management

Creating and managing investment opportunities is a core function of the MarsBase Community Deals Platform. This chapter outlines how deals are created, how documents and key terms are stored, the lifecycle states each deal progresses through, how broker approval is handled, and how issuers and admins oversee these deals.


5.1 Deal Wizard (Zod-Validated Steps)

5.1.1 Purpose

  • The Deal Wizard is an interactive, multi-step form guiding issuers through all required information (basic deal details, compliance data, documents, etc.).
  • Ensures consistent data collection and reduces errors through Zod validation at each step.

5.1.2 Step Breakdown

  1. Basic Information
    • Deal name, short description, type (equity, debt, real estate, tokenized security), target raise.
    • Regulations selected (e.g., Reg D 506(c), Reg S).
  2. Key Terms & Timelines
    • Minimum/maximum investment, start/end date, softcap/hardcap.
    • Potential vesting or lockup details.
  3. Documents
    • Pitch deck, financial statements, or marketing materials.
    • Required disclaimers for investor compliance.
  4. Required Investor Docs
    • Identify which documents an investor must provide (e.g., KYC docs, accreditation proof).
  5. FAQs
    • Common questions about the deal: “What’s the exit strategy?” “How do dividends work?”
  6. Review & Confirmation
    • Final summary of all data before submission.
    • Zod re-validates all fields.
    • Option to save as draft or proceed for broker approval.

5.1.3 Draft & Autosave

  • Deals can be saved as draft at any point, allowing issuers to come back later.
  • The platform auto-saves partial data to prevent losing progress.

5.2 Required Documents & Templates (Offering Memorandum, Subscription Agreement)

5.2.1 Document Types

  1. General Documents: Pitch decks, marketing PDFs, disclaimers.
  2. Legal/Required:
    • Offering Memorandum
    • Subscription Agreement
    • “Know Your Rights” or disclaimers (varies by regulation).

5.2.2 Template Generation

  • If the issuer doesn’t have custom docs, the platform can auto-generate from template libraries.
  • Fields like deal name, issuer name, target raise are auto-filled.
  • The user can preview or edit placeholders (like risk statements, disclaimers).

5.2.3 Document Storage

  • All final docs are stored in IPFS + Cloudflare R2.
  • Some required docs might be flagged for e-signing or mandatory investor acceptance.

5.3 Key Terms, FAQ, and Document Repositories

5.3.1 Key Terms

  • Examples: Minimum investment, interest rate (for debt), share class (equity), special privileges, etc.
  • The wizard step fosters clarity by highlighting major terms so potential investors can quickly reference them.

5.3.2 FAQ

  • Each question-answer is stored in the DB, displayed on the deal detail page.
  • In the wizard, the issuer can add or remove common queries.
  • Some frequently used templates might be auto-populated based on the asset type.

5.3.3 Document Repository

  • The platform organizes all documents for a deal under a single repository, including:
    • Admin-only docs (private financial statements).
    • Investor-facing docs (pitch deck, disclaimers).

5.4 Lifecycle States (Draft → Pending → Active → Closed)

  1. Draft
    • The deal is incomplete. Only the issuer or admin can see it.
  2. Pending
    • Once the issuer finishes the wizard, it may require broker approval (or direct admin approval if broker step is disabled).
    • Status is “pending_broker_approval” or “pending_admin_approval.”
  3. Active
    • The deal is now publicly visible to accredited or KYC-approved investors (or general public if regs allow).
    • Investors can apply or invest (fiat or crypto).
  4. Closed / Funded
    • The deal has reached its end date or target raise.
    • Potential next steps: distributing tokens, finalizing docs, or unlocking tokens.
    • The issuer can manage post-close tasks like dividends or further compliance checks.

Variations: Some deals might have an “Upcoming” state (scheduled future start date) or an “Application Phase” for private testing the waters.


5.5 Broker Approval Workflow

5.5.1 When Broker Approval is Required

  • If the regulations or the tenant’s settings call for an authorized broker to sign off, the deal transitions from draft to pending.
  • The wizard ensures all mandatory fields are completed before the issuer can request broker approval.

5.5.2 Broker Action

  • Review: The broker sees the entire deal (terms, docs, disclaimers).
  • Approve/Reject: If approved, the deal’s status becomes “active.”
    • If rejected, it returns to the issuer as “draft” or “changes_requested” with broker notes.

5.5.3 Logging & Notifications

  • The platform logs the timestamp, the broker’s ID, and any comments.
  • Issuer is notified of the broker’s decision.
  • If a broker is not used, the platform can skip this step if compliance allows.

5.6 Issuer Dashboard & Admin Oversight

5.6.1 Issuer Dashboard

  • Displays all deals the issuer created: draft, active, closed.
  • Summaries: how many investors joined, how much capital raised, pending approvals, etc.
  • Tools for uploading or updating docs, setting disclaimers, or halting an active deal.

5.6.2 Admin Panel

  • Admin sees all deals across the entire platform or tenant.
  • Can override certain issuer changes, handle escalations, or forcibly close deals if regulatory issues arise.
  • May also manage global config (like enabling multi-reg for certain deals or setting compliance flags).

5.7 E-Signature Implementation

5.7.1 SignatureDialog Component

  • The platform features a professional-grade SignatureDialog component for legally binding document acceptance.
  • Dual Signature Methods:
    • Type Signature: Uses the Dancing Script cursive font to create a realistic typed signature experience.
    • Draw Signature: Canvas-based interface with proper touch and mouse support for drawn signatures.

5.7.2 Technical Implementation

  • Canvas properly initializes and scales for different devices with responsive design.
  • Touch event handling prevents page scrolling while drawing signatures.
  • Tab-based interface allows users to easily switch between signature methods.
  • Real-time preview shows typed signatures in cursive font before submission.

5.7.3 Integration with Document System

  • Signatures are recorded in the e_signature_events table with timestamps for audit purposes.
  • Platform maintains a complete history of document views, accesses, and signatures.
  • API endpoints at /api/documents/signature handle secure submission of signature data.

6. Blockchain Integrations

The MarsBase Community Deals Platform harnesses blockchain technology to automate the issuance, transfer, and management of tokenized assets, offering transparency and trustless compliance mechanisms. This chapter explores the platform’s focused smart contract architecture (Core ERC-20, Registry, Access Control), token issuance and management, secondary market enablement, investment pooling, and the dividend/reward distribution approach.


6.1 Smart Contract Architecture

6.1.1 Overview

The platform employs a specialized suite of Ethereum-based (EVM-compatible) smart contracts:

  1. Core ERC-20 Contract

    • Represents the security token or fund token, extended with compliance features.
    • Supports restricted transfers, snapshot functionality, and hooks for regulatory checks.
  2. Registry Contract

    • Maintains a record of all deal tokens, their compliance metadata, and current statuses (active, closed, etc.).
    • Useful for quickly enumerating all on-chain deals under the platform.
  3. Access Control Module

    • Manages investor whitelisting (addresses allowed to receive tokens).
    • Integrates with off-chain KYC checks (the platform sets flags indicating who’s cleared to trade or hold).
    • Enforces lockup or restricted periods, blocking unapproved transfers.

6.1.2 Key Goals

  • Automated Compliance: Enforce restricted transfers based on whether an address is whitelisted or meets certain rules.
  • Auditable: On-chain events record every issuance, transfer, or snapshot, forming an immutable ledger.
  • Modular: Each deal can deploy a new instance of the Core ERC-20 or reference a standard code base.

6.2 Token Issuance & Management

6.2.1 Custom Security Tokens (Equity, Debt, Revenue Shares)

  1. Deployment

    • Issuers can deploy a token contract (or the platform does it on their behalf) via a web wizard.
    • The token typically includes name, symbol, decimals, and total supply or mint functions.
  2. Specialized Fields

    • Debt tokens may track interest or redemption schedules.
    • Equity-like tokens might represent share classes with different voting rights.
  3. Compliance Modules

    • Each token can enforce partial or total restrictions:
      • Whitelist-based transfers only.
      • Time-based lockups for certain addresses.

6.2.2 Transfer Restrictions & Automated Compliance Checks

  • Address Whitelisting: The contract references the Access Control module to see if a “transferFrom(sender, receiver)” is permitted.
  • Regulatory Conditions: If locked or restricted (due to jurisdiction or investor type), the contract reverts the transfer.
  • Admin/Transfer Agent: Might have privileged roles to override certain locks or forcibly correct compliance errors if allowed by local laws.

6.2.3 Snapshot Functionality (Dividends & Governance Voting)

  1. Why Snapshots

    • For paying dividends, the platform needs to know exactly how many tokens each holder had at a certain block.
    • For governance or corporate actions, the snapshot ensures fairness—holders cannot quickly buy or sell to influence votes or dividend counts.
  2. Implementation

    • The extended ERC-20 may record each user’s balance at key block heights or rely on a specialized library (e.g., OpenZeppelin’s ERC20Snapshot).
  3. Distribution & Voting

    • Dividends: The platform checks snapshot balances, then instructs the contract or an off-chain engine to distribute stablecoins/ETH.
    • Voting: A governance module might let holders propose and vote on changes, referencing the snapshot for weighting.
  • Each token can store URIs referencing IPFS-based docs or disclaimers.
  • Helpful for investors to see the offering’s memorandums or disclaimers directly from a blockchain explorer or wallet interface.

6.3 Secondary Market (On-Chain Trading)

6.3.1 Live Marketplace Capabilities (Order Book, P2P Escrow)

  1. Multiple Approaches

    • Off-chain order book: The platform’s database tracks orders, but settlement occurs on-chain.
    • P2PEscrow contract: Peer-to-peer trades with a single listing approach, bridging directly with the tokens.
  2. Order Matching

    • The system might match buy/sell orders off-chain, then call the escrow contract for final settlement.
    • Or a user simply interacts with a single “deal” in the P2PEscrow, specifying tokenIn and tokenOut amounts.

6.3.2 Automated Regulatory Checks Before Trade Execution

  • The P2PEscrow or the token contract itself verifies if both parties are whitelisted or meet any region/lockup conditions.
  • If the transfer agent must sign off, the platform can hold the transaction or revert if not approved.

6.3.3 Integration with Primary Issuance for Seamless Transitions

  • After a TokenSale completes, tokens remain restricted.
  • If an investor wants to sell, they can list it in the on-chain or platform’s secondary market.
  • The system shares the same compliance data, so no second KYC or check is needed for known addresses.

6.4 Investment Pooling & Fund Management

6.4.1 Tracking Individual Investor Contributions

  • The platform’s DB records how many tokens each investor has.
  • On-chain, the contract maintains their balances.
  • Reconciliation merges these data points if the token enforces restricted transfers.

6.4.2 Cap Table Management for Token Holders

  • The platform can produce a “cap table” for each token, showing the top holders, total supply, etc.
  • Potentially used by the issuer or admin for reporting.

6.4.3 Basic Aggregation vs. Future Advanced Pooling

  • Basic: Summaries of how much each investor put in.
  • Advanced: Could revolve around multiple share classes, redemption windows, or multi-deal SPVs.

6.5 Dividend & Reward Distribution

6.5.1 ERC-20 Snapshot Method

  • At the end of a quarter or a predetermined event, the contract calls a snapshot().
  • Dividends are calculated off that snapshot’s balances.

6.5.2 Calculating Dividends Proportionally

  • The issuer or an automated script:
    1. Iterates over snapshot balances,
    2. Multiplies each balance by the declared dividend per token,
    3. Disburses stablecoins, ETH, or other tokens.

6.5.3 Governance Voting via Snapshot Points

  • If a token acts like an equity, governance actions may require a snapshot at block X.
  • Each holder can cast votes in proportion to their snapshot balance.

6.5.4 Audit Trails for Distribution

  • The platform logs each distribution event in the DB and on-chain.
  • The issuer or admin can see who was paid how much, ensuring transparency.

6.6 Transaction Management & Logging

6.6.1 Gas Estimation & Transaction Monitoring

  • For each user-initiated action (purchase, escrow trade, dividend claim), the platform:
    1. Estimates gas.
    2. Either uses a user’s wallet or an MPC approach to sign the transaction.
    3. Waits for confirmations or reverts if out of gas or fails compliance checks.

6.6.2 Gasless Transactions

  • The platform supports gasless transactions, allowing users to interact with blockchain without holding native tokens.
  • Implementation uses meta-transactions where the platform pays gas fees on behalf of users.
  • EIP-712 signatures verify user intent without requiring them to submit transactions directly.
  • Relayer infrastructure forwards properly signed user transactions to the blockchain.

6.6.3 Comprehensive On-Chain Logging & Status Tracking

  • Each contract emits events: Transfer, Snapshot, DealExecuted, etc.
  • The platform listens to these logs (via WebSockets or JSON-RPC) and updates internal DB states:
    • E.g. if a Transfer event occurs with a restricted token, the DB confirms it was an allowed address.

6.6.4 Off-Chain Sync with Platform DB

  • The system ensures that the off-chain DB remains consistent:
    1. For every on-chain event, it updates the local record.
    2. For new minted tokens in a sale, the user’s “portfolio” in the platform gets updated.
    3. If a trade is rejected, a “transfer failed” state is recorded.

7. TokenSale & P2PEscrow Contracts

Two key contracts – TokenSale and P2PEscrow – power the on-chain fundraising and secondary trading functionalities. TokenSale automates on-chain purchases, refunds, lockups, and more for new deals, while P2PEscrow supports peer-to-peer transactions on the secondary market with whitelisting, escrow logic, and partial customization.


7.1 TokenSale Contract (Crypto-Based Contributions)

7.1.1 Purpose

  • Facilitate trustless or semi-trustless token sales, where investors pay in ETH or whitelisted stablecoins.
  • Automate the distribution (or minting) of tokens to investors, handle refunds if softcap fails, track lockups, and ensure compliance restrictions.

7.1.2 Payment Flows (ETH, Stablecoins)

  1. ETH Contribution
    • The user calls purchase(address(0), amount) with a specified token amount.
    • Must send the equivalent ETH value for that token amount based on the “price” variable in the contract.
    • The contract verifies the correct ETH value was sent (e.g., require(msg.value == calculatedCost, ...)).
  2. Stablecoin Contribution
    • The user calls purchase(stablecoinAddress, amount).
    • The contract calculates the stablecoin cost using (amount * price) / 1e18 or a similar formula.
    • The user must have approved the TokenSale contract for that stablecoin, which is then transferred from buyer → contract or buyer → owner.

7.1.3 Softcap/Hardcap & Refund Logic

  1. Softcap
    • The contract tracks total purchases. If the final amount is below the softcap at end of the sale (block.timestamp > createdAt + duration), the sale is in a “Failed” state.
    • Investors call claimBack() to get a refund of their contributed ETH/stablecoins.
  2. Hardcap
    • The sale disallows purchases if total purchases + new amount would exceed hardcap.
    • Provides an upper limit to how many tokens can be sold or how much capital is accepted.

7.1.4 Lockup & Vesting Schedules

  • The contract can impose a lockupPercent on each purchased amount, storing locked tokens in a user mapping (e.g. lockedBalanceOf).
  • Once conditions are met (like a minimum TVL or time-based schedule), the user can call unlock() to retrieve their locked portion.
  • This prevents immediate dumping of tokens or ensures compliance with holding requirements.

7.1.5 Integration with Platform (Investor UI, Admin Tools)

  • UI: The front-end calculates how much ETH or stablecoins the user must send.
  • Admin:
    • Sets up the TokenSale parameters (price, softcap/hardcap, duration, lockup) in the wizard.
    • After the sale, can finalize or call a “transferFunds” method to withdraw contributed assets.

7.2 P2PEscrow Contract (Secondary Trading)

7.2.1 Deal Listing & Whitelisting Mechanisms

  1. createDeal()
    • The seller specifies tokenIn (they want to receive), tokenOut (they will give), and amounts.
    • Optionally sets a specific buyer or a whitelist of addresses.
    • No tokens are locked upfront; the contract checks allowances at execution time.
  2. Whitelisting
    • updateWhitelist() allows the seller to define or modify which addresses can buy.
    • If whitelisting is empty and no fixed buyer is set, anyone can execute the deal.

7.2.2 Execution Flow (Ask/Bid, Transfer)

  1. executeDeal(dealId)
    • The buyer calls it, the contract verifies the buyer is either the named buyer or in the whitelist.
    • Checks token allowance from the seller (for tokenOut) and from the buyer (for tokenIn).
    • If all is good, it transfers amountIn from buyer → seller, and amountOut from seller → buyer.
    • Marks the deal as completed.

7.2.3 Cancel & Update Options for Sellers

  • The seller can call cancelDeal(dealId) if it’s still active and not executed. This simply marks it inactive.
  • They can also assignBuyer() to set a specific address or modify the whitelist.
  • This design allows the seller to remain in control until a buyer locks in the transaction.

7.2.4 Off-Chain Broker/Transfer Agent Checks

  • If the platform enforces manual or automatic checks, the UI or the token’s compliance module ensures only addresses with appropriate KYC/regulatory clearance can call executeDeal.
  • The contract itself just enforces whitelists but does not do advanced compliance. The platform’s role is to orchestrate any broker or transfer agent approvals behind the scenes.

8. Payments & Settlement

Payments are a critical part of the MarsBase Community Deals Platform, spanning both off-chain (fiat) and on-chain (crypto) transactions. This chapter covers fiat payment handling with manual confirmations by issuers, crypto settlement flows, how escrow vs. direct payment approaches differ, and how the system manages fees & commissions across deals.


8.1 Fiat Payment Handling (Issuer Manual Confirmation)

8.1.1 Why Manual Confirmation

  • Some issuers prefer or require a traditional bank transfer (wire, ACH, SWIFT) for compliance reasons or convenience.
  • The platform doesn’t directly integrate with banks or payment gateways for certain jurisdictions, so it allows manual tracking.

8.1.2 Workflow

  1. Investor chooses fiat payment at checkout, sees wire instructions or a bank account number.
  2. Platform records an “intent to purchase” with the chosen deal, capturing the desired investment amount.
  3. Investor completes the wire or bank transfer externally.
  4. Issuer (or admin) checks their bank statement, then in the platform’s admin UI marks “Payment Received.”
  5. Once confirmed, the system finalizes the investment, allocating tokens or updating the investor’s record.

8.1.3 Limitations & Safeguards

  • Because the system must rely on manual steps, there is a risk of human error.
  • The platform can require the issuer to specify an approximate date/time or transaction ID to reduce confusion.
  • Investors are flagged with a “pending_fiat” status until the issuer’s confirmation.

8.2 Crypto Payment Confirmation & On-Chain Settlement

8.2.1 TokenSale Integration

  • When an investor pays with ETH or a stablecoin (e.g., USDC), the TokenSale contract handles the logic for:
    1. Checking if the user sent the correct amount of ETH or transferred enough stablecoins.
    2. Minting or releasing tokens if the deal is still “active” and under the hardcap.
    3. Triggering refunds if the softcap fails post-sale.

8.2.2 Direct vs. Payment Gateways

  1. Direct:
    • The user’s wallet calls purchase(...) on-chain.
    • The platform monitors the transaction hash for success, then updates the DB automatically.
  2. Payment Gateway (optional integration):

8.2.3 Monitoring & Automatic Reconciliation

  • The platform listens for transaction events (via Web3 or node watchers).
  • Once a confirmed event (e.g., TokensPurchased) is detected, the platform updates the user’s portfolio to reflect the new tokens minted or locked.

8.3 Escrow vs. Direct Payment Models

8.3.1 Escrow Model

  • The P2PEscrow contract ensures that in a secondary sale (investor-to-investor), both sides either both transfer or nothing occurs.
  • The contract checks allowances from seller and buyer, then executes in a single atomic transaction.
  • No side can run away with the other’s tokens or funds.

8.3.2 Direct Payment

  • In some direct purchase flows (like the initial TokenSale or simpler deals), the user simply transfers funds to the issuer or the contract.
  • No third party or contract is required to hold tokens in escrow if the contract design automatically mints or transfers tokens upon payment.

8.3.3 Use Cases

  • Primary Sale: Typically direct, with the TokenSale contract.
  • Secondary Market: Typically escrow-based to ensure trustless or semi-trustless peer-to-peer trades.

8.4 Fee & Commission Structures

8.4.1 Platform Fees

  • The platform might charge a success fee or a listing fee for each deal, or a percentage of total capital raised.
  • In crypto flows, this can be automatically deducted by the contract and sent to a platform wallet or the tenant’s wallet.

8.4.2 Broker/Transfer Agent Commissions

  • If a broker is involved, they might receive a portion of each successful investment or a flat retainer.
  • The system can track these commissions in the DB and distribute them manually or automatically, depending on contract logic.

8.4.3 Potential Referral Fees

  • A future “referral” or “affiliate” system can pay a portion of fees to a user who referred the investor, recorded off-chain or on-chain.
  • The system would store referral codes and attribute them to the final purchase.

9. Investor & Issuer Flows

The Investor and Issuer roles represent two core user types in the MarsBase Community Deals Platform. This chapter outlines how investors discover and participate in deals, manage their portfolios, and engage with secondary trading, and how issuers create, configure, and oversee their offerings, track investor applications, and interact with brokers/transfer agents.


9.1 Registration & Onboarding (KYC)

9.1.1 Account Creation

  1. User Sign-Up
    • Basic fields: email, password (hashed via Bcrypt/Argon2), optional wallet address.
    • Optionally triggered from a referral link or sponsor code.
  2. Verification Prompt
    • The user is guided to complete KYC/AML checks through Sumsub or ShuftiPro for compliance.
    • Until KYC is approved, the user may be restricted from investing or creating deals.

9.1.2 KYC/AML Flow

  • The system obtains the user’s identity data and any proof of address or accreditation.
  • A status is stored (e.g., “pending,” “approved,” “rejected”).
  • If the user is rejected, the platform either denies them from certain activities or flags them for admin review.

9.1.3 Optional Accreditation Declaration

  • For deals requiring accredited investors, a user can self-declare or upload financial statements.
  • The platform or admin must confirm before the user can join 506(c) deals or equivalents.

9.2 Browsing & Evaluating Deals (Investor Perspective)

9.2.1 Deal Discovery

  1. Deal Listing Page
    • Shows active/upcoming deals, sorted by popularity, close date, or categories (real estate, equity, etc.).
    • The investor can filter by region or compliance type (e.g., “Reg D only”).
  2. Quick Preview
    • Each deal card shows the summary, min/max investment, timeline, and ROI projections if applicable.

9.2.2 Deal Detail

  1. Key Terms: Summaries like share classes, expected returns, or coupon rates.
  2. Required Documents: Investor sees disclaimers, pitch decks, financial statements.
  3. FAQs: Common questions from the issuer.
  4. Regulatory Info: If multiple regs are applicable, the user sees disclaimers relevant to their region or accreditation.

9.2.3 Investment Decision

  • Once an investor is confident, they can initiate the “Invest” process, choosing fiat or crypto.
  • The system checks if the user has KYC/AML and (if needed) accreditation status or broker approval (for specific deals).

9.3 Deal Setup & Approval (Issuer & Broker Perspective)

9.3.1 Issuer Creating a Deal

  1. Wizard Launch
    • The issuer clicks “Create New Deal,” is guided by the multi-step flow (chapter 5).
  2. Regulation Selection
    • Possibly picks multiple regs (e.g. Reg D + Reg S).
  3. Documents & Terms
    • Upload or generate an offering memorandum, subscription agreement.
  4. Broker Requirement
    • If the chosen regs call for broker sign-off, the deal status moves to “pending_broker_approval.”

9.3.2 Broker Review

  1. Dashboards
    • The broker sees “Deals Pending” and can open each deal for a thorough check.
  2. Approve or Request Changes
    • If approved, the deal is live or transitions to “active.”
    • If changes are requested, it reverts to draft or “changes_requested,” with broker notes.
  3. Logging
    • The platform logs the broker’s ID, timestamp, and any comments.

9.4 Transfer Agent Oversight for Secondary Trades

9.4.1 Investor Trading

  • Post-sale, an investor may want to sell tokens on the secondary market.
  • The P2PEscrow contract requires either direct whitelisting or an automatic check from the Transfer Agent if the deal demands it.

9.4.2 Transfer Agent Dashboard

  1. Pending Transfers
    • The agent sees lists of trades or address changes requiring sign-off (if the regulation calls for it).
  2. Approve or Reject
    • They confirm the buyer is KYC’d, accredited if needed, not in a lockup.
    • If all is good, the agent triggers or allows the escrow to finalize.
  3. Historical Records
    • The agent can see who traded what, ensuring a complete paper trail for compliance audits.

9.5 Admin & Super Admin Dashboards

9.5.1 Admin Dashboard

  • Analytics: Summaries of how many deals are live, total capital raised, user metrics.
  • User Management: Possibly reset passwords, assign roles (e.g. make a user a broker).

9.6 Admin Panel Implementation

9.6.1 Admin Architecture

  • Authentication and Authorization:
    • Custom admin middleware enforces role-based access control.
    • AdminGuard component protects all admin routes from unauthorized access.
    • Only users with the 'admin' role can access admin functionality.

9.6.2 Admin Dashboard

  • Provides key platform metrics:
    • User counts by role and verification status
    • Deal statistics (active, pending, funded)
    • Investment totals and conversion rates
    • Quick action buttons for common administrative tasks

9.6.3 User Management

  • Comprehensive list view with search, filter, and sort capabilities.
  • Detailed user profile view with options to modify:
    • User status (active, suspended)
    • Role assignments (investor, issuer, broker)
    • KYC verification overrides
  • Soft-delete functionality that preserves data integrity for audit purposes.

9.6.4 Deal Administration

  • Deal list with advanced filtering options and bulk actions.
  • Direct edit capabilities for all deal attributes.
  • Status transition controls with appropriate logging.
  • Comment and notification system for communicating with issuers.

9.6.5 API Structure

  • RESTful endpoints under /api/admin/* namespace:
    • /api/admin/stats - Platform-wide statistics
    • /api/admin/users - User management operations
    • /api/admin/deals - Deal administration

10. Notifications & Communication

Investors, issuers, brokers, and other roles in the MarsBase Community Deals Platform depend on timely notifications to stay updated on deal status changes, pending approvals, or compliance alerts. This chapter covers in-app notifications, email integrations, and how users configure these alerts.


10.1 In-App Notifications (Pending Approvals, Deal Updates)

10.1.1 Notification Center

  1. UI Component

    • A bell icon or notifications panel in the main navigation bar.
    • Displays a count of unread notifications.
  2. Typical Triggers

    • Broker sees “Deal #123 is awaiting your approval.”
    • Issuer sees “Your deal is now approved by broker,” or “An investor has purchased tokens.”
    • Transfer Agent sees “Trade request #456 needs your sign-off.”
  3. Persistence & Read Status

    • Each notification has a read or unread status.
    • The user can click to see details and mark it as read.

10.1.2 Real-Time Feeds

  • Depending on the deployment, Next.js or WebSocket/Server-Sent Events may push new notifications in real time.
  • Alternatively, a simple polling approach checks for updates every few minutes.

10.2 Email & External Channels (Telegram, Slack, Webhooks)

10.2.1 Email Notifications

  1. System Emails
    • Registration confirmations, password resets.
    • Deal updates (e.g., “Your application to [Deal Name] was approved”).
  2. Compliance/Alerts
    • If the user fails KYC or hits a regulatory block, the platform emails them with next steps.
  3. Backend Implementation
    • The platform uses Resend for system emails (like deal approvals, user confirmations).
    • Email templates are stored in the platform’s config or code.

10.2.2 External Integrations (Telegram, Slack, Webhooks)

  1. Telegram Bot
    • Some organizations prefer a Telegram channel for major updates (like “Sale is live!” or broker sign-off messages).
    • The platform can push these events to a private group or direct message.
  2. Slack
    • Slack channels might receive automated notifications for new deals or KYC flags in a #compliance channel.
  3. Webhooks
    • For enterprise clients or advanced custom logic, the platform can send POST requests to a specified endpoint whenever significant events occur (deal created, investor invests, etc.).

10.3 Configurable Alerts & Preferences

10.3.1 User Settings

  1. Notification Preferences
    • A user can choose which categories they want:
      • “Deal updates,” “Application status,” “Secondary market trades,” etc.
    • They can enable/disable email or in-app for each category.
  2. Frequency
    • Immediate emails vs. daily/weekly digests for non-urgent items.

10.3.2 Role-Specific Defaults

  • Broker: Might want immediate pings for pending approvals.
  • Issuer: Typically needs instant notifications for new investor applications or broker rejections.
  • Investor: Might prefer only receiving big status changes (deal funded, tokens unlocked).

10.3.3 Unsubscribe / GDPR Compliance

  • All emails include an “unsubscribe” link for marketing or optional updates.
  • Mandatory compliance or security alerts are typically not unsubscribable (e.g., KYC rejections).

11. Database & API Schemas (Reference Appendix)

The MarsBase Community Deals Platform relies on a structured relational database (PostgreSQL) to maintain user accounts, deals, compliance info, trading records, and application data. Additionally, the system exposes REST-like API endpoints (within Next.js API routes) for both internal and external interactions.


11.1 Core Tables (Users, Deals, KYC, Applications, P2P Trades)

11.1.1 Users Table

  • Purpose: Store basic user info, role(s), status, KYC reference, accreditation.
  • Key Columns:
    • id (serial or uuid): Primary key
    • email, password_hash
    • roles text[]: e.g. {user, issuer, broker, admin}
    • kyc_status: e.g. pending, approved, rejected
    • accreditation_status: e.g. unverified, accredited, expired
    • created_at, updated_at

11.1.2 Deals Table

  • Purpose: Represent each investment offering (equity, tokenized, real estate, debt).
  • Key Columns:
    • id (uuid): Primary key
    • issuer_id (fk -> users.id)
    • title, description, status (draft, pending_broker, active, closed, etc.)
    • softcap, hardcap, min_investment, max_investment
    • regulations text[]: e.g. {reg_d_506c, reg_s}
    • created_at, updated_at, deleted_at (nullable)
    • documents jsonb: List of doc references (IPFS, R2 paths)
    • required_documents jsonb: For investor compliance
    • Potential JSON fields for disclaimers, faqs, etc.

11.1.3 KYC Data Table

  • Purpose: Detailed logs of each user’s KYC checks.
  • Key Columns:
    • id (uuid), user_id (fk -> users.id)
    • provider: e.g. sumsub, shuftipro
    • status: e.g. pending, approved, rejected
    • risk_score (nullable)
    • raw_result jsonb: The original response from the KYC provider
    • created_at, updated_at

11.1.4 Applications Table

  • Purpose: Tracks investor applications or “intents to invest” in a deal.
  • Key Columns:
    • id (uuid)
    • deal_id (fk -> deals.id)
    • user_id (fk -> users.id)
    • status: e.g. pending, approved, rejected, cancelled
    • investment_amount numeric
    • currency: e.g. fiat, eth, or stablecoin address
    • paid boolean, confirmed_by_issuer boolean
    • created_at, updated_at, approved_at (nullable)

11.1.5 P2P Trades Table

  • Purpose: Store high-level info on secondary trades listed via P2PEscrow or the off-chain order book.
  • Key Columns:
    • id (serial or uuid)
    • seller_id (fk -> users.id)
    • token_in_address, token_out_address
    • amount_in, amount_out, status (active, executed, cancelled)
    • created_at, updated_at
  • Additional references or foreign keys if needed.

11.2 Additional Tables (TokenSale Records, Lockup Tracking)

11.2.1 TokenSale Records

  • Purpose: Store references to a deployed TokenSale contract for a particular deal.
  • Key Columns:
    • id (uuid)
    • deal_id (fk -> deals.id)
    • contract_address (the on-chain TGE/TokenSale contract)
    • price numeric, softcap numeric, hardcap numeric, etc.
    • start_time, end_time, lockup_percent
    • created_at, updated_at

11.2.2 Lockup Balances (If Off-Chain)

  • If the platform chooses to store user locked balances in the DB (instead of purely on-chain):
    • id, user_id, deal_id, locked_amount, locked_until
    • This helps the admin or issuer quickly see who is locked how much, though the on-chain contract is still the final authority.

11.2.3 Activity Logs & Notifications

  • activity_logs: Already discussed, for record of every major action.
  • notifications: Stores user-targeted notifications.
  • Potential references:
    • id (uuid), user_id (fk -> users.id), title, description, status (read/unread), created_at.

11.3 ER Diagram / Relationship Overview

A simplified conceptual diagram might be:

  +-----------+      +-----------+      +-----------+
| users | 1--n | deals | 1--n | applications |
+-----------+ +-----------+ +-----------+
| KYC? |
| |
| 1--n |
+-----------+ |
| kyc_data | |
+-----------+ |
(details)...

+-----------+ +---------------+
| p2p_trades| n--1 | token_sale |
+-----------+ +---------------+
(some references to deals or direct to on-chain addresses)
  • The relationships are mostly 1-to-many from usersdeals (an issuer can create many deals, though some deals might belong to multiple users if co-issuers are supported).
  • applications link a single user (investor) to a single deal.
  • p2p_trades are typically created by a single user (seller) referencing a token_out_address for compliance, plus buyer references if needed.

11.4 API Endpoint Summaries (Auth, Deals, P2PEscrow, TGE)

The platform’s Next.js API routes are typically grouped by feature. For example:

11.4.1 Auth Endpoints

  • POST /api/auth/login: Takes email/password or wallet signature, returns JWT.
  • POST /api/auth/register: Creates new user, triggers KYC if needed.
  • GET /api/user/profile: Returns user’s roles, KYC status, accreditation info.
  • Potential POST /api/auth/logout or session revoke endpoints.

11.4.2 Deals Endpoints

  • GET /api/deals: List deals (with filters like status, issuer, or search).
  • POST /api/deals: Create a new deal (wizard step data or final submission).
  • GET /api/deals/[id]: Show details of a single deal.
  • PATCH /api/deals/[id]: Update partial fields (if the user is issuer/admin).
  • POST /api/deals/[id]/approve: Broker or admin approval.
  • DELETE /api/deals/[id]: Potentially used for a draft or forcibly removing a deal if not active.

11.4.3 P2PEscrow Endpoints

  • GET /api/p2p-trades: List active trades.
  • POST /api/p2p-trades: Create a new P2P listing.
  • POST /api/p2p-trades/[id]/execute: Buyer executes the trade.
  • PATCH /api/p2p-trades/[id]/cancel: Seller cancels the trade.

11.4.4 TGE/TokenSale Endpoints

  • GET /api/token-sale/[dealId]: Returns the contract address, price, status, etc.
  • POST /api/token-sale/[dealId]/purchase: (Off-chain logic) Initiates or helps user with on-chain purchase.
  • GET /api/token-sale/[dealId]/status: Checks if softcap is met, how many tokens sold, etc.

11.5 Request & Response Samples

11.5.1 Deal Creation (POST /api/deals)

Request (JSON):

{
"title": "Manhattan Office Investment",
"description": "Tokenized real estate in NYC.",
"softcap": 500000,
"hardcap": 1500000,
"min_investment": 5000,
"max_investment": 20000,
"regulations": ["reg_d_506c", "reg_s"],
"documents": [
{
"name": "Offering Memorandum",
"url": "ipfs://Qm...someHash"
}
]
}

Response (JSON):

{
"id": "d85faf0e-2527-4721-a72f-12e90f9edccb",
"status": "draft",
"title": "Manhattan Office Investment",
"issuer_id": "0c1c558b-0213-4d6f-b645-1f24b01747f1",
"created_at": "2025-04-01T10:20:43.289Z",
...
}

11.5.2 P2P Trade Execution (POST /api/p2p-trades/[id]/execute)

Request:

{
"buyerAddress": "0xBuyerWallet",
"expectedAmountIn": "100.0",
"expectedAmountOut": "50.0"
}

Response:

{
"success": true,
"transactionHash": "0x123abc...def",
"dealStatus": "executed"
}

12. Performance & Scalability

The MarsBase Community Deals Platform is designed to support global offerings and thousands of concurrent investors across multiple deals. This chapter covers how we test and optimize performance, how the system can scale horizontally, what caching strategies we employ, and how we monitor and alert in real-time to maintain responsiveness and uptime.


12.1 Load Testing Results & Benchmark Goals

12.1.1 Methodology

  • We conduct load tests (e.g., using Locust, JMeter, or Artillery) simulating real user behavior:
    1. Investor sign-ups and logins.
    2. Deal browsing with various filters.
    3. Crypto purchase calls (TokenSale) or P2P trade executions.
    4. Admin/issuer dashboards with multi-step forms.
  • We test both the API routes (Next.js backend) and the database concurrency under typical usage spikes (e.g., an active sale nearing its close date).

12.1.2 Key Findings

  1. 200–300 RPS (requests per second) with average response times under 200–300 ms for standard queries.
  2. Under peak loads (simulating 10,000 concurrent users):
    • The system still responded within 1–2 seconds for most user interactions, though certain queries (like large aggregate analytics) might take longer.
  3. Bottlenecks were found primarily in:
    • Database queries involving multiple JOINs for compliance checks.
    • Real-time event handling for large volumes of buy/sell transactions.

12.1.3 Target Benchmarks

  • Average API response time under 500 ms.
  • P95 (95th percentile) under 1–1.5 seconds.
  • Ability to scale horizontally to handle 3–5x user surges around major deal launches.

12.2 Horizontal Scaling of Services & Databases

12.2.1 Next.js Application Scaling

  1. Docker Replicas
    • We can run multiple instances of the Next.js server behind a load balancer (e.g., Nginx or AWS ALB).
    • Each instance manages its own ephemeral session data, with shared DB state.
  2. Stateful vs. Stateless
    • Since the Next.js app is largely stateless (besides user sessions handled via JWT or cookies), scaling is implemented by actively adding more replicas as demand increases.

12.2.2 Database Scaling

  1. Vertical:
    • Increase the DB instance’s CPU/RAM, tune PostgreSQL for concurrency.
  2. Horizontal (Read Replicas):
    • For read-heavy workloads (e.g., deal listing, investor queries), we can add read replicas.
    • Writes (like investor purchase updates) still go to the primary.
  3. Sharding (Future)
    • If the platform expands globally or stores high-volume event data, advanced partitioning or multi-shard strategies may be employed.

12.2.3 Caching & Edge

  • Edge Caching for static or SSR-generated pages (like a public deal listing) can drastically reduce server load.
  • A separate caching layer (Redis or Memcached) can store ephemeral data (like recent broker approvals) if required.

12.3 Caching Strategies (React Query, SSR, Edge Caching)

12.3.1 React Query (Client-Side)

  • The front-end uses React Query or SWR for data fetching, caching frequently accessed endpoints.
  • Minimizes repeated calls for the same data within short intervals.

12.3.2 Server-Side Rendering (SSR) Cache

  1. Next.js SSR or SSG
    • For publicly visible pages (e.g., active deals list), we may do a short TTL (time-to-live) cache.
    • Users see near-real-time data, but the platform avoids regenerating the entire page on every request.
  2. Incremental Static Regeneration
    • Some deals pages can be revalidated after a certain timeframe if the data isn’t hyper-dynamic.

12.3.3 Edge Delivery (CDN)

  • The platform leverages Cloudflare's global CDN to accelerate content distribution (images, documents).
  • Cloudflare integration provides dynamic caching of partial SSR results, reducing latency for users worldwide.

12.4 Monitoring & Alerting (Prometheus, Datadog, etc.)

12.4.1 Metrics & Observability

  1. Infrastructure Metrics
    • CPU, memory, container restarts, DB iops.
    • Monitored through the platform's Prometheus and Grafana implementation for real-time visibility.
  2. Application Metrics
    • Response times, request throughput, error rates.
    • Web3 node connections or missed block events if on-chain watchers are used.
    • Real-time or near real-time dashboards help detect slow queries or partial outages.

12.4.2 Alerts & Incident Response

  1. Threshold Alerts
    • High CPU usage (>80%), DB connection saturation, memory leaks, or spikes in error rates.
    • Slack or email alerts triggered automatically.
  2. On-Call Rotation
    • For serious issues, a DevOps or SRE on-call schedule can escalate incidents.
  3. Incident Logging
    • Each incident has a post-mortem to identify root causes and add new fail-safes or improvements.

13. Proactive Security & Auditing Plan

Maintaining robust security is an ongoing process that requires regular reviews, third-party audits, penetration tests, and a clear roadmap of improvement. This chapter describes how the MarsBase Community Deals Platform stays ahead of threats through a structured approach to smart contract and infrastructure security, alignment with best practices (SOC 2, ISO 27001), and a forward-looking strategy for advanced cryptography and compliance.


13.1 Overall Security Enhancement Strategy

13.1.1 Ongoing Internal Code Reviews

  1. Weekly or Biweekly Reviews

    • Key team members (developers, security champions) examine recent merges for potential vulnerabilities or logic flaws.
    • Tools: ESLint, SonarQube, or manual review for issues like insecure usage of external libraries.
  2. Peer-Review Requirements

    • Every pull request must be reviewed by at least one senior engineer with a focus on security.
    • Check for best practices around authentication, data validation, and rate limiting.
  3. Secure Development Lifecycle (SDL)

    • The platform adopts an SDL model: threat modeling at feature design, code scanning, routine audits, and post-deployment checks.

13.1.2 Adherence to Regulatory Security Frameworks

  1. SOC 2 Readiness

    • The platform’s controls aim to align with SOC 2 trust services criteria (Security, Availability, Confidentiality, etc.).
    • Logging and evidence gathering are put in place for future SOC 2 Type I or II audits.
  2. ISO 27001

    • The organization may work toward ISO 27001 certification, establishing formal InfoSec policies for risk management, vendor oversight, and incident handling.
  3. Other

    • Region-specific frameworks (e.g., GDPR for EU, CAIQ for cloud security) are considered in the design of data flows and vendor selection.

13.2 Smart Contract Audits

13.2.1 Third-Party Audit Partnerships

  1. Professional Auditors

    • The TokenSale, P2PEscrow, and Core ERC-20 compliance modules undergo external audits by reputable firms.
    • At least once a year or after major feature changes, these firms re-check the codebase.
  2. Scope & Deliverables

    • The audits focus on potential vulnerabilities: reentrancy, integer overflow, front-running, permission misconfiguration, etc.
    • The deliverable is a formal report, with a list of findings (Critical, High, Medium, Low), and recommended mitigations.
  3. Transparency

    • Summaries or even full audit reports may be published so that issuers and investors have confidence in the contracts’ security.

13.2.2 Regular Re-Audit for Upgrades or Major Changes

  • If the platform modifies the contract logic significantly (e.g., new vesting approach, new multi-reg compliance checks), a re-audit is triggered.
  • Minimizes the risk of introducing regressions or new vulnerabilities.

13.2.3 Bug Bounty Programs & Responsible Disclosure

  1. Public Bounty

    • The platform can offer bounties to security researchers who responsibly disclose vulnerabilities.
    • Payment tiers scale with severity (from code injection to potential fund loss).
  2. Responsible Disclosure

    • Clear guidelines for how researchers submit issues, timeline for patching, and when they can share results publicly.
  3. Encouraging White-Hat Participation

    • This fosters a positive relationship with the security community and helps uncover edge cases.

13.3 Penetration Testing & Threat Modeling

13.3.1 External Pen Tests for Frontend & API

  • The platform commissions third-party pentesters to probe the Next.js API routes, searching for injection flaws, insecure direct object references, or misconfigured auth.
  • Tools: Burp Suite, OWASP ZAP, custom scripts, etc.

13.3.2 Threat Modeling for On-Chain Logic

  1. Smart Contract Attack Vectors
    • Reentrancy, integer underflow/overflow, front-running, incorrectly handled external calls (ERC-777 tokens?), etc.
  2. Layer-1 or Layer-2 Integrations
    • Evaluate bridging, fork scenarios, or chain reorg vulnerabilities.
  3. Off-Chain → On-Chain
    • Potentially malicious data from off-chain compliance modules or back-end services that attempt to call contract methods. The platform ensures all references are validated before contract calls.

13.4 Security Roadmap & Timeline

13.4.1 Short-Term Actions (Bug Bounties, Automated Tools)

  • Launch or expand a bug bounty program on platforms like HackerOne or Bugcrowd.
  • Integrate static analysis tools (MythX, Slither) for continuous scanning of Solidity code.
  • Expand automated scanning for Node.js and Next.js dependencies (npm audit, Snyk, Dependabot).

13.4.2 Mid-Term Goals (Scheduled Audits, SOC 2 Readiness)

  • Schedule semi-annual or annual third-party contract + infrastructure audits.
  • Finalize internal InfoSec policies for SOC 2 readiness, collecting evidence for Type I or II audits.
  • Deploy an advanced WAF (Web Application Firewall) in front of the Next.js backend, checking for injection or anomalies.

13.4.3 Long-Term Vision (Zero-Knowledge Proofs, Additional MPC Enhancements)

  • Explore Zero-Knowledge identity or accreditation proofs, letting investors verify they meet certain thresholds without revealing raw personal data.
  • Expand MPC usage for multi-sign wallets, removing single points of failure even for platform admin keys.
  • Potential full ISO 27001 certification or deeper compliance expansions.

14. Future Enhancements & Roadmap

To remain a leading platform for tokenized investments and global deals, the MarsBase Community Deals Platform envisions an active development roadmap. This chapter outlines upcoming features that enhance user engagement, expand DeFi capabilities, integrate advanced analytics, and further improve multi-regulatory alignment.


14.1 Referral & Rewards System

14.1.1 User Invitation Mechanics

  1. Unique Referral Links

    • Each user or partner can generate a link.
    • Potential new users who sign up via that link are tracked for referral credit.
  2. Rewards

    • The platform can reward the referrer with a portion of platform fees or a fixed bonus.
    • Could be distributed as stablecoins, platform tokens, or direct credits.

14.1.2 Conversion Analytics

  • The system tracks how many referred users become active investors, their average deal size, etc.
  • Data may be shown in a “Referral Dashboard” for the referrer and in admin analytics.

14.1.3 Anti-Spam & KYC Requirements

  • Referred users still must pass KYC/AML; the reward only triggers if they complete an actual investment.
  • The platform can set constraints (e.g., minimal investment threshold) to avoid abuse.

14.2 DeFi Integrations (Collateralized Lending, Yield Farming)

14.2.1 Collateralization of Security Tokens

  1. Use Case
    • Investors might want to borrow stablecoins by pledging their tokenized real estate or equity as collateral.
  2. Implementation
    • Integrate with existing DeFi protocols or build a specialized lending contract that recognizes “compliant tokens” with restricted transfers.
    • The platform ensures ownership, lockups, and compliance are not violated by these DeFi actions.

14.2.2 Yield Farming Partnerships

  • Some tokens might be used in liquidity pools or yield strategies if the deal’s governance allows.
  • The platform can provide direct links to whitelisted DeFi protocols, or host its own curated yield aggregator.

14.2.3 Risk & Regulatory Considerations

  • DeFi often introduces new complexities (smart contract risks, impermanent loss).
  • The platform must disclaim these to remain aligned with securities laws, especially for regulated assets.

14.3 Advanced Analytics & AI-Driven Risk Management

14.3.1 Investor Analytics

  • Real-time dashboards for each investor, summarizing portfolio performance, upcoming lockup expirations, potential secondary market opportunities.
  • AI-driven insights on “what deals fit your risk profile” or “expected ROI based on historical data.”

14.3.2 Issuer & Admin Analytics

  1. Deal Performance
    • Summaries of application conversions, average ticket size, top investor nationalities (while respecting privacy).
    • AI-based forecasting of how quickly a raise might close given current velocity.
  2. Compliance Risk Scores
    • The system can cross-reference KYC data with external risk signals to highlight potential money-laundering patterns or aggregator alerts.

14.3.3 ML or Predictive Models

  • “What-if” scenario modeling for interest rates, real estate fluctuations, or dynamic compliance changes.
  • Some advanced models might detect suspicious trades or collusion in secondary markets.

14.4 Layer-2 / Cross-Chain Expansions

14.4.1 Layer-2 Adoption

  • The platform could deploy the TokenSale & P2PEscrow contracts on L2 solutions like Arbitrum, Optimism, or zkSync to reduce gas costs.
  • This lowers friction for smaller investors who find mainnet gas fees prohibitive.

14.4.2 Cross-Chain Bridges

  • Potential bridging of the security tokens between EVM networks or even non-EVM chains.
  • Maintains a unified compliance approach with an off-chain registry, ensuring locked tokens remain locked across all chains.

14.4.3 Multi-Chain UI

  • The platform’s front-end can detect which network the user’s wallet is on, prompting them to switch networks or bridging tokens for secondary trades.

14.5 Additional Regulation Presets & Jurisdiction Support

14.5.1 Expanded Jurisdictions

  1. Asia-Pacific
    • Deepening support for MAS (Singapore), SFC (Hong Kong), ASIC (Australia).
  2. Latin America
    • Potential for Brazil’s CVM or Mexico’s Fintech laws.
  3. Africa & Middle East
    • Building presets for local securities regulators.

14.5.2 More Complex Regulatory Integrations

  • The platform can handle multi-lingual disclaimers, region-based blocking, or multiple broker sign-offs if a single offering touches multiple countries with distinct local laws.
  • Partnerships with global law firms or compliance consultancies that continuously update preset disclaimers and logic as regulations evolve.

15. Conclusion

15.1 Summary of Technical Strengths & Compliance Alignment

The MarsBase Community Deals Platform combines:

  • Regulatory-Grade Compliance:

    • KYC/AML checks, broker/transfer-agent approvals, and multiple regulation support ensure offerings meet local and international rules.
    • Role-based workflows (issuer, investor, broker, transfer agent, admin) each have dedicated panels and permissions to handle specialized tasks seamlessly.
  • On-Chain & Off-Chain Synergy:

    • Smart contracts (TokenSale, P2PEscrow) automate primary offerings and secondary trades, delivering trustless execution.
    • Off-chain logic in Next.js handles nuanced compliance, accreditation checks, and asynchronous fiat confirmations, bridging traditional finance with blockchain operations.
  • Scalability & Security:

    • Horizontal scaling for Next.js, read-replica DB setups, caching (React Query, SSR) to handle surges in user activity.
    • Security posture includes thorough code reviews, third-party audits, a bug bounty mindset, strong cryptographic measures for data at rest and in transit, plus an evolving plan for advanced frameworks like SOC 2 or ISO 27001 certification.
  • Future-Ready Roadmap:

    • Plans for referral and rewards programs, deeper DeFi integrations (collateralized lending, yield farming), advanced analytics powered by AI, and expansions to multi-chain or L2 solutions.
    • Ongoing regulatory expansions: new disclaimers for APAC, Latin America, or other markets, ensuring the platform can continuously adapt to a global investor base.

15.2 Next Steps & Implementation Guidance

  1. Deployment & Testing

    • Ensure each tenant or environment runs the recommended load tests, monitors real-time metrics, and calibrates DB performance.
    • Thoroughly test the KYC integrations (Sumsub/ShuftiPro) with real or sandbox user flows.
  2. User Training

    • Provide training modules or manuals for issuers, brokers, and transfer agents, so they fully grasp the multi-step compliance workflows and dashboards.
  3. Security Audit & Launch

    • Conduct or finalize the third-party contract audit for any newly introduced token or escrow logic.
    • Start bug bounty or internal penetration tests prior to production release, ensuring minimal vulnerabilities.
  4. Refinement & Regional Rollouts

    • Gather user feedback from early adopters, especially on the deal wizard UI and compliance friction points.
    • Expand to additional jurisdictions or L2 networks as the user base grows.

15.3 Contact & Support Info