ваше сообщение коммита

This commit is contained in:
2026-02-20 14:18:08 +03:00
parent 8702a355a1
commit 24e560fc83
44 changed files with 8354 additions and 95 deletions

View File

@@ -0,0 +1,109 @@
**English** | [Русский](../../docs.ru/back-docs/MULTICHAIN_GOVERNANCE_TOKEN_TRANSFER.md)
# DLE Multichain Governance Token Transfer
## Overview
The DLE multichain governance system lets token holders create proposals to transfer tokens from their wallet to another address (or treasury) through voting in every network where the DLE contract is deployed. Each network has its own quorum; proposals are coordinated and shown as a single card.
## Architecture
- One DLE can be deployed on several chains (e.g. Sepolia, Arbitrum Sepolia, Base Sepolia).
- Each DLE contract per chain runs independently.
- Proposals are created, voted on, and executed **per chain**.
- Proposal IDs are **unique per chain** (e.g. ID=1 on Sepolia and ID=1 on Arbitrum Sepolia are different).
Proposals with the same description and initiator are **grouped** into one card showing status and voting in all chains.
---
## Process: Token transfer
### Stage 1: Create proposal
1. User fills form: description, recipient address, amount (tokens), voting duration, connected wallet (sender).
2. System determines all networks with deployed DLE.
3. **Sequential creation per chain:** switch MetaMask to each network (1 s delay), call DLE `createProposal(...)`, get proposal ID for that chain, delay 3 s (5 s Base Sepolia) after tx. Retry on RPC errors (e.g. up to 3 with exponential backoff).
4. User signs **one transaction per chain** in MetaMask.
**Contract:** `createProposal(description, duration, operation, targetChains, timelockDelay)`.
**Operation:** `_transferTokens(sender, recipient, amount)`**signature `_transferTokens(address,address,uint256)`**. All three parameters required. **Sender** must be initiator (from `signer.getAddress()` when creating in **that** chain). **Amount** must be in wei: `ethers.parseUnits(amount.toString(), 18)`.
**Encoding (ethers.js):** use Interface with `_transferTokens(address,address,uint256)` and encode sender (from signer for current chain), recipient, amountInWei. **Critical:** encode operation **inside** the loop over chains so sender is correct per chain.
**Result:** N proposals (one per chain), each with its own ID; UI shows one card with status per chain.
---
### Stage 2: Voting
1. User sees one card with all chains.
2. Chooses vote For or Against.
3. **Sequential voting:** for each active chain (state active, not executed/canceled): switch network, 1 s delay, **check token balance in that chain** (if none, skip with warning), call `vote(proposalId, support)` with **that chains proposal ID**, delay after tx.
4. One MetaMask signature per active chain.
**Contract:** `vote(proposalId, support)`. Use per-chain proposal ID. Quorum is per chain. Balance checked per chain; if no tokens in a chain, skip voting there.
---
### Stage 3: Execute proposal
**Condition:** Proposal can be executed only when it is **ReadyForExecution** (and quorum reached) **in every** chain where it is active.
1. System checks readiness in all chains.
2. **Sequential execution:** for each ready chain: switch network, 1 s delay, call `executeProposal(proposalId)` with **that chains ID**, delay after tx.
3. One signature per ready chain.
**Contract:** `executeProposal(proposalId)`. Operation `_transferTokens(sender, recipient, amount)`: sender = initiator (checked), recipient and amount from proposal. Tokens are transferred from initiators wallet.
---
## Cancel proposal
Only initiator can cancel, while proposal is active. **Sequential cancel** in all active chains (switch network, delay, `cancelProposal(proposalId, reason)`), one signature per chain.
---
## Important details
1. **Proposal IDs:** Each chain has its own counter. Same numeric ID on different chains = different proposals. UI stores per-chain IDs and uses them for vote/execute/cancel.
2. **Grouping:** Key `${description}_${initiator}`. One card = one logical proposal across chains.
3. **Quorum:** Independent per chain. Execution requires quorum **in all** chains.
4. **Sequential operations:** Create, vote, execute, cancel are done **one chain at a time** (no `Promise.all`) because MetaMask works with one network at a time.
5. **Errors:** Retry on retryable RPC errors; if one chain fails, continue others and report. On vote, skip chains where user has no balance (with warning).
6. **Security:** Sender must equal initiator on execute; balance checked per chain; state and data validated before each call.
7. **Token source:** Tokens are transferred **from the initiators wallet**, not from the contract balance.
---
## UI (summary)
Card: description, initiator, list of chains (name, status, proposal ID, For/Against, quorum), actions: Vote For/Against (if active), Execute (if ready in all), Cancel (if initiator). Statuses: Active, Ready for execution, Executed, Canceled, Expired.
---
## Contract functions (reference)
- `createProposal(description, duration, operation, targetChains, timelockDelay)` → proposalId
- `vote(proposalId, support)`
- `executeProposal(proposalId)`
- `cancelProposal(proposalId, reason)`
- `_transferTokens(sender, recipient, amount)` (internal)
---
## Encoding and implementation notes
- **Correct:** Encode `_transferTokens(sender, recipient, amountInWei)` **inside** the chain loop with `sender = await signer.getAddress()` for that chain. Use `ethers.parseUnits(amount.toString(), 18)`.
- **Wrong:** Encode once before loop; use `_transferTokens(address,uint256)`; omit sender; wrong parameter order in `createProposal`.
- **Wrong:** Use `Promise.all` for execute/vote across chains (MetaMask cannot handle multiple networks in parallel).
All critical encoding and multichain flow issues in the codebase are documented as fixed; implementation follows this spec and the contract.
---
## Conclusion
Multichain governance for DLE provides decentralized token transfer decisions with per-chain quorums and a single UI for managing proposals across all deployed networks.
**Important:** All critical bugs in operation encoding have been fixed; code matches the documentation and contract.

