Skip to content

Latest commit

 

History

History
672 lines (513 loc) · 20.7 KB

File metadata and controls

672 lines (513 loc) · 20.7 KB

Synaptic Forge — Developer Documentation

URL: https://forge.synapticchain.xyz
Version: 2.0
Last Updated: 2026-06-05


Table of Contents

  1. Overview
  2. Architecture
  3. Getting Started
  4. Contract Templates
  5. AI Natural Language Generator
  6. API Reference
  7. Wallet Integration
  8. Subdomain Auto-Provisioning
  9. Contract Verification
  10. Template Marketplace
  11. Frontend Generation
  12. Deployment Guide
  13. Security Considerations
  14. Troubleshooting

Overview

Synaptic Forge is a no-code smart contract development environment for SynapticChain. It allows anyone to generate, compile, deploy, and verify audited smart contracts through a professional web interface — no coding required.

Key Features

  • 10 Verified Contract Templates — All compiler-safe, tested with synlang v2
  • AI Natural Language Generation — Describe your contract in English, get SynapticLang code
  • One-Click Compile & Deploy — Server-side synlang compilation, direct testnet/mainnet deploy
  • Contract Verification — Submit source code to explorer for public auditability
  • Subdomain Auto-Provisioning — Deployed dApps get their own *.forge.synapticchain.xyz URL
  • Template Marketplace — Save and share custom contract templates
  • Web4 Wallet Connect — Ed25519-based wallet with balance/nonce queries
  • BYOK AI Frontend Generation — Use your own Kimi API key for AI-generated React frontends

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        USER BROWSER                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐   │
│  │  Forge UI    │  │  Wallet Lib  │  │  Kimi API (BYOK)     │   │
│  │  (React)     │  │  (Ed25519)   │  │  (client-side)       │   │
│  └──────┬───────┘  └──────┬───────┘  └──────────┬───────────┘   │
└─────────┼─────────────────┼─────────────────────┼───────────────┘
          │                 │                     │
          │ HTTPS           │ RPC                 │ HTTPS
          │                 │                     │
┌─────────┼─────────────────┼─────────────────────┼───────────────┐
│         │                 │                     │               │
│  ┌──────▼───────┐  ┌──────▼───────┐  ┌─────────▼────────┐      │
│  │   Nginx      │  │  Gateway-v3  │  │  api.moonshot.cn │      │
│  │  (Charlie)   │  │  (Charlie)   │  │  (Kimi)          │      │
│  └──────┬───────┘  └──────┬───────┘  └──────────────────┘      │
│         │                 │                                     │
│  ┌──────▼─────────────────▼────────┐                            │
│  │      Synaptic Forge App          │                            │
│  │      (Next.js 14, port 3456)     │                            │
│  │                                  │                            │
│  │  ┌─────────┐ ┌──────────────┐   │                            │
│  │  │Compile  │ │Deploy        │   │  → synlang CLI             │
│  │  │API      │ │API           │   │                            │
│  │  └─────────┘ └──────────────┘   │                            │
│  │  ┌─────────┐ ┌──────────────┐   │                            │
│  │  │Verify   │ │Subdomain     │   │  → nginx + certbot         │
│  │  │API      │ │API           │   │                            │
│  │  └─────────┘ └──────────────┘   │                            │
│  │  ┌─────────┐ ┌──────────────┐   │                            │
│  │  │AI Gen   │ │Marketplace   │   │  → taxonomy.json + files   │
│  │  │API      │ │API           │   │                            │
│  │  └─────────┘ └──────────────┘   │                            │
│  └─────────────────────────────────┘                            │
│                              Charlie Gateway (203.161.56.222)   │
└─────────────────────────────────────────────────────────────────┘

Tech Stack

Layer Technology
Frontend Next.js 14 (App Router), React 18, Tailwind CSS 3
Icons Lucide React
Crypto @noble/curves/ed25519.js, js-sha3
Fonts Inter (UI), JetBrains Mono (code)
Backend Next.js API Routes (Node.js)
Compiler synlang CLI (Rust binary)
Reverse Proxy Nginx 1.24
SSL Let's Encrypt (Certbot)
Process Manager PM2

Getting Started

For End Users

  1. Visit https://forge.synapticchain.xyz
  2. Click Templates in the sidebar to browse 10 verified categories
  3. Or click AI Generator and describe your contract in natural language
  4. Fill parameters, click Build Contract
  5. Click Compile to generate .plan file
  6. Enter your private key and RPC endpoint in Settings
  7. Click Deploy to deploy to the blockchain
  8. Click Verify on Explorer to publish source code
  9. Click Provision Subdomain to get a public URL