View File

@@ -0,0 +1,82 @@
**English** | [Русский](../../docs.ru/back-docs/TASK_REQUIREMENTS.md)
# Task: Multichain Governance System for DLE
## Status
- ✅ Transfer proposal form works
- ✅ Proposals created in all DLE chains
- ✅ Voting in each chain separately
- ✅ Quorum per chain
- ✅ Personal transfer from proposal initiator
- ✅ Proposals grouped by description + initiator
- ✅ Server coordination with cryptographic proofs
- ✅ No hardcoded chains — deployedNetworks from API
## Context
DLE (Digital Legal Entity) is a decentralized legal entity with contracts in multiple blockchain networks. The task is to implement token governance via multichain governance: token holders can transfer tokens through voting with quorum.
## Architecture
- **Frontend:** Vue.js with Web3
- **Backend:** Node.js for coordination and API
- **Smart contracts:** DLE contracts in each supported network
- **Database:** PostgreSQL for metadata
- **WebSocket:** Real-time sync across networks
## Supported networks
- Ethereum Sepolia (chainId: 11155111)
- Arbitrum Sepolia (chainId: 421614)
- Base Sepolia (chainId: 84532)
## Functional requirements
### 1. Transfer tokens proposal form
**URL:** `/management/transfer-tokens?address=<DLE_ADDRESS>`
**Fields:** Recipient address (required), Amount (tokens, required), Description (optional), Voting duration (days, required).
### 2. Proposal creation
1. Get `deployedNetworks` from API `/dle-v2`
2. Create proposals in all DLE networks (sequentially with MetaMask; one proposal per chain)
3. Encode operation: `_transferTokens(sender, recipient, amount)` — sender = initiator
### 3. Voting
1. Voting is per chain
2. Quorum per chain: `(forVotes / totalSupply) >= quorumPercentage`
3. Vote weight = voters token balance
### 4. Execution
1. Each contract checks its local quorum
2. Backend aggregates quorum results and can sign global status
3. Execution with global quorum proof or per-chain execution
## Technical spec (summary)
- **Proposal:** id, description, forVotes, againstVotes, executed, canceled, deadline, initiator, operation, targetChains, snapshotTimepoint, hasVoted
- **_transferTokens(sender, recipient, amount)** internal; emits TokensTransferredByGovernance
- **Backend:** QuorumCoordinator (collect results, generate global proof)
- **API:** GET /dle-v2, POST create/vote/execute proposal endpoints
- **Frontend:** TransferTokensFormView (validation, encode operation, create in all chains), DleProposalsView (grouped list, status per chain, vote/execute)
## Security
On-chain checks (balance, deadlines, quorum), cryptographic proofs for global quorum, validation, graceful degradation if a chain is down.
## Testing
Acceptance: form works; proposals in all chains; voting per chain; quorum per chain; transfer from initiator; server coordination; grouping; error handling. Cases: create in multichain; vote when one chain down; execute with global quorum; execute with partial quorum (must fail); sufficient/insufficient initiator balance.
## Deployment
Backend with RPC to all networks, DB, SSL, monitoring. Env: RPC URLs, DATABASE_URL, SERVER_PRIVATE_KEY for signing.
---
Fully functional multichain governance for DLE tokens is implemented, with decentralized decisions and optional trusted-server coordination with cryptographic proofs.

View File