For Developers (Local Setup)

cd /opt/synapticchain/forge
npm install
npm run dev        # port 3456
# or
npm run build
npm start          # production

Required environment:

  • Node.js 18+
  • synlang binary in PATH or at /usr/local/bin/synlang
  • Nginx (for subdomain provisioning)
  • Certbot (for SSL)

Contract Templates

Verified Templates (10 Categories)

ID Name Complexity Functions Compiles
token Fungible Token (SRC-20) simple 17
staking Staking Vault simple 13
nft NFT Collection (ERC-721) simple 15
dex AMM DEX (Constant Product) advanced 12
governance Simple DAO Governance intermediate 8
vesting Token Vesting intermediate 8
referral Referral Rewards simple 10
crowdfunding Crowdfunding Campaign simple 9
escrow Two-Party Escrow simple 10
multisig Multi-Signature Wallet intermediate 11

Compiler-Safe Patterns

All templates follow these rules for guaranteed compilation with synlang v2:

  1. Every function MUST declare #[reads(...)] and/or #[writes(...)] annotations
  2. Use direct map indexing: self.balances[key]
  3. Use .insert(key, value) for map writes
  4. Use emit EventName { field: value } syntax
  5. Use return for return values
  6. Use require!(condition, "message") for assertions
  7. Helper functions also need reads/writes annotations

AI Natural Language Generator

How It Works

The /api/ai-generate endpoint uses keyword-based intent detection:

  1. Intent Detection — Scans prompt for category keywords (e.g., "staking", "vault", "farm" → staking)
  2. Parameter Extraction — Regex patterns extract values from natural language:
    • Token names: "called GreenCoin"TOKEN_NAME=GreenCoin
    • Percentages: "10% APY"REWARD_RATE_BPS=1000
    • Durations: "30 days"CLIFF_DURATION=2592000 (seconds)
  3. Template Selection — Loads the matching template from data/templates/
  4. Substitution — Fills {{PARAM}} placeholders with extracted values

Example Prompts

Prompt Detected Extracted Params
"Create a token called GreenCoin with symbol GRC" token name=GreenCoin, symbol=GRC
"Staking vault with 10% APY" staking rate=1000 bps
"NFT collection called CryptoArt, max 10000" nft name=CryptoArt, max_supply=10000
"Multisig wallet with 3 signers" multisig threshold=3

Extending Intent Detection

Edit forge/app/api/ai-generate/route.ts:

const INTENTS: CategoryIntent[] = [
  {
    id: 'your_category',
    keywords: ['keyword1', 'keyword2'],
    requiredParams: ['PARAM_NAME'],
    paramExtractors: {
      PARAM_NAME: /regex pattern (\d+)/i,
    },
  },
];

API Reference

POST /api/generate

Generate contract code from template + parameters.

Request:

{
  "categoryId": "token",
  "params": {
    "TOKEN_NAME": "MyToken",
    "TOKEN_SYMBOL": "MTK",
    "TOKEN_DECIMALS": "18",
    "MAX_SUPPLY": "0"
  }
}

Response:

{
  "code": "contract MyToken { ... }",
  "category": { ... }
}

POST /api/compile

Compile SynapticLang code to .plan file.

Request:

{
  "code": "contract Test { ... }"
}

Response:

{
  "success": true,
  "message": "Compilation successful!",
  "planPath": "/tmp/forge_123.plan"
}

POST /api/deploy

Deploy compiled .plan to blockchain.

Request:

{
  "planPath": "/tmp/forge_123.plan",
  "rpcUrl": "https://forge.synapticchain.xyz/rpc",
  "privateKey": "0x..."
}

Response:

{
  "success": true,
  "message": "Deployed successfully",
  "contractAddress": "syn1..."
}

POST /api/ai-generate

Generate contract from natural language prompt.

Request:

{
  "prompt": "Create a staking vault with 10% APY"
}

POST /api/verify

Verify contract source code on explorer.

Request:

{
  "contractAddress": "syn1...",
  "code": "contract Test { ... }",
  "contractName": "Test",
  "deployer": "syn1...",
  "rpcUrl": "https://..."
}

Response:

{
  "success": true,
  "explorerUrl": "https://explorer.synapticchain.xyz/contract/syn1..."
}

POST /api/subdomain

Provision a subdomain for a deployed contract.

Request:

{
  "subdomain": "my-project",
  "contractAddress": "syn1..."
}

Response:

{
  "success": true,
  "url": "https://my-project.forge.synapticchain.xyz"
}

Note: If DNS isn't ready, falls back to HTTP-only. For full auto-SSL, add a wildcard A record:

*.forge.synapticchain.xyz → 203.161.56.222

GET|POST|DELETE /api/templates

Marketplace CRUD operations.

GET — List all templates
POST — Save new template ({name, description, categoryId, code, params, author})
DELETE — Remove template (?id=<template_id>)


POST /api/generate-frontend

Generate basic Web4 frontend (server fallback).

For AI-enhanced generation, use BYOK in the UI with your Kimi API key.


Wallet Integration

Current Implementation

The Forge includes a lightweight Ed25519 wallet implementation (app/lib/wallet.ts):

  • Address derivationprivateKey → publicKey → sha3_256 → last 20 bytes → bech32m('syn', ...)
  • Balance querysyn_getBalance RPC call (returns data.result directly)
  • Nonce querysyn_getNonce RPC call
  • Balance displayfromUnits() converts raw 18-decimal units to human-readable SYN

Usage

  1. Go to Settings sidebar tab
  2. Paste your private key (hex, with or without 0x prefix)
  3. Click Connect Wallet
  4. Address and balance display in the top bar

Security

  • Private keys are stored in component state only (never persisted)
  • All signing happens in the browser
  • For production, integrate with the SynapticChain wallet app or hardware wallets

Subdomain Auto-Provisioning

How It Works

  1. User deploys a contract
  2. User enters a subdomain prefix (e.g., my-project)
  3. Forge API creates:
    • Nginx server block for my-project.greenverse.synapticchain.xyz
    • Web root directory at /opt/synaptic/apps/subdomains/my-project/
    • Placeholder index.html
  4. Certbot attempts SSL certificate expansion
  5. Nginx reloads

DNS Requirements

Option A: Wildcard DNS (Recommended)

Add this A record in your DNS provider (Namecheap):

*.forge.synapticchain.xyz → 203.161.56.222

Option B: Per-Subdomain DNS

Manually add A records for each subdomain, or implement the Namecheap API:

// In subdomain API — add before nginx config creation
await createNamecheapDNSRecord({
  type: 'A',
  host: subdomain,
  value: '203.161.56.222',
});

Namecheap API Credentials:

  • Set NAMECHEAP_API_USER, NAMECHEAP_API_KEY, NAMECHEAP_CLIENT_IP env vars
  • Requires whitelisted IP

Contract Verification

Process

  1. Deploy contract
  2. Click Verify on Explorer
  3. Forge saves:
    • Contract address
    • Source code
    • Compiler version
    • Deployer address
    • Timestamp
  4. Returns explorer URL for public viewing

Storage

Verified contracts are stored at:

forge/data/verified/<contract_address>.json

Explorer Integration

The verify endpoint also attempts to forward data to the explorer backend:

POST http://127.0.0.1:8000/api/contracts/verify

Template Marketplace

Features

  • Save — Publish your generated contract as a community template
  • Browse — View all saved templates with author, date, stars, downloads
  • Load — One-click import of any marketplace template into the editor

Storage

Templates are stored server-side at:

forge/data/marketplace/<template_id>.json

Data Structure

{
  "id": "abc123",
  "name": "My Custom Token",
  "description": "...",
  "categoryId": "token",
  "code": "contract ...",
  "params": { "TOKEN_NAME": "MyToken" },
  "author": "syn1...",
  "createdAt": "2026-06-05T00:00:00Z",
  "stars": 0,
  "downloads": 0
}

Frontend Generation

Basic Template (Server)

If no Kimi API key is configured, Forge generates a basic React + Tailwind dApp with:

  • Read function buttons
  • Write function forms
  • Wallet connect placeholder
  • Web4 RPC integration

AI-Enhanced (BYOK)

For cinema-quality frontends:

  1. Get a Kimi API key from https://platform.moonshot.cn
  2. Go to SettingsKimi API Key (BYOK)
  3. Paste your key (stored in localStorage, never sent to server)
  4. Click Generate Frontend
  5. Forge calls Kimi directly from your browser with the contract code
  6. Returns a complete, styled React component

Why BYOK?

  • You pay for your own API usage
  • Your contract code stays private
  • No key management liability for the operator

Deployment Guide

Production (Charlie Gateway)

# On Charlie (203.161.56.222)
cd /opt/synaptic/apps/forge
npm install
npm run build
pm2 start npm --name forge -- start
pm2 save

# Nginx config already exists at:
# /etc/nginx/sites-enabled/forge.synapticchain.xyz

# SSL cert (shared with other subdomains):
# /etc/letsencrypt/live/rpc.synapticchain.xyz/

Environment Variables