@@ -0,0 +1,165 @@
**English** | [Русский](../../docs.ru/back-docs/blockchain-integration-technical.md)
# Digital Legal Entity (DLE) Blockchain Integration
## Table of Contents
1. [Introduction](#introduction)
2. [Smart Contract Architecture](#smart-contract-architecture)
3. [DLE Core Contract](#dle-core-contract)
4. [Module System](#module-system)
5. [Multichain Architecture](#multichain-architecture)
6. [Voting (Governance) System](#voting-governance-system)
7. [Smart Contract Deployment](#smart-contract-deployment)
8. [Wallet Authentication](#wallet-authentication)
9. [Frontend Integration](#frontend-integration)
10. [Security](#security)
11. [Practical Examples](#practical-examples)
---
## Introduction
Digital Legal Entity (DLE) uses blockchain for **tokenized governance** (similar to a blockchain-based joint-stock company) and **transparent decision-making** via smart contracts.
### Why Blockchain in DLE?
1. **Governance like a joint-stock company** — decisions by token holders through on-chain voting
2. **Transparency** — all votes and operations recorded on blockchain
3. **Censorship resistance** — smart contract enforces token holder rights
4. **Immutability** — decision history cannot be altered
5. **Multichain support** — operation across multiple chains
### DLE Governance Model
| Aspect | Implementation |
|--------|----------------|
| **Voting** | Token holders (as shareholders) |
| **Quorum** | 51%+ of tokens to pass decisions |
| **Asset distribution** | Via voting (as in JSC) |
| **Parameter changes** | Via token holder voting |
| **Application code** | Proprietary (author) |
| **Updates** | Author develops; token holders vote on priorities |
### Supported Blockchains
DLE works with **EVM-compatible** networks: Ethereum (mainnet & testnets), Polygon, Arbitrum, BSC, Base, and others.
---
## Smart Contract Architecture
DLE ecosystem: **DLE Core Contract** (ERC20Votes, tokens, proposals, multichain) ↔ **Modules** (HierarchicalVotingModule, TreasuryModule, TimelockModule) ↔ **DLEReader** (batch reads, RPC optimization).
Standards: OpenZeppelin ERC20, ERC20Votes, ERC20Permit, ReentrancyGuard, ECDSA.
---
## DLE Core Contract
File: `backend/contracts/DLE.sol`
Structures: **DLEInfo** (name, symbol, location, coordinates, jurisdiction, okvedCodes, kpp, creationTimestamp, isActive), **Proposal** (id, description, forVotes, againstVotes, executed, canceled, deadline, initiator, operation, governanceChainId, targetChains, snapshotTimepoint, hasVoted).
### Main Features
- **Governance tokens (ERC20):** 1 token = 1 vote; transfers disabled (only via governance); EIP-712 for meta-transactions.
- **Voting (ERC20Votes):** snapshots (flash-loan protection), votes from past block, optional delegation.
- **Multichain:** same address across chains (deterministic deploy); voting on one chain; execution on target chains.
- **Modules:** mapping(bytes32 => address) modules, activeModules; add/remove only via voting.
### Operations Available via Voting
_addModule, _removeModule, _addSupportedChain, _removeSupportedChain, _transferTokens, _updateDLEInfo, _updateQuorumPercentage, _updateVotingDurations.
---
## Module System
### 1. HierarchicalVotingModule
DLE can hold tokens of other DLEs and vote in them. Functions: addExternalDLE, createProposalInExternalDLE, voteInExternalDLE.
### 2. TreasuryModule
Treasury and asset management. transferTokens(token, recipient, amount) only callable by DLE contract. getTokenBalance(token).
### 3. TimelockModule
Delayed execution (timelock), cancel before execution. scheduleProposal(proposalId, operation, delay), executeTimelockProposal(operationHash).
### 4. DLEReader
Batch read: getDLEFullInfo(dleAddress), getAllProposals(dleAddress).
---
## Multichain Architecture
Deterministic deploy: same address on all chains. Voting on one chain (governance chain); execution on target chains via executeWithSignatures(proposalId, operationHash, signers, signatures).
---
## Voting (Governance) System
**createProposal(description, duration, operation, chainId, targetChains, initiator)** — returns proposalId.
**vote(proposalId, support)** — true = For, false = Against.
**execute(proposalId)** — when deadline passed, quorum reached, For > Against, not executed.
**Quorum:** quorumPercentage of totalSupply; change only via voting.
---
## Smart Contract Deployment
**Script:** `backend/scripts/deploy/deploy-multichain.js` — multichain deploy, deterministic address, verification, retry, nonce management. Run: `yarn deploy:multichain`.
**Modules:** `backend/scripts/deploy/deploy-modules.js``yarn deploy:modules`. Config in DB (settings: supported_chain_ids, rpc_providers, dle_config). Verification via Etherscan API; supported: Etherscan, Polygonscan, Arbiscan, BSCScan, Basescan.
---
## Wallet Authentication
**SIWE (Sign-In with Ethereum):** request nonce → sign message in wallet → POST signature → backend verifies signature and token balance → session created. getUserAccessLevel(address) from contract balance and thresholds (editor, readonly).
---
## Frontend Integration
Connect wallet (MetaMask/WalletConnect), sign SIWE message, authenticateWithWallet. getDLEContract, createProposal, voteOnProposal, getProposal. Vue component example for proposal card and vote buttons.
---
## Security
See [DLE Security](../security.md). Summary: ReentrancyGuard, transfers disabled, vote snapshots, EIP-712, parameter validation, custom errors.
---
## Practical Examples
See [Blockchain for Business](../blockchain-for-business.md). Technical scenarios: multichain deploy, adding modules, hierarchical voting, treasury management.
---
## Conclusion
Blockchain in DLE provides: governance like a JSC, full transparency, multichain support, modular design, OpenZeppelin-based security.
### Resources
- [Main README](../../README.md)
- [FAQ](../FAQ.md)
- [Setup](./setup-instruction.md)
- [Terms](../service-terms.md)
- [Legal](../../legal.en/README.md)
**Contacts:** https://hb3-accelerator.com/ | info@hb3-accelerator.com | https://github.com/VC-HB3-Accelerator
---
**© 2024-2025 Alexander Viktorovich Tarabanov. All rights reserved.**
**Last updated:** October 2025

View File

@@ -0,0 +1,118 @@
**English** | [Русский](../../docs.ru/back-docs/multi-agent-architecture.md)
# Multi-Agent AI Architecture in DLE
> **Concept:** Separate specialized agents for different tasks, using one local Ollama model with different system prompts, rules, and interfaces.
---
## Table of Contents
1. [Architecture concept](#architecture-concept)
2. [Agent types](#agent-types)
3. [System architecture](#system-architecture)
4. [Agent configuration](#agent-configuration)
5. [Agent interfaces](#agent-interfaces)
6. [Knowledge base](#knowledge-base)
7. [Agent workflow](#agent-workflow)
---
## Architecture concept
### Principles
1. **One model, many agents** — all use one Ollama instance (e.g. qwen2.5:7b); differentiation by prompts and rules.
2. **Isolation** — each agent has its own prompt, rules, RAG tables, channels, route, permissions.
3. **Task specialization** — support (user Q&A), content editor (posts, articles), others (analyst, translator, procurement).
4. **Separate interfaces** — each agent has its own UI and access path.
---
## Agent types
### 1. Support agent
**Role:** Answer user messages. Uses RAG (FAQ, docs), strict mode (minimal generation), system prompt “professional support assistant”. Interface: chat (web, Telegram, email). Knowledge: FAQ, product docs, client knowledge base.
### 2. Content editor agent
**Role:** Create content on request. RAG: platform instructions, company style, examples. Creative mode. System prompt “content marketer and editor”. Interface: `/content-editor` page. Knowledge: platform instructions, style, examples, keywords, CTAs.
### 3. Other possible agents
Analyst (reports, trends), Translator (localization), Procurement (suppliers, terms).
---
## System architecture
Single Ollama model → multiple agents (Support, Content editor, Others), each with own prompt, rules, RAG, interface.
**Storage:** table `ai_agents` — id, name, role, description, system_prompt_encrypted, rules_id, selected_rag_tables, enabled_channels, interface_route, permissions_required, is_active. Links to `ai_assistant_rules` and RAG tables.
---
## Agent configuration
Steps: (1) Basic info — name, role, description. (2) System prompt. (3) Rules (from or new). (4) RAG tables. (5) Interface — route, permissions, channels. (6) Activate and test.
Example: Support — strict (temperature 0.3, searchRagFirst, no generateIfNoRag), FAQ + docs, chat. Content editor — creative (0.7, generateIfNoRag), instructions + style + examples, `/content-editor`, web only.
---
## Agent interfaces
**Support:** embedded in main chat (HomeView); auto on message; expand/collapse; history.
**Content editor:** page `/content-editor` — request field, content type, platform, generate → edit → save/export, history. Editor role only.
---
## Knowledge base
Support: FAQ, Documentation, Client knowledge base. Content editor: Platform instructions, Company style, Content examples, Keywords, CTAs. RAG search → context → LLM; each agent only sees its own tables.
---
## Agent workflow
**Support:** message → RAG search (FAQ, docs) → if found use it, else suggest operator → send reply.
**Content editor:** request + type + platform → RAG (instructions, style, examples, keywords) → generate content → show in UI → edit/save/export.
---
## Advantages
Specialization, flexibility, isolation, scalability (one model, many agents), clear responsibility.
---
## Comparison: single vs multiple agents
| | Single agent | Multiple agents |
|--|--------------|-----------------|
| Specialization | General, less precise | Per-task, more precise |
| Configuration | One set for all | Per task |
| Knowledge base | Shared | Isolated per agent |
| Interface | One | Per agent |
| Flexibility | Harder to adapt | Easy to add agents |
---
## Next steps
1. Create `ai_agents` table
2. Agent management service
3. Adapt AI Assistant for multiple agents
4. Content editor UI
5. Support agent (adapt existing)
6. Content editor knowledge base
7. Test both agents
---
**© 2024-2025 Alexander Viktorovich Tarabanov. All rights reserved.**
**Last updated:** January 2026

View File

@@ -0,0 +1,132 @@
**English** | [Русский](../../docs.ru/back-docs/setup-ai-assistant.md)
# AI Assistant Setup with Vector Search
## Full guide to launching the intelligent assistant
This document describes the step-by-step setup of the AI assistant for business tasks using spreadsheets and vector search.
---
## What you will have after setup
✅ Working AI assistant with local model (Ollama)
✅ Knowledge base for customer answers (FAQ)
✅ Supplier and procurement automation
✅ Staff training system
✅ Vector search over your data
✅ Significant time and cost savings
> 💡 **Economics:** See [DLE AI Agents](../ai-assistant.md) for architecture, examples, and savings.
---
## Time required
- **Quick setup:** 2030 minutes (basic FAQ)
- **Full setup:** 12 hours (all features)
---
## Step 1: Install and run Ollama
1. **Settings****Integrations****Ollama****Details**
2. Check status: “Ollama is running” or “Ollama API not responding”
3. If not running: `docker-compose up -d ollama` or `ollama serve`
4. **Install model:** e.g. qwen2.5:7b (recommended), llama2:7b, mistral:7b
5. **Install embedding model:** mxbai-embed-large:latest (recommended) or nomic-embed-text:latest
> ⚠️ Embedding model is required for RAG (vector search).
---
## Step 2: Create knowledge base (spreadsheets)
### 2.1 FAQ table
1. **Tables****+ Create table**
2. Name: e.g. “FAQ Frequently asked questions”, description for AI
3. **Add columns:**
- **Question** — type Text, **purpose: Question for AI** (required for RAG)
- **Answer** — type Text, **purpose: Answer for AI**
- **Product** (optional) — Multiselect, purpose: Product filter
- **Tags** (optional) — Multiselect, purpose: User tags
- **Priority** (optional) — Number, purpose: Priority
### 2.2 Fill with sample Q&A
Add rows: e.g. “How to pay?” / “We accept card, PayPal, bank transfer…”; “Delivery time?” / “35 business days…”; “Return policy?” / “Within 14 days…”. Minimum ~2030 questions recommended.
### 2.3 Enable as AI source
In table settings enable **“Use as source for AI”** and save. Table is then indexed for vector search.
---
## Step 3: AI provider (Ollama) settings
1. **Settings****Integrations****Ollama**
2. Base URL: Docker `http://ollama:11434`, local `http://localhost:11434`
3. **LLM model:** e.g. qwen2.5:7b
4. **Embedding model:** mxbai-embed-large:latest
Save.
---
## Step 4: AI Assistant settings
1. **Settings****Integrations****AI Assistant****Details**
2. **System prompt** — e.g. “You are a professional support assistant. Answer from the knowledge base. If not found, suggest contacting an operator. Always end with How else can I help?’”
3. **Models:** select same LLM and embedding as above
4. **Selected RAG tables:** choose your FAQ table
5. **Rules (JSON):** e.g. `searchRagFirst: true`, `generateIfNoRag: true`, `temperature: 0.7`, `maxTokens: 500`
6. **RAG search:** e.g. Hybrid, max results 5, relevance threshold 0.1; optional keyword extraction, fuzzy search, stemming
Save.
---
## Step 5: Test
1. **RAG tester** (on assistant settings page): choose table, ask e.g. “How to pay?” → check answer and score (good: about -300 to 0).
2. **Web chat:** open main page, ask e.g. “What is the delivery cost?” — answer should come from your FAQ.
3. Try questions inside and outside the knowledge base; test with typos (fuzzy search).
---
## Step 6 (optional): Extra tables and channels
- **Suppliers table:** columns for company, category, contact, email, phone, prices, payment terms, delivery, rating. Enable as AI source; add prompt instructions for “TOP-3 suppliers” style answers.
- **Staff knowledge base:** questions/answers by category (Sales, HR, IT). Same RAG setup.
- **Telegram:** create bot via @BotFather, add token and username in Settings → Integrations → Telegram; link to AI assistant.
- **Email:** IMAP/SMTP in Settings; for Gmail use app password. Link to AI assistant.
---
## Step 7: Monitoring and tuning
- **Status:** Settings → AI Assistant → Monitoring: Backend, Postgres, Ollama, Vector Search should be green.
- **RAG quality:** Score -300…0 = good; >300 = not found. Improve by adding variants of questions and adjusting relevance threshold.
- **Speed:** Smaller model or fewer RAG results if responses are slow.
---
## Troubleshooting
- **Ollama not responding:** `docker-compose restart ollama`, check logs.
- **Wrong answers:** Check RAG score; add more questions; lower relevance threshold; ensure column purposes “Question for AI” and “Answer for AI”.
- **Vector search error:** Install embedding model; on table page use “Rebuild index”; ensure table is enabled as AI source.
- **Wrong language:** Add “Always answer in English” (or desired language) to system prompt; choose suitable model (e.g. qwen2.5:7b for multilingual).
---
## Technical reference (developers)
- **DB:** ai_providers_settings, ai_assistant_settings, ai_assistant_rules (encrypted fields, RAG tables, rules JSON).
- **API:** GET/PUT settings per provider and assistant; rules CRUD; Ollama status, models, install.
- **Flow:** Message → UnifiedMessageProcessor → language check → dedup → load settings and rules → RAG search → generate LLM response → return. Security: AES-256 for sensitive fields; admin-only for settings.
---
**© 2024-2025 Alexander Viktorovich Tarabanov. All rights reserved.**
Version: 1.0.0 | Date: October 25, 2025

View File

@@ -0,0 +1,157 @@
<!--
Copyright (c) 2024-2025 Alexander Viktorovich Tarabanov
All rights reserved.
This software is proprietary and confidential.
Unauthorized copying, modification, or distribution is prohibited.
For licensing inquiries: info@hb3-accelerator.com
Website: https://hb3-accelerator.com
GitHub: https://github.com/VC-HB3-Accelerator
-->
**English** | [Русский](../../docs.ru/back-docs/setup-instruction.md)
# Digital Legal Entity — Application Setup Guide
## Full system initialization
This document describes the full process of preparing the application for use with blockchain, smart contracts, and the access control system.
---
## Step 1: Install software
1. Clone the project repository to your machine
2. Run the application via Docker Compose or locally as per your setup
3. Open the web app in a browser: `http://localhost:9000` (production) or `http://localhost:5173` (dev)
---
## Step 2: Connect crypto wallet
1. Ensure a browser wallet is installed (MetaMask, WalletConnect, or similar)
2. Create or import an account that holds governance tokens
3. In the web app click **"Connect wallet"**
4. Choose wallet type and confirm connection
5. After success you will see your account address in the top corner
---
## Step 3: Add RPC providers (Security → RPC providers)
1. Go to **Settings****Security** tab
2. Find **"RPC providers"**
3. Click **"Add"**
4. For each blockchain network fill in:
- **Network name** (e.g. Ethereum, Polygon, BSC)
- **RPC URL** (e.g. `https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY`)
- **Chain ID**
5. Click **"Save"** for each provider
6. The system will verify the connection
> ⚠️ **Important:** Obtain API keys from providers (Alchemy, Infura, QuickNode, etc.) before adding
---
## Step 4: Multichain smart contract deployment
1. Go to **Settings****Blockchain** tab
2. Fill in the form
3. Click **"Start deployment"**
---
## Step 5: Complete deployment and save contract address
1. Wait for deployment to finish (typically 30120 seconds)
2. After success the **"Contract management"** page opens
3. **Copy the deployed contract address** (e.g. `0x742d35Cc6634C0532925a3b844Bc...`)
---
## Step 6: Configure authentication via smart contract
1. Return to **Settings****Authentication** tab
2. In **"Smart contract address"** paste the address from step 5
3. Set access thresholds:
- **Minimum tokens for editing** (e.g. 100)
- **Minimum tokens for viewing** (e.g. 1)
---
## Step 7: AI and database configuration
1. Go to **Settings****AI** tab
2. Open **"Database"** subsection
3. Change default passwords
4. Click **"Generate new encryption key"**
- The system creates a cryptographic key
- **Store the key securely** (needed for data recovery)
---
## Step 8: Internet access (optional)
If you need external access to the web app:
1. Go to **Settings****Server** tab
2. Select **WEB SSH** or another suitable service
3. Fill in the form to migrate the local app to a host with public IP and domain
4. Click **"Publish"**
5. Wait for migration to complete
> Requires a registered domain and DNS access
---
## Step 9: Legal documents for personal data
### 9.1 Company legal information
1. Go to **CRM****Content**
2. Open the **"Company legal information"** form
3. Fill in: full name, short name, legal form, legal address, actual address, Tax ID/OGRN/KPP, contacts, DPO responsible person, applicable jurisdiction (GDPR, CCPA, etc.)
4. Click **"Save"**
### 9.2 Document templates
1. In **Content** go to **"Templates"**
2. Select templates: Privacy Policy, User Agreement, Consent to data processing, Cookie policy
3. For each: **Preview**, edit if needed, then **Publish for public** / **Publish for internal** / **Print** (PDF)
4. Confirm; documents are added to the app
> ⚠️ Consult a lawyer before publishing to ensure legal compliance
---
## Application ready
After these steps the application is fully configured.
**Next:**
- AI assistant setup: see `setup-ai-assistant.md`
- Smart contract management: see `manage-smart-contracts.md`
---
## Security tips
✓ Store contract addresses and encryption keys securely
✓ Use strong DB passwords
✓ Back up configuration regularly
✓ Never share wallet private keys
✓ Use HTTPS in production
---
## Documentation
- [AI Agents](../ai-assistant.md)
- [Blockchain for Business](../blockchain-for-business.md)
- [Security](../security.md)
- [Blockchain technical docs](./blockchain-integration-technical.md)
- [FAQ](../FAQ.md)
- [Application description](../application-description.md)
**Support:** https://hb3-accelerator.com/ | info@hb3-accelerator.com

View File

@@ -0,0 +1,68 @@
**English** | [Русский](../../docs.ru/back-docs/system-messages-management.md)
# Technical Specification: System Messages Management
## 1. Goal and context
- Manage display of system messages on the home page (`/`, `HomeView.vue`) and provide an admin UI for creating and moderating them in Content (`/content`, `ContentListView.vue`).
- System messages support statuses “draft” and “published”, are stored in the database, and exposed via REST API.
## 2. Current state
- Home is built by `HomeView.vue` with assistant chat (`ChatInterface.vue`); system messages are those with `message.role === 'system'` (`Message.vue`).
- Content (`ContentListView.vue`) has cards: Create page, Templates, Published, Settings, Internal. No entity or API for system messages yet; `pagesService.js` only handles pages (`/pages`).
## 3. User scenarios
- **View on home (/):** Published system messages loaded into assistant chat as collapsible cards with clickable title. On click: expand to show full text **or** send a prepared AI assistant reply (content stored with message, chosen by `reply_type`). Messages visually marked as system; optional “read” state in localStorage.
- **Content section:** New card “System messages” with “Details” → `/content/system-messages/table` (user table, no separate dashboard). Table: rows per message, checkboxes for bulk: publish, unpublish, move to draft, delete. Row “Details” → view/edit form.
- **Create/Edit:** Routes `/content/system-messages/create`, `/content/system-messages/:id/edit`. Form: title, summary, main content (Markdown/HTML), reply type (`inline` | `assistant_reply`), assistant reply content (when `assistant_reply`), severity (info/warning/danger), publish_at, expire_at, visible to guests. Buttons: Save as draft, Publish; on edit: Update, Unpublish, Delete. Validation: title and main content (or assistant reply when applicable) required; expire_at ≥ publish_at.
## 4. UI requirements
- In `ContentListView.vue` add “System messages” card to `management-blocks`.
- Table page: BaseLayout, scoped styles; sort, filter by status, search by title; header and row checkboxes; action bar when selection exists; “Create message” opens create form.
- Form: rich text (at least Markdown), preview, character/word count; reply type switch with conditional “Assistant reply” field; severity presets (icon/color).
## 5. Routing and components
- Routes: `/content/system-messages/table` → SystemMessagesTableView; `/content/system-messages/create` → SystemMessageCreateView; `/content/system-messages/:id` → SystemMessageDetailsView; `/content/system-messages/:id/edit` → SystemMessageEditView.
- Components under `src/views/content/system-messages/` and shared in `src/components/system-messages/`.
- Service: `src/services/systemMessagesService.js`.
## 6. API and data
- **Table** `system_messages`: id (uuid), title, summary, content, reply_type (inline | assistant_reply), assistant_reply_content, severity (info | warning | danger), status (draft | published), visible_for (all | authenticated | guests), publish_at, expire_at, created_at, updated_at, created_by, updated_by, slug.
- **REST:** GET /system-messages (pagination, filters), GET /system-messages/published (public, by date/audience), GET /system-messages/:id (editors), POST, PATCH, DELETE; optional POST publish/unpublish.
- Auth and permission (e.g. MANAGE_LEGAL_DOCS) on protected endpoints. New migration, validation (e.g. Joi), logging (winston).
## 7. Frontend logic
- **HomeView:** On load, fetch published messages (by audience) via `systemMessagesService.getPublished({ includeExpired: false })`; cache; on expand either show content (inline) or trigger sending assistant_reply_content; optional “read” in localStorage.
- **ContentListView:** Add “System messages” card.
- List: pagination, sort by date, status badges.
- Form: client-side validation; on publish redirect to list; on draft save stay with notification.
## 8. Security and access
- Create/edit for roles with PERMISSIONS.MANAGE_LEGAL_DOCS.
- GET /system-messages/published: filter by status=published, publish_at ≤ now, expire_at > now (or null), visible_for by guest/auth.
- In chat response hide created_by, updated_by, internal fields. CSRF, CORS, rate-limit as in existing routes.
## 9. Testing
- Backend: CRUD tests in tests/system-messages/*.test.js (Mocha); filters and role access; migration rollback/apply.
- Frontend: unit tests for form and list if present; E2E: draft → publish → visible on home.
- Regression: existing content list and assistant chat still work; `yarn lint`, `yarn test`.
## 10. Integration and DevOps
- Update docker-compose if needed (e.g. migrations on startup). Document new env vars in README and setup-instruction. Optional seed script for test messages.
## 11. Open points
- Audit history (system_messages_history)? Multi-language? WebSocket event for new messages (wsHub)?
## 12. Deliverables
Backend: routes, controllers, service, migration. Frontend: pages, service, updated routes, HomeView, ContentListView. Docs: README, application-description or tables-system if schemas change, this spec.

View File

@@ -0,0 +1,188 @@
**English** | [Русский](../../docs.ru/back-docs/tables-system.md)
# DLE Spreadsheet (Tables) System
> **Internal working document**
---
## Table of Contents
1. [System overview](#system-overview)
2. [Database architecture](#database-architecture)
3. [Field types](#field-types)
4. [Features](#features)
5. [Table relations](#table-relations)
6. [AI (RAG) integration](#ai-rag-integration)
7. [API reference](#api-reference)
8. [Examples](#examples)
9. [Security](#security)
---
## System overview
### What it is
The tables system in DLE is a **full database with a GUI** — similar to **Notion Database** or **Airtable** — built into the app.
### Features
- 6 field types (text, number, relation, lookup, multiselect, multiselect-relation)
- Relations between tables (1:1, 1:N, N:N)
- Lookup and data rollup
- Filtering and sorting
- Real-time updates (WebSocket)
- AI integration (RAG search)
- AES-256 encryption for data
- Placeholders for API access
- Cascade delete, bulk operations
### vs Excel/Sheets
| | Excel/Sheets | DLE Tables |
|-|--------------|------------|
| Data typing | Weak | Strict (6 types) |
| Relations | No | Yes (relation, lookup) |
| AI search | No | Yes (RAG, vector) |
| Real-time | Partial | Full (WebSocket) |
| Encryption | No | AES-256 |
| API | Limited | Full REST |
---
## Database architecture
### Main tables (PostgreSQL)
- **user_tables:** id, name_encrypted, description_encrypted, is_rag_source_id, created_at, updated_at
- **user_columns:** id, table_id, name_encrypted, type_encrypted, placeholder_encrypted, placeholder, options (JSONB), order, created_at, updated_at
- **user_rows:** id, table_id, order, created_at, updated_at
- **user_cell_values:** id, row_id, column_id, value_encrypted, created_at, updated_at, UNIQUE(row_id, column_id)
- **user_table_relations:** id, from_row_id, column_id, to_table_id, to_row_id, created_at, updated_at
Cascade: delete table → columns, rows, cell values, relations. Indexes on relation columns for performance.
---
## Field types
1. **Text** — plain text
2. **Number** — numeric
3. **Multiselect** — multiple choices from a list (options.choices)
4. **Multiselect-relation** — multiple rows from another table (options: relatedTableId, relatedColumnId); stored in user_table_relations
5. **Relation** — single row in another table (1:1 or N:1); one row in user_table_relations
6. **Lookup** — value pulled from related table (options: relatedTableId, relatedColumnId, lookupColumnId)
---
## Features
### CRUD
- **Create table:** POST /tables (name, description, isRagSourceId); name/description encrypted
- **Add column:** POST /tables/:id/columns (name, type, order, purpose, options)
- **Add row:** POST /tables/:id/rows (auto index for RAG if applicable)
- **Save cell:** POST /tables/cell (row_id, column_id, value); upsert; update vector store
- **Delete row:** DELETE /tables/row/:rowId (rebuild vector store)
- **Delete column:** DELETE /tables/column/:columnId (cascade relations and cell values)
- **Delete table:** DELETE /tables/:id (admin; cascade all)
### Filtering
- GET /tables/:id/rows?product=… — by product
- ?tags=… — by user tags
- ?relation_&lt;columnId&gt;=&lt;to_row_ids&gt; — by relation
- ?multiselect_&lt;columnId&gt;=… — by multiselect
### Placeholders
Auto-generated from column name (transliteration, uniqueness). Used for API: GET /tables/:id/data?fields=placeholder1,placeholder2.
### Order
PATCH /tables/:id/rows/order with array of { rowId, order }.
### WebSocket
Events: table-update, table-relations-update, tags-update. Frontend subscribes and reloads when needed.
### Bulk
Select rows (checkboxes); bulk delete or other actions; after delete, vector store rebuilt as needed.
---
## Table relations
- **N:1 (Relation):** one column links to one row in another table (e.g. Task → Project).
- **N:N (Multiselect-relation):** multiple links (e.g. Contacts → Tags).
- **Lookup:** show a field from the related row (e.g. Order → Product → Product.price).
API: GET/POST/DELETE on /tables/:tableId/row/:rowId/relations (column_id, to_table_id, to_row_id or to_row_ids for multiselect).
---
## AI (RAG) integration
- Tables (or selected tables) can be **RAG sources**. Columns with **purpose** “question” and “answer” are used for vector indexing.
- On row create/update: rows with question/answer are upserted into vector store (FAISS). On row delete: rebuild for that table.
- **Rebuild index:** POST /tables/:id/rebuild-index (admin). Reads question/answer columns and rebuilds vector index.
- **RAG flow:** User asks → vector search in table(s) → top_k results with score and metadata (answer, product, userTags, priority) → LLM gets context and generates reply. Filter by product/tags in metadata if needed.
---
## API reference (summary)
- **Tables:** GET/POST /tables, GET/PATCH/DELETE /tables/:id
- **Columns:** POST /tables/:id/columns, PATCH/DELETE /tables/column/:columnId
- **Rows:** POST /tables/:id/rows, DELETE /tables/row/:rowId, PATCH /tables/:id/rows/order
- **Cell:** POST /tables/cell (upsert)
- **Filtered rows:** GET /tables/:id/rows?…
- **RAG:** POST /tables/:id/rebuild-index
- **Relations:** GET/POST/DELETE …/row/:rowId/relations
- **Placeholders:** GET /tables/:id/placeholders, GET /tables/placeholders/all
---
## Examples
### FAQ for AI
Create table with columns: Question (purpose: question), Answer (purpose: answer), Product (multiselect, purpose: product), Tags (multiselect, purpose: userTags). Add rows; enable as RAG source. AI will search by question and return answer; filter by product/tags.
### CRM
Tables: Companies (name, website, industry), Contacts (name, email, company relation, company website lookup). Relation from Contact to Company; lookup “company website” from Company via relation.
### Tasks
Tables: Projects (name, status), Tasks (name, project relation, priority, status). Filter tasks by project: GET .../rows?relation_&lt;projectColumnId&gt;=&lt;projectRowId&gt;.
---
## Security
- **Encryption:** AES-256 for name_encrypted, description_encrypted, value_encrypted, placeholder_encrypted. placeholder and options can be plain for indexing/performance.
- **Access:** View for authenticated users; edit for users with edit rights; delete and rebuild-index for admins (e.g. userAccessLevel.hasAccess). Token balance checked for access level.
- **SQL:** Parameterized queries only. Validate types, existence, uniqueness (e.g. placeholder). Cascade deletes to avoid orphaned data. Optional rate limiting on tables routes.
---
## Performance
- Parallel queries for table meta, columns, rows, cell values where possible. Indexes on user_table_relations. UNIQUE(row_id, column_id) for fast upsert. WebSocket instead of polling. Optional server-side cache for frequent GET /tables/:id.
Typical: GET /tables 50100 ms, GET /tables/:id 150300 ms, POST cell 100200 ms, rebuild-index 15 s. Tables up to ~10k rows fine; larger may need pagination/lazy load.
---
## Limits and future
Current: no server-side pagination, no formulas, no grouping, no change history, limited server-side sort. Possible: pagination, sort params, formula fields, audit table, export/import, table templates.
---
**© 2024-2025 Alexander Viktorovich Tarabanov. All rights reserved.**
Version: 1.0.0 | Date: October 25, 2025 | Status: Internal