Variable Required Description
SYNLANG_PATH No Path to synlang binary. Auto-detected if omitted.
PORT No Defaults to 3456

No server-side API keys required. All external AI calls are client-side (BYOK).

Updating After Code Changes

# On Delta (build box)
cd /opt/synapticchain/forge
npm run build
rsync -avz --exclude=node_modules --exclude=.next/cache . root@203.161.56.222:/opt/synaptic/apps/forge/

# On Charlie
ssh root@203.161.56.222
cd /opt/synaptic/apps/forge
npm run build
pm2 restart forge

Security Considerations

What's Safe

  • ✅ Contract templates are audited and compiler-safe
  • ✅ Kimi API keys are client-side only (BYOK)
  • ✅ Private keys are ephemeral (component state, not persisted)
  • .plan files are temporary and cleaned up

What Requires Care

  • ⚠️ Private keys — Users paste keys in the browser. Warn them about phishing.
  • ⚠️ Subdomain provisioning — Requires server access. Restrict API if needed.
  • ⚠️ Template marketplace — No auth currently. Add rate limiting for public instances.
  • ⚠️ Compiler binarysynlang runs server-side with shell execution. Keep binary trusted.

Recommended Hardening

  1. Add rate limiting to all API routes (express-rate-limit)
  2. Add CAPTCHA to template marketplace submissions
  3. Validate all user inputs (already done for subdomains)
  4. Run synlang in a sandbox/container for compilation
  5. Add authentication for admin functions

Troubleshooting

Compilation fails with "StateAccessViolation"

This means the generated code has a state access pattern the compiler doesn't allow. Check:

  • All functions have #[reads]/#[writes] annotations
  • No ! operator on state reads (use == false)
  • Only one write per state slot per function branch

Deploy fails with "Invalid nonce"

The deployer's nonce is out of sync. Solutions:

  1. Query current nonce via wallet connect
  2. Manually specify nonce in deploy request
  3. Wait for pending transactions to clear

Transfer fails with "Invalid recipient address" or "Invalid from address"

The wallet's bech32 implementation was using the wrong checksum variant or address length. Fixed in commit a13c5648:

  • bech32Encode must append 6 zeros for checksum computation: bech32Polymod([...combined, 0,0,0,0,0,0]) ^ 0x2bc830a3
  • bech32Decode must validate against 0x2bc830a3 (bech32m), not 1 (bech32)
  • Address derivation must use hashBytes.slice(12, 32) (last 20 bytes), not full 32 bytes
  • Transfer payload variant index must be 2 (matches Rust Payload::Transfer), not 0

Balance shows raw units (e.g., "500000000000000000" instead of "0.5")

Use fromUnits(balance) from wallet.ts to convert 18-decimal raw units to human-readable SYN.

Wallet shows 0 SYN but address has funds

Check that the derived address matches your working wallet. The bech32m checksum must match the Rust SDK implementation. If the address differs, the private key derivation is wrong (see transfer fix above).

Subdomain returns "DNS_PROBE_FINISHED_NXDOMAIN"

DNS record doesn't exist. Solutions:

  1. Add wildcard A record: *.greenverse.synapticchain.xyz → 203.161.56.222
  2. Or add specific A record for the subdomain
  3. Wait for DNS propagation (up to 24 hours)

Subdomain has no SSL

Certbot couldn't validate the domain. Solutions:

  1. Ensure DNS resolves before provisioning
  2. The API automatically falls back to HTTP-only
  3. Re-run provisioning after DNS is ready

"synlang not found"

The compiler binary isn't in the expected location. Solutions:

  1. Copy binary: scp synlang root@charlie:/usr/local/bin/
  2. Or set SYNLANG_PATH environment variable
  3. Ensure binary is executable: chmod +x /usr/local/bin/synlang

Roadmap

Feature Status Priority
10 verified templates ✅ Done
AI natural language ✅ Done
Compile & deploy ✅ Done
Contract verification ✅ Done
Subdomain provisioning ✅ Done
Template marketplace ✅ Done
Wallet connect ✅ Done
BYOK Kimi integration ✅ Done
Wildcard DNS automation 🔄 Needs DNS API Medium
Web4 real signing 🔄 Needs wallet protocol High
Contract import from address ⏳ Planned Low
Gas estimation UI ⏳ Planned Medium
Multi-chain support ⏳ Planned Low

License

Synaptic Forge is part of the SynapticChain project. See GIT_SAFE/LICENSE.txt for details.


Support

  • Explorer: https://explorer.synapticchain.xyz
  • Gateway: https://forge.synapticchain.xyz/rpc
  • Documentation: This file + GIT_SAFE/API_REFERENCE.md