Compare commits
50 Commits
bbad47b0e8
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| b3b0e882b2 | |||
| 37d54887d6 | |||
| 523bbe0860 | |||
| 2f4d80d5ef | |||
| 0f228b2ae5 | |||
| 0b36caf77d | |||
| f8a2309173 | |||
| 5813c526ae | |||
| f0831e4cd4 | |||
| e37f8415fb | |||
| 7fbeb8826b | |||
| 3313f8245e | |||
| d7b03c91b9 | |||
| 02aab8c3f6 | |||
| 7cf4f3a0f0 | |||
| b6aa14b62d | |||
| 574f90ddee | |||
| d036b4c79f | |||
| 467e488b36 | |||
| e6b7b2d419 | |||
| b6ab7bab9c | |||
| 081758995a | |||
| ac5bf10af6 | |||
| 60b8841895 | |||
| b034fdf1c4 | |||
| f90ca40202 | |||
| d4de95e6db | |||
| 2391d4c061 | |||
| 2fee5db206 | |||
| 6de137a232 | |||
| a741ab6fec | |||
| 6094b43ae3 | |||
| 04e09b0c97 | |||
| fbd4d5d6ef | |||
| 0ad6145091 | |||
| 54778373b8 | |||
| a7030d7d0f | |||
| 6d00c0ddf4 | |||
| 3b8e029cde | |||
| c36d6b9ded | |||
| f073b14e01 | |||
| 23dab2df85 | |||
| 073266a104 | |||
| ba4a4fdfb7 | |||
| e9bcca21cc | |||
| a9d26750fa | |||
| e754cb63bf | |||
| dcee5c9447 | |||
| ff3b20f13b | |||
| 83a8a879aa |
58
CHANGELOG.md
58
CHANGELOG.md
@@ -1,8 +1,54 @@
|
||||
<!-- file: CHANGELOG.md -->
|
||||
|
||||
0.0.1 - initial skel
|
||||
0.0.2 - Socle conforme
|
||||
0.1.0 - Transport WebSocket générique
|
||||
0.1.1 - Intégration Tauri minimale du WsClient
|
||||
0.2.0 - Couche JSON-RPC WS Solana
|
||||
0.3.0 - Registre subscriptions / notifications
|
||||
0.0.1 - initial skel
|
||||
0.0.2 - Socle conforme
|
||||
0.1.0 - Transport WebSocket générique
|
||||
0.1.1 - Intégration Tauri minimale du WsClient
|
||||
0.2.0 - Couche JSON-RPC WS Solana
|
||||
0.3.0 - Registre subscriptions / notifications
|
||||
0.3.1 - Ajout des helpers subscribe/unsubscribe à WsClient
|
||||
0.3.2 - Ajout des helpers typed et du parsing typed basé sur solana-rpc-client-api
|
||||
0.3.3 - Ajout du suffixe _raw aux helpers raw pour distinguer typed et raw
|
||||
0.3.4 - Ajout de la fenêtre Demo Ws dans kb_app pour tester les souscriptions live
|
||||
0.3.5 - Stabilisation de Demo Ws, lecture correcte des endpoints activés depuis la config, limitation/throttling de l’affichage UI sous fort débit
|
||||
0.4.0 - Socle HttpClient générique async clonable, JSON-RPC HTTP 2.0, résolution d’URL avec api_key_env_var, limiteur local req/sec + burst, helpers initiaux getHealth/getVersion/getSlot
|
||||
0.4.1 - Ajout des premiers helpers HTTP Solana haut niveau, dans la continuité de l’API du client WebSocket
|
||||
0.4.2 - Préparation de la politique HTTP avancée : états de pause avant envoi, quotas par famille de méthodes et futur pool d’endpoints
|
||||
0.4.3 - Pool d’endpoints HTTP
|
||||
0.4.4 - Ajout de la fenêtre Demo Http dans kb_app, exécution manuelle des méthodes HTTP via le pool, snapshot des endpoints et amélioration des presets UI
|
||||
0.5.0 - Début du socle SQLite : configuration database, ouverture/validation de la base et premières briques de persistance
|
||||
0.5.1 - Ajout des premières tables métier SQLite pour les endpoints connus HTTP/WS et les événements runtime, avec séparation entities/dtos/queries/types
|
||||
0.5.2 - Ajout de la table des tokens observés, de leur statut local et des premières requêtes de persistance associées
|
||||
0.5.3 - Préparation du stockage local des événements techniques et des signaux utiles à l’analyse, avec distinction runtime / on-chain / métier
|
||||
0.5.4 - Ajout du modèle métier normalisé initial pour les DEX, tokens, pools, paires, composition des pools et listings
|
||||
0.5.5 - Ajout des événements métier normalisés pour les swaps, liquidités, mints et burns de tokens
|
||||
0.5.6 - Consolidation de la couche stockage : activation des foreign keys SQLite, lectures ciblées sur le modèle métier normalisé, index supplémentaires et tests unitaires dédiés
|
||||
0.6.0 - Ajout du pipeline de détection technique : façade de persistance pour observations on-chain, signaux d’analyse et candidats tokens depuis les connecteurs RPC
|
||||
0.6.1 - Ajout du bridge de détection Solana WS : notifications JSON-RPC persistées en observations, avec détection initiale des mints SPL / Token-2022 depuis programNotification
|
||||
0.6.2 - Branchement de WsClient vers le pipeline de détection via un relais asynchrone de notifications JSON-RPC WebSocket
|
||||
0.6.3 - Enrichissement des notifications WebSocket utiles : extraction améliorée de pubkey, signature, owner, parsed account type et slot pour account/logs/signature notifications
|
||||
0.6.4 - Premières règles de détection technique pour candidats pools/listings depuis programNotification en s’appuyant sur les DEX connus en base
|
||||
0.6.5 - Ajout de ws_manager.rs pour l’orchestration multi-clients WebSocket, le bus d’événements unifié et le branchement centralisé du relais de détection
|
||||
0.6.6 - Ajout de la fenêtre Demo Ws Manager dans kb_app pour piloter plusieurs WsClient, visualiser le snapshot consolidé, tester le démarrage/arrêt par rôle et valider le flux unifié de WsEvent
|
||||
0.7.0 - Ajout du socle de résolution transactionnelle orientée DEX : relais WS vers file de résolution, récupération getTransaction via HttpEndpointPool et persistance des résolutions dans les observations/signaux
|
||||
0.7.1 - Ajout du modèle transactionnel enrichi : tables slots/transactions/instructions, requêtes d’accès et projection structurée des transactions résolues
|
||||
0.7.2 - Ajout du premier décodeur DEX spécifique Raydium AmmV4 / initialize2, persistance des événements DEX décodés et branchement automatique du décodage après résolution/projection transactionnelle
|
||||
0.7.3 - Ajout de la détection métier depuis les événements DEX décodés, avec alimentation de kb_pools, kb_pairs, kb_pool_tokens et kb_pool_listings, et signaux de première apparition
|
||||
0.7.4 - Ajout du premier lot multi-DEX v1 avec décodeurs Pump.fun (create_v2) et PumpSwap (buy/sell), plus détection métier Pump.fun vers token/pool/pair/listing
|
||||
0.7.5 - Enrichissement de PumpSwap avec extraction des mints et du pool_v2, persistance des événements décodés enrichis et détection métier automatique pool/pair/listing
|
||||
0.7.6 - Ajout du premier support Meteora DBC avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.7 - Ajout du premier support Meteora DAMM v2 avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.8 - Ajout du premier support Meteora DAMM v1 avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.9 - Ajout d’un registre des surfaces de lancement, d’une attribution automatique des pools détectés à une origine de lancement, et d’un premier support Meteora Fun Launch au-dessus de Meteora DBC / DAMM
|
||||
0.7.10 - Ajout du premier support Orca Whirlpools avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.11 - Ajout du premier support FluxBeam avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.12 - Ajout du premier support DexLab Swap/Pool avec décodage create_pool/swap, persistance des événements décodés et détection métier automatique pool/pair/listing
|
||||
0.7.13 - Extension de la couche launch origins avec Bags et Moonit, ajout d’un enregistrement programmatique des mappings Bags, et détection automatique Moonit via suffixe de token mint
|
||||
0.7.14 - Ajout d’une couche consolidée de traçabilité fondatrice multi-DEX avec enregistrement des pool origins, rattachement au decoded event, au pool/pair/listing et à l’éventuelle launch attribution
|
||||
0.7.15 - Ajout d’une couche wallets observés et participations observées, avec extraction des rôles depuis les payloads décodés et rattachement transaction / decoded event / pool / pair
|
||||
0.7.16 - Ajout d’une première couche trade events et pair metrics avec normalisation des swaps, agrégation par paire et branchement automatique dans le pipeline de résolution transactionnelle
|
||||
0.7.17 - Ajout d’une première couche WS hybride avec collecte de cibles `programSubscribe` / `accountSubscribe` et persistance technique dédupliquée des notifications `logs / program / account`
|
||||
0.7.18 - Ajout d’un premier backfill historique ciblé par token mint, basé sur `getSignaturesForAddress` + `getTransaction`, avec réutilisation du pipeline interne pour reconstruire transactions, pools, swaps, origins, wallets et métriques
|
||||
0.7.19 - Ajout d’une première couche holdings observés avec agrégation par couple wallet/token et branchement automatique dans le pipeline de résolution transactionnelle
|
||||
0.7.20 - Ajout d’une première couche candles / OHLCV avec matérialisation en base des timeframes usuels et régénération à la demande pour un timeframe arbitraire depuis les trade events
|
||||
0.7.21 - Ajout d’une première couche de signaux analytiques enrichis par paire avec persistance dédiée et détection de first trade, trade burst, buy/sell imbalance, price jump et volume spike
|
||||
|
||||
@@ -8,7 +8,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0"
|
||||
version = "0.7.21"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
repository = "https://git.sasedev.com/Sasedev/khadhroony-bobobot"
|
||||
|
||||
12
README.md
12
README.md
@@ -244,21 +244,13 @@ Exemple déjà présent :
|
||||
|
||||
## 12. État du projet
|
||||
|
||||
Le dépôt est actuellement à un stade de fondation.
|
||||
|
||||
Les premières priorités sont :
|
||||
|
||||
- remettre le squelette en conformité,
|
||||
- poser la configuration JSON,
|
||||
- poser le tracing,
|
||||
- préparer `WsClient` et `HttpClient`,
|
||||
- brancher une UI Tauri minimale.
|
||||
voir `CHANGELOG.md`
|
||||
|
||||
## 13. Feuille de route
|
||||
|
||||
La feuille de route détaillée est disponible dans :
|
||||
|
||||
- `Roadmap.md`
|
||||
- `ROADMAP.md`
|
||||
|
||||
## 14. Licence
|
||||
|
||||
|
||||
636
ROADMAP.md
636
ROADMAP.md
@@ -61,11 +61,11 @@ Le projet doit pouvoir évoluer progressivement vers les capacités suivantes :
|
||||
|
||||
## 4. Configuration cible
|
||||
|
||||
La configuration applicative sera stockée dans un fichier `config.json`.
|
||||
La configuration applicative est stockée dans un fichier `config.json`.
|
||||
|
||||
### 4.1. Points à couvrir dans la configuration
|
||||
|
||||
Le fichier devra à terme permettre de configurer :
|
||||
Le fichier doit permettre de configurer :
|
||||
|
||||
- les endpoints HTTP,
|
||||
- les endpoints WebSocket,
|
||||
@@ -93,12 +93,13 @@ Le fichier devra à terme permettre de configurer :
|
||||
|
||||
### 4.3. Exigences particulières
|
||||
|
||||
Chaque endpoint devra pouvoir porter sa propre configuration, par exemple :
|
||||
Chaque endpoint doit pouvoir porter sa propre configuration, par exemple :
|
||||
|
||||
- nom logique,
|
||||
- URL,
|
||||
- provider,
|
||||
- présence ou non d’une clé API,
|
||||
- variable d’environnement pour clé API,
|
||||
- plafond de requêtes,
|
||||
- burst,
|
||||
- timeout,
|
||||
@@ -116,7 +117,7 @@ Exemples de rôles futurs :
|
||||
|
||||
## 5. Tracing cible
|
||||
|
||||
Le tracing devra être centralisé dans `kb_lib`.
|
||||
Le tracing est centralisé dans `kb_lib`.
|
||||
|
||||
### 5.1. Exigences initiales
|
||||
|
||||
@@ -139,145 +140,567 @@ Le tracing devra être centralisé dans `kb_lib`.
|
||||
|
||||
## 6. Phasage par versions
|
||||
|
||||
## 6.1. Version `0.0.2` — Socle conforme
|
||||
|
||||
### 6.001. Version `0.0.2` — Socle conforme
|
||||
Objectif : corriger le squelette et poser la base de travail.
|
||||
|
||||
À faire :
|
||||
Réalisé :
|
||||
|
||||
- corriger `kb_lib/src/lib.rs`,
|
||||
- créer `KbError`,
|
||||
- créer `KbConfig`,
|
||||
- créer `init_tracing`,
|
||||
- créer les constantes Solana officielles,
|
||||
- préparer les modules `ws_client` et `http_client`,
|
||||
- remettre `kb_app/src/lib.rs` en conformité,
|
||||
- documenter `kb_app/src/splash.rs`,
|
||||
- garder une UI minimale avec bouton connect / disconnect et zone de sortie.
|
||||
|
||||
Livrables :
|
||||
|
||||
- squelette propre,
|
||||
- config JSON minimale,
|
||||
- tracing centralisé,
|
||||
- UI Tauri minimale opérationnelle,
|
||||
- premiers types partagés.
|
||||
|
||||
## 6.2. Version `0.1.x` — Transport WebSocket générique
|
||||
- correction de `kb_lib/src/lib.rs`,
|
||||
- création de `KbError`,
|
||||
- création de `KbConfig`,
|
||||
- création de `init_tracing`,
|
||||
- création des constantes Solana officielles,
|
||||
- préparation des modules `ws_client` et `http_client`,
|
||||
- remise de `kb_app/src/lib.rs` en conformité,
|
||||
- documentation de `kb_app/src/splash.rs`,
|
||||
- UI Tauri minimale.
|
||||
|
||||
### 6.002. Version `0.1.x` — Transport WebSocket générique
|
||||
Objectif : construire un vrai `WsClient` asynchrone clonable.
|
||||
|
||||
À faire :
|
||||
Réalisé :
|
||||
|
||||
- `connect`, `disconnect`, `is_connected`,
|
||||
- `connect`, `disconnect`, `connection_state`,
|
||||
- flux de lecture séparé du flux d’écriture,
|
||||
- identifiant incrémental interne par client,
|
||||
- canal sortant borné,
|
||||
- émission d’événements internes,
|
||||
- support de l’arrêt propre,
|
||||
- fermeture avec timeout.
|
||||
|
||||
Contraintes :
|
||||
|
||||
- aucune reconnexion implicite au départ,
|
||||
- pas d’usage de `solana-pubsub-client`,
|
||||
- fermeture avec timeout,
|
||||
- tests offline avec serveur mock.
|
||||
|
||||
## 6.3. Version `0.2.x` — Couche JSON-RPC WS Solana
|
||||
### 6.003. Version `0.1.1` — Intégration Tauri minimale du `WsClient`
|
||||
Objectif : valider le transport via l’application desktop.
|
||||
|
||||
Réalisé :
|
||||
|
||||
- intégration minimale de `WsClient` dans `kb_app`,
|
||||
- boutons start/stop,
|
||||
- zone de logs,
|
||||
- validation du flux `frontend -> tauri -> kb_lib -> frontend`.
|
||||
|
||||
### 6.004. Version `0.2.0` — Couche JSON-RPC WS Solana
|
||||
Objectif : séparer clairement transport, réponses RPC et notifications.
|
||||
|
||||
À faire :
|
||||
Réalisé :
|
||||
|
||||
- enveloppes JSON-RPC 2.0,
|
||||
- gestion des `request_id`,
|
||||
- registre des requêtes en attente,
|
||||
- distinction entre requêtes standard et subscribe/unsubscribe,
|
||||
- parsing des réponses,
|
||||
- séparation stricte des notifications.
|
||||
|
||||
Livrables :
|
||||
|
||||
- registre `request_id -> pending kind`,
|
||||
- registre `subscription_id -> metadata`,
|
||||
- tests de corrélation et de séparation des flux.
|
||||
|
||||
## 6.4. Version `0.3.x` — Registre subscriptions / notifications
|
||||
- parsing des réponses et erreurs,
|
||||
- parsing des notifications,
|
||||
- premiers helpers JSON-RPC sur `WsClient`.
|
||||
|
||||
### 6.005. Version `0.3.0` — Registre subscriptions / notifications
|
||||
Objectif : fiabiliser la gestion des subscriptions.
|
||||
|
||||
À faire :
|
||||
Réalisé :
|
||||
|
||||
- stockage des subscriptions actives,
|
||||
- mapping entre requête de subscribe et `subscription_id` serveur,
|
||||
- unsubscribe propre avant fermeture,
|
||||
- timeout d’attente sur unsubscribe,
|
||||
- purge locale même si le serveur ne répond pas,
|
||||
- purge locale si nécessaire,
|
||||
- routage séparé des notifications.
|
||||
|
||||
## 6.5. Version `0.4.x` — Transport HTTP générique
|
||||
### 6.006. Version `0.3.1` — Helpers subscribe/unsubscribe WebSocket
|
||||
Objectif : ajouter les helpers haut niveau correspondant aux principales méthodes PubSub Solana.
|
||||
|
||||
Objectif : construire un `HttpClient` clonable et limité.
|
||||
Réalisé :
|
||||
|
||||
À faire :
|
||||
- helpers pour `account`, `block`, `logs`, `program`, `root`, `signature`, `slot`, `slotsUpdates`, `vote`,
|
||||
- helpers d’unsubscribe correspondants,
|
||||
- premiers tests de validation des noms de méthodes.
|
||||
|
||||
- client `reqwest` asynchrone,
|
||||
- limites req/sec,
|
||||
### 6.007. Version `0.3.2` — Helpers typed et notifications typed
|
||||
Objectif : s’appuyer principalement sur `solana-rpc-client-api` pour typer les subscribe et les notifications.
|
||||
|
||||
Réalisé :
|
||||
|
||||
- helpers typed pour `account`, `block`, `logs`, `program`, `signature`,
|
||||
- parsing typed des notifications,
|
||||
- base de travail pour réduire l’usage direct de `serde_json::Value`.
|
||||
|
||||
### 6.008. Version `0.3.3` — Distinction API typed / raw
|
||||
Objectif : clarifier l’API publique de `WsClient`.
|
||||
|
||||
Réalisé :
|
||||
|
||||
- suffixe `_raw` sur les helpers raw,
|
||||
- conservation des helpers typed comme interface plus propre,
|
||||
- préparation d’une hiérarchie API plus explicite.
|
||||
|
||||
### 6.009. Version `0.3.4` — Fenêtre `Demo Ws` dans `kb_app`
|
||||
Objectif : tester manuellement les souscriptions live dans une fenêtre dédiée.
|
||||
|
||||
Réalisé :
|
||||
|
||||
- fenêtre séparée `demo_ws`,
|
||||
- ouverture depuis la fenêtre principale,
|
||||
- connexion/déconnexion d’un client de démo,
|
||||
- test de souscriptions live,
|
||||
- affichage des événements raw et typed,
|
||||
- premiers tests réels sur `wss://api.mainnet.solana.com`.
|
||||
|
||||
### 6.010. Version `0.3.5` — Stabilisation de `Demo Ws`
|
||||
Objectif : rendre la fenêtre de démonstration robuste sous flux élevé et cohérente avec la configuration.
|
||||
|
||||
Réalisé :
|
||||
|
||||
- lire correctement les endpoints activés depuis la config et refléter les URLs résolues avec `api_key_env_var`,
|
||||
- améliorer la sélection réelle des endpoints affichés et utilisables,
|
||||
- ajouter du throttling / rate limiting de l’affichage UI sous fort débit,
|
||||
- limiter ou résumer les événements affichés côté fenêtre,
|
||||
- conserver l’intégralité des traces côté `tracing`,
|
||||
- éviter le gel de la fenêtre sur `logsSubscribe` et `programSubscribe`,
|
||||
- conserver des compteurs et états UI exploitables,
|
||||
- mieux gérer les fermetures/ralentissements d’endpoints publics.
|
||||
|
||||
### 6.011. Version `0.4.x` — Transport HTTP générique et helpers RPC
|
||||
|
||||
Objectif : construire un `HttpClient` clonable, limité et extensible, puis ajouter les premiers helpers HTTP Solana.
|
||||
|
||||
### 6.012. Version `0.4.0` — Socle `HttpClient`
|
||||
Réalisé :
|
||||
|
||||
- client `reqwest` asynchrone clonable,
|
||||
- résolution d’URL avec support de `api_key_env_var`,
|
||||
- limiteur local req/sec,
|
||||
- burst configurable,
|
||||
- délais configurables,
|
||||
- profils par endpoint,
|
||||
- endpoints publics ou API-key.
|
||||
- abstraction JSON-RPC HTTP générique,
|
||||
- premiers appels de validation Solana.
|
||||
|
||||
Livrables :
|
||||
|
||||
- `HttpClient`,
|
||||
- abstraction de requêtes JSON-RPC HTTP,
|
||||
- premiers appels sur endpoints Solana.
|
||||
- enveloppes JSON-RPC HTTP,
|
||||
- premiers appels :
|
||||
- `getHealth`
|
||||
- `getVersion`
|
||||
- `getSlot`
|
||||
|
||||
## 6.6. Version `0.5.x` — Base de données SQLite
|
||||
### 6.013. Version `0.4.1` — Helpers HTTP Solana
|
||||
Réalisé :
|
||||
|
||||
Objectif : poser la persistance locale.
|
||||
- ajouter des helpers HTTP haut niveau comme pour le client WS,
|
||||
- distinguer helpers raw et helpers typed quand cela est pertinent,
|
||||
- couvrir les premières méthodes utiles du RPC HTTP Solana,
|
||||
- conserver `HttpClient` comme couche générique réutilisable.
|
||||
|
||||
À faire :
|
||||
### 6.014. Version `0.4.2` — Politique HTTP avancée
|
||||
Réalisé :
|
||||
|
||||
- préparer un état de pause avant envoi pour un endpoint HTTP,
|
||||
- préparer plusieurs quotas par famille de méthodes,
|
||||
- distinguer quota RPC général et quota `sendTransaction`,
|
||||
- préparer un futur pool d’endpoints HTTP et l’arbitrage entre eux.
|
||||
|
||||
### 6.015. Version `0.4.3` — Pool d’endpoints HTTP
|
||||
Réalisé :
|
||||
|
||||
- ajouter un pool d’`HttpClient`,
|
||||
- sélectionner un endpoint selon le rôle demandé,
|
||||
- ignorer les endpoints `Paused` ou `Disabled`,
|
||||
- préparer une rotation simple entre endpoints actifs,
|
||||
- prendre en compte la classe de méthode HTTP,
|
||||
- préparer le routage multi-RPC et la limitation de concurrence par endpoint.
|
||||
|
||||
### 6.016. Version `0.4.4` — Démo HTTP dans `kb_app`
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une fenêtre `Demo Http`,
|
||||
- ouverture depuis la fenêtre principale,
|
||||
- exécution manuelle de méthodes HTTP via le pool d’endpoints,
|
||||
- affichage des réponses JSON-RPC HTTP et des erreurs associées,
|
||||
- affichage de l’état du pool HTTP et des statuts des endpoints,
|
||||
- alignement visuel de la fenêtre sur le gabarit `Demo Ws`,
|
||||
- amélioration des presets UI, copie de réponse et bascule pretty/raw.
|
||||
|
||||
### 6.017. Version `0.5.x` — Base de données SQLite
|
||||
Objectif : poser la persistance locale avec une organisation préparée dès le départ à une future évolution vers PostgreSQL ou un autre backend.
|
||||
|
||||
### 6.018. Version `0.5.0` — Socle SQLite
|
||||
Réalisé :
|
||||
|
||||
- configuration DB dans `config.json`,
|
||||
- ouverture/validation SQLite,
|
||||
- premières tables techniques,
|
||||
- stockage des endpoints, événements, tokens observés, subscriptions actives si utile.
|
||||
- façade `KbDatabase`,
|
||||
- premier schéma technique,
|
||||
- table `kb_db_metadata`,
|
||||
- séparation `db/entities`, `db/dtos`, `db/queries`, `db/types`.
|
||||
|
||||
## 6.7. Version `0.6.x` — Détection technique on-chain / RPC
|
||||
### 6.019. Version `0.5.1` — Premières tables métier de stockage local
|
||||
Réalisé :
|
||||
|
||||
Objectif : commencer la détection utile pour l’application.
|
||||
- ajout des tables de référence pour les endpoints connus HTTP/WS,
|
||||
- ajout des tables techniques pour les événements runtime locaux,
|
||||
- mise en place des `entities`, `dtos`, `queries` et `types` associés,
|
||||
- préparation du stockage local des endpoints HTTP/WS connus et de leur état utile.
|
||||
|
||||
### 6.020. Version `0.5.2` — Stockage des tokens observés
|
||||
Réalisé :
|
||||
|
||||
- ajout de la table `kb_observed_tokens`,
|
||||
- stockage minimal des mints, symboles, noms, statuts et dates d’observation,
|
||||
- ajout du `token_program`,
|
||||
- préparation des relations futures avec pools, paires et événements on-chain,
|
||||
- conservation d’unicité locale par mint sans duplication par endpoint.
|
||||
|
||||
### 6.021. Version `0.5.3` — Événements et signaux locaux
|
||||
Réalisé :
|
||||
|
||||
- conservation des événements runtime techniques via `kb_db_runtime_events`,
|
||||
- ajout des observations on-chain brutes via `kb_onchain_observations`,
|
||||
- ajout des signaux d’analyse via `kb_analysis_signals`,
|
||||
- distinction explicite entre événements runtime, observations on-chain et événements métier,
|
||||
- préparation de la traçabilité de provenance par type de source et endpoint, sans remettre en cause l’unicité locale d’un token par mint.
|
||||
|
||||
### 6.022. Version `0.5.4` — Modèle métier normalisé initial
|
||||
Réalisé :
|
||||
|
||||
- ajouter les tables de référence métier pour les DEX, tokens, pools et paires,
|
||||
- distinguer clairement objets de référence et événements d’activité,
|
||||
- préparer les relations entre tokens, pools, paires et listings,
|
||||
- éviter que la détection technique `0.6.x` écrive directement dans des tables trop brutes ou ambiguës.
|
||||
|
||||
### 6.023. Version `0.5.5` — Activité métier normalisée
|
||||
Réalisé :
|
||||
|
||||
- ajout des tables de swaps,
|
||||
- ajout des événements de liquidité,
|
||||
- ajout des événements de mint et burn utiles au suivi des tokens,
|
||||
- préparation de l’historique métier nécessaire avant l’arrivée des connecteurs DEX complets.
|
||||
|
||||
### 6.024. Version `0.5.6` — Consolidation de la couche stockage
|
||||
Objectif : stabiliser le schéma avant la détection technique réelle.
|
||||
|
||||
À faire :
|
||||
|
||||
- réception de notifications ciblées,
|
||||
- détection de créations de comptes/programmes d’intérêt,
|
||||
- débuts de normalisation d’événements,
|
||||
- premiers connecteurs DEX.
|
||||
- conserver l’abstraction du backend dès le départ,
|
||||
- limiter la dépendance directe au SQL concret aux modules `queries`,
|
||||
- garder les conversions explicites entre entités DB et DTOs applicatifs,
|
||||
- durcir les relations, contraintes et index utiles,
|
||||
- préparer une future compatibilité PostgreSQL sans casser l’organisation générale.
|
||||
|
||||
## 6.8. Version `0.7.x` — DEX connectors v1
|
||||
### 6.025. Version `0.6.0` — Pipeline de détection technique
|
||||
Objectif : relier les connecteurs RPC à la couche de stockage technique et métier.
|
||||
|
||||
Objectif : structurer les connecteurs par protocole.
|
||||
À faire :
|
||||
|
||||
Cibles initiales possibles :
|
||||
- ajouter une façade de persistance pour les observations et signaux issus des connecteurs,
|
||||
- préparer l’enregistrement des candidats tokens détectés depuis les sources RPC,
|
||||
- éviter que les futurs watchers RPC écrivent directement dans la DB sans couche intermédiaire,
|
||||
- préparer les prochaines étapes de détection technique on-chain / RPC.
|
||||
|
||||
### 6.026. Version `0.6.1` — Détection technique RPC
|
||||
Réalisé :
|
||||
|
||||
- ajout d’un bridge `Solana WS notification -> pipeline de détection`,
|
||||
- persistance des notifications WS utiles comme observations on-chain normalisées,
|
||||
- génération d’un candidat token quand une `programNotification` expose un mint SPL / Token-2022 en JSON parsé,
|
||||
- préparation du branchement futur des watchers et règles RPC réelles sur une façade de détection unique.
|
||||
|
||||
### 6.027. Version `0.6.2` — Branchement `WsClient` vers la détection
|
||||
Réalisé :
|
||||
|
||||
- ajouter un relais interne de notifications WS vers la couche de détection,
|
||||
- permettre à `WsClient` de forwarder les `JsonRpcWsNotification` vers un worker dédié,
|
||||
- conserver le découplage entre transport WS et logique de détection,
|
||||
- éviter de bloquer la boucle de lecture WS si la détection est lente.
|
||||
|
||||
### 6.028. Version `0.6.3` — Enrichissement des notifications WS utiles
|
||||
Réalisé :
|
||||
|
||||
- enrichir `accountNotification`, `logsNotification` et `signatureNotification`,
|
||||
- mieux extraire slot, pubkey, signature, owner, parsed account type et clés pertinentes,
|
||||
- produire des observations plus précises et plus homogènes,
|
||||
- préparer les règles de détection techniques réelles.
|
||||
|
||||
### 6.029. Version `0.6.4` — Premières règles de détection technique
|
||||
Réalisé :
|
||||
|
||||
- détection des premiers candidats pools/listings techniques depuis `programNotification`,
|
||||
- appui sur les DEX connus en base via `program_id` / `router_program_id`,
|
||||
- enregistrement des pools candidats et de leur listing initial sans parsing DEX complet,
|
||||
- alimentation conjointe des observations techniques, signaux d’analyse et tables métier normalisées,
|
||||
- maintien d’une logique encore indépendante des connecteurs DEX `0.7.x`.
|
||||
|
||||
### 6.030. Version `0.6.5` — Orchestration multi-clients WebSocket
|
||||
Réalisé :
|
||||
|
||||
- introduction d’une abstraction `ws_manager.rs` pour piloter plusieurs `WsClient`,
|
||||
- construction des clients WS activés depuis la configuration d’endpoints,
|
||||
- démarrage et arrêt centralisés par endpoint ou globalement,
|
||||
- republication d’un flux unifié de `WsEvent` pour l’ensemble des clients gérés,
|
||||
- branchement optionnel du relais de détection WS sur tous les clients orchestrés,
|
||||
- préparation des futures politiques de répartition, supervision et reconnexion.
|
||||
|
||||
### 6.031. Version `0.6.6` — Démo légère `WsManager` dans `kb_app`
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une fenêtre `Demo Ws Manager` dans `kb_app`,
|
||||
- ouverture depuis la fenêtre principale,
|
||||
- affichage du snapshot consolidé du `WsManager`,
|
||||
- pilotage des endpoints WS gérés via `start/stop all` et `start/stop role`,
|
||||
- visualisation du flux unifié de `WsEvent`,
|
||||
- validation UI du branchement centralisé du relais de détection,
|
||||
- amélioration des messages de log UI pour les actions idempotentes déjà démarrées ou déjà arrêtées.
|
||||
|
||||
### 6.032. Version `0.7.0` — Résolution transactionnelle orientée DEX
|
||||
Réalisé :
|
||||
|
||||
- introduction d’une file de résolution transactionnelle alimentée par les signatures issues des flux WS utiles,
|
||||
- corrélation initiale des `logsNotification` et `signatureNotification` avec des appels `getTransaction`,
|
||||
- utilisation du pool HTTP existant pour enrichir les signaux détectés côté WS,
|
||||
- persistance des résolutions transactionnelles dans `kb_onchain_observations` et `kb_analysis_signals`,
|
||||
- préparation du futur modèle transactionnel enrichi sans bloquer les flux temps réel.
|
||||
|
||||
### 6.033. Version `0.7.1` — Modèle transactionnel Solana enrichi
|
||||
Réalisé :
|
||||
|
||||
- ajout des tables techniques `kb_chain_slots`, `kb_chain_transactions` et `kb_chain_instructions`,
|
||||
- distinction claire entre slot, transaction résolue et instructions normalisées,
|
||||
- support des instructions principales et inner instructions,
|
||||
- ajout des entités, DTOs et requêtes associées,
|
||||
- ajout d’un service de projection pour transformer une transaction JSON-RPC résolue en modèle transactionnel interne,
|
||||
- ajout des tests de roundtrip et de projection.
|
||||
|
||||
### 6.034. Version `0.7.2` — Décodeurs DEX spécifiques par programme et version
|
||||
Réalisé :
|
||||
|
||||
- ajout d’un premier décodeur transactionnel spécifique Raydium AmmV4 / initialize2,
|
||||
- lecture combinée du `transaction_json` et des instructions projetées,
|
||||
- extraction des comptes utiles à l’initialisation du pool,
|
||||
- persistance des événements DEX décodés dans une table dédiée,
|
||||
- émission d’observations et de signaux dérivés du décodage DEX,
|
||||
- branchement automatique du décodage DEX depuis le pipeline de résolution transactionnelle,
|
||||
- préparation de la future détection métier pool / pair / listing.
|
||||
|
||||
### 6.035. Version `0.7.3` — Détection des nouveaux pools et paires via logs + transaction
|
||||
Réalisé :
|
||||
|
||||
- transformation des événements DEX décodés en objets métier pool / pair / listing,
|
||||
- alimentation de `kb_pools`, `kb_pairs`, `kb_pool_tokens` et `kb_pool_listings`,
|
||||
- première détection métier pour Raydium AmmV4 / initialize2,
|
||||
- branchement automatique de la détection métier après résolution, projection et décodage DEX,
|
||||
- émission de signaux dédiés pour `new_pool`, `new_pair` et `first_listing_seen`,
|
||||
- garantie d’idempotence sur une même transaction déjà traitée.
|
||||
|
||||
### 6.036. Version `0.7.4` — Connecteurs DEX v1, vague 1
|
||||
Réalisé :
|
||||
|
||||
- ajout du décodeur `Pump.fun` pour les créations `create_v2`,
|
||||
- ajout du décodeur `PumpSwap` pour les trades `buy / sell`,
|
||||
- intégration des nouveaux décodeurs dans le pipeline générique `dex_decode`,
|
||||
- ajout de la détection métier `Pump.fun` vers `token / pool / pair / listing`,
|
||||
- maintien de `PumpSwap` au niveau décodage en attendant un mapping transactionnel plus riche,
|
||||
- préparation de l’extension vers `Meteora`, `Meteora DBC` et `LaunchLab`.
|
||||
|
||||
### 6.037. Version `0.7.5` — Connecteurs DEX v1, vague 2
|
||||
Réalisé :
|
||||
|
||||
- enrichissement du décodeur `PumpSwap` avec extraction des mints et du `pool_v2`,
|
||||
- persistance des événements `PumpSwap` enrichis dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `PumpSwap` vers `pool / pair / listing`,
|
||||
- émission des signaux dédiés `new_pool`, `new_pair` et `first_listing_seen`,
|
||||
- garantie d’idempotence sur une même transaction déjà traitée,
|
||||
- préparation du lot suivant pour `Meteora`, `Meteora DBC` et `LaunchLab`.
|
||||
|
||||
### 6.038. Version `0.7.6` — Connecteurs DEX v1, vague 3
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `Meteora DBC`,
|
||||
- prise en charge initiale des événements `create_pool` et `swap`,
|
||||
- persistance des événements `Meteora DBC` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `Meteora DBC` vers `pool / pair / listing`,
|
||||
- émission des signaux dédiés `new_pool`, `new_pair` et `first_listing_seen`,
|
||||
- préparation du lot suivant pour `Meteora DAMM v2`, `Meteora DAMM v1` et `LaunchLab / Fun Launch`.
|
||||
|
||||
### 6.039. Version `0.7.7` — Meteora DAMM v2
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `Meteora DAMM v2`,
|
||||
- prise en charge initiale des événements de création de pool via `initialize_pool`, `initialize_pool_with_dynamic_config` et `initialize_customizable_pool`,
|
||||
- prise en charge initiale des swaps via `swap` et `swap2`,
|
||||
- persistance des événements `Meteora DAMM v2` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `Meteora DAMM v2` vers `pool / pair / listing`,
|
||||
- préparation du rattachement futur entre `Meteora DBC` et `Meteora DAMM v2`.
|
||||
|
||||
### 6.040. Version `0.7.8` — Meteora DAMM v1
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `Meteora DAMM v1`,
|
||||
- prise en charge initiale des événements de création de pool via `initialize_pool` et `initialize_pool_with_config`,
|
||||
- prise en charge initiale des swaps via `swap`,
|
||||
- persistance des événements `Meteora DAMM v1` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `Meteora DAMM v1` vers `pool / pair / listing`,
|
||||
- préparation du rattachement futur entre `Meteora DBC` et `Meteora DAMM v1`.
|
||||
|
||||
### 6.041. Version `0.7.9` — Launch origins / Fun Launch
|
||||
Réalisé :
|
||||
|
||||
- ajout d’un registre des surfaces de lancement,
|
||||
- ajout d’un registre de clés observables par surface de lancement,
|
||||
- ajout d’une attribution entre événements/pools détectés et surfaces connues,
|
||||
- premier support de `Meteora Fun Launch` comme surface d’origine au-dessus de `Meteora DBC`,
|
||||
- branchement automatique de l’attribution depuis le pipeline de résolution transactionnelle,
|
||||
- conservation d’une séparation stricte entre protocole on-chain et origine de lancement.
|
||||
|
||||
### 6.042. Version `0.7.10` — Orca / Whirlpools
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `Orca Whirlpools`,
|
||||
- prise en charge initiale des événements de création de pool via `initialize_pool` et `initialize_pool_v2`,
|
||||
- prise en charge initiale des swaps via `swap` et `swap_v2`,
|
||||
- persistance des événements `Orca Whirlpools` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `Orca Whirlpools` vers `pool / pair / listing`,
|
||||
- utilisation de `KbPoolKind::Clmm` pour refléter la nature concentrée de `Whirlpools`.
|
||||
|
||||
### 6.043. Version `0.7.11` — FluxBeam
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `FluxBeam`,
|
||||
- prise en charge initiale des événements de création de pool via un premier décodage `create_pool / initialize_pool`,
|
||||
- prise en charge initiale des swaps via `swap`,
|
||||
- persistance des événements `FluxBeam` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `FluxBeam` vers `pool / pair / listing`,
|
||||
- conservation d’un premier décodage heuristique à raffiner ultérieurement avec des transactions FluxBeam réelles.
|
||||
|
||||
### 6.044. Version `0.7.12` — DexLab
|
||||
Réalisé :
|
||||
|
||||
- ajout du premier décodeur `DexLab Swap/Pool`,
|
||||
- prise en charge initiale des événements de création de pool via un premier décodage `create_pool / initialize_pool`,
|
||||
- prise en charge initiale des swaps via `swap`,
|
||||
- persistance des événements `DexLab` dans `kb_dex_decoded_events`,
|
||||
- ajout de la détection métier `DexLab` vers `pool / pair / listing`,
|
||||
- conservation d’une séparation entre pool DexLab natif et éventuel `OpenBook Market ID` créé ensuite.
|
||||
|
||||
### 6.045. Version `0.7.13` — Bags / Moonit comme origines de lancement
|
||||
Réalisé :
|
||||
|
||||
- extension de la couche `launch origins` à `Bags` et `Moonit`,
|
||||
- ajout d’un enregistrement programmatique des mappings `Bags` à partir des champs `tokenMint`, `dbcConfigKey`, `dbcPoolKey` et `dammV2PoolKey`,
|
||||
- prise en charge de l’attribution `Bags` par matching exact sur `config_account`, `pool_account` et `token_mint`,
|
||||
- prise en charge de l’attribution `Moonit` par détection automatique des token mints se terminant par `moon`,
|
||||
- conservation d’une séparation stricte entre origine de lancement et protocole on-chain.
|
||||
|
||||
### 6.046. Version `0.7.14` — Consolidation multi-DEX
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une couche commune `pool origins` pour enregistrer la première signature vue par le modèle pour chaque pool détecté,
|
||||
- rattachement d’un pool à son `decoded_event`, à son `pair`, à son `pool_listing` et à son éventuelle `launch_attribution`,
|
||||
- amélioration de la traçabilité inter-protocoles sans modifier les connecteurs DEX déjà validés,
|
||||
- conservation d’une logique idempotente avec mise à jour douce des liens `pair / listing / launch attribution`,
|
||||
- préparation de la future couche analytique sur une base multi-DEX plus cohérente.
|
||||
|
||||
### 6.047. Version `0.7.15` — Wallets, holdings et participants observés
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une première couche `wallets` pour les adresses observées dans le pipeline,
|
||||
- ajout d’une première couche `wallet participations` pour rattacher une adresse à une transaction, un decoded event, un pool et un pair,
|
||||
- extraction des rôles observés depuis les payloads décodés (`creator`, `payer`, `owner`, `user`),
|
||||
- branchement automatique depuis le pipeline de résolution transactionnelle,
|
||||
- report des holdings à l’étape suivante afin de conserver une séparation nette entre acteurs observés et balances observées.
|
||||
|
||||
### 6.048. Version `0.7.16` — Séries de prix, volumes et agrégats DEX
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une première table `trade events` pour normaliser les swaps observés,
|
||||
- ajout d’une première table `pair metrics` pour agréger les swaps par paire,
|
||||
- prise en charge des compteurs `trade_count`, `buy_count`, `sell_count`,
|
||||
- prise en charge optionnelle des volumes bruts `base` / `quote` et du dernier prix dérivé `quote_per_base`,
|
||||
- branchement automatique dans le pipeline de résolution transactionnelle,
|
||||
- conservation d’un modèle simple et idempotent en préparation de futures candles / séries temporelles.
|
||||
|
||||
### 6.049. Version `0.7.17` — Renforcement temps réel WS hybride
|
||||
Réalisé :
|
||||
|
||||
- conservation de `logsSubscribe` comme source canonique de signatures candidates,
|
||||
- ajout d’une collecte de cibles `programSubscribe` à partir des DEX actifs connus,
|
||||
- ajout d’une collecte de cibles `accountSubscribe` à partir des pools actifs connus,
|
||||
- ajout d’une couche d’observations techniques WS hybrides pour `logs / program / account`,
|
||||
- ajout d’une première déduplication en mémoire des notifications techniques reçues en parallèle,
|
||||
- ajout d’une façade runtime pour exposer ce comportement au futur branchement `ws_manager`.
|
||||
|
||||
### 6.050. Version `0.7.18` — Backfill historique ciblé par token
|
||||
Réalisé :
|
||||
|
||||
- ajout d’un premier service de backfill ciblé par `token_mint`,
|
||||
- récupération des signatures historiques via `getSignaturesForAddress`,
|
||||
- résolution des transactions pertinentes via `getTransaction`,
|
||||
- relecture du pipeline interne pour reconstruire transactions, décodage DEX, détection métier, origins, wallets et trade metrics,
|
||||
- ajout d’une seconde passe sur les pools découverts pour le token afin de récupérer des signatures supplémentaires liées à l’activité du pool,
|
||||
- conservation d’un périmètre ciblé sur des tokens encore actifs au lieu d’un scan exhaustif de la blockchain.
|
||||
|
||||
### 6.051. Version `0.7.19` — Holdings observés
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une première table `wallet holdings` pour agréger les couples `wallet/token` observés,
|
||||
- rattachement des holdings observés à la dernière transaction, au dernier decoded event, au dernier pool et au dernier pair connus,
|
||||
- conservation d’un champ `balance_raw` optionnel sans prétendre encore reconstruire un portefeuille complet,
|
||||
- alimentation automatique à partir des événements DEX déjà décodés et des wallets déjà observés,
|
||||
- branchement automatique dans le pipeline de résolution transactionnelle.
|
||||
|
||||
### 6.052. Version `0.7.20` — Candles / OHLCV
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une première table `pair candles` pour matérialiser les agrégats OHLCV par paire,
|
||||
- stockage en base des timeframes usuels (`1m`, `5m`, `15m`, `1h`),
|
||||
- conservation de `trade events` comme source brute de vérité,
|
||||
- ajout d’un service de régénération à la demande pour un timeframe arbitraire,
|
||||
- possibilité de choisir dynamiquement le timeframe lors d’une requête analytique,
|
||||
- branchement automatique dans le pipeline de résolution transactionnelle pour maintenir les candles matérialisées à jour.
|
||||
|
||||
### 6.053. Version `0.7.21` — Signaux analytiques plus riches
|
||||
Réalisé :
|
||||
|
||||
- ajout d’une première table `pair analytic signals` dédiée aux signaux dérivés par paire,
|
||||
- prise en charge initiale des signaux `first_trade_seen`, `trade_burst_60s`, `buy_sell_imbalance_60s`, `price_jump_up_60s`, `price_jump_down_60s` et `volume_spike_60s`,
|
||||
- calcul des signaux à partir des `pair metrics`, `pair candles` et `trade events`,
|
||||
- persistance idempotente des signaux par paire et par bucket,
|
||||
- branchement automatique dans le pipeline de résolution transactionnelle.
|
||||
|
||||
### 6.054. Version `0.7.22` — `kb_app` : inspection et tests du pipeline `0.7.x`
|
||||
Objectif : permettre depuis l’application desktop de tester, inspecter et valider tout le pipeline `0.7.x` sans recourir uniquement aux logs bruts ou à SQLite.
|
||||
|
||||
À faire :
|
||||
|
||||
- ajouter une ou plusieurs vues `kb_app` dédiées à l’inspection des transactions résolues, événements DEX décodés, pools, paires, launch origins, pool origins, wallets observés, holdings observés et trade events,
|
||||
- permettre la recherche par signature, pool, paire, token mint ou wallet,
|
||||
- afficher les liens entre objets techniques et objets métier,
|
||||
- permettre de lancer manuellement certains backfills ou inspections ciblées,
|
||||
- fournir un socle UI pour tester en pratique tout ce qui a été construit dans la série `0.7.x`.
|
||||
|
||||
### 6.055. Version `0.7.x` — Couverture DEX v1
|
||||
Objectif : structurer les connecteurs DEX autour d’un pipeline complet de résolution, décodage et normalisation métier.
|
||||
|
||||
Protocoles cibles :
|
||||
|
||||
- Meteora DBC
|
||||
- Meteora DAMM v2
|
||||
- Meteora DAMM v1
|
||||
- LaunchLab / Fun Launch
|
||||
- Pump.fun
|
||||
- PumpSwap
|
||||
- Raydium
|
||||
- Meteora
|
||||
- Orca
|
||||
- Bags
|
||||
- FluxBeam
|
||||
- DexLab
|
||||
- Moonit
|
||||
|
||||
À faire :
|
||||
Résultat attendu :
|
||||
|
||||
- identification des programmes,
|
||||
- décodage des événements utiles,
|
||||
- création de types métiers propres,
|
||||
- enrichissement des métadonnées token/pool/pair.
|
||||
|
||||
## 6.9. Version `0.8.x` — Analyse et filtrage
|
||||
- identification fiable des programmes et versions,
|
||||
- résolution des signatures pertinentes,
|
||||
- décodage des transactions utiles,
|
||||
- création d’objets métier riches pour tokens, pools, paires, listings, participants et holdings observés,
|
||||
- préparation d’une détection temps réel hybride et d’un backfill ciblé compatible avec les mêmes objets métier,
|
||||
- préparation d’agrégats DEX plus riches, de candles / OHLCV et d’une UI d’inspection du pipeline `0.7.x`.
|
||||
|
||||
### 6.056. Version `0.8.x` — Analyse et filtrage
|
||||
Objectif : transformer les événements bruts en signaux exploitables.
|
||||
|
||||
À faire :
|
||||
@@ -286,10 +709,10 @@ Objectif : transformer les événements bruts en signaux exploitables.
|
||||
- règles de filtrage,
|
||||
- exclusions des tokens non tradables,
|
||||
- statistiques de comportement,
|
||||
- premiers patterns.
|
||||
|
||||
## 6.10. Version `1.x.y` — Wallets et swap préparatoire
|
||||
- premiers patterns,
|
||||
- enrichissement des signaux analytiques préparés en fin de `0.7.x`.
|
||||
|
||||
### 6.057. Version `1.x.y` — Wallets et swap préparatoire
|
||||
Objectif : préparer la couche d’action.
|
||||
|
||||
À faire :
|
||||
@@ -300,8 +723,7 @@ Objectif : préparer la couche d’action.
|
||||
- préparation d’ordres et de swaps,
|
||||
- simulation et garde-fous.
|
||||
|
||||
## 6.11. Version `2.x.y` — Trading semi-automatisé
|
||||
|
||||
### 6.058. Version `2.x.y` — Trading semi-automatisé
|
||||
Objectif : brancher l’analyse à l’action tout en gardant des garde-fous explicites.
|
||||
|
||||
À faire :
|
||||
@@ -312,8 +734,7 @@ Objectif : brancher l’analyse à l’action tout en gardant des garde-fous exp
|
||||
- confirmations explicites ou semi-automatiques,
|
||||
- journaux d’exécution.
|
||||
|
||||
## 6.12. Version `3.x.y` — Yellowstone gRPC
|
||||
|
||||
### 6.059. Version `3.x.y` — Yellowstone gRPC
|
||||
Objectif : ajouter le connecteur gRPC dédié.
|
||||
|
||||
À faire :
|
||||
@@ -325,8 +746,7 @@ Objectif : ajouter le connecteur gRPC dédié.
|
||||
|
||||
## 7. Organisation des modules ciblés
|
||||
|
||||
## 7.1. `kb_lib`
|
||||
|
||||
### 7.1. `kb_lib`
|
||||
Modules cibles à court terme :
|
||||
|
||||
- `error.rs`
|
||||
@@ -335,22 +755,24 @@ Modules cibles à court terme :
|
||||
- `constants.rs`
|
||||
- `types.rs`
|
||||
- `ws_client.rs`
|
||||
- `ws_manager.rs`
|
||||
- `http_client.rs`
|
||||
- `rpc_json.rs`
|
||||
- `rpc_ws.rs`
|
||||
|
||||
## 7.2. `kb_app`
|
||||
- `http_pool.rs`
|
||||
- `json_rpc_ws.rs`
|
||||
- `solana_pubsub_ws.rs`
|
||||
- `detect.rs`
|
||||
|
||||
### 7.2. `kb_app`
|
||||
Responsabilités cibles :
|
||||
|
||||
- lancement Tauri,
|
||||
- commandes UI,
|
||||
- affichage des états et messages,
|
||||
- réception des événements venant de `kb_lib`,
|
||||
- persistance future des préférences UI.
|
||||
- persistance future des préférences UI,
|
||||
- fenêtres de démonstration / diagnostic isolées.
|
||||
|
||||
## 8. Ligne de conduite sur le `WsClient`
|
||||
|
||||
Le `WsClient` doit être conçu en plusieurs couches :
|
||||
|
||||
1. transport brut WebSocket,
|
||||
@@ -367,7 +789,6 @@ Cette séparation évite de mélanger :
|
||||
- les notifications push.
|
||||
|
||||
## 9. Politique initiale de reconnexion
|
||||
|
||||
Au départ :
|
||||
|
||||
- pas de reconnexion automatique,
|
||||
@@ -377,7 +798,6 @@ Au départ :
|
||||
Plus tard, ce comportement pourra devenir configurable dans `config.json` et pilotable depuis l’application.
|
||||
|
||||
## 10. Politique initiale de fermeture
|
||||
|
||||
À la fermeture d’un `WsClient` :
|
||||
|
||||
1. marquer le client en arrêt,
|
||||
@@ -389,24 +809,24 @@ Plus tard, ce comportement pourra devenir configurable dans `config.json` et pil
|
||||
7. journaliser clairement les cas dégradés.
|
||||
|
||||
## 11. Documentation et livrables de référence
|
||||
|
||||
Le projet doit maintenir au minimum :
|
||||
|
||||
- un `README.md` global,
|
||||
- un `Roadmap.md` global,
|
||||
- un `ROADMAP.md` global,
|
||||
- un `CHANGELOG.md` global,
|
||||
- des `README.md` et `TODO.md` par crate à mesure de l’évolution,
|
||||
- des tests unitaires robustes,
|
||||
- les bindings TS générés via `cargo test export_bindings` lorsque les types partagés évoluent.
|
||||
|
||||
## 12. Priorité immédiate
|
||||
|
||||
La priorité immédiate est la suivante :
|
||||
La priorité immédiate est désormais la suivante :
|
||||
|
||||
1. corriger le squelette,
|
||||
2. poser `KbError`,
|
||||
3. poser `KbConfig`,
|
||||
4. poser `init_tracing`,
|
||||
5. poser les constantes Solana,
|
||||
6. préparer `ws_client` et `http_client`,
|
||||
7. remettre `kb_app` en conformité,
|
||||
8. conserver une UI minimale, puis brancher progressivement les clients réseau.
|
||||
1. finaliser complètement la fin de série `0.7.x` avant l’ouverture de `0.8.x`,
|
||||
2. ajouter un renforcement temps réel hybride avec `logsSubscribe`, `programSubscribe` et `accountSubscribe` en parallèle des sources déjà exploitées,
|
||||
3. conserver la résolution transactionnelle comme source de normalisation commune,
|
||||
4. ajouter ensuite un mode de backfill historique ciblé par `token_mint` pour des tokens encore actifs donnés explicitement,
|
||||
5. compléter la couche métier avec des `holdings observés`,
|
||||
6. ajouter des `candles / OHLCV` et une première couche de signaux analytiques plus riches,
|
||||
7. doter `kb_app` d’une vraie UI d’inspection et de test pour l’ensemble du pipeline `0.7.x`,
|
||||
8. préparer enfin l’arrivée de Yellowstone gRPC comme extension de capacité, et non comme remplacement du socle existant.
|
||||
|
||||
@@ -24,9 +24,9 @@ kb_lib = { path = "../kb_lib" }
|
||||
rustls.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
solana-rpc-client-api.workspace = true
|
||||
tauri.workspace = true
|
||||
tauri-plugin-tracing.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
ts-rs.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main", "splash"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"tracing:default"
|
||||
]
|
||||
}
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": [
|
||||
"main",
|
||||
"splash",
|
||||
"demo_ws",
|
||||
"demo_http",
|
||||
"demo_ws_manager"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"tracing:default"
|
||||
]
|
||||
}
|
||||
166
kb_app/frontend/demo_http.html
Normal file
166
kb_app/frontend/demo_http.html
Normal file
@@ -0,0 +1,166 @@
|
||||
<!-- file: kb_app/frontend/demo_http.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Demo Http</title>
|
||||
<link rel="stylesheet" href="sass/main.scss" />
|
||||
</head>
|
||||
|
||||
<body class="bg-body-tertiary">
|
||||
<header class="app-header">
|
||||
<nav class="navbar navbar-expand-lg h-100 py-0 bg-light text-dark">
|
||||
<div class="container my-0">
|
||||
<a class="navbar-brand d-flex align-items-center" href="/">
|
||||
<img alt="Logo" src="imgs/logo.png" class="app-logo" />
|
||||
<span class="ps-2 fs-4 fw-bold text-primary font-logo">Khadhroony-BoBoBot</span>
|
||||
</a>
|
||||
<div class="ms-auto">
|
||||
<span id="demoHttpStatusBadge" class="badge text-bg-secondary">Ready</span>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="app-main">
|
||||
<div class="osb-scrollable pt-1 pb-4" data-simplebar>
|
||||
<div class="container py-4">
|
||||
<div class="row g-4">
|
||||
<div class="col-12">
|
||||
<div class="card shadow-sm border-0">
|
||||
<div class="card-body">
|
||||
<h1 class="h4 mb-3">Demo Http</h1>
|
||||
<p class="text-body-secondary mb-0">
|
||||
Fenêtre de test manuelle pour les requêtes HTTP Solana via le pool d’endpoints configurés.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-xxl-4">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Requête</h2>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoHttpRoleSelect" class="form-label">Role</label>
|
||||
<select id="demoHttpRoleSelect" class="form-select">
|
||||
<option value="http_queries">http_queries</option>
|
||||
<option value="http_transactions">http_transactions</option>
|
||||
<option value="http_heavy">http_heavy</option>
|
||||
<option value="http_fallback">http_fallback</option>
|
||||
</select>
|
||||
<div class="form-text">
|
||||
Le rôle détermine quel endpoint HTTP du pool sera sélectionné.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoHttpMethodSelect" class="form-label">Méthode</label>
|
||||
<select id="demoHttpMethodSelect" class="form-select">
|
||||
<option value="getHealth">getHealth</option>
|
||||
<option value="getVersion">getVersion</option>
|
||||
<option value="getSlot">getSlot</option>
|
||||
<option value="getBlockHeight">getBlockHeight</option>
|
||||
<option value="getLatestBlockhash">getLatestBlockhash</option>
|
||||
<option value="getBalance">getBalance</option>
|
||||
<option value="getAccountInfo">getAccountInfo</option>
|
||||
<option value="getProgramAccounts">getProgramAccounts</option>
|
||||
<option value="getSignaturesForAddress">getSignaturesForAddress</option>
|
||||
<option value="getTransaction">getTransaction</option>
|
||||
<option value="sendTransaction">sendTransaction</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="demoHttpFirstArgGroup" class="mb-3">
|
||||
<label for="demoHttpFirstArgInput" id="demoHttpFirstArgLabel" class="form-label">First arg</label>
|
||||
<input id="demoHttpFirstArgInput" type="text" class="form-control" spellcheck="false" />
|
||||
<div id="demoHttpFirstArgHelp" class="form-text">
|
||||
Adresse, program id, signature ou transaction encodée selon la méthode.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="demoHttpConfigGroup" class="mb-3">
|
||||
<label for="demoHttpConfigTextarea" class="form-label">Config JSON</label>
|
||||
<textarea id="demoHttpConfigTextarea" class="form-control font-monospace" rows="8" spellcheck="false"></textarea>
|
||||
<div id="demoHttpConfigHelp" class="form-text">
|
||||
Configuration JSON optionnelle.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<button id="demoHttpExecuteButton" type="button" class="btn btn-primary">Execute</button>
|
||||
<button id="demoHttpRefreshPoolButton" type="button" class="btn btn-outline-primary">Refresh pool</button>
|
||||
<button id="demoHttpCopyResponseButton" type="button" class="btn btn-outline-secondary">Copy response</button>
|
||||
<button id="demoHttpClearLogButton" type="button" class="btn btn-outline-secondary">Clear log</button>
|
||||
</div>
|
||||
|
||||
<div class="form-check form-switch mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="demoHttpPrettyToggle" checked />
|
||||
<label class="form-check-label" for="demoHttpPrettyToggle">Pretty JSON</label>
|
||||
</div>
|
||||
|
||||
<div class="small text-body-secondary">
|
||||
<div><strong>Endpoint:</strong> <span id="demoHttpLastEndpointText">-</span></div>
|
||||
<div><strong>Provider:</strong> <span id="demoHttpLastProviderText">-</span></div>
|
||||
<div><strong>Method class:</strong> <span id="demoHttpLastMethodClassText">-</span></div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-xxl-8">
|
||||
<div class="card shadow-sm border-0 mb-4">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Pool HTTP</h2>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm align-middle mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Endpoint</th>
|
||||
<th>Status</th>
|
||||
<th>Paused</th>
|
||||
<th>Conc.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="demoHttpPoolTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card shadow-sm border-0 mb-4">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Latest response</h2>
|
||||
<textarea id="demoHttpResponseTextarea" class="form-control font-monospace" rows="12" readonly spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card shadow-sm border-0">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Logs</h2>
|
||||
<textarea id="demoHttpLogTextarea" class="form-control font-monospace" rows="14" readonly spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="app-footer bg-dark text-light">
|
||||
<div class="container h-100 d-flex align-items-center">
|
||||
<div class="row flex-grow-1 align-items-center">
|
||||
<div class="col-12 col-md-6 text-center text-small my-1 my-md-0">
|
||||
© 2026 SASEDEV — Demo Http
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script type="module" src="ts/demo_http.ts" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
157
kb_app/frontend/demo_ws.html
Normal file
157
kb_app/frontend/demo_ws.html
Normal file
@@ -0,0 +1,157 @@
|
||||
<!-- file: kb_app/frontend/demo_ws.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Demo Ws Subscribe</title>
|
||||
<link rel="stylesheet" href="sass/main.scss" />
|
||||
</head>
|
||||
|
||||
<body class="bg-body-tertiary">
|
||||
<header class="app-header">
|
||||
<nav class="navbar navbar-expand-lg h-100 py-0 bg-light text-dark">
|
||||
<div class="container my-0">
|
||||
<a class="navbar-brand d-flex align-items-center" href="/">
|
||||
<img alt="Logo" src="imgs/logo.png" class="app-logo" />
|
||||
<span class="ps-2 fs-4 fw-bold text-primary font-logo">Khadhroony-BoBoBot</span>
|
||||
</a>
|
||||
<div class="ms-auto">
|
||||
<span id="demoWsStatusBadge" class="badge text-bg-secondary">Disconnected</span>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="app-main">
|
||||
<div class="osb-scrollable pt-1 pb-4" data-simplebar>
|
||||
<div class="container py-4">
|
||||
<div class="row g-4">
|
||||
<div class="col-12">
|
||||
<div class="card shadow-sm border-0">
|
||||
<div class="card-body">
|
||||
<h1 class="h4 mb-3">Demo Ws Subscribe</h1>
|
||||
<p class="text-body-secondary mb-0">
|
||||
Fenêtre de test complète pour les souscriptions WebSocket Solana en mode raw ou typed.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-xxl-4">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Connexion</h2>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoWsEndpointSelect" class="form-label">Endpoint WS activé</label>
|
||||
<select id="demoWsEndpointSelect" class="form-select"></select>
|
||||
<div class="form-text">
|
||||
Seuls les endpoints définis dans <code>config.solana.ws_endpoints</code> et marqués
|
||||
<code>enabled: true</code> apparaissent ici. Les endpoints HTTP ne sont pas utilisés
|
||||
par cette fenêtre.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<button id="demoWsConnectButton" type="button" class="btn btn-success">Connect</button>
|
||||
<button id="demoWsDisconnectButton" type="button" class="btn btn-danger">Disconnect</button>
|
||||
</div>
|
||||
|
||||
<div class="small text-body-secondary">
|
||||
<div><strong>State:</strong> <span id="demoWsStateText">Disconnected</span></div>
|
||||
<div><strong>Endpoint:</strong> <span id="demoWsEndpointText">-</span></div>
|
||||
</div>
|
||||
|
||||
<div class="small text-body-secondary mt-2">
|
||||
<div><strong>Events:</strong> <span id="demoWsEventCountText">0</span></div>
|
||||
<div><strong>Notifications:</strong> <span id="demoWsNotificationCountText">0</span></div>
|
||||
<div><strong>UI logs:</strong> <span id="demoWsUiLogCountText">0</span></div>
|
||||
<div><strong>Suppressed:</strong> <span id="demoWsSuppressedLogCountText">0</span></div>
|
||||
<div><strong>Last event:</strong> <span id="demoWsLastEventKindText">-</span></div>
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
<h2 class="h5 mb-3">Souscription</h2>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoWsMethodSelect" class="form-label">Méthode</label>
|
||||
<select id="demoWsMethodSelect" class="form-select">
|
||||
<option value="account">account</option>
|
||||
<option value="block">block</option>
|
||||
<option value="logs">logs</option>
|
||||
<option value="program">program</option>
|
||||
<option value="root">root</option>
|
||||
<option value="signature">signature</option>
|
||||
<option value="slot" selected>slot</option>
|
||||
<option value="slotsUpdates">slotsUpdates</option>
|
||||
<option value="vote">vote</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoWsModeSelect" class="form-label">Mode</label>
|
||||
<select id="demoWsModeSelect" class="form-select">
|
||||
<option value="typed" selected>typed</option>
|
||||
<option value="raw">raw</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="demoWsTargetGroup" class="mb-3">
|
||||
<label for="demoWsTargetInput" id="demoWsTargetLabel" class="form-label">Target</label>
|
||||
<input id="demoWsTargetInput" type="text" class="form-control" spellcheck="false" />
|
||||
</div>
|
||||
|
||||
<div id="demoWsFilterGroup" class="mb-3">
|
||||
<label for="demoWsFilterTextarea" class="form-label">Filter JSON</label>
|
||||
<textarea id="demoWsFilterTextarea" class="form-control font-monospace" rows="5" spellcheck="false"></textarea>
|
||||
</div>
|
||||
|
||||
<div id="demoWsConfigGroup" class="mb-3">
|
||||
<label for="demoWsConfigTextarea" class="form-label">Config JSON</label>
|
||||
<textarea id="demoWsConfigTextarea" class="form-control font-monospace" rows="6" spellcheck="false"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-3">
|
||||
<button id="demoWsSubscribeButton" type="button" class="btn btn-primary">Subscribe</button>
|
||||
<button id="demoWsUnsubscribeButton" type="button" class="btn btn-warning">Unsubscribe current</button>
|
||||
<button id="demoWsClearLogButton" type="button" class="btn btn-outline-secondary">Clear log</button>
|
||||
</div>
|
||||
|
||||
<div class="small text-body-secondary">
|
||||
<div><strong>Current subscription:</strong> <span id="demoWsSubscriptionText">-</span></div>
|
||||
<div><strong>Request:</strong> <span id="demoWsRequestText">-</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-xxl-8">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Logs</h2>
|
||||
<textarea id="demoWsLogTextarea" class="form-control font-monospace" rows="28" readonly spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="app-footer bg-dark text-light">
|
||||
<div class="container h-100 d-flex align-items-center">
|
||||
<div class="row flex-grow-1 align-items-center">
|
||||
<div class="col-12 col-md-6 text-center text-small my-1 my-md-0">
|
||||
© 2026 SASEDEV — Demo Ws
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script type="module" src="ts/demo_ws.ts" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
109
kb_app/frontend/demo_ws_manager.html
Normal file
109
kb_app/frontend/demo_ws_manager.html
Normal file
@@ -0,0 +1,109 @@
|
||||
<!-- file: kb_app/frontend/demo_ws_manager.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Khadhroony-BoBoBot — Demo Ws Manager</title>
|
||||
<link rel="stylesheet" href="sass/main.scss" />
|
||||
</head>
|
||||
|
||||
<body class="bg-body-tertiary">
|
||||
<header class="app-header">
|
||||
<nav class="navbar navbar-expand-lg h-100 py-0 bg-light text-dark">
|
||||
<div class="container my-0">
|
||||
<a class="navbar-brand d-flex align-items-center" href="/">
|
||||
<img alt="Logo" src="imgs/logo.png" class="app-logo" />
|
||||
<span class="ps-2 fs-4 fw-bold text-primary font-logo">Demo Ws Manager</span>
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="app-main">
|
||||
<div class="osb-scrollable pt-1 pb-4" data-simplebar>
|
||||
<div class="container vcentered sketchy-translucid py-4">
|
||||
<div class="row g-4">
|
||||
<div class="col-12 col-xxl-4">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body">
|
||||
<h1 class="h4 mb-3">Pilotage</h1>
|
||||
<p class="text-body-secondary mb-3">
|
||||
Démo légère du <code>WsManager</code> : démarrage/arrêt groupé, pilotage par rôle et bus unifié d’événements.
|
||||
</p>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-4">
|
||||
<button id="demoWsManagerStartAllButton" type="button" class="btn btn-primary">Start all</button>
|
||||
<button id="demoWsManagerStopAllButton" type="button" class="btn btn-outline-primary">Stop all</button>
|
||||
<button id="demoWsManagerRefreshButton" type="button" class="btn btn-outline-secondary">Refresh snapshot</button>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="demoWsManagerRoleSelect" class="form-label">Rôle</label>
|
||||
<select id="demoWsManagerRoleSelect" class="form-select"></select>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-4">
|
||||
<button id="demoWsManagerStartRoleButton" type="button" class="btn btn-primary">Start role</button>
|
||||
<button id="demoWsManagerStopRoleButton" type="button" class="btn btn-outline-primary">Stop role</button>
|
||||
</div>
|
||||
|
||||
<div class="small text-body-secondary">
|
||||
<div><strong>Managed endpoints:</strong> <span id="demoWsManagerEndpointCountText">0</span></div>
|
||||
<div><strong>Started endpoints:</strong> <span id="demoWsManagerStartedCountText">0</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-12 col-xxl-8">
|
||||
<div class="card shadow-sm border-0 mb-4">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-3">Snapshot</h2>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm align-middle mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Endpoint</th>
|
||||
<th>Provider</th>
|
||||
<th>Roles</th>
|
||||
<th>State</th>
|
||||
<th>Subs.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="demoWsManagerTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card shadow-sm border-0">
|
||||
<div class="card-body">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<h2 class="h5 mb-0">Unified event log</h2>
|
||||
<button id="demoWsManagerClearLogButton" type="button" class="btn btn-outline-secondary btn-sm">Clear log</button>
|
||||
</div>
|
||||
<textarea id="demoWsManagerLogTextarea" class="form-control font-monospace" rows="18" readonly spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="app-footer bg-dark text-light">
|
||||
<div class="container h-100 d-flex align-items-center">
|
||||
<div class="row flex-grow-1 align-items-center">
|
||||
<div class="col-12 col-md-6 text-center text-small my-1 my-md-0">
|
||||
© 2026 SASEDEV — Demo Ws Manager
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script type="module" src="ts/demo_ws_manager.ts" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,79 +0,0 @@
|
||||
<!-- file: kb_app/frontend/index.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Khadhroony-BoBoBot</title>
|
||||
<link rel="stylesheet" href="sass/main.scss" />
|
||||
</head>
|
||||
<body class="bg-body-tertiary">
|
||||
<header class="app-header">
|
||||
<nav class="navbar navbar-expand-lg h-100 py-0 bg-light text-dark">
|
||||
<div class="container my-0">
|
||||
<a class="navbar-brand d-flex align-items-center" href="/">
|
||||
<img alt="Logo" src="imgs/logo.png" class="app-logo" />
|
||||
<span class="ps-2 fs-4 fw-bold text-primary font-logo">Khadhroony-BoBoBot</span>
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="app-main">
|
||||
<div class="osb-scrollable pt-1 pb-4" data-simplebar>
|
||||
<div class="container vcentered sketchy-translucid">
|
||||
<div class="row">
|
||||
<div class="col-lg-12 text-center">
|
||||
<h1>Khadhroony-BoBoBot</h1>
|
||||
|
||||
<div class="container py-4">
|
||||
<div class="row g-4 justify-content-center">
|
||||
<div class="col-12 col-xl-8">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body text-start">
|
||||
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-3">
|
||||
<div>
|
||||
<h3 class="h5 card-title mb-1">WebSocket transport</h3>
|
||||
<p class="text-body-secondary mb-0">
|
||||
Démarre ou arrête tous les endpoints WebSocket activés dans <code>config.json</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span id="wsStatusBadge" class="badge text-bg-secondary">Disconnected</span>
|
||||
<button id="wsConnectButton" class="btn btn-success" type="button">Start</button>
|
||||
<button id="wsDisconnectButton" class="btn btn-danger" type="button" disabled>Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-2">
|
||||
<label for="wsLogTextarea" class="form-label fw-semibold">Transport log</label>
|
||||
<textarea
|
||||
id="wsLogTextarea"
|
||||
class="form-control font-monospace"
|
||||
rows="18"
|
||||
readonly
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="app-footer bg-dark text-light">
|
||||
<div class="container h-100 d-flex align-items-center">
|
||||
<div class="row flex-grow-1 align-items-center">
|
||||
<div class="col-12 col-md-4 text-center text-small my-1 my-md-0">© 2026 SASEDEV</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script type="module" src="ts/main.ts" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
105
kb_app/frontend/main.html
Normal file
105
kb_app/frontend/main.html
Normal file
@@ -0,0 +1,105 @@
|
||||
<!-- file: kb_app/frontend/index.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Khadhroony-BoBoBot</title>
|
||||
<link rel="stylesheet" href="sass/main.scss" />
|
||||
</head>
|
||||
|
||||
<body class="bg-body-tertiary">
|
||||
<header class="app-header">
|
||||
<nav class="navbar navbar-expand-lg h-100 py-0 bg-light text-dark">
|
||||
<div class="container my-0">
|
||||
<a class="navbar-brand d-flex align-items-center" href="/">
|
||||
<img alt="Logo" src="imgs/logo.png" class="app-logo" />
|
||||
<span class="ps-2 fs-4 fw-bold text-primary font-logo">Khadhroony-BoBoBot</span>
|
||||
</a>
|
||||
|
||||
<div class="ms-auto d-flex align-items-center gap-2">
|
||||
<button id="openDemoWsButton" type="button" class="btn btn-outline-primary">
|
||||
Demo Ws
|
||||
</button>
|
||||
<button id="openDemoHttpButton" class="btn btn-outline-primary">
|
||||
Demo Http
|
||||
</button>
|
||||
<button id="openDemoWsManagerButton" type="button" class="btn btn-outline-primary">
|
||||
Demo Ws Manager
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="app-main">
|
||||
<div class="osb-scrollable pt-1 pb-4" data-simplebar>
|
||||
<div class="container vcentered sketchy-translucid">
|
||||
<div class="row">
|
||||
<div class="col-lg-12 text-center">
|
||||
<h1>Khadhroony-BoBoBot</h1>
|
||||
|
||||
<div class="container py-4">
|
||||
<div class="row g-4 justify-content-center">
|
||||
<div class="col-12 col-xl-8">
|
||||
<div class="card shadow-sm border-0 h-100">
|
||||
<div class="card-body text-start">
|
||||
<h3 class="h5 card-title mb-3">Desktop shell</h3>
|
||||
<p class="text-body-secondary mb-3">
|
||||
La fenêtre principale reste volontairement légère.
|
||||
</p>
|
||||
<p class="text-body-secondary mb-3">
|
||||
Les tests WebSocket manuels sont disponibles dans la fenêtre dédiée
|
||||
<strong>Demo Ws</strong>.
|
||||
</p>
|
||||
<p class="text-body-secondary mb-3">
|
||||
Les tests PRC Http manuels sont disponibles dans la fenêtre dédiée
|
||||
<strong>Demo Http</strong>.
|
||||
</p>
|
||||
<p class="text-body-secondary mb-3">
|
||||
La démonstration légère de pilotage multi-clients est disponible dans la fenêtre
|
||||
<strong>Demo Ws Manager</strong>.
|
||||
</p>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<button id="openDemoWsButtonSecondary" type="button" class="btn btn-primary">
|
||||
Ouvrir Demo Ws
|
||||
</button>
|
||||
<button id="openDemoHttpButtonSecondary" type="button" class="btn btn-primary">
|
||||
Ouvrir Demo Http
|
||||
</button>
|
||||
<button id="openDemoWsManagerButtonSecondary" type="button" class="btn btn-primary">
|
||||
Ouvrir Demo Ws Manager
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
<p class="mb-0 text-body-secondary">
|
||||
Cette fenêtre sert de point d’entrée applicatif. Les démonstrations de
|
||||
souscriptions Solana live sont isolées dans la fenêtre de test dédiée.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="app-footer bg-dark text-light">
|
||||
<div class="container h-100 d-flex align-items-center">
|
||||
<div class="row flex-grow-1 align-items-center">
|
||||
<div class="col-12 col-md-4 text-center text-small my-1 my-md-0">© 2026 SASEDEV</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script type="module" src="ts/main.ts" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,12 +1,14 @@
|
||||
<!-- file: kb_app/frontend/splash.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Loading ... Khadhroony Solana BoBot</title>
|
||||
<link rel="stylesheet" href="sass/splash.scss" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="splash-container">
|
||||
<img id="splash-image" src="imgs/splash.png" alt="Application Loading" />
|
||||
@@ -16,4 +18,5 @@
|
||||
</div>
|
||||
<script type="module" src="ts/splash.ts" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
437
kb_app/frontend/ts/demo_http.ts
Normal file
437
kb_app/frontend/ts/demo_http.ts
Normal file
@@ -0,0 +1,437 @@
|
||||
import * as bootstrap from "bootstrap";
|
||||
import "simplebar";
|
||||
import ResizeObserver from "resize-observer-polyfill";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { debug, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
|
||||
|
||||
(window as Window & typeof globalThis & { bootstrap?: typeof bootstrap }).bootstrap = bootstrap;
|
||||
(window as Window & typeof globalThis & { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserver;
|
||||
|
||||
interface DemoHttpPoolClientSnapshot {
|
||||
endpointName: string;
|
||||
provider: string;
|
||||
endpointUrl: string;
|
||||
roles: string[];
|
||||
status: string;
|
||||
pausedRemainingMs: number | null;
|
||||
availableConcurrencySlots: number;
|
||||
}
|
||||
|
||||
interface DemoHttpRequest {
|
||||
role: string;
|
||||
method: string;
|
||||
firstArg: string | null;
|
||||
configJson: string | null;
|
||||
}
|
||||
|
||||
interface DemoHttpExecutionPayload {
|
||||
endpointName: string;
|
||||
provider: string;
|
||||
endpointUrl: string;
|
||||
role: string;
|
||||
method: string;
|
||||
methodClass: string;
|
||||
responseJson: string;
|
||||
}
|
||||
|
||||
let demoHttpLastResponseRawText = "";
|
||||
|
||||
function appendLogLine(textarea: HTMLTextAreaElement, line: string): void {
|
||||
const now = new Date();
|
||||
const timestamp = now.toLocaleTimeString("fr-CH", { hour12: false });
|
||||
|
||||
const lines = textarea.value === "" ? [] : textarea.value.split("\n");
|
||||
lines.push(`[${timestamp}] ${line}`);
|
||||
|
||||
const maxLines = 400;
|
||||
textarea.value = lines.slice(-maxLines).join("\n");
|
||||
textarea.scrollTop = textarea.scrollHeight;
|
||||
}
|
||||
|
||||
function methodNeedsFirstArg(method: string): boolean {
|
||||
return [
|
||||
"getBalance",
|
||||
"getAccountInfo",
|
||||
"getProgramAccounts",
|
||||
"getSignaturesForAddress",
|
||||
"getTransaction",
|
||||
"sendTransaction",
|
||||
].includes(method);
|
||||
}
|
||||
|
||||
function firstArgLabelForMethod(method: string): string {
|
||||
if (method === "getBalance") return "Address";
|
||||
if (method === "getAccountInfo") return "Address";
|
||||
if (method === "getProgramAccounts") return "Program id";
|
||||
if (method === "getSignaturesForAddress") return "Address";
|
||||
if (method === "getTransaction") return "Signature";
|
||||
if (method === "sendTransaction") return "Encoded transaction (base64)";
|
||||
return "First arg";
|
||||
}
|
||||
|
||||
function firstArgHelpForMethod(method: string): string {
|
||||
if (method === "getBalance") return "Adresse Solana dont on veut lire le solde.";
|
||||
if (method === "getAccountInfo") return "Adresse Solana du compte à lire.";
|
||||
if (method === "getProgramAccounts") return "Program id dont on veut lister les comptes.";
|
||||
if (method === "getSignaturesForAddress") return "Adresse Solana dont on veut lire les signatures récentes.";
|
||||
if (method === "getTransaction") return "Signature exacte d’une transaction.";
|
||||
if (method === "sendTransaction") {
|
||||
return "Transaction signée encodée en base64. Le preset fourni est volontairement invalide et sert seulement à tester la gestion d’erreur.";
|
||||
}
|
||||
return "Adresse, program id, signature ou transaction encodée selon la méthode.";
|
||||
}
|
||||
|
||||
function configHelpForMethod(method: string): string {
|
||||
if (method === "getProgramAccounts") {
|
||||
return "Preset volontairement filtré pour éviter une réponse trop large.";
|
||||
}
|
||||
|
||||
if (method === "sendTransaction") {
|
||||
return "Configuration d’envoi. Avec le preset de transaction invalide, la requête doit échouer côté RPC.";
|
||||
}
|
||||
|
||||
return "Configuration JSON optionnelle.";
|
||||
}
|
||||
|
||||
function defaultRoleForMethod(method: string): string {
|
||||
if (method === "sendTransaction") return "http_transactions";
|
||||
if (method === "getProgramAccounts") return "http_heavy";
|
||||
return "http_queries";
|
||||
}
|
||||
|
||||
function defaultFirstArgForMethod(method: string): string {
|
||||
if (method === "getBalance") return "11111111111111111111111111111111";
|
||||
if (method === "getAccountInfo") return "11111111111111111111111111111111";
|
||||
if (method === "getProgramAccounts") return "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
||||
if (method === "getSignaturesForAddress") return "11111111111111111111111111111111";
|
||||
if (method === "getTransaction") {
|
||||
return "5h6xBEauJ3PK6SWC7r7J2W8mE1D7aQj4J6Jg8n1SmWnVqSg9H6gq2K7xwJkL2GZ2RZ6n9wYk9cW1b2V3a4d5e6f7";
|
||||
}
|
||||
if (method === "sendTransaction") return "AQ==";
|
||||
return "";
|
||||
}
|
||||
|
||||
function defaultConfigForMethod(method: string): string {
|
||||
if (method === "getSlot" || method === "getBlockHeight" || method === "getLatestBlockhash") {
|
||||
return `{"commitment":"confirmed"}`;
|
||||
}
|
||||
|
||||
if (method === "getBalance") {
|
||||
return `{"commitment":"confirmed"}`;
|
||||
}
|
||||
|
||||
if (method === "getAccountInfo") {
|
||||
return `{"encoding":"base64","commitment":"confirmed"}`;
|
||||
}
|
||||
|
||||
if (method === "getProgramAccounts") {
|
||||
return `{
|
||||
"encoding":"base64",
|
||||
"commitment":"confirmed",
|
||||
"dataSlice":{"offset":0,"length":0},
|
||||
"filters":[
|
||||
{"dataSize":165},
|
||||
{"memcmp":{"offset":32,"bytes":"11111111111111111111111111111111"}}
|
||||
]
|
||||
}`;
|
||||
}
|
||||
|
||||
if (method === "getSignaturesForAddress") {
|
||||
return `{"limit":10,"commitment":"confirmed"}`;
|
||||
}
|
||||
|
||||
if (method === "getTransaction") {
|
||||
return `{"encoding":"json","commitment":"confirmed","maxSupportedTransactionVersion":0}`;
|
||||
}
|
||||
|
||||
if (method === "sendTransaction") {
|
||||
return `{"encoding":"base64","skipPreflight":true,"maxRetries":0}`;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
function renderPoolSnapshots(
|
||||
snapshots: DemoHttpPoolClientSnapshot[],
|
||||
tableBody: HTMLTableSectionElement,
|
||||
): void {
|
||||
tableBody.innerHTML = "";
|
||||
|
||||
for (const snapshot of snapshots) {
|
||||
const row = document.createElement("tr");
|
||||
|
||||
const endpointCell = document.createElement("td");
|
||||
endpointCell.innerHTML = `<div class="fw-semibold">${snapshot.endpointName}</div><div class="small text-body-secondary">${snapshot.endpointUrl}</div>`;
|
||||
|
||||
const providerCell = document.createElement("td");
|
||||
providerCell.textContent = snapshot.provider;
|
||||
|
||||
const statusCell = document.createElement("td");
|
||||
statusCell.textContent = snapshot.status;
|
||||
|
||||
const pausedCell = document.createElement("td");
|
||||
pausedCell.textContent = snapshot.pausedRemainingMs === null ? "-" : String(snapshot.pausedRemainingMs);
|
||||
|
||||
const concurrencyCell = document.createElement("td");
|
||||
concurrencyCell.textContent = String(snapshot.availableConcurrencySlots);
|
||||
|
||||
const rolesCell = document.createElement("td");
|
||||
rolesCell.textContent = snapshot.roles.join(", ");
|
||||
|
||||
row.appendChild(endpointCell);
|
||||
row.appendChild(providerCell);
|
||||
row.appendChild(statusCell);
|
||||
row.appendChild(pausedCell);
|
||||
row.appendChild(concurrencyCell);
|
||||
row.appendChild(rolesCell);
|
||||
|
||||
tableBody.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
function renderResponse(
|
||||
responseTextarea: HTMLTextAreaElement,
|
||||
prettyToggle: HTMLInputElement,
|
||||
): void {
|
||||
if (demoHttpLastResponseRawText.trim() === "") {
|
||||
responseTextarea.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!prettyToggle.checked) {
|
||||
responseTextarea.value = demoHttpLastResponseRawText;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(demoHttpLastResponseRawText);
|
||||
responseTextarea.value = JSON.stringify(parsed, null, 2);
|
||||
} catch {
|
||||
responseTextarea.value = demoHttpLastResponseRawText;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyTextToClipboard(text: string): Promise<void> {
|
||||
if (typeof navigator !== "undefined" && navigator.clipboard && navigator.clipboard.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
}
|
||||
|
||||
const tempTextarea = document.createElement("textarea");
|
||||
tempTextarea.value = text;
|
||||
tempTextarea.style.position = "fixed";
|
||||
tempTextarea.style.left = "-9999px";
|
||||
document.body.appendChild(tempTextarea);
|
||||
tempTextarea.focus();
|
||||
tempTextarea.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(tempTextarea);
|
||||
}
|
||||
|
||||
function updateMethodForm(
|
||||
roleSelect: HTMLSelectElement,
|
||||
methodSelect: HTMLSelectElement,
|
||||
firstArgGroup: HTMLDivElement,
|
||||
firstArgLabel: HTMLLabelElement,
|
||||
firstArgHelp: HTMLDivElement,
|
||||
firstArgInput: HTMLInputElement,
|
||||
configTextarea: HTMLTextAreaElement,
|
||||
configHelp: HTMLDivElement,
|
||||
): void {
|
||||
const method = methodSelect.value;
|
||||
|
||||
firstArgGroup.style.display = methodNeedsFirstArg(method) ? "" : "none";
|
||||
firstArgLabel.textContent = firstArgLabelForMethod(method);
|
||||
firstArgHelp.textContent = firstArgHelpForMethod(method);
|
||||
firstArgInput.value = defaultFirstArgForMethod(method);
|
||||
configTextarea.value = defaultConfigForMethod(method);
|
||||
configHelp.textContent = configHelpForMethod(method);
|
||||
roleSelect.value = defaultRoleForMethod(method);
|
||||
}
|
||||
|
||||
async function refreshPoolSnapshot(
|
||||
tableBody: HTMLTableSectionElement,
|
||||
logTextarea: HTMLTextAreaElement,
|
||||
shouldLog: boolean,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const snapshots = await invoke<DemoHttpPoolClientSnapshot[]>("demo_http_list_pool_clients");
|
||||
renderPoolSnapshots(snapshots, tableBody);
|
||||
|
||||
if (shouldLog) {
|
||||
appendLogLine(logTextarea, `[ui] refreshed http pool snapshot (${snapshots.length} endpoint(s))`);
|
||||
}
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] refresh pool error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
void takeoverConsole();
|
||||
debug("demo_http window loaded");
|
||||
|
||||
const sidebarToggle = document.querySelector<HTMLButtonElement>('#sidebarToggle');
|
||||
if (sidebarToggle) {
|
||||
// restaurer l’état depuis localStorage
|
||||
if (localStorage.getItem('sidebar-toggle') === 'true') {
|
||||
document.body.classList.add('sidenav-toggled');
|
||||
}
|
||||
|
||||
sidebarToggle.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
document.body.classList.toggle('sidenav-toggled');
|
||||
localStorage.setItem('sidebar-toggle', document.body.classList.contains('sidenav-toggled') ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
Array.from(tooltipTriggerList).map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
|
||||
const toastElList = document.querySelectorAll('.toast');
|
||||
Array.from(toastElList).map(toastEl => new bootstrap.Toast(toastEl));
|
||||
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
|
||||
Array.from(popoverTriggerList).map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl));
|
||||
|
||||
const gobackto = location.pathname + location.search;
|
||||
|
||||
document.querySelectorAll<HTMLAnchorElement>('a[data-setlang]').forEach((a) => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!href) return; // pas de href => on ignore
|
||||
|
||||
const url = new URL(href, location.origin);
|
||||
url.searchParams.set("gobackto", gobackto);
|
||||
|
||||
// conserve une URL relative (path + query)
|
||||
a.setAttribute("href", url.pathname + "?" + url.searchParams.toString());
|
||||
});
|
||||
|
||||
const roleSelect = document.querySelector<HTMLSelectElement>("#demoHttpRoleSelect");
|
||||
const methodSelect = document.querySelector<HTMLSelectElement>("#demoHttpMethodSelect");
|
||||
const firstArgGroup = document.querySelector<HTMLDivElement>("#demoHttpFirstArgGroup");
|
||||
const firstArgLabel = document.querySelector<HTMLLabelElement>("#demoHttpFirstArgLabel");
|
||||
const firstArgHelp = document.querySelector<HTMLDivElement>("#demoHttpFirstArgHelp");
|
||||
const firstArgInput = document.querySelector<HTMLInputElement>("#demoHttpFirstArgInput");
|
||||
const configTextarea = document.querySelector<HTMLTextAreaElement>("#demoHttpConfigTextarea");
|
||||
const configHelp = document.querySelector<HTMLDivElement>("#demoHttpConfigHelp");
|
||||
const executeButton = document.querySelector<HTMLButtonElement>("#demoHttpExecuteButton");
|
||||
const refreshPoolButton = document.querySelector<HTMLButtonElement>("#demoHttpRefreshPoolButton");
|
||||
const clearLogButton = document.querySelector<HTMLButtonElement>("#demoHttpClearLogButton");
|
||||
const copyResponseButton = document.querySelector<HTMLButtonElement>("#demoHttpCopyResponseButton");
|
||||
const prettyToggle = document.querySelector<HTMLInputElement>("#demoHttpPrettyToggle");
|
||||
const responseTextarea = document.querySelector<HTMLTextAreaElement>("#demoHttpResponseTextarea");
|
||||
const logTextarea = document.querySelector<HTMLTextAreaElement>("#demoHttpLogTextarea");
|
||||
const poolTableBody = document.querySelector<HTMLTableSectionElement>("#demoHttpPoolTableBody");
|
||||
const lastEndpointText = document.querySelector<HTMLSpanElement>("#demoHttpLastEndpointText");
|
||||
const lastProviderText = document.querySelector<HTMLSpanElement>("#demoHttpLastProviderText");
|
||||
const lastMethodClassText = document.querySelector<HTMLSpanElement>("#demoHttpLastMethodClassText");
|
||||
|
||||
if (
|
||||
!roleSelect ||
|
||||
!methodSelect ||
|
||||
!firstArgGroup ||
|
||||
!firstArgLabel ||
|
||||
!firstArgHelp ||
|
||||
!firstArgInput ||
|
||||
!configTextarea ||
|
||||
!configHelp ||
|
||||
!executeButton ||
|
||||
!refreshPoolButton ||
|
||||
!clearLogButton ||
|
||||
!copyResponseButton ||
|
||||
!prettyToggle ||
|
||||
!responseTextarea ||
|
||||
!logTextarea ||
|
||||
!poolTableBody ||
|
||||
!lastEndpointText ||
|
||||
!lastProviderText ||
|
||||
!lastMethodClassText
|
||||
) {
|
||||
debug("demo_http UI controls not found");
|
||||
return;
|
||||
}
|
||||
|
||||
updateMethodForm(
|
||||
roleSelect,
|
||||
methodSelect,
|
||||
firstArgGroup,
|
||||
firstArgLabel,
|
||||
firstArgHelp,
|
||||
firstArgInput,
|
||||
configTextarea,
|
||||
configHelp,
|
||||
);
|
||||
|
||||
methodSelect.addEventListener("change", () => {
|
||||
updateMethodForm(
|
||||
roleSelect,
|
||||
methodSelect,
|
||||
firstArgGroup,
|
||||
firstArgLabel,
|
||||
firstArgHelp,
|
||||
firstArgInput,
|
||||
configTextarea,
|
||||
configHelp,
|
||||
);
|
||||
});
|
||||
|
||||
prettyToggle.addEventListener("change", () => {
|
||||
renderResponse(responseTextarea, prettyToggle);
|
||||
});
|
||||
|
||||
refreshPoolButton.addEventListener("click", async () => {
|
||||
await refreshPoolSnapshot(poolTableBody, logTextarea, true);
|
||||
});
|
||||
|
||||
clearLogButton.addEventListener("click", () => {
|
||||
logTextarea.value = "";
|
||||
});
|
||||
|
||||
copyResponseButton.addEventListener("click", async () => {
|
||||
if (responseTextarea.value.trim() === "") {
|
||||
appendLogLine(logTextarea, "[ui] copy skipped: no response available");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await copyTextToClipboard(responseTextarea.value);
|
||||
appendLogLine(logTextarea, "[ui] response copied to clipboard");
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] copy response error: ${String(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
executeButton.addEventListener("click", async () => {
|
||||
const request: DemoHttpRequest = {
|
||||
role: roleSelect.value,
|
||||
method: methodSelect.value,
|
||||
firstArg: firstArgInput.value.trim() === "" ? null : firstArgInput.value.trim(),
|
||||
configJson: configTextarea.value.trim() === "" ? null : configTextarea.value.trim(),
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await invoke<DemoHttpExecutionPayload>("demo_http_execute_request", { request });
|
||||
|
||||
lastEndpointText.textContent = `${response.endpointName} (${response.endpointUrl})`;
|
||||
lastProviderText.textContent = response.provider;
|
||||
lastMethodClassText.textContent = response.methodClass;
|
||||
|
||||
demoHttpLastResponseRawText = response.responseJson;
|
||||
renderResponse(responseTextarea, prettyToggle);
|
||||
|
||||
appendLogLine(
|
||||
logTextarea,
|
||||
`[ui] ${response.method} via ${response.endpointName} / role=${response.role} / class=${response.methodClass}`,
|
||||
);
|
||||
|
||||
await refreshPoolSnapshot(poolTableBody, logTextarea, true);
|
||||
} catch (error) {
|
||||
demoHttpLastResponseRawText = String(error);
|
||||
renderResponse(responseTextarea, prettyToggle);
|
||||
|
||||
appendLogLine(logTextarea, `[ui] execute error: ${String(error)}`);
|
||||
await refreshPoolSnapshot(poolTableBody, logTextarea, true);
|
||||
}
|
||||
});
|
||||
|
||||
appendLogLine(logTextarea, "[ui] demo_http window loaded");
|
||||
await refreshPoolSnapshot(poolTableBody, logTextarea, true);
|
||||
});
|
||||
520
kb_app/frontend/ts/demo_ws.ts
Normal file
520
kb_app/frontend/ts/demo_ws.ts
Normal file
@@ -0,0 +1,520 @@
|
||||
// file: kb_app/frontend/ts/demo_ws.ts
|
||||
|
||||
import * as bootstrap from "bootstrap";
|
||||
import "simplebar";
|
||||
import ResizeObserver from "resize-observer-polyfill";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { debug, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
|
||||
|
||||
(window as Window & typeof globalThis & { bootstrap?: typeof bootstrap }).bootstrap = bootstrap;
|
||||
(window as Window & typeof globalThis & { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserver;
|
||||
|
||||
interface DemoWsEndpointSummary {
|
||||
name: string;
|
||||
resolvedUrl: string;
|
||||
provider: string;
|
||||
enabled: boolean;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
interface DemoWsStatusPayload {
|
||||
connectionState: string;
|
||||
endpointName: string | null;
|
||||
endpointUrl: string | null;
|
||||
currentSubscriptionId: number | null;
|
||||
currentSubscribeMethod: string | null;
|
||||
currentUnsubscribeMethod: string | null;
|
||||
currentNotificationMethod: string | null;
|
||||
eventCountTotal: number;
|
||||
notificationCountTotal: number;
|
||||
uiLogCount: number;
|
||||
suppressedLogCount: number;
|
||||
lastEventKind: string | null;
|
||||
}
|
||||
|
||||
interface DemoWsSubscribeRequest {
|
||||
method: string;
|
||||
mode: string;
|
||||
target: string | null;
|
||||
filterJson: string | null;
|
||||
configJson: string | null;
|
||||
}
|
||||
|
||||
function shortenLine(line: string, maxChars = 3000): string {
|
||||
if (line.length <= maxChars) {
|
||||
return line;
|
||||
}
|
||||
|
||||
return `${line.slice(0, maxChars)} …[truncated ${line.length - maxChars} chars]`;
|
||||
}
|
||||
|
||||
function appendLogLine(textarea: HTMLTextAreaElement, line: string): void {
|
||||
const now = new Date();
|
||||
const timestamp = now.toLocaleTimeString("fr-CH", { hour12: false });
|
||||
const safeLine = shortenLine(line, 3000);
|
||||
|
||||
const existingLines = textarea.value === "" ? [] : textarea.value.split("\n");
|
||||
existingLines.push(`[${timestamp}] ${safeLine}`);
|
||||
|
||||
const maxLines = 800;
|
||||
const trimmedLines = existingLines.length > maxLines
|
||||
? existingLines.slice(existingLines.length - maxLines)
|
||||
: existingLines;
|
||||
|
||||
textarea.value = trimmedLines.join("\n");
|
||||
textarea.scrollTop = textarea.scrollHeight;
|
||||
}
|
||||
|
||||
function setStatusBadge(badge: HTMLSpanElement, state: string): void {
|
||||
badge.textContent = state;
|
||||
|
||||
if (state === "Connected") {
|
||||
badge.className = "badge text-bg-success";
|
||||
return;
|
||||
}
|
||||
|
||||
if (state === "Connecting" || state === "Disconnecting") {
|
||||
badge.className = "badge text-bg-warning";
|
||||
return;
|
||||
}
|
||||
|
||||
badge.className = "badge text-bg-secondary";
|
||||
}
|
||||
|
||||
function methodSupportsTypedMode(method: string): boolean {
|
||||
return ["account", "block", "logs", "program", "signature"].includes(method);
|
||||
}
|
||||
|
||||
function methodNeedsTarget(method: string): boolean {
|
||||
return ["account", "program", "signature"].includes(method);
|
||||
}
|
||||
|
||||
function methodNeedsFilter(method: string): boolean {
|
||||
return ["block", "logs"].includes(method);
|
||||
}
|
||||
|
||||
function methodNeedsConfig(method: string): boolean {
|
||||
return ["account", "block", "logs", "program", "signature"].includes(method);
|
||||
}
|
||||
|
||||
function targetLabelForMethod(method: string): string {
|
||||
if (method === "account") return "Account pubkey";
|
||||
if (method === "program") return "Program id";
|
||||
if (method === "signature") return "Signature";
|
||||
return "Target";
|
||||
}
|
||||
|
||||
function methodPreset(method: string, mode: string): {
|
||||
target: string;
|
||||
filterJson: string;
|
||||
configJson: string;
|
||||
} {
|
||||
if (method === "account") {
|
||||
return {
|
||||
target: "11111111111111111111111111111111",
|
||||
filterJson: "",
|
||||
configJson: mode === "typed"
|
||||
? `{"encoding":"base64","commitment":"confirmed"}`
|
||||
: `{"encoding":"base64","commitment":"confirmed"}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (method === "block") {
|
||||
return {
|
||||
target: "",
|
||||
filterJson: `{"mentionsAccountOrProgram":"11111111111111111111111111111111"}`,
|
||||
configJson: mode === "typed"
|
||||
? `{"commitment":"confirmed","encoding":"base64","transactionDetails":"signatures","showRewards":false,"maxSupportedTransactionVersion":0}`
|
||||
: `{"commitment":"confirmed","encoding":"base64","transactionDetails":"signatures","showRewards":false,"maxSupportedTransactionVersion":0}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (method === "logs") {
|
||||
return {
|
||||
target: "",
|
||||
filterJson: `{"mentions":["11111111111111111111111111111111"]}`,
|
||||
configJson: `{"commitment":"confirmed"}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (method === "program") {
|
||||
return {
|
||||
target: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
|
||||
filterJson: "",
|
||||
configJson: mode === "typed"
|
||||
? `{"encoding":"base64","commitment":"confirmed","filters":[]}`
|
||||
: `{"encoding":"base64","commitment":"confirmed","filters":[]}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (method === "signature") {
|
||||
return {
|
||||
target: "2EBVM6cB8vAAD93Ktr6Vd8p67XPbQzCJX47MpReuiCXJAtcjaxpvWpcg9Ege1Nr5Tk3a2GFrByT7WPBjdsTycY9b",
|
||||
filterJson: "",
|
||||
configJson: `{"commitment":"confirmed","enableReceivedNotification":true}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
target: "",
|
||||
filterJson: "",
|
||||
configJson: "",
|
||||
};
|
||||
}
|
||||
|
||||
function updateFormVisibility(
|
||||
methodSelect: HTMLSelectElement,
|
||||
modeSelect: HTMLSelectElement,
|
||||
targetGroup: HTMLDivElement,
|
||||
targetLabel: HTMLLabelElement,
|
||||
targetInput: HTMLInputElement,
|
||||
filterGroup: HTMLDivElement,
|
||||
filterTextarea: HTMLTextAreaElement,
|
||||
configGroup: HTMLDivElement,
|
||||
configTextarea: HTMLTextAreaElement,
|
||||
): void {
|
||||
const method = methodSelect.value;
|
||||
const supportsTypedMode = methodSupportsTypedMode(method);
|
||||
|
||||
modeSelect.disabled = !supportsTypedMode;
|
||||
if (!supportsTypedMode) {
|
||||
modeSelect.value = "typed";
|
||||
}
|
||||
|
||||
targetGroup.style.display = methodNeedsTarget(method) ? "" : "none";
|
||||
filterGroup.style.display = methodNeedsFilter(method) ? "" : "none";
|
||||
configGroup.style.display = methodNeedsConfig(method) ? "" : "none";
|
||||
|
||||
targetLabel.textContent = targetLabelForMethod(method);
|
||||
|
||||
const preset = methodPreset(method, modeSelect.value);
|
||||
targetInput.value = preset.target;
|
||||
filterTextarea.value = preset.filterJson;
|
||||
configTextarea.value = preset.configJson;
|
||||
}
|
||||
|
||||
function applyStatusToUi(
|
||||
status: DemoWsStatusPayload,
|
||||
statusBadge: HTMLSpanElement,
|
||||
stateText: HTMLSpanElement,
|
||||
endpointText: HTMLSpanElement,
|
||||
subscriptionText: HTMLSpanElement,
|
||||
eventCountText: HTMLSpanElement,
|
||||
notificationCountText: HTMLSpanElement,
|
||||
uiLogCountText: HTMLSpanElement,
|
||||
suppressedLogCountText: HTMLSpanElement,
|
||||
lastEventKindText: HTMLSpanElement,
|
||||
connectButton: HTMLButtonElement,
|
||||
disconnectButton: HTMLButtonElement,
|
||||
subscribeButton: HTMLButtonElement,
|
||||
unsubscribeButton: HTMLButtonElement,
|
||||
): void {
|
||||
setStatusBadge(statusBadge, status.connectionState);
|
||||
stateText.textContent = status.connectionState;
|
||||
endpointText.textContent = status.endpointName && status.endpointUrl
|
||||
? `${status.endpointName} (${status.endpointUrl})`
|
||||
: "-";
|
||||
|
||||
if (status.currentSubscriptionId !== null) {
|
||||
subscriptionText.textContent =
|
||||
`${status.currentSubscribeMethod ?? "?"} / #${status.currentSubscriptionId} / ${status.currentNotificationMethod ?? "?"}`;
|
||||
} else {
|
||||
subscriptionText.textContent = "-";
|
||||
}
|
||||
|
||||
eventCountText.textContent = String(status.eventCountTotal);
|
||||
notificationCountText.textContent = String(status.notificationCountTotal);
|
||||
uiLogCountText.textContent = String(status.uiLogCount);
|
||||
suppressedLogCountText.textContent = String(status.suppressedLogCount);
|
||||
lastEventKindText.textContent = status.lastEventKind ?? "-";
|
||||
|
||||
const isConnected = status.connectionState === "Connected";
|
||||
const isBusy = status.connectionState === "Connecting" || status.connectionState === "Disconnecting";
|
||||
|
||||
connectButton.disabled = isConnected || isBusy;
|
||||
disconnectButton.disabled = !isConnected && status.connectionState !== "Disconnecting";
|
||||
subscribeButton.disabled = !isConnected || isBusy;
|
||||
unsubscribeButton.disabled = !isConnected || isBusy || status.currentSubscriptionId === null;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
void takeoverConsole();
|
||||
|
||||
debug("demo_ws window loaded");
|
||||
|
||||
const sidebarToggle = document.querySelector<HTMLButtonElement>('#sidebarToggle');
|
||||
if (sidebarToggle) {
|
||||
// restaurer l’état depuis localStorage
|
||||
if (localStorage.getItem('sidebar-toggle') === 'true') {
|
||||
document.body.classList.add('sidenav-toggled');
|
||||
}
|
||||
|
||||
sidebarToggle.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
document.body.classList.toggle('sidenav-toggled');
|
||||
localStorage.setItem('sidebar-toggle', document.body.classList.contains('sidenav-toggled') ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
Array.from(tooltipTriggerList).map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
|
||||
const toastElList = document.querySelectorAll('.toast');
|
||||
Array.from(toastElList).map(toastEl => new bootstrap.Toast(toastEl));
|
||||
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
|
||||
Array.from(popoverTriggerList).map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl));
|
||||
|
||||
const gobackto = location.pathname + location.search;
|
||||
|
||||
document.querySelectorAll<HTMLAnchorElement>('a[data-setlang]').forEach((a) => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!href) return; // pas de href => on ignore
|
||||
|
||||
const url = new URL(href, location.origin);
|
||||
url.searchParams.set("gobackto", gobackto);
|
||||
|
||||
// conserve une URL relative (path + query)
|
||||
a.setAttribute("href", url.pathname + "?" + url.searchParams.toString());
|
||||
});
|
||||
|
||||
const endpointSelect = document.querySelector<HTMLSelectElement>("#demoWsEndpointSelect");
|
||||
const methodSelect = document.querySelector<HTMLSelectElement>("#demoWsMethodSelect");
|
||||
const modeSelect = document.querySelector<HTMLSelectElement>("#demoWsModeSelect");
|
||||
const targetGroup = document.querySelector<HTMLDivElement>("#demoWsTargetGroup");
|
||||
const targetLabel = document.querySelector<HTMLLabelElement>("#demoWsTargetLabel");
|
||||
const targetInput = document.querySelector<HTMLInputElement>("#demoWsTargetInput");
|
||||
const filterGroup = document.querySelector<HTMLDivElement>("#demoWsFilterGroup");
|
||||
const filterTextarea = document.querySelector<HTMLTextAreaElement>("#demoWsFilterTextarea");
|
||||
const configGroup = document.querySelector<HTMLDivElement>("#demoWsConfigGroup");
|
||||
const configTextarea = document.querySelector<HTMLTextAreaElement>("#demoWsConfigTextarea");
|
||||
const statusBadge = document.querySelector<HTMLSpanElement>("#demoWsStatusBadge");
|
||||
const stateText = document.querySelector<HTMLSpanElement>("#demoWsStateText");
|
||||
const endpointText = document.querySelector<HTMLSpanElement>("#demoWsEndpointText");
|
||||
const subscriptionText = document.querySelector<HTMLSpanElement>("#demoWsSubscriptionText");
|
||||
const requestText = document.querySelector<HTMLSpanElement>("#demoWsRequestText");
|
||||
const eventCountText = document.querySelector<HTMLSpanElement>("#demoWsEventCountText");
|
||||
const notificationCountText = document.querySelector<HTMLSpanElement>("#demoWsNotificationCountText");
|
||||
const uiLogCountText = document.querySelector<HTMLSpanElement>("#demoWsUiLogCountText");
|
||||
const suppressedLogCountText = document.querySelector<HTMLSpanElement>("#demoWsSuppressedLogCountText");
|
||||
const lastEventKindText = document.querySelector<HTMLSpanElement>("#demoWsLastEventKindText");
|
||||
const connectButton = document.querySelector<HTMLButtonElement>("#demoWsConnectButton");
|
||||
const disconnectButton = document.querySelector<HTMLButtonElement>("#demoWsDisconnectButton");
|
||||
const subscribeButton = document.querySelector<HTMLButtonElement>("#demoWsSubscribeButton");
|
||||
const unsubscribeButton = document.querySelector<HTMLButtonElement>("#demoWsUnsubscribeButton");
|
||||
const clearLogButton = document.querySelector<HTMLButtonElement>("#demoWsClearLogButton");
|
||||
const logTextarea = document.querySelector<HTMLTextAreaElement>("#demoWsLogTextarea");
|
||||
|
||||
if (
|
||||
!eventCountText || !notificationCountText || !uiLogCountText || !suppressedLogCountText || !lastEventKindText ||
|
||||
!endpointSelect || !methodSelect || !modeSelect || !targetGroup || !targetLabel || !targetInput ||
|
||||
!filterGroup || !filterTextarea || !configGroup || !configTextarea || !statusBadge ||
|
||||
!stateText || !endpointText || !subscriptionText || !requestText || !connectButton ||
|
||||
!disconnectButton || !subscribeButton || !unsubscribeButton || !clearLogButton || !logTextarea
|
||||
) {
|
||||
debug("demo_ws UI controls not found");
|
||||
return;
|
||||
}
|
||||
|
||||
let unlistenLogEvent: UnlistenFn | null = null;
|
||||
let unlistenStatusEvent: UnlistenFn | null = null;
|
||||
|
||||
try {
|
||||
unlistenLogEvent = await listen<string>("demo-ws-log", (event) => {
|
||||
appendLogLine(logTextarea, event.payload);
|
||||
});
|
||||
|
||||
unlistenStatusEvent = await listen<DemoWsStatusPayload>("demo-ws-status", (event) => {
|
||||
applyStatusToUi(
|
||||
event.payload,
|
||||
statusBadge,
|
||||
stateText,
|
||||
endpointText,
|
||||
subscriptionText,
|
||||
eventCountText,
|
||||
notificationCountText,
|
||||
uiLogCountText,
|
||||
suppressedLogCountText,
|
||||
lastEventKindText,
|
||||
connectButton,
|
||||
disconnectButton,
|
||||
subscribeButton,
|
||||
unsubscribeButton,
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] event listen error: ${String(error)}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const endpoints = await invoke<DemoWsEndpointSummary[]>("demo_ws_list_endpoints");
|
||||
|
||||
endpointSelect.innerHTML = "";
|
||||
for (const endpoint of endpoints) {
|
||||
const option = document.createElement("option");
|
||||
option.value = endpoint.name;
|
||||
option.textContent = `${endpoint.name} — ${endpoint.provider} — ${endpoint.resolvedUrl}`;
|
||||
option.disabled = !endpoint.enabled;
|
||||
endpointSelect.appendChild(option);
|
||||
}
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] endpoint list error: ${String(error)}`);
|
||||
}
|
||||
|
||||
updateFormVisibility(
|
||||
methodSelect,
|
||||
modeSelect,
|
||||
targetGroup,
|
||||
targetLabel,
|
||||
targetInput,
|
||||
filterGroup,
|
||||
filterTextarea,
|
||||
configGroup,
|
||||
configTextarea,
|
||||
);
|
||||
|
||||
methodSelect.addEventListener("change", () => {
|
||||
updateFormVisibility(
|
||||
methodSelect,
|
||||
modeSelect,
|
||||
targetGroup,
|
||||
targetLabel,
|
||||
targetInput,
|
||||
filterGroup,
|
||||
filterTextarea,
|
||||
configGroup,
|
||||
configTextarea,
|
||||
);
|
||||
});
|
||||
|
||||
modeSelect.addEventListener("change", () => {
|
||||
updateFormVisibility(
|
||||
methodSelect,
|
||||
modeSelect,
|
||||
targetGroup,
|
||||
targetLabel,
|
||||
targetInput,
|
||||
filterGroup,
|
||||
filterTextarea,
|
||||
configGroup,
|
||||
configTextarea,
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
const status = await invoke<DemoWsStatusPayload>("demo_ws_get_status");
|
||||
applyStatusToUi(
|
||||
status,
|
||||
statusBadge,
|
||||
stateText,
|
||||
endpointText,
|
||||
subscriptionText,
|
||||
eventCountText,
|
||||
notificationCountText,
|
||||
uiLogCountText,
|
||||
suppressedLogCountText,
|
||||
lastEventKindText,
|
||||
connectButton,
|
||||
disconnectButton,
|
||||
subscribeButton,
|
||||
unsubscribeButton,
|
||||
);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] initial status error: ${String(error)}`);
|
||||
}
|
||||
|
||||
appendLogLine(logTextarea, "[ui] demo_ws window loaded");
|
||||
|
||||
connectButton.addEventListener("click", async () => {
|
||||
try {
|
||||
const status = await invoke<DemoWsStatusPayload>("demo_ws_connect", {
|
||||
endpointName: endpointSelect.value,
|
||||
});
|
||||
|
||||
applyStatusToUi(
|
||||
status,
|
||||
statusBadge,
|
||||
stateText,
|
||||
endpointText,
|
||||
subscriptionText,
|
||||
eventCountText,
|
||||
notificationCountText,
|
||||
uiLogCountText,
|
||||
suppressedLogCountText,
|
||||
lastEventKindText,
|
||||
connectButton,
|
||||
disconnectButton,
|
||||
subscribeButton,
|
||||
unsubscribeButton,
|
||||
);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] connect error: ${String(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
disconnectButton.addEventListener("click", async () => {
|
||||
try {
|
||||
const status = await invoke<DemoWsStatusPayload>("demo_ws_disconnect");
|
||||
|
||||
applyStatusToUi(
|
||||
status,
|
||||
statusBadge,
|
||||
stateText,
|
||||
endpointText,
|
||||
subscriptionText,
|
||||
eventCountText,
|
||||
notificationCountText,
|
||||
uiLogCountText,
|
||||
suppressedLogCountText,
|
||||
lastEventKindText,
|
||||
connectButton,
|
||||
disconnectButton,
|
||||
subscribeButton,
|
||||
unsubscribeButton,
|
||||
);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] disconnect error: ${String(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
subscribeButton.addEventListener("click", async () => {
|
||||
const request: DemoWsSubscribeRequest = {
|
||||
method: methodSelect.value,
|
||||
mode: modeSelect.value,
|
||||
target: targetInput.value.trim() === "" ? null : targetInput.value.trim(),
|
||||
filterJson: filterTextarea.value.trim() === "" ? null : filterTextarea.value.trim(),
|
||||
configJson: configTextarea.value.trim() === "" ? null : configTextarea.value.trim(),
|
||||
};
|
||||
|
||||
try {
|
||||
const requestId = await invoke<number>("demo_ws_subscribe", { request });
|
||||
requestText.textContent = `request_id=${requestId}`;
|
||||
appendLogLine(logTextarea, `[ui] subscribe request sent: request_id=${requestId}`);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] subscribe error: ${String(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
unsubscribeButton.addEventListener("click", async () => {
|
||||
try {
|
||||
const requestId = await invoke<number>("demo_ws_unsubscribe_current");
|
||||
requestText.textContent = `unsubscribe_request_id=${requestId}`;
|
||||
appendLogLine(logTextarea, `[ui] unsubscribe request sent: request_id=${requestId}`);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] unsubscribe error: ${String(error)}`);
|
||||
}
|
||||
});
|
||||
|
||||
clearLogButton.addEventListener("click", () => {
|
||||
logTextarea.value = "";
|
||||
});
|
||||
|
||||
window.addEventListener("beforeunload", () => {
|
||||
if (unlistenLogEvent) {
|
||||
unlistenLogEvent();
|
||||
}
|
||||
|
||||
if (unlistenStatusEvent) {
|
||||
unlistenStatusEvent();
|
||||
}
|
||||
});
|
||||
});
|
||||
237
kb_app/frontend/ts/demo_ws_manager.ts
Normal file
237
kb_app/frontend/ts/demo_ws_manager.ts
Normal file
@@ -0,0 +1,237 @@
|
||||
// file: kb_app/frontend/ts/demo_ws_manager.ts
|
||||
|
||||
import * as bootstrap from "bootstrap";
|
||||
import "simplebar";
|
||||
import ResizeObserver from "resize-observer-polyfill";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { debug, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
|
||||
|
||||
(window as Window & typeof globalThis & { bootstrap?: typeof bootstrap }).bootstrap = bootstrap;
|
||||
(window as Window & typeof globalThis & { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserver;
|
||||
|
||||
type DemoWsManagerEndpointSummary = {
|
||||
name: string;
|
||||
resolvedUrl: string;
|
||||
provider: string;
|
||||
roles: string[];
|
||||
connectionState: string;
|
||||
activeSubscriptionCount: number;
|
||||
};
|
||||
|
||||
type DemoWsManagerSnapshotPayload = {
|
||||
endpointCount: number;
|
||||
startedCount: number;
|
||||
endpoints: DemoWsManagerEndpointSummary[];
|
||||
};
|
||||
|
||||
const endpointCountText = document.querySelector<HTMLSpanElement>("#demoWsManagerEndpointCountText");
|
||||
const startedCountText = document.querySelector<HTMLSpanElement>("#demoWsManagerStartedCountText");
|
||||
const roleSelect = document.querySelector<HTMLSelectElement>("#demoWsManagerRoleSelect");
|
||||
const tableBody = document.querySelector<HTMLTableSectionElement>("#demoWsManagerTableBody");
|
||||
const logTextarea = document.querySelector<HTMLTextAreaElement>("#demoWsManagerLogTextarea");
|
||||
const startAllButton = document.querySelector<HTMLButtonElement>("#demoWsManagerStartAllButton");
|
||||
const stopAllButton = document.querySelector<HTMLButtonElement>("#demoWsManagerStopAllButton");
|
||||
const refreshButton = document.querySelector<HTMLButtonElement>("#demoWsManagerRefreshButton");
|
||||
const startRoleButton = document.querySelector<HTMLButtonElement>("#demoWsManagerStartRoleButton");
|
||||
const stopRoleButton = document.querySelector<HTMLButtonElement>("#demoWsManagerStopRoleButton");
|
||||
const clearLogButton = document.querySelector<HTMLButtonElement>("#demoWsManagerClearLogButton");
|
||||
|
||||
function appendLogLine(line: string): void {
|
||||
if (!logTextarea) {
|
||||
return;
|
||||
}
|
||||
const prefix = logTextarea.value.length > 0 ? "\n" : "";
|
||||
logTextarea.value += `${prefix}${line}`;
|
||||
logTextarea.scrollTop = logTextarea.scrollHeight;
|
||||
}
|
||||
|
||||
function renderSnapshot(snapshot: DemoWsManagerSnapshotPayload): void {
|
||||
if (endpointCountText) {
|
||||
endpointCountText.textContent = String(snapshot.endpointCount);
|
||||
}
|
||||
if (startedCountText) {
|
||||
startedCountText.textContent = String(snapshot.startedCount);
|
||||
}
|
||||
if (!tableBody) {
|
||||
return;
|
||||
}
|
||||
|
||||
tableBody.innerHTML = "";
|
||||
|
||||
for (const endpoint of snapshot.endpoints) {
|
||||
const row = document.createElement("tr");
|
||||
row.innerHTML = `
|
||||
<td>
|
||||
<div class="fw-semibold">${endpoint.name}</div>
|
||||
<div class="small text-body-secondary">${endpoint.resolvedUrl}</div>
|
||||
</td>
|
||||
<td>${endpoint.provider}</td>
|
||||
<td>${endpoint.roles.join(", ")}</td>
|
||||
<td>${endpoint.connectionState}</td>
|
||||
<td>${endpoint.activeSubscriptionCount}</td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSnapshot(): Promise<void> {
|
||||
try {
|
||||
const snapshot = await invoke<DemoWsManagerSnapshotPayload>("demo_ws_manager_get_snapshot");
|
||||
renderSnapshot(snapshot);
|
||||
appendLogLine("[ui] refreshed manager snapshot");
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] snapshot error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRoles(): Promise<void> {
|
||||
if (!roleSelect) {
|
||||
return;
|
||||
}
|
||||
|
||||
roleSelect.innerHTML = "";
|
||||
|
||||
try {
|
||||
const roles = await invoke<string[]>("demo_ws_manager_list_roles");
|
||||
for (const role of roles) {
|
||||
const option = document.createElement("option");
|
||||
option.value = role;
|
||||
option.textContent = role;
|
||||
roleSelect.appendChild(option);
|
||||
}
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] list roles error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function startAll(): Promise<void> {
|
||||
try {
|
||||
const snapshot = await invoke<DemoWsManagerSnapshotPayload>("demo_ws_manager_start_all");
|
||||
renderSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] start all error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAll(): Promise<void> {
|
||||
try {
|
||||
const snapshot = await invoke<DemoWsManagerSnapshotPayload>("demo_ws_manager_stop_all");
|
||||
renderSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] stop all error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function startRole(): Promise<void> {
|
||||
if (!roleSelect || roleSelect.value.trim().length === 0) {
|
||||
appendLogLine("[ui] no role selected");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = await invoke<DemoWsManagerSnapshotPayload>("demo_ws_manager_start_role", {
|
||||
role: roleSelect.value,
|
||||
});
|
||||
renderSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] start role error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopRole(): Promise<void> {
|
||||
if (!roleSelect || roleSelect.value.trim().length === 0) {
|
||||
appendLogLine("[ui] no role selected");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = await invoke<DemoWsManagerSnapshotPayload>("demo_ws_manager_stop_role", {
|
||||
role: roleSelect.value,
|
||||
});
|
||||
renderSnapshot(snapshot);
|
||||
} catch (error) {
|
||||
appendLogLine(`[ui] stop role error: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
void takeoverConsole();
|
||||
debug("demo_ws_manager window loaded");
|
||||
|
||||
const sidebarToggle = document.querySelector<HTMLButtonElement>('#sidebarToggle');
|
||||
if (sidebarToggle) {
|
||||
// restaurer l’état depuis localStorage
|
||||
if (localStorage.getItem('sidebar-toggle') === 'true') {
|
||||
document.body.classList.add('sidenav-toggled');
|
||||
}
|
||||
|
||||
sidebarToggle.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
document.body.classList.toggle('sidenav-toggled');
|
||||
localStorage.setItem('sidebar-toggle', document.body.classList.contains('sidenav-toggled') ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
Array.from(tooltipTriggerList).map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
|
||||
const toastElList = document.querySelectorAll('.toast');
|
||||
Array.from(toastElList).map(toastEl => new bootstrap.Toast(toastEl));
|
||||
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
|
||||
Array.from(popoverTriggerList).map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl));
|
||||
|
||||
const gobackto = location.pathname + location.search;
|
||||
|
||||
document.querySelectorAll<HTMLAnchorElement>('a[data-setlang]').forEach((a) => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!href) return; // pas de href => on ignore
|
||||
|
||||
const url = new URL(href, location.origin);
|
||||
url.searchParams.set("gobackto", gobackto);
|
||||
|
||||
// conserve une URL relative (path + query)
|
||||
a.setAttribute("href", url.pathname + "?" + url.searchParams.toString());
|
||||
});
|
||||
|
||||
if (startAllButton) {
|
||||
startAllButton.addEventListener("click", () => {
|
||||
void startAll();
|
||||
});
|
||||
}
|
||||
if (stopAllButton) {
|
||||
stopAllButton.addEventListener("click", () => {
|
||||
void stopAll();
|
||||
});
|
||||
}
|
||||
if (refreshButton) {
|
||||
refreshButton.addEventListener("click", () => {
|
||||
void refreshSnapshot();
|
||||
});
|
||||
}
|
||||
if (startRoleButton) {
|
||||
startRoleButton.addEventListener("click", () => {
|
||||
void startRole();
|
||||
});
|
||||
}
|
||||
if (stopRoleButton) {
|
||||
stopRoleButton.addEventListener("click", () => {
|
||||
void stopRole();
|
||||
});
|
||||
}
|
||||
if (clearLogButton && logTextarea) {
|
||||
clearLogButton.addEventListener("click", () => {
|
||||
logTextarea.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
await listen<string>("kb-demo-ws-manager-log", (event) => {
|
||||
appendLogLine(event.payload);
|
||||
});
|
||||
|
||||
await listen<DemoWsManagerSnapshotPayload>("kb-demo-ws-manager-snapshot", (event) => {
|
||||
renderSnapshot(event.payload);
|
||||
});
|
||||
|
||||
await loadRoles();
|
||||
await refreshSnapshot();
|
||||
});
|
||||
@@ -4,51 +4,32 @@ import * as bootstrap from "bootstrap";
|
||||
import "simplebar";
|
||||
import ResizeObserver from "resize-observer-polyfill";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
//import { error } from "@fltsci/tauri-plugin-tracing";
|
||||
//import { info } from "@fltsci/tauri-plugin-tracing";
|
||||
import { trace, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
|
||||
import { debug, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
|
||||
|
||||
(window as Window & typeof globalThis & { bootstrap?: typeof bootstrap }).bootstrap = bootstrap;
|
||||
(window as Window & typeof globalThis & { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserver;
|
||||
|
||||
function appendLogLine(textarea: HTMLTextAreaElement, line: string): void {
|
||||
const now = new Date();
|
||||
const timestamp = now.toLocaleTimeString("fr-CH", { hour12: false });
|
||||
textarea.value += `[${timestamp}] ${line}\n`;
|
||||
textarea.scrollTop = textarea.scrollHeight;
|
||||
}
|
||||
|
||||
function setRunningState(
|
||||
isRunning: boolean,
|
||||
statusBadge: HTMLSpanElement,
|
||||
connectButton: HTMLButtonElement,
|
||||
disconnectButton: HTMLButtonElement,
|
||||
): void {
|
||||
if (isRunning) {
|
||||
statusBadge.textContent = "Connected";
|
||||
statusBadge.className = "badge text-bg-success";
|
||||
connectButton.disabled = true;
|
||||
disconnectButton.disabled = false;
|
||||
return;
|
||||
async function openDemoWsWindow(): Promise<void> {
|
||||
try {
|
||||
await invoke("open_demo_ws_window");
|
||||
} catch (error) {
|
||||
console.error("open_demo_ws_window failed:", error);
|
||||
}
|
||||
}
|
||||
async function openDemoHttpWindow(): Promise<void> {
|
||||
try {
|
||||
await invoke("open_demo_http_window");
|
||||
} catch (error) {
|
||||
console.error("open_demo_http_window failed:", error);
|
||||
}
|
||||
|
||||
statusBadge.textContent = "Disconnected";
|
||||
statusBadge.className = "badge text-bg-secondary";
|
||||
connectButton.disabled = false;
|
||||
disconnectButton.disabled = true;
|
||||
}
|
||||
|
||||
function setBusyState(
|
||||
label: string,
|
||||
statusBadge: HTMLSpanElement,
|
||||
connectButton: HTMLButtonElement,
|
||||
disconnectButton: HTMLButtonElement,
|
||||
): void {
|
||||
statusBadge.textContent = label;
|
||||
statusBadge.className = "badge text-bg-warning";
|
||||
connectButton.disabled = true;
|
||||
disconnectButton.disabled = true;
|
||||
async function openDemoWsManagerWindow(): Promise<void> {
|
||||
try {
|
||||
await invoke("open_demo_ws_manager_window");
|
||||
} catch (error) {
|
||||
console.error("open_demo_ws_manager_window failed:", error);
|
||||
}
|
||||
}
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
void takeoverConsole();
|
||||
@@ -86,61 +67,50 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
a.setAttribute("href", url.pathname + "?" + url.searchParams.toString());
|
||||
});
|
||||
|
||||
const connectButton = document.querySelector<HTMLButtonElement>("#wsConnectButton");
|
||||
const disconnectButton = document.querySelector<HTMLButtonElement>("#wsDisconnectButton");
|
||||
const statusBadge = document.querySelector<HTMLSpanElement>("#wsStatusBadge");
|
||||
const logTextarea = document.querySelector<HTMLTextAreaElement>("#wsLogTextarea");
|
||||
|
||||
if (!connectButton || !disconnectButton || !statusBadge || !logTextarea) {
|
||||
trace("main UI controls not found");
|
||||
return;
|
||||
}
|
||||
|
||||
let unlistenLogEvent: UnlistenFn | null = null;
|
||||
|
||||
try {
|
||||
unlistenLogEvent = await listen<string>("kb-log", (event) => {
|
||||
appendLogLine(logTextarea, event.payload);
|
||||
});
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] event listen error: ${String(error)}`);
|
||||
}
|
||||
|
||||
setRunningState(false, statusBadge, connectButton, disconnectButton);
|
||||
appendLogLine(logTextarea, "[ui] main window loaded");
|
||||
|
||||
connectButton.addEventListener("click", async () => {
|
||||
setBusyState("Starting", statusBadge, connectButton, disconnectButton);
|
||||
|
||||
try {
|
||||
const startedCount = await invoke<number>("start_ws_clients");
|
||||
appendLogLine(logTextarea, `[ui] started ${startedCount} websocket client(s)`);
|
||||
setRunningState(true, statusBadge, connectButton, disconnectButton);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] start error: ${String(error)}`);
|
||||
setRunningState(false, statusBadge, connectButton, disconnectButton);
|
||||
}
|
||||
});
|
||||
|
||||
disconnectButton.addEventListener("click", async () => {
|
||||
setBusyState("Stopping", statusBadge, connectButton, disconnectButton);
|
||||
|
||||
try {
|
||||
const stoppedCount = await invoke<number>("stop_ws_clients");
|
||||
appendLogLine(logTextarea, `[ui] stopped ${stoppedCount} websocket client(s)`);
|
||||
setRunningState(false, statusBadge, connectButton, disconnectButton);
|
||||
} catch (error) {
|
||||
appendLogLine(logTextarea, `[ui] stop error: ${String(error)}`);
|
||||
setRunningState(true, statusBadge, connectButton, disconnectButton);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener("beforeunload", () => {
|
||||
if (unlistenLogEvent) {
|
||||
unlistenLogEvent();
|
||||
}
|
||||
});
|
||||
const openDemoWsButton = document.querySelector<HTMLButtonElement>("#openDemoWsButton");
|
||||
const openDemoWsButtonSecondary = document.querySelector<HTMLButtonElement>("#openDemoWsButtonSecondary");
|
||||
|
||||
trace("window loaded");
|
||||
const openDemoHttpButton = document.querySelector<HTMLButtonElement>("#openDemoHttpButton");
|
||||
const openDemoHttpButtonSecondary = document.querySelector<HTMLButtonElement>("#openDemoHttpButtonSecondary");
|
||||
const openDemoWsManagerButton = document.querySelector<HTMLButtonElement>("#openDemoWsManagerButton");
|
||||
const openDemoWsManagerButtonSecondary = document.querySelector<HTMLButtonElement>("#openDemoWsManagerButtonSecondary");
|
||||
|
||||
if (openDemoWsButton) {
|
||||
openDemoWsButton.addEventListener("click", () => {
|
||||
void openDemoWsWindow();
|
||||
});
|
||||
}
|
||||
|
||||
if (openDemoWsButtonSecondary) {
|
||||
openDemoWsButtonSecondary.addEventListener("click", () => {
|
||||
void openDemoWsWindow();
|
||||
});
|
||||
}
|
||||
|
||||
if (openDemoHttpButton) {
|
||||
openDemoHttpButton.addEventListener("click", () => {
|
||||
void openDemoHttpWindow();
|
||||
});
|
||||
}
|
||||
|
||||
if (openDemoHttpButtonSecondary) {
|
||||
openDemoHttpButtonSecondary.addEventListener("click", () => {
|
||||
void openDemoHttpWindow();
|
||||
});
|
||||
}
|
||||
|
||||
if (openDemoWsManagerButton) {
|
||||
openDemoWsManagerButton.addEventListener("click", () => {
|
||||
void openDemoWsManagerWindow();
|
||||
});
|
||||
}
|
||||
|
||||
if (openDemoWsManagerButtonSecondary) {
|
||||
openDemoWsManagerButtonSecondary.addEventListener("click", () => {
|
||||
void openDemoWsManagerWindow();
|
||||
});
|
||||
}
|
||||
|
||||
debug("window loaded");
|
||||
|
||||
});
|
||||
@@ -6,58 +6,58 @@ import { SplashOrder } from './bindings/SplashOrder.ts';
|
||||
|
||||
// Fonction d'animation d'opacité
|
||||
async function animateOpacity(
|
||||
element: HTMLElement,
|
||||
fromOpacity: number,
|
||||
toOpacity: number,
|
||||
durationMs: number
|
||||
element: HTMLElement,
|
||||
fromOpacity: number,
|
||||
toOpacity: number,
|
||||
durationMs: number
|
||||
): Promise<void> {
|
||||
console.log(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);
|
||||
//debug(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const startTime = performance.now();
|
||||
const startOpacity = fromOpacity;
|
||||
const changeOpacity = toOpacity - fromOpacity;
|
||||
|
||||
function update(currentTime: number) {
|
||||
const elapsed = currentTime - startTime;
|
||||
if (elapsed >= durationMs) {
|
||||
element.style.opacity = toOpacity.toString();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const progress = elapsed / durationMs;
|
||||
element.style.opacity = (startOpacity + changeOpacity * progress).toString();
|
||||
requestAnimationFrame(update);
|
||||
}
|
||||
|
||||
requestAnimationFrame(update);
|
||||
});
|
||||
console.log(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);
|
||||
//debug(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const startTime = performance.now();
|
||||
const startOpacity = fromOpacity;
|
||||
const changeOpacity = toOpacity - fromOpacity;
|
||||
|
||||
function update(currentTime: number) {
|
||||
const elapsed = currentTime - startTime;
|
||||
if (elapsed >= durationMs) {
|
||||
element.style.opacity = toOpacity.toString();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const progress = elapsed / durationMs;
|
||||
element.style.opacity = (startOpacity + changeOpacity * progress).toString();
|
||||
requestAnimationFrame(update);
|
||||
}
|
||||
|
||||
requestAnimationFrame(update);
|
||||
});
|
||||
}
|
||||
|
||||
// Journalisation
|
||||
function addLogMessage(message: string): void {
|
||||
console.log(`Splash: ${message}`);
|
||||
const debugInfo = document.getElementById('debug-info');
|
||||
if (debugInfo) {
|
||||
const time = new Date().toLocaleTimeString();
|
||||
let msg = `${time}: ${message}<br>`;
|
||||
debugInfo.innerHTML += msg;
|
||||
}
|
||||
console.log(`Splash: ${message}`);
|
||||
const debugInfo = document.getElementById('debug-info');
|
||||
if (debugInfo) {
|
||||
const time = new Date().toLocaleTimeString();
|
||||
let msg = `${time}: ${message}<br>`;
|
||||
debugInfo.innerHTML += msg;
|
||||
}
|
||||
}
|
||||
|
||||
// Pour ajouter des messages directement (sans événements)
|
||||
function addMessage(message: string, status: string): void {
|
||||
const messagesContainer = document.getElementById('messages-container');
|
||||
if (!messagesContainer) return;
|
||||
|
||||
const messageElement = document.createElement('div');
|
||||
messageElement.className = `splash-message ${status}`;
|
||||
messageElement.textContent = message;
|
||||
|
||||
messagesContainer.appendChild(messageElement);
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
const messagesContainer = document.getElementById('messages-container');
|
||||
if (!messagesContainer) return;
|
||||
|
||||
const messageElement = document.createElement('div');
|
||||
messageElement.className = `splash-message ${status}`;
|
||||
messageElement.textContent = message;
|
||||
|
||||
messagesContainer.appendChild(messageElement);
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
}
|
||||
listen("splash", (event) => {
|
||||
const splashorder = event.payload as SplashOrder;
|
||||
@@ -80,7 +80,7 @@ listen("splash", (event) => {
|
||||
} else if (splashorder.order == "add_log" && splashorder.msg) {
|
||||
addLogMessage(splashorder.msg);
|
||||
} else {
|
||||
error("unknown order:"+splashorder.order);
|
||||
error("unknown order:" + splashorder.order);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main","splash"],"permissions":["core:default","tracing:default"]}}
|
||||
{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main","splash","demo_ws","demo_http","demo_ws_manager"],"permissions":["core:default","tracing:default"]}}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "kb-app",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
226
kb_app/src/demo_http.rs
Normal file
226
kb_app/src/demo_http.rs
Normal file
@@ -0,0 +1,226 @@
|
||||
// file: kb_app/src/demo_http.rs
|
||||
|
||||
//! Tauri commands for the HTTP demo window.
|
||||
//!
|
||||
//! This module exposes a small manual test surface over the HTTP endpoint pool.
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
/// Request payload for one demo HTTP execution.
|
||||
#[derive(Clone, Debug, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct KbDemoHttpRequest {
|
||||
/// Logical role used to select one endpoint from the pool.
|
||||
pub role: std::string::String,
|
||||
/// JSON-RPC HTTP method name.
|
||||
pub method: std::string::String,
|
||||
/// Optional first string argument, used by methods such as
|
||||
/// `getBalance`, `getAccountInfo`, `getProgramAccounts`,
|
||||
/// `getSignaturesForAddress`, `getTransaction`, `sendTransaction`.
|
||||
pub first_arg: std::option::Option<std::string::String>,
|
||||
/// Optional JSON config payload encoded as a string.
|
||||
pub config_json: std::option::Option<std::string::String>,
|
||||
}
|
||||
|
||||
/// Response payload for one demo HTTP execution.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct KbDemoHttpExecutionPayload {
|
||||
/// Selected endpoint name.
|
||||
pub endpoint_name: std::string::String,
|
||||
/// Selected endpoint provider.
|
||||
pub provider: std::string::String,
|
||||
/// Selected endpoint URL.
|
||||
pub endpoint_url: std::string::String,
|
||||
/// Requested role.
|
||||
pub role: std::string::String,
|
||||
/// Executed method name.
|
||||
pub method: std::string::String,
|
||||
/// Classified method family.
|
||||
pub method_class: std::string::String,
|
||||
/// Pretty-printed JSON response payload.
|
||||
pub response_json: std::string::String,
|
||||
}
|
||||
|
||||
/// Opens the dedicated HTTP demo window.
|
||||
#[tauri::command]
|
||||
pub(crate) fn open_demo_http_window(
|
||||
app_handle: tauri::AppHandle,
|
||||
) -> Result<(), std::string::String> {
|
||||
let existing_window_option = app_handle.get_webview_window("demo_http");
|
||||
|
||||
let demo_window = match existing_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
let builder = tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"demo_http",
|
||||
tauri::WebviewUrl::App("demo_http.html".into()),
|
||||
)
|
||||
.title("Demo Http")
|
||||
.inner_size(1400.0, 768.0)
|
||||
.min_inner_size(800.0, 600.0)
|
||||
.center()
|
||||
.visible(true)
|
||||
.transparent(false)
|
||||
.decorations(true);
|
||||
let build_result = builder.build();
|
||||
match build_result {
|
||||
Ok(window) => window,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create demo_http window: {error:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let show_result = demo_window.show();
|
||||
if let Err(error) = show_result {
|
||||
return Err(format!("cannot show demo_http window: {error:?}"));
|
||||
}
|
||||
let focus_result = demo_window.set_focus();
|
||||
if let Err(error) = focus_result {
|
||||
return Err(format!("cannot focus demo_http window: {error:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a fresh snapshot of the HTTP endpoint pool.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_http_list_pool_clients(
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<std::vec::Vec<kb_lib::KbHttpPoolClientSnapshot>, std::string::String> {
|
||||
Ok(state.http_pool.snapshot().await)
|
||||
}
|
||||
|
||||
/// Executes one manual HTTP request through the endpoint pool.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_http_execute_request(
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
request: KbDemoHttpRequest,
|
||||
) -> Result<KbDemoHttpExecutionPayload, std::string::String> {
|
||||
let role = request.role.trim().to_string();
|
||||
if role.is_empty() {
|
||||
return Err("demo http role must not be empty".to_string());
|
||||
}
|
||||
let method = request.method.trim().to_string();
|
||||
if method.is_empty() {
|
||||
return Err("demo http method must not be empty".to_string());
|
||||
}
|
||||
let config_json_value_result = kb_parse_optional_demo_http_json(request.config_json);
|
||||
let config_json_value = match config_json_value_result {
|
||||
Ok(config_json_value) => config_json_value,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let params_result =
|
||||
kb_build_demo_http_params(&method, request.first_arg.as_deref(), config_json_value);
|
||||
let params = match params_result {
|
||||
Ok(params) => params,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let selected_client_result = state
|
||||
.http_pool
|
||||
.select_client_for_role_and_method(&role, &method)
|
||||
.await;
|
||||
let selected_client = match selected_client_result {
|
||||
Ok(selected_client) => selected_client,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let method_class = kb_lib::HttpClient::classify_method(&method);
|
||||
let method_class_text = kb_demo_http_method_class_to_string(method_class);
|
||||
tracing::info!(
|
||||
endpoint_name = %selected_client.endpoint_name(),
|
||||
endpoint_url = %selected_client.endpoint_url(),
|
||||
role = %role,
|
||||
method = %method,
|
||||
method_class = %method_class_text,
|
||||
"executing demo http request"
|
||||
);
|
||||
let response_value_result = selected_client
|
||||
.execute_json_rpc_result_raw(method.clone(), params)
|
||||
.await;
|
||||
let response_value = match response_value_result {
|
||||
Ok(response_value) => response_value,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let response_json_result = serde_json::to_string_pretty(&response_value);
|
||||
let response_json = match response_json_result {
|
||||
Ok(response_json) => response_json,
|
||||
Err(error) => {
|
||||
return Err(format!(
|
||||
"cannot pretty-print demo http response for method '{}': {}",
|
||||
method, error
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(KbDemoHttpExecutionPayload {
|
||||
endpoint_name: selected_client.endpoint_name().to_string(),
|
||||
provider: selected_client.endpoint_config().provider.clone(),
|
||||
endpoint_url: selected_client.endpoint_url().to_string(),
|
||||
role,
|
||||
method,
|
||||
method_class: method_class_text.to_string(),
|
||||
response_json,
|
||||
})
|
||||
}
|
||||
|
||||
fn kb_parse_optional_demo_http_json(
|
||||
config_json: std::option::Option<std::string::String>,
|
||||
) -> Result<std::option::Option<serde_json::Value>, std::string::String> {
|
||||
let config_json = match config_json {
|
||||
Some(config_json) => config_json.trim().to_string(),
|
||||
None => {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
if config_json.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let value_result = serde_json::from_str::<serde_json::Value>(&config_json);
|
||||
match value_result {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(error) => Err(format!("invalid configJson: {}", error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_build_demo_http_params(
|
||||
method: &str,
|
||||
first_arg: std::option::Option<&str>,
|
||||
config_json: std::option::Option<serde_json::Value>,
|
||||
) -> Result<std::vec::Vec<serde_json::Value>, std::string::String> {
|
||||
let needs_first_arg = matches!(
|
||||
method,
|
||||
"getBalance"
|
||||
| "getAccountInfo"
|
||||
| "getProgramAccounts"
|
||||
| "getSignaturesForAddress"
|
||||
| "getTransaction"
|
||||
| "sendTransaction"
|
||||
);
|
||||
if needs_first_arg {
|
||||
let first_arg = match first_arg {
|
||||
Some(first_arg) => first_arg.trim(),
|
||||
None => "",
|
||||
};
|
||||
if first_arg.is_empty() {
|
||||
return Err(format!("method '{}' requires firstArg", method));
|
||||
}
|
||||
let mut params = vec![serde_json::Value::String(first_arg.to_string())];
|
||||
if let Some(config_json) = config_json {
|
||||
params.push(config_json);
|
||||
}
|
||||
return Ok(params);
|
||||
}
|
||||
let mut params = std::vec::Vec::new();
|
||||
if let Some(config_json) = config_json {
|
||||
params.push(config_json);
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
fn kb_demo_http_method_class_to_string(method_class: kb_lib::KbHttpMethodClass) -> &'static str {
|
||||
match method_class {
|
||||
kb_lib::KbHttpMethodClass::GeneralRpc => "GeneralRpc",
|
||||
kb_lib::KbHttpMethodClass::SendTransaction => "SendTransaction",
|
||||
kb_lib::KbHttpMethodClass::HeavyRead => "HeavyRead",
|
||||
}
|
||||
}
|
||||
1041
kb_app/src/demo_ws.rs
Normal file
1041
kb_app/src/demo_ws.rs
Normal file
File diff suppressed because it is too large
Load Diff
565
kb_app/src/demo_ws_manager.rs
Normal file
565
kb_app/src/demo_ws_manager.rs
Normal file
@@ -0,0 +1,565 @@
|
||||
// file: kb_app/src/demo_ws_manager.rs
|
||||
|
||||
//! Demo WebSocket manager window commands and runtime state.
|
||||
//!
|
||||
//! This module provides a lightweight test bench for `kb_lib::WsManager`.
|
||||
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
/// Static endpoint summary enriched with current manager state.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct KbDemoWsManagerEndpointSummary {
|
||||
name: std::string::String,
|
||||
resolved_url: std::string::String,
|
||||
provider: std::string::String,
|
||||
roles: std::vec::Vec<std::string::String>,
|
||||
connection_state: std::string::String,
|
||||
active_subscription_count: usize,
|
||||
}
|
||||
|
||||
/// Global demo manager snapshot payload.
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct KbDemoWsManagerSnapshotPayload {
|
||||
endpoint_count: usize,
|
||||
started_count: usize,
|
||||
endpoints: std::vec::Vec<KbDemoWsManagerEndpointSummary>,
|
||||
}
|
||||
|
||||
/// Runtime state for the demo WebSocket manager window.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct KbDemoWsManagerRuntimeState {
|
||||
relay_task: std::option::Option<tauri::async_runtime::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl KbDemoWsManagerRuntimeState {
|
||||
/// Creates a new empty runtime state.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { relay_task: None }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DemoWsManagerActionResult {
|
||||
action: std::string::String,
|
||||
target: std::string::String,
|
||||
matched_count: usize,
|
||||
changed_count: usize,
|
||||
unchanged_count: usize,
|
||||
}
|
||||
|
||||
/// Shows and focuses the preconfigured `demo_ws_manager` window.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn open_demo_ws_manager_window(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<(), std::string::String> {
|
||||
kb_ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let existing_window_option = app_handle.get_webview_window("demo_ws_manager");
|
||||
let demo_window = match existing_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
let builder = tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"demo_ws_manager",
|
||||
tauri::WebviewUrl::App("demo_ws_manager.html".into()),
|
||||
)
|
||||
.title("Demo Ws Manager")
|
||||
.inner_size(1280.0, 800.0)
|
||||
.min_inner_size(900.0, 620.0)
|
||||
.center()
|
||||
.visible(true)
|
||||
.transparent(false)
|
||||
.decorations(true);
|
||||
let build_result = builder.build();
|
||||
match build_result {
|
||||
Ok(window) => window,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create demo_ws_manager window: {error:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let show_result = demo_window.show();
|
||||
if let Err(error) = show_result {
|
||||
return Err(format!("cannot show demo_ws_manager window: {error:?}"));
|
||||
}
|
||||
let focus_result = demo_window.set_focus();
|
||||
if let Err(error) = focus_result {
|
||||
return Err(format!("cannot focus demo_ws_manager window: {error:?}"));
|
||||
}
|
||||
kb_emit_demo_ws_manager_log(&app_handle, "[ui] demo_ws_manager window loaded");
|
||||
kb_emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the current manager snapshot.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_get_snapshot(
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
kb_build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Returns the distinct configured roles for enabled websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_list_roles(
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<std::vec::Vec<std::string::String>, std::string::String> {
|
||||
let mut roles = std::collections::BTreeSet::new();
|
||||
for endpoint in &state.config.solana.ws_endpoints {
|
||||
if !endpoint.enabled {
|
||||
continue;
|
||||
}
|
||||
for role in &endpoint.roles {
|
||||
roles.insert(role.clone());
|
||||
}
|
||||
}
|
||||
Ok(roles.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Starts all managed websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_start_all(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
kb_ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let matched_count = state.ws_manager.endpoint_names().await.len();
|
||||
let start_result = state.ws_manager.start_all().await;
|
||||
let changed_count = match start_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = kb_build_action_result("start", "all", matched_count, changed_count);
|
||||
kb_emit_demo_ws_manager_log(
|
||||
&app_handle,
|
||||
kb_format_action_result_for_log(&action_result).as_str(),
|
||||
);
|
||||
kb_emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
kb_build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Stops all managed websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_stop_all(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let matched_count = state.ws_manager.endpoint_names().await.len();
|
||||
let stop_result = state.ws_manager.stop_all().await;
|
||||
let changed_count = match stop_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = kb_build_action_result("stop", "all", matched_count, changed_count);
|
||||
kb_emit_demo_ws_manager_log(
|
||||
&app_handle,
|
||||
kb_format_action_result_for_log(&action_result).as_str(),
|
||||
);
|
||||
kb_emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
kb_build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Starts all managed websocket endpoints having the selected role.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_start_role(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
role: std::string::String,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
kb_ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let matched_count = state
|
||||
.ws_manager
|
||||
.endpoint_names_for_role(role.as_str())
|
||||
.await
|
||||
.len();
|
||||
let start_result = state.ws_manager.start_role(role.as_str()).await;
|
||||
let changed_count = match start_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result =
|
||||
kb_build_action_result("start", role.as_str(), matched_count, changed_count);
|
||||
kb_emit_demo_ws_manager_log(
|
||||
&app_handle,
|
||||
kb_format_action_result_for_log(&action_result).as_str(),
|
||||
);
|
||||
kb_emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
kb_build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Stops all managed websocket endpoints having the selected role.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_stop_role(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::KbAppState>,
|
||||
role: std::string::String,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let matched_count = state
|
||||
.ws_manager
|
||||
.endpoint_names_for_role(role.as_str())
|
||||
.await
|
||||
.len();
|
||||
let stop_result = state.ws_manager.stop_role(role.as_str()).await;
|
||||
let changed_count = match stop_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = kb_build_action_result("stop", role.as_str(), matched_count, changed_count);
|
||||
kb_emit_demo_ws_manager_log(
|
||||
&app_handle,
|
||||
kb_format_action_result_for_log(&action_result).as_str(),
|
||||
);
|
||||
kb_emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
kb_build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
async fn kb_build_demo_ws_manager_snapshot(
|
||||
state: &tauri::State<'_, crate::KbAppState>,
|
||||
) -> Result<KbDemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let snapshot_result = state.ws_manager.snapshot().await;
|
||||
let snapshot = match snapshot_result {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let mut endpoints = std::vec::Vec::new();
|
||||
for managed_endpoint in snapshot.endpoints {
|
||||
let config_endpoint_option = state
|
||||
.config
|
||||
.find_ws_endpoint(&managed_endpoint.endpoint_name);
|
||||
let config_endpoint = match config_endpoint_option {
|
||||
Some(config_endpoint) => config_endpoint,
|
||||
None => {
|
||||
return Err(format!(
|
||||
"managed websocket endpoint '{}' is missing from config",
|
||||
managed_endpoint.endpoint_name
|
||||
));
|
||||
}
|
||||
};
|
||||
endpoints.push(KbDemoWsManagerEndpointSummary {
|
||||
name: managed_endpoint.endpoint_name,
|
||||
resolved_url: managed_endpoint.resolved_url,
|
||||
provider: managed_endpoint.provider,
|
||||
roles: config_endpoint.roles.clone(),
|
||||
connection_state: kb_connection_state_to_string(managed_endpoint.state),
|
||||
active_subscription_count: managed_endpoint.active_subscription_count,
|
||||
});
|
||||
}
|
||||
Ok(KbDemoWsManagerSnapshotPayload {
|
||||
endpoint_count: snapshot.endpoint_count,
|
||||
started_count: snapshot.started_count,
|
||||
endpoints,
|
||||
})
|
||||
}
|
||||
|
||||
async fn kb_emit_demo_ws_manager_snapshot(
|
||||
app_handle: &tauri::AppHandle,
|
||||
state: &tauri::State<'_, crate::KbAppState>,
|
||||
) {
|
||||
let snapshot_result = kb_build_demo_ws_manager_snapshot(state).await;
|
||||
let snapshot = match snapshot_result {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(error) => {
|
||||
kb_emit_demo_ws_manager_log(app_handle, &format!("[ui] snapshot error: {error}"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let emit_result = app_handle.emit("kb-demo-ws-manager-snapshot", snapshot);
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo_ws_manager snapshot event: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn kb_ensure_demo_ws_manager_relay(
|
||||
app_handle: &tauri::AppHandle,
|
||||
state: &tauri::State<'_, crate::KbAppState>,
|
||||
) {
|
||||
let mut runtime_guard = state.demo_ws_manager_runtime.lock().await;
|
||||
if runtime_guard.relay_task.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut receiver = state.ws_manager.subscribe_events();
|
||||
let relay_app_handle = app_handle.clone();
|
||||
let relay_state = state.demo_ws_manager_runtime.clone();
|
||||
let relay_task = tauri::async_runtime::spawn(async move {
|
||||
loop {
|
||||
let recv_result = receiver.recv().await;
|
||||
match recv_result {
|
||||
Ok(event) => {
|
||||
let line = kb_format_ws_event(&event);
|
||||
kb_emit_demo_ws_manager_log(&relay_app_handle, line.as_str());
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
kb_emit_demo_ws_manager_log(
|
||||
&relay_app_handle,
|
||||
&format!(
|
||||
"[manager] event receiver lagged and skipped {} message(s)",
|
||||
skipped
|
||||
),
|
||||
);
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut runtime_guard = relay_state.lock().await;
|
||||
runtime_guard.relay_task = None;
|
||||
});
|
||||
|
||||
runtime_guard.relay_task = Some(relay_task);
|
||||
}
|
||||
|
||||
fn kb_emit_demo_ws_manager_log(app_handle: &tauri::AppHandle, message: &str) {
|
||||
let emit_result = app_handle.emit("kb-demo-ws-manager-log", message.to_string());
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo_ws_manager log event: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_connection_state_to_string(state: kb_lib::KbConnectionState) -> std::string::String {
|
||||
match state {
|
||||
kb_lib::KbConnectionState::Disconnected => "Disconnected".to_string(),
|
||||
kb_lib::KbConnectionState::Connecting => "Connecting".to_string(),
|
||||
kb_lib::KbConnectionState::Connected => "Connected".to_string(),
|
||||
kb_lib::KbConnectionState::Disconnecting => "Disconnecting".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_format_ws_event(event: &kb_lib::WsEvent) -> std::string::String {
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected {
|
||||
endpoint_name,
|
||||
endpoint_url,
|
||||
} => {
|
||||
format!("[ws:{endpoint_name}] connected to {endpoint_url}")
|
||||
}
|
||||
kb_lib::WsEvent::TextMessage {
|
||||
endpoint_name,
|
||||
text,
|
||||
} => {
|
||||
format!("[ws:{endpoint_name}] text: {text}")
|
||||
}
|
||||
kb_lib::WsEvent::JsonRpcMessage {
|
||||
endpoint_name,
|
||||
message,
|
||||
} => match message {
|
||||
kb_lib::KbJsonRpcWsIncomingMessage::SuccessResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc success id={} result={}",
|
||||
response.id, response.result
|
||||
)
|
||||
}
|
||||
kb_lib::KbJsonRpcWsIncomingMessage::ErrorResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc error id={} code={} message={}",
|
||||
response.id, response.error.code, response.error.message
|
||||
)
|
||||
}
|
||||
kb_lib::KbJsonRpcWsIncomingMessage::Notification(notification) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc notification method={} subscription={} result={}",
|
||||
notification.method,
|
||||
notification.params.subscription,
|
||||
notification.params.result
|
||||
)
|
||||
}
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcParseError {
|
||||
endpoint_name,
|
||||
text,
|
||||
error,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc parse error: {} | raw={}",
|
||||
error, text
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::SubscriptionRegistered {
|
||||
endpoint_name,
|
||||
subscription,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription registered subscribe_method={} unsubscribe_method={} notification_method={} request_id={} subscription_id={}",
|
||||
subscription.subscribe_method,
|
||||
subscription.unsubscribe_method,
|
||||
subscription.notification_method,
|
||||
subscription.request_id,
|
||||
subscription.subscription_id
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::SubscriptionNotification {
|
||||
endpoint_name,
|
||||
subscription,
|
||||
notification,
|
||||
method_matches_registry,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] tracked notification subscription_id={} method={} expected={} matches={} result={}",
|
||||
subscription.subscription_id,
|
||||
notification.method,
|
||||
subscription.notification_method,
|
||||
method_matches_registry,
|
||||
notification.params.result
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::JsonRpcNotificationWithoutSubscription {
|
||||
endpoint_name,
|
||||
notification,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] untracked notification method={} subscription={} result={}",
|
||||
notification.method, notification.params.subscription, notification.params.result
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::SubscriptionUnregistered {
|
||||
endpoint_name,
|
||||
subscription_id,
|
||||
unsubscribe_method,
|
||||
was_active,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription unregistered subscription_id={} unsubscribe_method={} was_active={}",
|
||||
subscription_id, unsubscribe_method, was_active
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::BinaryMessage {
|
||||
endpoint_name,
|
||||
data,
|
||||
} => {
|
||||
format!("[{endpoint_name}] binary ({} bytes)", data.len())
|
||||
}
|
||||
kb_lib::WsEvent::Ping {
|
||||
endpoint_name,
|
||||
data,
|
||||
} => {
|
||||
format!("[{endpoint_name}] ping ({} bytes)", data.len())
|
||||
}
|
||||
kb_lib::WsEvent::Pong {
|
||||
endpoint_name,
|
||||
data,
|
||||
} => {
|
||||
format!("[{endpoint_name}] pong ({} bytes)", data.len())
|
||||
}
|
||||
kb_lib::WsEvent::CloseReceived {
|
||||
endpoint_name,
|
||||
code,
|
||||
reason,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] close received code={:?} reason={:?}",
|
||||
code, reason
|
||||
)
|
||||
}
|
||||
kb_lib::WsEvent::Disconnected { endpoint_name } => {
|
||||
format!("[ws:{endpoint_name}] disconnected")
|
||||
}
|
||||
kb_lib::WsEvent::Error {
|
||||
endpoint_name,
|
||||
error,
|
||||
} => {
|
||||
format!("[ws:{endpoint_name}] error: {error}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_build_action_result(
|
||||
action: &str,
|
||||
target: &str,
|
||||
matched_count: usize,
|
||||
changed_count: usize,
|
||||
) -> DemoWsManagerActionResult {
|
||||
let unchanged_count = matched_count.saturating_sub(changed_count);
|
||||
DemoWsManagerActionResult {
|
||||
action: action.to_string(),
|
||||
target: target.to_string(),
|
||||
matched_count,
|
||||
changed_count,
|
||||
unchanged_count,
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_action_past_tense(action: &str) -> &'static str {
|
||||
match action {
|
||||
"start" => "started",
|
||||
"stop" => "stopped",
|
||||
_ => "processed",
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_format_action_result_for_log(result: &DemoWsManagerActionResult) -> std::string::String {
|
||||
let is_all = result.target == "all";
|
||||
let past = kb_action_past_tense(result.action.as_str());
|
||||
if result.matched_count == 0 {
|
||||
if is_all {
|
||||
return "[ui] no managed websocket endpoint is configured".to_string();
|
||||
}
|
||||
return format!(
|
||||
"[ui] no managed websocket endpoint matches role '{}'",
|
||||
result.target
|
||||
);
|
||||
}
|
||||
if result.changed_count == 0 {
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] all managed websocket endpoints were already {}",
|
||||
if result.action == "start" {
|
||||
"started"
|
||||
} else {
|
||||
"stopped"
|
||||
}
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"[ui] role '{}' was already {} on {} endpoint(s)",
|
||||
result.target,
|
||||
if result.action == "start" {
|
||||
"started"
|
||||
} else {
|
||||
"stopped"
|
||||
},
|
||||
result.unchanged_count
|
||||
);
|
||||
}
|
||||
if result.unchanged_count == 0 {
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] {}ed {} managed websocket endpoint(s)",
|
||||
past, result.changed_count
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"[ui] {}ed role '{}' on {} endpoint(s)",
|
||||
past, result.target, result.changed_count
|
||||
);
|
||||
}
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] {}ed {} managed websocket endpoint(s); {} already {}",
|
||||
past,
|
||||
result.changed_count,
|
||||
result.unchanged_count,
|
||||
if result.action == "start" {
|
||||
"started"
|
||||
} else {
|
||||
"stopped"
|
||||
}
|
||||
);
|
||||
}
|
||||
format!(
|
||||
"[ui] {}ed role '{}' on {} endpoint(s); {} already {}",
|
||||
result.action,
|
||||
result.target,
|
||||
result.changed_count,
|
||||
result.unchanged_count,
|
||||
if result.action == "start" {
|
||||
"started"
|
||||
} else {
|
||||
"stopped"
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -9,9 +9,12 @@
|
||||
#![deny(unreachable_pub)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod demo_http;
|
||||
mod demo_ws;
|
||||
mod demo_ws_manager;
|
||||
mod splash;
|
||||
|
||||
pub use crate::splash::SplashOrder;
|
||||
pub use splash::SplashOrder;
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
@@ -34,6 +37,10 @@ impl KbWsRuntimeState {
|
||||
struct KbAppState {
|
||||
config: kb_lib::KbConfig,
|
||||
ws_runtime: tokio::sync::Mutex<KbWsRuntimeState>,
|
||||
demo_ws_runtime: std::sync::Arc<tokio::sync::Mutex<crate::demo_ws::KbDemoWsRuntimeState>>,
|
||||
demo_ws_manager_runtime: std::sync::Arc<tokio::sync::Mutex<crate::demo_ws_manager::KbDemoWsManagerRuntimeState>>,
|
||||
ws_manager: std::sync::Arc<kb_lib::WsManager>,
|
||||
http_pool: kb_lib::HttpEndpointPool,
|
||||
}
|
||||
|
||||
/// Runs the desktop application.
|
||||
@@ -70,15 +77,58 @@ pub fn run() {
|
||||
environment = %config.app.environment,
|
||||
"starting desktop application"
|
||||
);
|
||||
let http_pool_result = kb_lib::HttpEndpointPool::from_config(&config);
|
||||
let http_pool = match http_pool_result {
|
||||
Ok(http_pool) => http_pool,
|
||||
Err(error) => {
|
||||
tracing::error!("cannot create http endpoint pool: {}", error);
|
||||
panic!("cannot create http endpoint pool: {}", error);
|
||||
}
|
||||
};
|
||||
let ws_manager_result = kb_lib::WsManager::from_config(&config);
|
||||
let ws_manager = match ws_manager_result {
|
||||
Ok(ws_manager) => ws_manager,
|
||||
Err(error) => {
|
||||
tracing::error!("cannot create websocket manager: {}", error);
|
||||
panic!("cannot create websocket manager: {}", error);
|
||||
}
|
||||
};
|
||||
let app_state = KbAppState {
|
||||
config: config.clone(),
|
||||
ws_runtime: tokio::sync::Mutex::new(KbWsRuntimeState::new()),
|
||||
demo_ws_runtime: std::sync::Arc::new(tokio::sync::Mutex::new(
|
||||
crate::demo_ws::KbDemoWsRuntimeState::new(),
|
||||
)),
|
||||
demo_ws_manager_runtime: std::sync::Arc::new(tokio::sync::Mutex::new(
|
||||
crate::demo_ws_manager::KbDemoWsManagerRuntimeState::new(),
|
||||
)),
|
||||
ws_manager: std::sync::Arc::new(ws_manager),
|
||||
http_pool,
|
||||
};
|
||||
let tracing_builder = tauri_plugin_tracing::Builder::new();
|
||||
let mut tauri_builder = tauri::Builder::default();
|
||||
tauri_builder = tauri_builder.manage(app_state);
|
||||
tauri_builder =
|
||||
tauri_builder.invoke_handler(tauri::generate_handler![start_ws_clients, stop_ws_clients]);
|
||||
tauri_builder = tauri_builder.invoke_handler(tauri::generate_handler![
|
||||
start_ws_clients,
|
||||
stop_ws_clients,
|
||||
crate::demo_ws::open_demo_ws_window,
|
||||
crate::demo_ws::demo_ws_list_endpoints,
|
||||
crate::demo_ws::demo_ws_get_status,
|
||||
crate::demo_ws::demo_ws_connect,
|
||||
crate::demo_ws::demo_ws_disconnect,
|
||||
crate::demo_ws::demo_ws_subscribe,
|
||||
crate::demo_ws::demo_ws_unsubscribe_current,
|
||||
crate::demo_http::open_demo_http_window,
|
||||
crate::demo_http::demo_http_list_pool_clients,
|
||||
crate::demo_http::demo_http_execute_request,
|
||||
crate::demo_ws_manager::open_demo_ws_manager_window,
|
||||
crate::demo_ws_manager::demo_ws_manager_get_snapshot,
|
||||
crate::demo_ws_manager::demo_ws_manager_list_roles,
|
||||
crate::demo_ws_manager::demo_ws_manager_start_all,
|
||||
crate::demo_ws_manager::demo_ws_manager_stop_all,
|
||||
crate::demo_ws_manager::demo_ws_manager_start_role,
|
||||
crate::demo_ws_manager::demo_ws_manager_stop_role,
|
||||
]);
|
||||
tauri_builder = tauri_builder.plugin(tracing_builder.build::<tauri::Wry>());
|
||||
tauri_builder = tauri_builder.setup(|app| {
|
||||
let app_handle = app.handle().clone();
|
||||
@@ -133,7 +183,7 @@ pub fn run() {
|
||||
emit_splash_order(&splash_window, "fadeout", None, None);
|
||||
tracing::debug!("end splash fadeout");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(3100)).await;
|
||||
let close_result = splash_window.close();
|
||||
let close_result = splash_window.destroy();
|
||||
if let Err(error) = close_result {
|
||||
tracing::error!("error closing splash window: {error:?}");
|
||||
}
|
||||
@@ -337,13 +387,13 @@ fn kb_format_ws_event(event: &kb_lib::WsEvent) -> std::string::String {
|
||||
endpoint_url,
|
||||
} => {
|
||||
format!("[ws:{endpoint_name}] connected to {endpoint_url}")
|
||||
},
|
||||
}
|
||||
kb_lib::WsEvent::TextMessage {
|
||||
endpoint_name,
|
||||
text,
|
||||
} => {
|
||||
format!("[ws:{endpoint_name}] text: {text}")
|
||||
},
|
||||
}
|
||||
kb_lib::WsEvent::JsonRpcMessage {
|
||||
endpoint_name,
|
||||
message,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "kb-bapp",
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.6",
|
||||
"identifier": "com.sasedev.kb-app",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
@@ -36,6 +36,48 @@
|
||||
"visible": false,
|
||||
"transparent": false,
|
||||
"decorations": true
|
||||
},
|
||||
{
|
||||
"label": "demo_ws",
|
||||
"url": "demo_ws.html",
|
||||
"title": "Demo Ws Subscribe",
|
||||
"width": 1400,
|
||||
"height": 768,
|
||||
"minWidth": 800,
|
||||
"minHeight": 600,
|
||||
"center": true,
|
||||
"visible": false,
|
||||
"create": false,
|
||||
"transparent": false,
|
||||
"decorations": true
|
||||
},
|
||||
{
|
||||
"label": "demo_http",
|
||||
"url": "demo_http.html",
|
||||
"title": "Demo Http",
|
||||
"width": 1100,
|
||||
"height": 820,
|
||||
"minWidth": 860,
|
||||
"minHeight": 620,
|
||||
"center": true,
|
||||
"visible": false,
|
||||
"create": false,
|
||||
"transparent": false,
|
||||
"decorations": true
|
||||
},
|
||||
{
|
||||
"label": "demo_ws_manager",
|
||||
"url": "demo_ws_manager.html",
|
||||
"title": "Demo Ws Manager",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"minWidth": 900,
|
||||
"minHeight": 620,
|
||||
"center": true,
|
||||
"visible": false,
|
||||
"create": false,
|
||||
"transparent": false,
|
||||
"decorations": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
@@ -50,4 +92,4 @@
|
||||
"icons/favicon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,9 @@ export default defineConfig(() => ({
|
||||
emptyOutDir: true,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
"main": normalizePath(resolve(__dirname, 'frontend/index.html'))
|
||||
"main": normalizePath(resolve(__dirname, 'frontend/main.html')),
|
||||
"splash": normalizePath(resolve(__dirname, 'frontend/splash.html')),
|
||||
"demo_ws": normalizePath(resolve(__dirname, 'frontend/demo_ws.html'))
|
||||
},
|
||||
output: {
|
||||
entryFileNames: 'js/[name]-[hash].js',
|
||||
|
||||
@@ -9,38 +9,23 @@ authors.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait.workspace = true
|
||||
base64.workspace = true
|
||||
chrono.workspace = true
|
||||
futures-util.workspace = true
|
||||
reqwest.workspace = true
|
||||
rustls.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
solana-account-decoder-client-types.workspace = true
|
||||
solana-address-lookup-table-interface.workspace = true
|
||||
solana-client.workspace = true
|
||||
solana-compute-budget-interface.workspace = true
|
||||
solana-rpc-client-api.workspace = true
|
||||
solana-rpc-client-types.workspace = true
|
||||
solana-sdk.workspace = true
|
||||
solana-sdk-ids.workspace = true
|
||||
solana-system-interface.workspace = true
|
||||
solana-transaction-status-client-types.workspace = true
|
||||
spl-associated-token-account-interface.workspace = true
|
||||
spl-memo-interface.workspace = true
|
||||
spl-token-2022-interface.workspace = true
|
||||
spl-token-interface.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-appender.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
yellowstone-grpc-client.workspace = true
|
||||
yellowstone-grpc-proto.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -13,6 +13,8 @@ pub struct KbConfig {
|
||||
pub data: KbDataConfig,
|
||||
/// Solana endpoint configuration.
|
||||
pub solana: KbSolanaConfig,
|
||||
/// Database configuration.
|
||||
pub database: KbDatabaseConfig,
|
||||
}
|
||||
|
||||
impl KbConfig {
|
||||
@@ -166,7 +168,7 @@ impl KbConfig {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a named HTTP endpoint by reference.
|
||||
/// Finds one HTTP endpoint by its logical name.
|
||||
pub fn find_http_endpoint(
|
||||
&self,
|
||||
endpoint_name: &str,
|
||||
@@ -216,9 +218,9 @@ impl KbConfig {
|
||||
endpoint.name
|
||||
)));
|
||||
}
|
||||
if endpoint.burst == 0 {
|
||||
if endpoint.burst_capacity == 0 {
|
||||
return Err(crate::KbError::Config(format!(
|
||||
"http endpoint '{}' burst must be > 0",
|
||||
"http endpoint '{}' burst_capacity must be > 0",
|
||||
endpoint.name
|
||||
)));
|
||||
}
|
||||
@@ -384,33 +386,70 @@ pub struct KbSolanaConfig {
|
||||
|
||||
/// HTTP endpoint configuration.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KbHttpEndpointConfig {
|
||||
/// Stable internal endpoint name used by the application.
|
||||
/// Logical endpoint name.
|
||||
pub name: std::string::String,
|
||||
/// Enables or disables the endpoint.
|
||||
/// Whether this endpoint is enabled.
|
||||
pub enabled: bool,
|
||||
/// Provider name such as `solana-public`, `helius`, or `custom`.
|
||||
/// Provider name.
|
||||
pub provider: std::string::String,
|
||||
/// Base HTTP RPC URL.
|
||||
/// Base HTTP URL.
|
||||
pub url: std::string::String,
|
||||
/// Optional environment variable name used to resolve an API key later.
|
||||
/// Optional environment variable name containing an API key.
|
||||
pub api_key_env_var: std::option::Option<std::string::String>,
|
||||
/// Logical roles assigned to this endpoint.
|
||||
/// Allowed roles for this endpoint.
|
||||
pub roles: std::vec::Vec<std::string::String>,
|
||||
/// Allowed average request rate.
|
||||
/// Requests per second allowed by the local limiter for general RPC methods.
|
||||
pub requests_per_second: u32,
|
||||
/// Burst capacity for future rate-limiting.
|
||||
pub burst: u32,
|
||||
/// HTTP connect timeout in milliseconds.
|
||||
/// Maximum local burst capacity for general RPC methods.
|
||||
pub burst_capacity: u32,
|
||||
/// Optional requests per second override for `sendTransaction`-class methods.
|
||||
pub send_transaction_requests_per_second: std::option::Option<u32>,
|
||||
/// Optional burst override for `sendTransaction`-class methods.
|
||||
pub send_transaction_burst_capacity: std::option::Option<u32>,
|
||||
/// Optional requests per second override for heavy read methods.
|
||||
pub heavy_requests_per_second: std::option::Option<u32>,
|
||||
/// Optional burst override for heavy read methods.
|
||||
pub heavy_burst_capacity: std::option::Option<u32>,
|
||||
/// Connect timeout in milliseconds.
|
||||
pub connect_timeout_ms: u64,
|
||||
/// HTTP request timeout in milliseconds.
|
||||
/// Total request timeout in milliseconds.
|
||||
pub request_timeout_ms: u64,
|
||||
/// Maximum idle pooled connections per host.
|
||||
pub max_idle_connections_per_host: usize,
|
||||
/// Automatic pause duration after an HTTP 429 response, in milliseconds.
|
||||
pub pause_after_http_429_ms: std::option::Option<u64>,
|
||||
/// Maximum number of concurrent in-flight HTTP requests for this endpoint.
|
||||
pub max_concurrent_requests_per_endpoint: usize,
|
||||
}
|
||||
|
||||
impl KbHttpEndpointConfig {
|
||||
/// Returns the resolved endpoint URL.
|
||||
/// Returns the resolved URL, replacing an `${ENV_VAR}` placeholder when
|
||||
/// `api_key_env_var` is configured.
|
||||
pub fn resolved_url(&self) -> Result<std::string::String, crate::KbError> {
|
||||
kb_resolve_endpoint_url(&self.url, &self.api_key_env_var)
|
||||
let env_var_name_option = self.api_key_env_var.as_ref();
|
||||
let env_var_name = match env_var_name_option {
|
||||
Some(env_var_name) => env_var_name,
|
||||
None => {
|
||||
return Ok(self.url.clone());
|
||||
}
|
||||
};
|
||||
let api_key_result = std::env::var(env_var_name);
|
||||
let api_key = match api_key_result {
|
||||
Ok(api_key) => api_key,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Config(format!(
|
||||
"cannot resolve api key env var '{}' for http endpoint '{}': {}",
|
||||
env_var_name, self.name, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let placeholder = format!("${{{}}}", env_var_name);
|
||||
if self.url.contains(&placeholder) {
|
||||
return Ok(self.url.replace(&placeholder, &api_key));
|
||||
}
|
||||
Ok(self.url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,6 +491,36 @@ impl KbWsEndpointConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// SQLite configuration.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KbSqliteDatabaseConfig {
|
||||
/// SQLite database path.
|
||||
pub path: std::string::String,
|
||||
/// Whether the file should be created if missing.
|
||||
pub create_if_missing: bool,
|
||||
/// SQLite busy timeout in milliseconds.
|
||||
pub busy_timeout_ms: u64,
|
||||
/// Maximum pool connections.
|
||||
pub max_connections: u32,
|
||||
/// Whether the schema should be initialized automatically at startup.
|
||||
pub auto_initialize_schema: bool,
|
||||
/// Whether WAL journal mode should be enabled.
|
||||
pub use_wal: bool,
|
||||
}
|
||||
|
||||
/// Database configuration.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KbDatabaseConfig {
|
||||
/// Whether the database layer is enabled.
|
||||
pub enabled: bool,
|
||||
/// Selected backend.
|
||||
pub backend: crate::KbDatabaseBackend,
|
||||
/// SQLite-specific configuration.
|
||||
pub sqlite: KbSqliteDatabaseConfig,
|
||||
}
|
||||
|
||||
fn kb_workspace_root_dir() -> std::path::PathBuf {
|
||||
let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
match manifest_dir.parent() {
|
||||
|
||||
180
kb_lib/src/db.rs
Normal file
180
kb_lib/src/db.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
// file: kb_lib/src/db.rs
|
||||
|
||||
//! Database facade.
|
||||
//!
|
||||
//! This module centralizes the database layer and exposes a storage API that is
|
||||
//! intentionally structured to remain evolutive across backends.
|
||||
|
||||
mod connection;
|
||||
mod dtos;
|
||||
mod entities;
|
||||
mod queries;
|
||||
mod schema;
|
||||
mod sqlite;
|
||||
mod types;
|
||||
|
||||
pub use connection::KbDatabase;
|
||||
pub use connection::KbDatabaseConnection;
|
||||
pub use dtos::KbAnalysisSignalDto;
|
||||
pub use dtos::KbChainInstructionDto;
|
||||
pub use dtos::KbChainSlotDto;
|
||||
pub use dtos::KbChainTransactionDto;
|
||||
pub use dtos::KbDbMetadataDto;
|
||||
pub use dtos::KbDbRuntimeEventDto;
|
||||
pub use dtos::KbDexDecodedEventDto;
|
||||
pub use dtos::KbDexDto;
|
||||
pub use dtos::KbKnownHttpEndpointDto;
|
||||
pub use dtos::KbKnownWsEndpointDto;
|
||||
pub use dtos::KbLaunchAttributionDto;
|
||||
pub use dtos::KbLaunchSurfaceDto;
|
||||
pub use dtos::KbLaunchSurfaceKeyDto;
|
||||
pub use dtos::KbLiquidityEventDto;
|
||||
pub use dtos::KbObservedTokenDto;
|
||||
pub use dtos::KbOnchainObservationDto;
|
||||
pub use dtos::KbPairAnalyticSignalDto;
|
||||
pub use dtos::KbPairCandleDto;
|
||||
pub use dtos::KbPairDto;
|
||||
pub use dtos::KbPairMetricDto;
|
||||
pub use dtos::KbPoolDto;
|
||||
pub use dtos::KbPoolListingDto;
|
||||
pub use dtos::KbPoolOriginDto;
|
||||
pub use dtos::KbPoolTokenDto;
|
||||
pub use dtos::KbSwapDto;
|
||||
pub use dtos::KbTokenBurnEventDto;
|
||||
pub use dtos::KbTokenDto;
|
||||
pub use dtos::KbTokenMintEventDto;
|
||||
pub use dtos::KbTradeEventDto;
|
||||
pub use dtos::KbWalletDto;
|
||||
pub use dtos::KbWalletHoldingDto;
|
||||
pub use dtos::KbWalletParticipationDto;
|
||||
pub use entities::KbAnalysisSignalEntity;
|
||||
pub use entities::KbChainInstructionEntity;
|
||||
pub use entities::KbChainSlotEntity;
|
||||
pub use entities::KbChainTransactionEntity;
|
||||
pub use entities::KbDbMetadataEntity;
|
||||
pub use entities::KbDbRuntimeEventEntity;
|
||||
pub use entities::KbDexDecodedEventEntity;
|
||||
pub use entities::KbDexEntity;
|
||||
pub use entities::KbKnownHttpEndpointEntity;
|
||||
pub use entities::KbKnownWsEndpointEntity;
|
||||
pub use entities::KbLaunchAttributionEntity;
|
||||
pub use entities::KbLaunchSurfaceEntity;
|
||||
pub use entities::KbLaunchSurfaceKeyEntity;
|
||||
pub use entities::KbLiquidityEventEntity;
|
||||
pub use entities::KbObservedTokenEntity;
|
||||
pub use entities::KbOnchainObservationEntity;
|
||||
pub use entities::KbPairAnalyticSignalEntity;
|
||||
pub use entities::KbPairCandleEntity;
|
||||
pub use entities::KbPairEntity;
|
||||
pub use entities::KbPairMetricEntity;
|
||||
pub use entities::KbPoolEntity;
|
||||
pub use entities::KbPoolListingEntity;
|
||||
pub use entities::KbPoolOriginEntity;
|
||||
pub use entities::KbPoolTokenEntity;
|
||||
pub use entities::KbSwapEntity;
|
||||
pub use entities::KbTokenBurnEventEntity;
|
||||
pub use entities::KbTokenEntity;
|
||||
pub use entities::KbTokenMintEventEntity;
|
||||
pub use entities::KbTradeEventEntity;
|
||||
pub use entities::KbWalletEntity;
|
||||
pub use entities::KbWalletHoldingEntity;
|
||||
pub use entities::KbWalletParticipationEntity;
|
||||
pub use queries::delete_chain_instructions_by_transaction_id;
|
||||
pub use queries::get_chain_slot;
|
||||
pub use queries::get_chain_transaction_by_signature;
|
||||
pub use queries::get_db_metadata;
|
||||
pub use queries::get_dex_by_code;
|
||||
pub use queries::get_dex_decoded_event_by_key;
|
||||
pub use queries::get_known_http_endpoint;
|
||||
pub use queries::get_known_ws_endpoint;
|
||||
pub use queries::get_launch_attribution_by_decoded_event_id;
|
||||
pub use queries::get_launch_surface_by_code;
|
||||
pub use queries::get_launch_surface_key_by_match;
|
||||
pub use queries::get_observed_token_by_mint;
|
||||
pub use queries::get_pair_analytic_signal_by_key;
|
||||
pub use queries::get_pair_by_pool_id;
|
||||
pub use queries::get_pair_candle_by_key;
|
||||
pub use queries::get_pair_metric_by_pair_id;
|
||||
pub use queries::get_pool_by_address;
|
||||
pub use queries::get_pool_listing_by_pool_id;
|
||||
pub use queries::get_pool_origin_by_pool_id;
|
||||
pub use queries::get_token_by_mint;
|
||||
pub use queries::get_trade_event_by_decoded_event_id;
|
||||
pub use queries::get_wallet_by_address;
|
||||
pub use queries::get_wallet_holding_by_wallet_and_token;
|
||||
pub use queries::get_wallet_participation_by_unique_key;
|
||||
pub use queries::insert_analysis_signal;
|
||||
pub use queries::insert_chain_instruction;
|
||||
pub use queries::insert_db_runtime_event;
|
||||
pub use queries::insert_onchain_observation;
|
||||
pub use queries::list_chain_instructions_by_transaction_id;
|
||||
pub use queries::list_db_metadata;
|
||||
pub use queries::list_dex_decoded_events_by_transaction_id;
|
||||
pub use queries::list_dexes;
|
||||
pub use queries::list_known_http_endpoints;
|
||||
pub use queries::list_known_ws_endpoints;
|
||||
pub use queries::list_launch_attributions_by_pool_id;
|
||||
pub use queries::list_launch_surface_keys_by_surface_id;
|
||||
pub use queries::list_launch_surfaces;
|
||||
pub use queries::list_observed_tokens;
|
||||
pub use queries::list_pair_analytic_signals_by_pair_id;
|
||||
pub use queries::list_pair_candles_by_pair_and_timeframe;
|
||||
pub use queries::list_pair_metrics;
|
||||
pub use queries::list_pairs;
|
||||
pub use queries::list_pool_listings;
|
||||
pub use queries::list_pool_origins;
|
||||
pub use queries::list_pool_tokens_by_pool_id;
|
||||
pub use queries::list_pools;
|
||||
pub use queries::list_recent_analysis_signals;
|
||||
pub use queries::list_recent_chain_slots;
|
||||
pub use queries::list_recent_chain_transactions;
|
||||
pub use queries::list_recent_db_runtime_events;
|
||||
pub use queries::list_recent_liquidity_events;
|
||||
pub use queries::list_recent_onchain_observations;
|
||||
pub use queries::list_recent_swaps;
|
||||
pub use queries::list_recent_token_burn_events;
|
||||
pub use queries::list_recent_token_mint_events;
|
||||
pub use queries::list_trade_events_by_pair_id;
|
||||
pub use queries::list_trade_events_by_transaction_id;
|
||||
pub use queries::list_wallet_holdings_by_wallet_id;
|
||||
pub use queries::list_wallet_participations_by_pool_id;
|
||||
pub use queries::list_wallet_participations_by_wallet_id;
|
||||
pub use queries::list_wallets;
|
||||
pub use queries::upsert_chain_slot;
|
||||
pub use queries::upsert_chain_transaction;
|
||||
pub use queries::upsert_db_metadata;
|
||||
pub use queries::upsert_dex;
|
||||
pub use queries::upsert_dex_decoded_event;
|
||||
pub use queries::upsert_known_http_endpoint;
|
||||
pub use queries::upsert_known_ws_endpoint;
|
||||
pub use queries::upsert_launch_attribution;
|
||||
pub use queries::upsert_launch_surface;
|
||||
pub use queries::upsert_launch_surface_key;
|
||||
pub use queries::upsert_liquidity_event;
|
||||
pub use queries::upsert_observed_token;
|
||||
pub use queries::upsert_pair;
|
||||
pub use queries::upsert_pair_analytic_signal;
|
||||
pub use queries::upsert_pair_candle;
|
||||
pub use queries::upsert_pair_metric;
|
||||
pub use queries::upsert_pool;
|
||||
pub use queries::upsert_pool_listing;
|
||||
pub use queries::upsert_pool_origin;
|
||||
pub use queries::upsert_pool_token;
|
||||
pub use queries::upsert_swap;
|
||||
pub use queries::upsert_token;
|
||||
pub use queries::upsert_token_burn_event;
|
||||
pub use queries::upsert_token_mint_event;
|
||||
pub use queries::upsert_trade_event;
|
||||
pub use queries::upsert_wallet;
|
||||
pub use queries::upsert_wallet_holding;
|
||||
pub use queries::upsert_wallet_participation;
|
||||
pub use types::KbAnalysisSignalSeverity;
|
||||
pub use types::KbDatabaseBackend;
|
||||
pub use types::KbDbRuntimeEventLevel;
|
||||
pub use types::KbLiquidityEventKind;
|
||||
pub use types::KbObservationSourceKind;
|
||||
pub use types::KbObservedTokenStatus;
|
||||
pub use types::KbPoolKind;
|
||||
pub use types::KbPoolStatus;
|
||||
pub use types::KbPoolTokenRole;
|
||||
pub use types::KbSwapTradeSide;
|
||||
140
kb_lib/src/db/connection.rs
Normal file
140
kb_lib/src/db/connection.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
// file: kb_lib/src/db/connection.rs
|
||||
|
||||
//! Database connection facade.
|
||||
|
||||
/// Concrete database connection.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum KbDatabaseConnection {
|
||||
/// SQLite connection pool.
|
||||
Sqlite(sqlx::SqlitePool),
|
||||
}
|
||||
|
||||
/// Database facade.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KbDatabase {
|
||||
backend: crate::KbDatabaseBackend,
|
||||
database_url: std::string::String,
|
||||
connection: KbDatabaseConnection,
|
||||
}
|
||||
|
||||
impl KbDatabase {
|
||||
/// Opens a database connection without initializing the schema.
|
||||
pub async fn connect(
|
||||
config: &crate::KbDatabaseConfig,
|
||||
) -> Result<Self, crate::KbError> {
|
||||
if !config.enabled {
|
||||
return Err(crate::KbError::Config(
|
||||
"database is disabled in configuration".to_string(),
|
||||
));
|
||||
}
|
||||
match config.backend {
|
||||
crate::KbDatabaseBackend::Sqlite => {
|
||||
let database_url_result =
|
||||
crate::db::sqlite::sqlite_database_url_from_config(config);
|
||||
let database_url = match database_url_result {
|
||||
Ok(database_url) => database_url,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let pool_result = crate::db::sqlite::connect_sqlite(config).await;
|
||||
let pool = match pool_result {
|
||||
Ok(pool) => pool,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(Self {
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
database_url,
|
||||
connection: KbDatabaseConnection::Sqlite(pool),
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a database connection and initializes the schema if configured.
|
||||
pub async fn connect_and_initialize(
|
||||
config: &crate::KbDatabaseConfig,
|
||||
) -> Result<Self, crate::KbError> {
|
||||
let connect_result = Self::connect(config).await;
|
||||
let database = match connect_result {
|
||||
Ok(database) => database,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if config.sqlite.auto_initialize_schema {
|
||||
let init_result = crate::db::schema::ensure_schema(&database).await;
|
||||
if let Err(error) = init_result {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(database)
|
||||
}
|
||||
|
||||
/// Returns the configured backend.
|
||||
pub fn backend(
|
||||
&self,
|
||||
) -> crate::KbDatabaseBackend {
|
||||
self.backend
|
||||
}
|
||||
|
||||
/// Returns a displayable database URL-like string.
|
||||
pub fn database_url(
|
||||
&self,
|
||||
) -> &str {
|
||||
&self.database_url
|
||||
}
|
||||
|
||||
/// Pings the database.
|
||||
pub async fn ping(
|
||||
&self,
|
||||
) -> Result<(), crate::KbError> {
|
||||
match &self.connection {
|
||||
KbDatabaseConnection::Sqlite(pool) => {
|
||||
let ping_result = sqlx::query("SELECT 1").execute(pool).await;
|
||||
match ping_result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) => Err(crate::KbError::Db(format!(
|
||||
"cannot ping sqlite database '{}': {}",
|
||||
self.database_url,
|
||||
error
|
||||
))),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the underlying connection enum.
|
||||
pub(crate) fn connection(
|
||||
&self,
|
||||
) -> &KbDatabaseConnection {
|
||||
&self.connection
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[tokio::test]
|
||||
async fn connect_and_ping_sqlite_database_works() {
|
||||
let tempdir = tempfile::tempdir().expect("tempdir must succeed");
|
||||
let database_path = tempdir.path().join("connection.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
let database = crate::KbDatabase::connect_and_initialize(&config)
|
||||
.await
|
||||
.expect("database init must succeed");
|
||||
assert_eq!(database.backend(), crate::KbDatabaseBackend::Sqlite);
|
||||
assert!(database.database_url().starts_with("sqlite://"));
|
||||
database.ping().await.expect("ping must succeed");
|
||||
let metadata = crate::get_db_metadata(&database, "schema_version")
|
||||
.await
|
||||
.expect("metadata fetch must succeed");
|
||||
assert!(metadata.is_some());
|
||||
}
|
||||
}
|
||||
69
kb_lib/src/db/dtos.rs
Normal file
69
kb_lib/src/db/dtos.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
// file: kb_lib/src/db/dtos.rs
|
||||
|
||||
//! Database data transfer objects.
|
||||
|
||||
mod analysis_signal;
|
||||
mod chain_instruction;
|
||||
mod chain_slot;
|
||||
mod chain_transaction;
|
||||
mod db_metadata;
|
||||
mod db_runtime_event;
|
||||
mod dex;
|
||||
mod dex_decoded_event;
|
||||
mod known_http_endpoint;
|
||||
mod known_ws_endpoint;
|
||||
mod launch_attribution;
|
||||
mod launch_surface;
|
||||
mod launch_surface_key;
|
||||
mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_analytic_signal;
|
||||
mod pair_candle;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
mod pool_token;
|
||||
mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_holding;
|
||||
mod wallet_participation;
|
||||
|
||||
pub use analysis_signal::KbAnalysisSignalDto;
|
||||
pub use chain_instruction::KbChainInstructionDto;
|
||||
pub use chain_slot::KbChainSlotDto;
|
||||
pub use chain_transaction::KbChainTransactionDto;
|
||||
pub use db_metadata::KbDbMetadataDto;
|
||||
pub use db_runtime_event::KbDbRuntimeEventDto;
|
||||
pub use dex::KbDexDto;
|
||||
pub use dex_decoded_event::KbDexDecodedEventDto;
|
||||
pub use known_http_endpoint::KbKnownHttpEndpointDto;
|
||||
pub use known_ws_endpoint::KbKnownWsEndpointDto;
|
||||
pub use launch_attribution::KbLaunchAttributionDto;
|
||||
pub use launch_surface::KbLaunchSurfaceDto;
|
||||
pub use launch_surface_key::KbLaunchSurfaceKeyDto;
|
||||
pub use liquidity_event::KbLiquidityEventDto;
|
||||
pub use observed_token::KbObservedTokenDto;
|
||||
pub use onchain_observation::KbOnchainObservationDto;
|
||||
pub use pair::KbPairDto;
|
||||
pub use pair_analytic_signal::KbPairAnalyticSignalDto;
|
||||
pub use pair_candle::KbPairCandleDto;
|
||||
pub use pair_metric::KbPairMetricDto;
|
||||
pub use pool::KbPoolDto;
|
||||
pub use pool_listing::KbPoolListingDto;
|
||||
pub use pool_origin::KbPoolOriginDto;
|
||||
pub use pool_token::KbPoolTokenDto;
|
||||
pub use swap::KbSwapDto;
|
||||
pub use token::KbTokenDto;
|
||||
pub use token_burn_event::KbTokenBurnEventDto;
|
||||
pub use token_mint_event::KbTokenMintEventDto;
|
||||
pub use trade_event::KbTradeEventDto;
|
||||
pub use wallet::KbWalletDto;
|
||||
pub use wallet_holding::KbWalletHoldingDto;
|
||||
pub use wallet_participation::KbWalletParticipationDto;
|
||||
89
kb_lib/src/db/dtos/analysis_signal.rs
Normal file
89
kb_lib/src/db/dtos/analysis_signal.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
// file: kb_lib/src/db/dtos/analysis_signal.rs
|
||||
|
||||
//! Analysis signal DTO.
|
||||
|
||||
/// Application-facing analysis signal DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbAnalysisSignalDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Signal kind.
|
||||
pub signal_kind: std::string::String,
|
||||
/// Signal severity.
|
||||
pub severity: crate::KbAnalysisSignalSeverity,
|
||||
/// Logical object key, for example a mint, signature or pool address.
|
||||
pub object_key: std::string::String,
|
||||
/// Optional related on-chain observation id.
|
||||
pub related_observation_id: std::option::Option<i64>,
|
||||
/// Optional numeric score.
|
||||
pub score: std::option::Option<f64>,
|
||||
/// Signal payload.
|
||||
pub payload: serde_json::Value,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbAnalysisSignalDto {
|
||||
/// Creates a new analysis signal DTO with the current timestamp.
|
||||
pub fn new(
|
||||
signal_kind: std::string::String,
|
||||
severity: crate::KbAnalysisSignalSeverity,
|
||||
object_key: std::string::String,
|
||||
related_observation_id: std::option::Option<i64>,
|
||||
score: std::option::Option<f64>,
|
||||
payload: serde_json::Value,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
signal_kind,
|
||||
severity,
|
||||
object_key,
|
||||
related_observation_id,
|
||||
score,
|
||||
payload,
|
||||
created_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbAnalysisSignalEntity> for KbAnalysisSignalDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbAnalysisSignalEntity) -> Result<Self, Self::Error> {
|
||||
let severity_result = crate::KbAnalysisSignalSeverity::from_i16(entity.severity);
|
||||
let severity = match severity_result {
|
||||
Ok(severity) => severity,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse analysis signal created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let payload_result = serde_json::from_str::<serde_json::Value>(&entity.payload_json);
|
||||
let payload = match payload_result {
|
||||
Ok(payload) => payload,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse analysis signal payload_json '{}': {}",
|
||||
entity.payload_json, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
signal_kind: entity.signal_kind,
|
||||
severity,
|
||||
object_key: entity.object_key,
|
||||
related_observation_id: entity.related_observation_id,
|
||||
score: entity.score,
|
||||
payload,
|
||||
created_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
140
kb_lib/src/db/dtos/chain_instruction.rs
Normal file
140
kb_lib/src/db/dtos/chain_instruction.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
// file: kb_lib/src/db/dtos/chain_instruction.rs
|
||||
|
||||
//! Application-facing normalized chain instruction DTO.
|
||||
|
||||
/// Application-facing normalized chain instruction DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbChainInstructionDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Parent transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional parent instruction id for inner instructions.
|
||||
pub parent_instruction_id: std::option::Option<i64>,
|
||||
/// Outer instruction index.
|
||||
pub instruction_index: u32,
|
||||
/// Optional inner instruction index.
|
||||
pub inner_instruction_index: std::option::Option<u32>,
|
||||
/// Optional program id.
|
||||
pub program_id: std::option::Option<std::string::String>,
|
||||
/// Optional program name.
|
||||
pub program_name: std::option::Option<std::string::String>,
|
||||
/// Optional stack height.
|
||||
pub stack_height: std::option::Option<u32>,
|
||||
/// Serialized accounts JSON array.
|
||||
pub accounts_json: std::string::String,
|
||||
/// Optional serialized data JSON.
|
||||
pub data_json: std::option::Option<std::string::String>,
|
||||
/// Optional parsed type.
|
||||
pub parsed_type: std::option::Option<std::string::String>,
|
||||
/// Optional serialized parsed JSON.
|
||||
pub parsed_json: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbChainInstructionDto {
|
||||
/// Creates a new chain instruction DTO.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
transaction_id: i64,
|
||||
parent_instruction_id: std::option::Option<i64>,
|
||||
instruction_index: u32,
|
||||
inner_instruction_index: std::option::Option<u32>,
|
||||
program_id: std::option::Option<std::string::String>,
|
||||
program_name: std::option::Option<std::string::String>,
|
||||
stack_height: std::option::Option<u32>,
|
||||
accounts_json: std::string::String,
|
||||
data_json: std::option::Option<std::string::String>,
|
||||
parsed_type: std::option::Option<std::string::String>,
|
||||
parsed_json: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
transaction_id,
|
||||
parent_instruction_id,
|
||||
instruction_index,
|
||||
inner_instruction_index,
|
||||
program_id,
|
||||
program_name,
|
||||
stack_height,
|
||||
accounts_json,
|
||||
data_json,
|
||||
parsed_type,
|
||||
parsed_json,
|
||||
created_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbChainInstructionEntity> for KbChainInstructionDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbChainInstructionEntity) -> Result<Self, Self::Error> {
|
||||
let instruction_index_result = u32::try_from(entity.instruction_index);
|
||||
let instruction_index = match instruction_index_result {
|
||||
Ok(instruction_index) => instruction_index,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain instruction instruction_index '{}' to u32: {}",
|
||||
entity.instruction_index, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let inner_instruction_index = match entity.inner_instruction_index {
|
||||
Some(inner_instruction_index) => {
|
||||
let inner_instruction_index_result = u32::try_from(inner_instruction_index);
|
||||
match inner_instruction_index_result {
|
||||
Ok(inner_instruction_index) => Some(inner_instruction_index),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain instruction inner_instruction_index '{}' to u32: {}",
|
||||
inner_instruction_index, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let stack_height = match entity.stack_height {
|
||||
Some(stack_height) => {
|
||||
let stack_height_result = u32::try_from(stack_height);
|
||||
match stack_height_result {
|
||||
Ok(stack_height) => Some(stack_height),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain instruction stack_height '{}' to u32: {}",
|
||||
stack_height, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse chain instruction created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
transaction_id: entity.transaction_id,
|
||||
parent_instruction_id: entity.parent_instruction_id,
|
||||
instruction_index,
|
||||
inner_instruction_index,
|
||||
program_id: entity.program_id,
|
||||
program_name: entity.program_name,
|
||||
stack_height,
|
||||
accounts_json: entity.accounts_json,
|
||||
data_json: entity.data_json,
|
||||
parsed_type: entity.parsed_type,
|
||||
parsed_json: entity.parsed_json,
|
||||
created_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
95
kb_lib/src/db/dtos/chain_slot.rs
Normal file
95
kb_lib/src/db/dtos/chain_slot.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
// file: kb_lib/src/db/dtos/chain_slot.rs
|
||||
|
||||
//! Application-facing normalized chain slot DTO.
|
||||
|
||||
/// Application-facing normalized chain slot DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbChainSlotDto {
|
||||
/// Slot number.
|
||||
pub slot: u64,
|
||||
/// Optional parent slot number.
|
||||
pub parent_slot: std::option::Option<u64>,
|
||||
/// Optional block time in unix seconds.
|
||||
pub block_time_unix: std::option::Option<i64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbChainSlotDto {
|
||||
/// Creates a new chain slot DTO.
|
||||
pub fn new(
|
||||
slot: u64,
|
||||
parent_slot: std::option::Option<u64>,
|
||||
block_time_unix: std::option::Option<i64>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
slot,
|
||||
parent_slot,
|
||||
block_time_unix,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbChainSlotEntity> for KbChainSlotDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbChainSlotEntity) -> Result<Self, Self::Error> {
|
||||
let slot_result = u64::try_from(entity.slot);
|
||||
let slot = match slot_result {
|
||||
Ok(slot) => slot,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain slot '{}' to u64: {}",
|
||||
entity.slot, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let parent_slot = match entity.parent_slot {
|
||||
Some(parent_slot) => {
|
||||
let parent_slot_result = u64::try_from(parent_slot);
|
||||
match parent_slot_result {
|
||||
Ok(parent_slot) => Some(parent_slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain parent_slot '{}' to u64: {}",
|
||||
parent_slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse chain slot created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse chain slot updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
slot,
|
||||
parent_slot,
|
||||
block_time_unix: entity.block_time_unix,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
115
kb_lib/src/db/dtos/chain_transaction.rs
Normal file
115
kb_lib/src/db/dtos/chain_transaction.rs
Normal file
@@ -0,0 +1,115 @@
|
||||
// file: kb_lib/src/db/dtos/chain_transaction.rs
|
||||
|
||||
//! Application-facing normalized chain transaction DTO.
|
||||
|
||||
/// Application-facing normalized chain transaction DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbChainTransactionDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Optional block time in unix seconds.
|
||||
pub block_time_unix: std::option::Option<i64>,
|
||||
/// Optional source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Optional version text.
|
||||
pub version_text: std::option::Option<std::string::String>,
|
||||
/// Optional serialized transaction error JSON.
|
||||
pub err_json: std::option::Option<std::string::String>,
|
||||
/// Optional serialized meta JSON.
|
||||
pub meta_json: std::option::Option<std::string::String>,
|
||||
/// Serialized full transaction JSON.
|
||||
pub transaction_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbChainTransactionDto {
|
||||
/// Creates a new chain transaction DTO.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
signature: std::string::String,
|
||||
slot: std::option::Option<u64>,
|
||||
block_time_unix: std::option::Option<i64>,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
version_text: std::option::Option<std::string::String>,
|
||||
err_json: std::option::Option<std::string::String>,
|
||||
meta_json: std::option::Option<std::string::String>,
|
||||
transaction_json: std::string::String,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
signature,
|
||||
slot,
|
||||
block_time_unix,
|
||||
source_endpoint_name,
|
||||
version_text,
|
||||
err_json,
|
||||
meta_json,
|
||||
transaction_json,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbChainTransactionEntity> for KbChainTransactionDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbChainTransactionEntity) -> Result<Self, Self::Error> {
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain transaction slot '{}' to u64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse chain transaction created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse chain transaction updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
signature: entity.signature,
|
||||
slot,
|
||||
block_time_unix: entity.block_time_unix,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
version_text: entity.version_text,
|
||||
err_json: entity.err_json,
|
||||
meta_json: entity.meta_json,
|
||||
transaction_json: entity.transaction_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
57
kb_lib/src/db/dtos/db_metadata.rs
Normal file
57
kb_lib/src/db/dtos/db_metadata.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
// file: kb_lib/src/db/dtos/db_metadata.rs
|
||||
|
||||
//! Metadata DTOs.
|
||||
|
||||
/// Metadata DTO used by the application layer.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbDbMetadataDto {
|
||||
/// Metadata key.
|
||||
pub key: std::string::String,
|
||||
/// Metadata value.
|
||||
pub value: std::string::String,
|
||||
/// Last update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbDbMetadataDto {
|
||||
/// Creates a new metadata DTO with the current UTC timestamp.
|
||||
pub fn new(key: std::string::String, value: std::string::String) -> Self {
|
||||
Self {
|
||||
key,
|
||||
value,
|
||||
updated_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbDbMetadataEntity> for KbDbMetadataDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbDbMetadataEntity) -> Result<Self, Self::Error> {
|
||||
let parsed_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let parsed = match parsed_result {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse db metadata timestamp '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
key: entity.key,
|
||||
value: entity.value,
|
||||
updated_at: parsed.with_timezone(&chrono::Utc),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<KbDbMetadataDto> for crate::KbDbMetadataEntity {
|
||||
fn from(dto: KbDbMetadataDto) -> Self {
|
||||
Self {
|
||||
key: dto.key,
|
||||
value: dto.value,
|
||||
updated_at: dto.updated_at.to_rfc3339(),
|
||||
}
|
||||
}
|
||||
}
|
||||
69
kb_lib/src/db/dtos/db_runtime_event.rs
Normal file
69
kb_lib/src/db/dtos/db_runtime_event.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
// file: kb_lib/src/db/dtos/db_runtime_event.rs
|
||||
|
||||
//! Runtime event DTO.
|
||||
|
||||
/// Application-facing runtime event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbDbRuntimeEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Event kind.
|
||||
pub event_kind: std::string::String,
|
||||
/// Severity level.
|
||||
pub level: crate::KbDbRuntimeEventLevel,
|
||||
/// Event source.
|
||||
pub source: std::string::String,
|
||||
/// Human-readable message.
|
||||
pub message: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbDbRuntimeEventDto {
|
||||
/// Creates a new runtime event DTO with the current creation timestamp.
|
||||
pub fn new(
|
||||
event_kind: std::string::String,
|
||||
level: crate::KbDbRuntimeEventLevel,
|
||||
source: std::string::String,
|
||||
message: std::string::String,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
event_kind,
|
||||
level,
|
||||
source,
|
||||
message,
|
||||
created_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbDbRuntimeEventEntity> for KbDbRuntimeEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbDbRuntimeEventEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse runtime event created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let level_result = crate::KbDbRuntimeEventLevel::from_i16(entity.level);
|
||||
let level = match level_result {
|
||||
Ok(level) => level,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
event_kind: entity.event_kind,
|
||||
level,
|
||||
source: entity.source,
|
||||
message: entity.message,
|
||||
created_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
84
kb_lib/src/db/dtos/dex.rs
Normal file
84
kb_lib/src/db/dtos/dex.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
// file: kb_lib/src/db/dtos/dex.rs
|
||||
|
||||
//! DEX DTO.
|
||||
|
||||
/// Application-facing normalized DEX DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbDexDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Stable short code.
|
||||
pub code: std::string::String,
|
||||
/// Display name.
|
||||
pub name: std::string::String,
|
||||
/// Optional primary program id.
|
||||
pub program_id: std::option::Option<std::string::String>,
|
||||
/// Optional router program id.
|
||||
pub router_program_id: std::option::Option<std::string::String>,
|
||||
/// Whether this DEX is enabled.
|
||||
pub is_enabled: bool,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbDexDto {
|
||||
/// Creates a new DEX DTO.
|
||||
pub fn new(
|
||||
code: std::string::String,
|
||||
name: std::string::String,
|
||||
program_id: std::option::Option<std::string::String>,
|
||||
router_program_id: std::option::Option<std::string::String>,
|
||||
is_enabled: bool,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
code,
|
||||
name,
|
||||
program_id,
|
||||
router_program_id,
|
||||
is_enabled,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbDexEntity> for KbDexDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbDexEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse dex created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse dex updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
code: entity.code,
|
||||
name: entity.name,
|
||||
program_id: entity.program_id,
|
||||
router_program_id: entity.router_program_id,
|
||||
is_enabled: entity.is_enabled != 0,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
100
kb_lib/src/db/dtos/dex_decoded_event.rs
Normal file
100
kb_lib/src/db/dtos/dex_decoded_event.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
// file: kb_lib/src/db/dtos/dex_decoded_event.rs
|
||||
|
||||
//! Application-facing decoded DEX event DTO.
|
||||
|
||||
/// Application-facing decoded DEX event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbDexDecodedEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Parent transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional parent instruction id.
|
||||
pub instruction_id: std::option::Option<i64>,
|
||||
/// Decoded protocol name.
|
||||
pub protocol_name: std::string::String,
|
||||
/// Program id that produced the decoded event.
|
||||
pub program_id: std::string::String,
|
||||
/// Event kind.
|
||||
pub event_kind: std::string::String,
|
||||
/// Optional decoded pool account.
|
||||
pub pool_account: std::option::Option<std::string::String>,
|
||||
/// Optional decoded lp mint.
|
||||
pub lp_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded token A mint.
|
||||
pub token_a_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded token B mint.
|
||||
pub token_b_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded market account.
|
||||
pub market_account: std::option::Option<std::string::String>,
|
||||
/// Serialized decoded payload.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbDexDecodedEventDto {
|
||||
/// Creates a new decoded DEX event DTO.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
transaction_id: i64,
|
||||
instruction_id: std::option::Option<i64>,
|
||||
protocol_name: std::string::String,
|
||||
program_id: std::string::String,
|
||||
event_kind: std::string::String,
|
||||
pool_account: std::option::Option<std::string::String>,
|
||||
lp_mint: std::option::Option<std::string::String>,
|
||||
token_a_mint: std::option::Option<std::string::String>,
|
||||
token_b_mint: std::option::Option<std::string::String>,
|
||||
market_account: std::option::Option<std::string::String>,
|
||||
payload_json: std::string::String,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
transaction_id,
|
||||
instruction_id,
|
||||
protocol_name,
|
||||
program_id,
|
||||
event_kind,
|
||||
pool_account,
|
||||
lp_mint,
|
||||
token_a_mint,
|
||||
token_b_mint,
|
||||
market_account,
|
||||
payload_json,
|
||||
created_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbDexDecodedEventEntity> for KbDexDecodedEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbDexDecodedEventEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse dex decoded event created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
transaction_id: entity.transaction_id,
|
||||
instruction_id: entity.instruction_id,
|
||||
protocol_name: entity.protocol_name,
|
||||
program_id: entity.program_id,
|
||||
event_kind: entity.event_kind,
|
||||
pool_account: entity.pool_account,
|
||||
lp_mint: entity.lp_mint,
|
||||
token_a_mint: entity.token_a_mint,
|
||||
token_b_mint: entity.token_b_mint,
|
||||
market_account: entity.market_account,
|
||||
payload_json: entity.payload_json,
|
||||
created_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
121
kb_lib/src/db/dtos/known_http_endpoint.rs
Normal file
121
kb_lib/src/db/dtos/known_http_endpoint.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
// file: kb_lib/src/db/dtos/known_http_endpoint.rs
|
||||
|
||||
//! Known HTTP endpoint DTO.
|
||||
|
||||
/// Application-facing known HTTP endpoint DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbKnownHttpEndpointDto {
|
||||
/// Logical endpoint name.
|
||||
pub name: std::string::String,
|
||||
/// Provider name.
|
||||
pub provider: std::string::String,
|
||||
/// Endpoint URL.
|
||||
pub url: std::string::String,
|
||||
/// Whether this endpoint is enabled.
|
||||
pub enabled: bool,
|
||||
/// Declared roles.
|
||||
pub roles: std::vec::Vec<std::string::String>,
|
||||
/// Optional last seen timestamp.
|
||||
pub last_seen_at: std::option::Option<chrono::DateTime<chrono::Utc>>,
|
||||
/// Last update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbKnownHttpEndpointDto {
|
||||
/// Creates a new DTO with the current update timestamp.
|
||||
pub fn new(
|
||||
name: std::string::String,
|
||||
provider: std::string::String,
|
||||
url: std::string::String,
|
||||
enabled: bool,
|
||||
roles: std::vec::Vec<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
provider,
|
||||
url,
|
||||
enabled,
|
||||
roles,
|
||||
last_seen_at: None,
|
||||
updated_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbKnownHttpEndpointEntity> for KbKnownHttpEndpointDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbKnownHttpEndpointEntity) -> Result<Self, Self::Error> {
|
||||
let roles_result =
|
||||
serde_json::from_str::<std::vec::Vec<std::string::String>>(&entity.roles_json);
|
||||
let roles = match roles_result {
|
||||
Ok(roles) => roles,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known http endpoint roles_json '{}': {}",
|
||||
entity.roles_json, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known http endpoint updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let last_seen_at = match entity.last_seen_at {
|
||||
Some(last_seen_at_text) => {
|
||||
let parsed_result = chrono::DateTime::parse_from_rfc3339(&last_seen_at_text);
|
||||
match parsed_result {
|
||||
Ok(parsed) => Some(parsed.with_timezone(&chrono::Utc)),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known http endpoint last_seen_at '{}': {}",
|
||||
last_seen_at_text, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
name: entity.name,
|
||||
provider: entity.provider,
|
||||
url: entity.url,
|
||||
enabled: entity.enabled != 0,
|
||||
roles,
|
||||
last_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<KbKnownHttpEndpointDto> for crate::KbKnownHttpEndpointEntity {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(dto: KbKnownHttpEndpointDto) -> Result<Self, Self::Error> {
|
||||
let roles_json_result = serde_json::to_string(&dto.roles);
|
||||
let roles_json = match roles_json_result {
|
||||
Ok(roles_json) => roles_json,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot serialize known http endpoint roles: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
name: dto.name,
|
||||
provider: dto.provider,
|
||||
url: dto.url,
|
||||
enabled: if dto.enabled { 1 } else { 0 },
|
||||
roles_json,
|
||||
last_seen_at: dto.last_seen_at.map(|value| value.to_rfc3339()),
|
||||
updated_at: dto.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
}
|
||||
121
kb_lib/src/db/dtos/known_ws_endpoint.rs
Normal file
121
kb_lib/src/db/dtos/known_ws_endpoint.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
// file: kb_lib/src/db/dtos/known_ws_endpoint.rs
|
||||
|
||||
//! Known WebSocket endpoint DTO.
|
||||
|
||||
/// Application-facing known WebSocket endpoint DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbKnownWsEndpointDto {
|
||||
/// Logical endpoint name.
|
||||
pub name: std::string::String,
|
||||
/// Provider name.
|
||||
pub provider: std::string::String,
|
||||
/// Endpoint URL.
|
||||
pub url: std::string::String,
|
||||
/// Whether this endpoint is enabled.
|
||||
pub enabled: bool,
|
||||
/// Declared roles.
|
||||
pub roles: std::vec::Vec<std::string::String>,
|
||||
/// Optional last seen timestamp.
|
||||
pub last_seen_at: std::option::Option<chrono::DateTime<chrono::Utc>>,
|
||||
/// Last update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbKnownWsEndpointDto {
|
||||
/// Creates a new DTO with the current update timestamp.
|
||||
pub fn new(
|
||||
name: std::string::String,
|
||||
provider: std::string::String,
|
||||
url: std::string::String,
|
||||
enabled: bool,
|
||||
roles: std::vec::Vec<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
provider,
|
||||
url,
|
||||
enabled,
|
||||
roles,
|
||||
last_seen_at: None,
|
||||
updated_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbKnownWsEndpointEntity> for KbKnownWsEndpointDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbKnownWsEndpointEntity) -> Result<Self, Self::Error> {
|
||||
let roles_result =
|
||||
serde_json::from_str::<std::vec::Vec<std::string::String>>(&entity.roles_json);
|
||||
let roles = match roles_result {
|
||||
Ok(roles) => roles,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known ws endpoint roles_json '{}': {}",
|
||||
entity.roles_json, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known ws endpoint updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let last_seen_at = match entity.last_seen_at {
|
||||
Some(last_seen_at_text) => {
|
||||
let parsed_result = chrono::DateTime::parse_from_rfc3339(&last_seen_at_text);
|
||||
match parsed_result {
|
||||
Ok(parsed) => Some(parsed.with_timezone(&chrono::Utc)),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse known ws endpoint last_seen_at '{}': {}",
|
||||
last_seen_at_text, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
name: entity.name,
|
||||
provider: entity.provider,
|
||||
url: entity.url,
|
||||
enabled: entity.enabled != 0,
|
||||
roles,
|
||||
last_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<KbKnownWsEndpointDto> for crate::KbKnownWsEndpointEntity {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(dto: KbKnownWsEndpointDto) -> Result<Self, Self::Error> {
|
||||
let roles_json_result = serde_json::to_string(&dto.roles);
|
||||
let roles_json = match roles_json_result {
|
||||
Ok(roles_json) => roles_json,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot serialize known ws endpoint roles: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
name: dto.name,
|
||||
provider: dto.provider,
|
||||
url: dto.url,
|
||||
enabled: if dto.enabled { 1 } else { 0 },
|
||||
roles_json,
|
||||
last_seen_at: dto.last_seen_at.map(|value| value.to_rfc3339()),
|
||||
updated_at: dto.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
}
|
||||
104
kb_lib/src/db/dtos/launch_attribution.rs
Normal file
104
kb_lib/src/db/dtos/launch_attribution.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
// file: kb_lib/src/db/dtos/launch_attribution.rs
|
||||
|
||||
//! Launch attribution DTO.
|
||||
|
||||
/// Application-facing launch attribution DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbLaunchAttributionDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related launch surface id.
|
||||
pub launch_surface_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Optional related pool id.
|
||||
pub pool_id: std::option::Option<i64>,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Optional related matched key id.
|
||||
pub matched_key_id: std::option::Option<i64>,
|
||||
/// Decoded protocol name.
|
||||
pub protocol_name: std::string::String,
|
||||
/// Match kind used for attribution.
|
||||
pub match_kind: std::string::String,
|
||||
/// Matched value used for attribution.
|
||||
pub matched_value: std::string::String,
|
||||
/// Attribution timestamp.
|
||||
pub attributed_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbLaunchAttributionDto {
|
||||
/// Creates a new launch attribution DTO.
|
||||
pub fn new(
|
||||
launch_surface_id: i64,
|
||||
transaction_id: i64,
|
||||
decoded_event_id: i64,
|
||||
pool_id: std::option::Option<i64>,
|
||||
pair_id: std::option::Option<i64>,
|
||||
matched_key_id: std::option::Option<i64>,
|
||||
protocol_name: std::string::String,
|
||||
match_kind: std::string::String,
|
||||
matched_value: std::string::String,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
launch_surface_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
matched_key_id,
|
||||
protocol_name,
|
||||
match_kind,
|
||||
matched_value,
|
||||
attributed_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbLaunchAttributionEntity> for KbLaunchAttributionDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbLaunchAttributionEntity) -> Result<Self, Self::Error> {
|
||||
let attributed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.attributed_at);
|
||||
let attributed_at = match attributed_at_result {
|
||||
Ok(attributed_at) => attributed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_attribution attributed_at '{}': {}",
|
||||
entity.attributed_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_attribution updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
launch_surface_id: entity.launch_surface_id,
|
||||
transaction_id: entity.transaction_id,
|
||||
decoded_event_id: entity.decoded_event_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
matched_key_id: entity.matched_key_id,
|
||||
protocol_name: entity.protocol_name,
|
||||
match_kind: entity.match_kind,
|
||||
matched_value: entity.matched_value,
|
||||
attributed_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
79
kb_lib/src/db/dtos/launch_surface.rs
Normal file
79
kb_lib/src/db/dtos/launch_surface.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
// file: kb_lib/src/db/dtos/launch_surface.rs
|
||||
|
||||
//! Launch surface DTO.
|
||||
|
||||
/// Application-facing launch surface DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbLaunchSurfaceDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Stable short code.
|
||||
pub code: std::string::String,
|
||||
/// Display name.
|
||||
pub name: std::string::String,
|
||||
/// Optional protocol family hint.
|
||||
pub protocol_family: std::option::Option<std::string::String>,
|
||||
/// Whether the surface is enabled.
|
||||
pub is_enabled: bool,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbLaunchSurfaceDto {
|
||||
/// Creates a new launch surface DTO.
|
||||
pub fn new(
|
||||
code: std::string::String,
|
||||
name: std::string::String,
|
||||
protocol_family: std::option::Option<std::string::String>,
|
||||
is_enabled: bool,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
code,
|
||||
name,
|
||||
protocol_family,
|
||||
is_enabled,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbLaunchSurfaceEntity> for KbLaunchSurfaceDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbLaunchSurfaceEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_surface created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_surface updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
code: entity.code,
|
||||
name: entity.name,
|
||||
protocol_family: entity.protocol_family,
|
||||
is_enabled: entity.is_enabled != 0,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
74
kb_lib/src/db/dtos/launch_surface_key.rs
Normal file
74
kb_lib/src/db/dtos/launch_surface_key.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
// file: kb_lib/src/db/dtos/launch_surface_key.rs
|
||||
|
||||
//! Launch surface key DTO.
|
||||
|
||||
/// Application-facing launch surface key DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbLaunchSurfaceKeyDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related launch surface id.
|
||||
pub launch_surface_id: i64,
|
||||
/// Stable key kind.
|
||||
pub match_kind: std::string::String,
|
||||
/// Stable key value.
|
||||
pub match_value: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbLaunchSurfaceKeyDto {
|
||||
/// Creates a new launch surface key DTO.
|
||||
pub fn new(
|
||||
launch_surface_id: i64,
|
||||
match_kind: std::string::String,
|
||||
match_value: std::string::String,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
launch_surface_id,
|
||||
match_kind,
|
||||
match_value,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbLaunchSurfaceKeyEntity> for KbLaunchSurfaceKeyDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbLaunchSurfaceKeyEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_surface_key created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse launch_surface_key updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
launch_surface_id: entity.launch_surface_id,
|
||||
match_kind: entity.match_kind,
|
||||
match_value: entity.match_value,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
134
kb_lib/src/db/dtos/liquidity_event.rs
Normal file
134
kb_lib/src/db/dtos/liquidity_event.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
// file: kb_lib/src/db/dtos/liquidity_event.rs
|
||||
|
||||
//! Liquidity event DTO.
|
||||
|
||||
/// Application-facing normalized liquidity event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbLiquidityEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Liquidity event kind.
|
||||
pub event_kind: crate::KbLiquidityEventKind,
|
||||
/// Optional actor wallet.
|
||||
pub actor_wallet: std::option::Option<std::string::String>,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional LP token id.
|
||||
pub lp_token_id: std::option::Option<i64>,
|
||||
/// Base amount as decimal text.
|
||||
pub base_amount: std::string::String,
|
||||
/// Quote amount as decimal text.
|
||||
pub quote_amount: std::string::String,
|
||||
/// Optional LP amount as decimal text.
|
||||
pub lp_amount: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp.
|
||||
pub executed_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbLiquidityEventDto {
|
||||
/// Creates a new liquidity event DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: std::option::Option<i64>,
|
||||
signature: std::string::String,
|
||||
instruction_index: i64,
|
||||
slot: std::option::Option<u64>,
|
||||
event_kind: crate::KbLiquidityEventKind,
|
||||
actor_wallet: std::option::Option<std::string::String>,
|
||||
base_token_id: i64,
|
||||
quote_token_id: i64,
|
||||
lp_token_id: std::option::Option<i64>,
|
||||
base_amount: std::string::String,
|
||||
quote_amount: std::string::String,
|
||||
lp_amount: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
signature,
|
||||
instruction_index,
|
||||
slot,
|
||||
event_kind,
|
||||
actor_wallet,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
lp_token_id,
|
||||
base_amount,
|
||||
quote_amount,
|
||||
lp_amount,
|
||||
executed_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbLiquidityEventEntity> for KbLiquidityEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbLiquidityEventEntity) -> Result<Self, Self::Error> {
|
||||
let event_kind_result = crate::KbLiquidityEventKind::from_i16(entity.event_kind);
|
||||
let event_kind = match event_kind_result {
|
||||
Ok(event_kind) => event_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let executed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.executed_at);
|
||||
let executed_at = match executed_at_result {
|
||||
Ok(executed_at) => executed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse liquidity event executed_at '{}': {}",
|
||||
entity.executed_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert liquidity event slot '{}' to u64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
signature: entity.signature,
|
||||
instruction_index: entity.instruction_index,
|
||||
slot,
|
||||
event_kind,
|
||||
actor_wallet: entity.actor_wallet,
|
||||
base_token_id: entity.base_token_id,
|
||||
quote_token_id: entity.quote_token_id,
|
||||
lp_token_id: entity.lp_token_id,
|
||||
base_amount: entity.base_amount,
|
||||
quote_amount: entity.quote_amount,
|
||||
lp_amount: entity.lp_amount,
|
||||
executed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
129
kb_lib/src/db/dtos/observed_token.rs
Normal file
129
kb_lib/src/db/dtos/observed_token.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
// file: kb_lib/src/db/dtos/observed_token.rs
|
||||
|
||||
//! Observed token DTO.
|
||||
|
||||
/// Application-facing observed token DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbObservedTokenDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Token mint address.
|
||||
pub mint: std::string::String,
|
||||
/// Optional token symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// Optional token display name.
|
||||
pub name: std::option::Option<std::string::String>,
|
||||
/// Optional decimals value.
|
||||
pub decimals: std::option::Option<u8>,
|
||||
/// Token program id.
|
||||
pub token_program: std::string::String,
|
||||
/// Local status.
|
||||
pub status: crate::KbObservedTokenStatus,
|
||||
/// First seen timestamp.
|
||||
pub first_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Last seen timestamp.
|
||||
pub last_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Last update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbObservedTokenDto {
|
||||
/// Creates a new observed token DTO with current timestamps.
|
||||
pub fn new(
|
||||
mint: std::string::String,
|
||||
symbol: std::option::Option<std::string::String>,
|
||||
name: std::option::Option<std::string::String>,
|
||||
decimals: std::option::Option<u8>,
|
||||
token_program: std::string::String,
|
||||
status: crate::KbObservedTokenStatus,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
mint,
|
||||
symbol,
|
||||
name,
|
||||
decimals,
|
||||
token_program,
|
||||
status,
|
||||
first_seen_at: now,
|
||||
last_seen_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbObservedTokenEntity> for KbObservedTokenDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(
|
||||
entity: crate::KbObservedTokenEntity,
|
||||
) -> Result<Self, Self::Error> {
|
||||
let status_result = crate::KbObservedTokenStatus::from_i16(entity.status);
|
||||
let status = match status_result {
|
||||
Ok(status) => status,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
|
||||
let first_seen_at = match first_seen_at_result {
|
||||
Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse observed token first_seen_at '{}': {}",
|
||||
entity.first_seen_at,
|
||||
error
|
||||
)));
|
||||
},
|
||||
};
|
||||
let last_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.last_seen_at);
|
||||
let last_seen_at = match last_seen_at_result {
|
||||
Ok(last_seen_at) => last_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse observed token last_seen_at '{}': {}",
|
||||
entity.last_seen_at,
|
||||
error
|
||||
)));
|
||||
},
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse observed token updated_at '{}': {}",
|
||||
entity.updated_at,
|
||||
error
|
||||
)));
|
||||
},
|
||||
};
|
||||
let decimals = match entity.decimals {
|
||||
Some(decimals) => {
|
||||
let decimals_u8_result = u8::try_from(decimals);
|
||||
match decimals_u8_result {
|
||||
Ok(decimals_u8) => Some(decimals_u8),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert observed token decimals '{}' to u8: {}",
|
||||
decimals,
|
||||
error
|
||||
)));
|
||||
},
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
mint: entity.mint,
|
||||
symbol: entity.symbol,
|
||||
name: entity.name,
|
||||
decimals,
|
||||
token_program: entity.token_program,
|
||||
status,
|
||||
first_seen_at,
|
||||
last_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
104
kb_lib/src/db/dtos/onchain_observation.rs
Normal file
104
kb_lib/src/db/dtos/onchain_observation.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
// file: kb_lib/src/db/dtos/onchain_observation.rs
|
||||
|
||||
//! On-chain observation DTO.
|
||||
|
||||
/// Application-facing on-chain observation DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbOnchainObservationDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Observation kind.
|
||||
pub observation_kind: std::string::String,
|
||||
/// Observation source family.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional source endpoint logical name.
|
||||
pub endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Logical object key, for example a mint, signature or pool address.
|
||||
pub object_key: std::string::String,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Raw JSON payload.
|
||||
pub payload: serde_json::Value,
|
||||
/// Observation timestamp.
|
||||
pub observed_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbOnchainObservationDto {
|
||||
/// Creates a new on-chain observation DTO with the current timestamp.
|
||||
pub fn new(
|
||||
observation_kind: std::string::String,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
endpoint_name: std::option::Option<std::string::String>,
|
||||
object_key: std::string::String,
|
||||
slot: std::option::Option<u64>,
|
||||
payload: serde_json::Value,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
observation_kind,
|
||||
source_kind,
|
||||
endpoint_name,
|
||||
object_key,
|
||||
slot,
|
||||
payload,
|
||||
observed_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbOnchainObservationEntity> for KbOnchainObservationDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbOnchainObservationEntity) -> Result<Self, Self::Error> {
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let observed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.observed_at);
|
||||
let observed_at = match observed_at_result {
|
||||
Ok(observed_at) => observed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse on-chain observation observed_at '{}': {}",
|
||||
entity.observed_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let payload_result = serde_json::from_str::<serde_json::Value>(&entity.payload_json);
|
||||
let payload = match payload_result {
|
||||
Ok(payload) => payload,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse on-chain observation payload_json '{}': {}",
|
||||
entity.payload_json, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert on-chain observation slot '{}' to u64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
observation_kind: entity.observation_kind,
|
||||
source_kind,
|
||||
endpoint_name: entity.endpoint_name,
|
||||
object_key: entity.object_key,
|
||||
slot,
|
||||
payload,
|
||||
observed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
84
kb_lib/src/db/dtos/pair.rs
Normal file
84
kb_lib/src/db/dtos/pair.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
// file: kb_lib/src/db/dtos/pair.rs
|
||||
|
||||
//! Normalized pair DTO.
|
||||
|
||||
/// Application-facing normalized pair DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPairDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional display symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// First seen timestamp.
|
||||
pub first_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPairDto {
|
||||
/// Creates a new pair DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
base_token_id: i64,
|
||||
quote_token_id: i64,
|
||||
symbol: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
symbol,
|
||||
first_seen_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPairEntity> for KbPairDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPairEntity) -> Result<Self, Self::Error> {
|
||||
let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
|
||||
let first_seen_at = match first_seen_at_result {
|
||||
Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair first_seen_at '{}': {}",
|
||||
entity.first_seen_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
base_token_id: entity.base_token_id,
|
||||
quote_token_id: entity.quote_token_id,
|
||||
symbol: entity.symbol,
|
||||
first_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
120
kb_lib/src/db/dtos/pair_analytic_signal.rs
Normal file
120
kb_lib/src/db/dtos/pair_analytic_signal.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
// file: kb_lib/src/db/dtos/pair_analytic_signal.rs
|
||||
|
||||
//! Pair-analytic-signal DTO.
|
||||
|
||||
/// Application-facing pair-analytic-signal DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPairAnalyticSignalDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Stable signal kind.
|
||||
pub signal_kind: std::string::String,
|
||||
/// Signal severity.
|
||||
pub severity: crate::KbAnalysisSignalSeverity,
|
||||
/// Timeframe in seconds. Zero means non-bucketed signal.
|
||||
pub timeframe_seconds: i64,
|
||||
/// Inclusive bucket start in unix seconds. Zero means non-bucketed signal.
|
||||
pub bucket_start_unix: i64,
|
||||
/// Optional numeric score.
|
||||
pub score: std::option::Option<f64>,
|
||||
/// Signal value payload.
|
||||
pub signal_value: serde_json::Value,
|
||||
/// Optional first transaction id that produced this signal key.
|
||||
pub first_transaction_id: std::option::Option<i64>,
|
||||
/// Optional last transaction id that produced this signal key.
|
||||
pub last_transaction_id: std::option::Option<i64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPairAnalyticSignalDto {
|
||||
/// Creates a new pair-analytic-signal DTO.
|
||||
pub fn new(
|
||||
pair_id: i64,
|
||||
signal_kind: std::string::String,
|
||||
severity: crate::KbAnalysisSignalSeverity,
|
||||
timeframe_seconds: i64,
|
||||
bucket_start_unix: i64,
|
||||
score: std::option::Option<f64>,
|
||||
signal_value: serde_json::Value,
|
||||
first_transaction_id: std::option::Option<i64>,
|
||||
last_transaction_id: std::option::Option<i64>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
pair_id,
|
||||
signal_kind,
|
||||
severity,
|
||||
timeframe_seconds,
|
||||
bucket_start_unix,
|
||||
score,
|
||||
signal_value,
|
||||
first_transaction_id,
|
||||
last_transaction_id,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPairAnalyticSignalEntity> for KbPairAnalyticSignalDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPairAnalyticSignalEntity) -> Result<Self, Self::Error> {
|
||||
let severity_result = crate::KbAnalysisSignalSeverity::from_i16(entity.severity);
|
||||
let severity = match severity_result {
|
||||
Ok(severity) => severity,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let signal_value_result =
|
||||
serde_json::from_str::<serde_json::Value>(entity.signal_value_json.as_str());
|
||||
let signal_value = match signal_value_result {
|
||||
Ok(signal_value) => signal_value,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_analytic_signal signal_value_json '{}': {}",
|
||||
entity.signal_value_json, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(entity.created_at.as_str());
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_analytic_signal created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(entity.updated_at.as_str());
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_analytic_signal updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
pair_id: entity.pair_id,
|
||||
signal_kind: entity.signal_kind,
|
||||
severity,
|
||||
timeframe_seconds: entity.timeframe_seconds,
|
||||
bucket_start_unix: entity.bucket_start_unix,
|
||||
score: entity.score,
|
||||
signal_value,
|
||||
first_transaction_id: entity.first_transaction_id,
|
||||
last_transaction_id: entity.last_transaction_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
135
kb_lib/src/db/dtos/pair_candle.rs
Normal file
135
kb_lib/src/db/dtos/pair_candle.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
// file: kb_lib/src/db/dtos/pair_candle.rs
|
||||
|
||||
//! Pair-candle DTO.
|
||||
|
||||
/// Application-facing pair-candle DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPairCandleDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Candle timeframe in seconds.
|
||||
pub timeframe_seconds: i64,
|
||||
/// Inclusive bucket start in unix seconds.
|
||||
pub bucket_start_unix: i64,
|
||||
/// Exclusive bucket end in unix seconds.
|
||||
pub bucket_end_unix: i64,
|
||||
/// Open price in quote-per-base units.
|
||||
pub open_price_quote_per_base: f64,
|
||||
/// High price in quote-per-base units.
|
||||
pub high_price_quote_per_base: f64,
|
||||
/// Low price in quote-per-base units.
|
||||
pub low_price_quote_per_base: f64,
|
||||
/// Close price in quote-per-base units.
|
||||
pub close_price_quote_per_base: f64,
|
||||
/// Trade count inside the candle.
|
||||
pub trade_count: i64,
|
||||
/// Buy count inside the candle.
|
||||
pub buy_count: i64,
|
||||
/// Sell count inside the candle.
|
||||
pub sell_count: i64,
|
||||
/// Aggregated base volume as decimal text when available.
|
||||
pub base_volume_raw: std::option::Option<std::string::String>,
|
||||
/// Aggregated quote volume as decimal text when available.
|
||||
pub quote_volume_raw: std::option::Option<std::string::String>,
|
||||
/// Optional first trade signature inside the candle.
|
||||
pub first_trade_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last trade signature inside the candle.
|
||||
pub last_trade_signature: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPairCandleDto {
|
||||
/// Creates a new pair-candle DTO.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
pair_id: i64,
|
||||
timeframe_seconds: i64,
|
||||
bucket_start_unix: i64,
|
||||
bucket_end_unix: i64,
|
||||
open_price_quote_per_base: f64,
|
||||
high_price_quote_per_base: f64,
|
||||
low_price_quote_per_base: f64,
|
||||
close_price_quote_per_base: f64,
|
||||
trade_count: i64,
|
||||
buy_count: i64,
|
||||
sell_count: i64,
|
||||
base_volume_raw: std::option::Option<std::string::String>,
|
||||
quote_volume_raw: std::option::Option<std::string::String>,
|
||||
first_trade_signature: std::option::Option<std::string::String>,
|
||||
last_trade_signature: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
pair_id,
|
||||
timeframe_seconds,
|
||||
bucket_start_unix,
|
||||
bucket_end_unix,
|
||||
open_price_quote_per_base,
|
||||
high_price_quote_per_base,
|
||||
low_price_quote_per_base,
|
||||
close_price_quote_per_base,
|
||||
trade_count,
|
||||
buy_count,
|
||||
sell_count,
|
||||
base_volume_raw,
|
||||
quote_volume_raw,
|
||||
first_trade_signature,
|
||||
last_trade_signature,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPairCandleEntity> for KbPairCandleDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPairCandleEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_candle created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_candle updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
pair_id: entity.pair_id,
|
||||
timeframe_seconds: entity.timeframe_seconds,
|
||||
bucket_start_unix: entity.bucket_start_unix,
|
||||
bucket_end_unix: entity.bucket_end_unix,
|
||||
open_price_quote_per_base: entity.open_price_quote_per_base,
|
||||
high_price_quote_per_base: entity.high_price_quote_per_base,
|
||||
low_price_quote_per_base: entity.low_price_quote_per_base,
|
||||
close_price_quote_per_base: entity.close_price_quote_per_base,
|
||||
trade_count: entity.trade_count,
|
||||
buy_count: entity.buy_count,
|
||||
sell_count: entity.sell_count,
|
||||
base_volume_raw: entity.base_volume_raw,
|
||||
quote_volume_raw: entity.quote_volume_raw,
|
||||
first_trade_signature: entity.first_trade_signature,
|
||||
last_trade_signature: entity.last_trade_signature,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
102
kb_lib/src/db/dtos/pair_metric.rs
Normal file
102
kb_lib/src/db/dtos/pair_metric.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
// file: kb_lib/src/db/dtos/pair_metric.rs
|
||||
|
||||
//! Pair-metric DTO.
|
||||
|
||||
/// Application-facing pair-metric DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPairMetricDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Optional first observed slot.
|
||||
pub first_slot: std::option::Option<i64>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot: std::option::Option<i64>,
|
||||
/// Optional first observed signature.
|
||||
pub first_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last observed signature.
|
||||
pub last_signature: std::option::Option<std::string::String>,
|
||||
/// Total trade count.
|
||||
pub trade_count: i64,
|
||||
/// Total buy count.
|
||||
pub buy_count: i64,
|
||||
/// Total sell count.
|
||||
pub sell_count: i64,
|
||||
/// Optional cumulative raw base volume.
|
||||
pub cumulative_base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional cumulative raw quote volume.
|
||||
pub cumulative_quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last derived quote-per-base price.
|
||||
pub last_price_quote_per_base: std::option::Option<f64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPairMetricDto {
|
||||
/// Creates a new pair-metric DTO.
|
||||
pub fn new(pair_id: i64) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
pair_id,
|
||||
first_slot: None,
|
||||
last_slot: None,
|
||||
first_signature: None,
|
||||
last_signature: None,
|
||||
trade_count: 0,
|
||||
buy_count: 0,
|
||||
sell_count: 0,
|
||||
cumulative_base_amount_raw: None,
|
||||
cumulative_quote_amount_raw: None,
|
||||
last_price_quote_per_base: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPairMetricEntity> for KbPairMetricDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPairMetricEntity) -> Result<Self, Self::Error> {
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_metric created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pair_metric updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
pair_id: entity.pair_id,
|
||||
first_slot: entity.first_slot,
|
||||
last_slot: entity.last_slot,
|
||||
first_signature: entity.first_signature,
|
||||
last_signature: entity.last_signature,
|
||||
trade_count: entity.trade_count,
|
||||
buy_count: entity.buy_count,
|
||||
sell_count: entity.sell_count,
|
||||
cumulative_base_amount_raw: entity.cumulative_base_amount_raw,
|
||||
cumulative_quote_amount_raw: entity.cumulative_quote_amount_raw,
|
||||
last_price_quote_per_base: entity.last_price_quote_per_base,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
89
kb_lib/src/db/dtos/pool.rs
Normal file
89
kb_lib/src/db/dtos/pool.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
// file: kb_lib/src/db/dtos/pool.rs
|
||||
|
||||
//! Normalized pool DTO.
|
||||
|
||||
/// Application-facing normalized pool DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPoolDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Pool address.
|
||||
pub address: std::string::String,
|
||||
/// Pool kind.
|
||||
pub pool_kind: crate::KbPoolKind,
|
||||
/// Pool status.
|
||||
pub status: crate::KbPoolStatus,
|
||||
/// First seen timestamp.
|
||||
pub first_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPoolDto {
|
||||
/// Creates a new pool DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
address: std::string::String,
|
||||
pool_kind: crate::KbPoolKind,
|
||||
status: crate::KbPoolStatus,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
address,
|
||||
pool_kind,
|
||||
status,
|
||||
first_seen_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPoolEntity> for KbPoolDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPoolEntity) -> Result<Self, Self::Error> {
|
||||
let pool_kind_result = crate::KbPoolKind::from_i16(entity.pool_kind);
|
||||
let pool_kind = match pool_kind_result {
|
||||
Ok(pool_kind) => pool_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let status_result = crate::KbPoolStatus::from_i16(entity.status);
|
||||
let status = match status_result {
|
||||
Ok(status) => status,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
|
||||
let first_seen_at = match first_seen_at_result {
|
||||
Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool first_seen_at '{}': {}",
|
||||
entity.first_seen_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
address: entity.address,
|
||||
pool_kind,
|
||||
status,
|
||||
first_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
104
kb_lib/src/db/dtos/pool_listing.rs
Normal file
104
kb_lib/src/db/dtos/pool_listing.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
// file: kb_lib/src/db/dtos/pool_listing.rs
|
||||
|
||||
//! Pool listing DTO.
|
||||
|
||||
/// Application-facing normalized pool listing DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPoolListingDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Discovery source family.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional source endpoint logical name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Detection timestamp.
|
||||
pub detected_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Optional initial base reserve estimate.
|
||||
pub initial_base_reserve: std::option::Option<f64>,
|
||||
/// Optional initial quote reserve estimate.
|
||||
pub initial_quote_reserve: std::option::Option<f64>,
|
||||
/// Optional initial price estimate in quote units.
|
||||
pub initial_price_quote: std::option::Option<f64>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPoolListingDto {
|
||||
/// Creates a new pool listing DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: std::option::Option<i64>,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
initial_base_reserve: std::option::Option<f64>,
|
||||
initial_quote_reserve: std::option::Option<f64>,
|
||||
initial_price_quote: std::option::Option<f64>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
detected_at: now,
|
||||
initial_base_reserve,
|
||||
initial_quote_reserve,
|
||||
initial_price_quote,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPoolListingEntity> for KbPoolListingDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPoolListingEntity) -> Result<Self, Self::Error> {
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let detected_at_result = chrono::DateTime::parse_from_rfc3339(&entity.detected_at);
|
||||
let detected_at = match detected_at_result {
|
||||
Ok(detected_at) => detected_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_listing detected_at '{}': {}",
|
||||
entity.detected_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_listing updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
detected_at,
|
||||
initial_base_reserve: entity.initial_base_reserve,
|
||||
initial_quote_reserve: entity.initial_quote_reserve,
|
||||
initial_price_quote: entity.initial_price_quote,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
124
kb_lib/src/db/dtos/pool_origin.rs
Normal file
124
kb_lib/src/db/dtos/pool_origin.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
// file: kb_lib/src/db/dtos/pool_origin.rs
|
||||
|
||||
//! Pool origin DTO.
|
||||
|
||||
/// Application-facing pool-origin DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPoolOriginDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Optional related pool listing id.
|
||||
pub pool_listing_id: std::option::Option<i64>,
|
||||
/// Founding transaction id in the local model.
|
||||
pub founding_transaction_id: i64,
|
||||
/// Founding decoded-event id in the local model.
|
||||
pub founding_decoded_event_id: i64,
|
||||
/// Founding signature in the local model.
|
||||
pub founding_signature: std::string::String,
|
||||
/// Founding protocol name.
|
||||
pub founding_protocol_name: std::string::String,
|
||||
/// Founding event kind.
|
||||
pub founding_event_kind: std::string::String,
|
||||
/// Discovery source kind.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional source endpoint logical name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Optional related launch attribution id.
|
||||
pub launch_attribution_id: std::option::Option<i64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPoolOriginDto {
|
||||
/// Creates a new pool-origin DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: std::option::Option<i64>,
|
||||
pool_listing_id: std::option::Option<i64>,
|
||||
founding_transaction_id: i64,
|
||||
founding_decoded_event_id: i64,
|
||||
founding_signature: std::string::String,
|
||||
founding_protocol_name: std::string::String,
|
||||
founding_event_kind: std::string::String,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
launch_attribution_id: std::option::Option<i64>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
pool_listing_id,
|
||||
founding_transaction_id,
|
||||
founding_decoded_event_id,
|
||||
founding_signature,
|
||||
founding_protocol_name,
|
||||
founding_event_kind,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
launch_attribution_id,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPoolOriginEntity> for KbPoolOriginDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPoolOriginEntity) -> Result<Self, Self::Error> {
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_origin created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_origin updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
pool_listing_id: entity.pool_listing_id,
|
||||
founding_transaction_id: entity.founding_transaction_id,
|
||||
founding_decoded_event_id: entity.founding_decoded_event_id,
|
||||
founding_signature: entity.founding_signature,
|
||||
founding_protocol_name: entity.founding_protocol_name,
|
||||
founding_event_kind: entity.founding_event_kind,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
launch_attribution_id: entity.launch_attribution_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
89
kb_lib/src/db/dtos/pool_token.rs
Normal file
89
kb_lib/src/db/dtos/pool_token.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
// file: kb_lib/src/db/dtos/pool_token.rs
|
||||
|
||||
//! Pool token DTO.
|
||||
|
||||
/// Application-facing normalized pool token DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbPoolTokenDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Token role.
|
||||
pub role: crate::KbPoolTokenRole,
|
||||
/// Optional vault address.
|
||||
pub vault_address: std::option::Option<std::string::String>,
|
||||
/// Optional token order inside the pool.
|
||||
pub token_order: std::option::Option<i64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbPoolTokenDto {
|
||||
/// Creates a new pool token DTO.
|
||||
pub fn new(
|
||||
pool_id: i64,
|
||||
token_id: i64,
|
||||
role: crate::KbPoolTokenRole,
|
||||
vault_address: std::option::Option<std::string::String>,
|
||||
token_order: std::option::Option<i64>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
pool_id,
|
||||
token_id,
|
||||
role,
|
||||
vault_address,
|
||||
token_order,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbPoolTokenEntity> for KbPoolTokenDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbPoolTokenEntity) -> Result<Self, Self::Error> {
|
||||
let role_result = crate::KbPoolTokenRole::from_i16(entity.role);
|
||||
let role = match role_result {
|
||||
Ok(role) => role,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_token created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse pool_token updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
pool_id: entity.pool_id,
|
||||
token_id: entity.token_id,
|
||||
role,
|
||||
vault_address: entity.vault_address,
|
||||
token_order: entity.token_order,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
129
kb_lib/src/db/dtos/swap.rs
Normal file
129
kb_lib/src/db/dtos/swap.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
// file: kb_lib/src/db/dtos/swap.rs
|
||||
|
||||
//! Swap DTO.
|
||||
|
||||
/// Application-facing normalized swap DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbSwapDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Optional trader wallet.
|
||||
pub trader_wallet: std::option::Option<std::string::String>,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Base amount as decimal text.
|
||||
pub base_amount: std::string::String,
|
||||
/// Quote amount as decimal text.
|
||||
pub quote_amount: std::string::String,
|
||||
/// Optional price in quote units as decimal text.
|
||||
pub price_quote: std::option::Option<std::string::String>,
|
||||
/// Trade side relative to the base token.
|
||||
pub trade_side: crate::KbSwapTradeSide,
|
||||
/// Execution timestamp.
|
||||
pub executed_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbSwapDto {
|
||||
/// Creates a new swap DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: std::option::Option<i64>,
|
||||
signature: std::string::String,
|
||||
instruction_index: i64,
|
||||
slot: std::option::Option<u64>,
|
||||
trader_wallet: std::option::Option<std::string::String>,
|
||||
base_token_id: i64,
|
||||
quote_token_id: i64,
|
||||
base_amount: std::string::String,
|
||||
quote_amount: std::string::String,
|
||||
price_quote: std::option::Option<std::string::String>,
|
||||
trade_side: crate::KbSwapTradeSide,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
signature,
|
||||
instruction_index,
|
||||
slot,
|
||||
trader_wallet,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount,
|
||||
quote_amount,
|
||||
price_quote,
|
||||
trade_side,
|
||||
executed_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbSwapEntity> for KbSwapDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbSwapEntity) -> Result<Self, Self::Error> {
|
||||
let trade_side_result = crate::KbSwapTradeSide::from_i16(entity.trade_side);
|
||||
let trade_side = match trade_side_result {
|
||||
Ok(trade_side) => trade_side,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let executed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.executed_at);
|
||||
let executed_at = match executed_at_result {
|
||||
Ok(executed_at) => executed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse swap executed_at '{}': {}",
|
||||
entity.executed_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert swap slot '{}' to u64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
signature: entity.signature,
|
||||
instruction_index: entity.instruction_index,
|
||||
slot,
|
||||
trader_wallet: entity.trader_wallet,
|
||||
base_token_id: entity.base_token_id,
|
||||
quote_token_id: entity.quote_token_id,
|
||||
base_amount: entity.base_amount,
|
||||
quote_amount: entity.quote_amount,
|
||||
price_quote: entity.price_quote,
|
||||
trade_side,
|
||||
executed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
104
kb_lib/src/db/dtos/token.rs
Normal file
104
kb_lib/src/db/dtos/token.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
// file: kb_lib/src/db/dtos/token.rs
|
||||
|
||||
//! Normalized token DTO.
|
||||
|
||||
/// Application-facing normalized token DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbTokenDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Mint address.
|
||||
pub mint: std::string::String,
|
||||
/// Optional token symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// Optional token display name.
|
||||
pub name: std::option::Option<std::string::String>,
|
||||
/// Optional decimals value.
|
||||
pub decimals: std::option::Option<u8>,
|
||||
/// Token program id.
|
||||
pub token_program: std::string::String,
|
||||
/// Whether this token is typically used as quote token.
|
||||
pub is_quote_token: bool,
|
||||
/// First seen timestamp.
|
||||
pub first_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbTokenDto {
|
||||
/// Creates a new token DTO.
|
||||
pub fn new(
|
||||
mint: std::string::String,
|
||||
symbol: std::option::Option<std::string::String>,
|
||||
name: std::option::Option<std::string::String>,
|
||||
decimals: std::option::Option<u8>,
|
||||
token_program: std::string::String,
|
||||
is_quote_token: bool,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
mint,
|
||||
symbol,
|
||||
name,
|
||||
decimals,
|
||||
token_program,
|
||||
is_quote_token,
|
||||
first_seen_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbTokenEntity> for KbTokenDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbTokenEntity) -> Result<Self, Self::Error> {
|
||||
let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
|
||||
let first_seen_at = match first_seen_at_result {
|
||||
Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse token first_seen_at '{}': {}",
|
||||
entity.first_seen_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse token updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let decimals = match entity.decimals {
|
||||
Some(decimals) => {
|
||||
let decimals_result = u8::try_from(decimals);
|
||||
match decimals_result {
|
||||
Ok(decimals) => Some(decimals),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert token decimals '{}' to u8: {}",
|
||||
decimals, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
mint: entity.mint,
|
||||
symbol: entity.symbol,
|
||||
name: entity.name,
|
||||
decimals,
|
||||
token_program: entity.token_program,
|
||||
is_quote_token: entity.is_quote_token != 0,
|
||||
first_seen_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
103
kb_lib/src/db/dtos/token_burn_event.rs
Normal file
103
kb_lib/src/db/dtos/token_burn_event.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
// file: kb_lib/src/db/dtos/token_burn_event.rs
|
||||
|
||||
//! Token burn event DTO.
|
||||
|
||||
/// Application-facing normalized token burn event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbTokenBurnEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Optional authority wallet.
|
||||
pub authority_wallet: std::option::Option<std::string::String>,
|
||||
/// Optional source wallet.
|
||||
pub source_wallet: std::option::Option<std::string::String>,
|
||||
/// Burned amount as decimal text.
|
||||
pub amount: std::string::String,
|
||||
/// Optional supply after burn as decimal text.
|
||||
pub supply_after: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp.
|
||||
pub executed_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbTokenBurnEventDto {
|
||||
/// Creates a new token burn event DTO.
|
||||
pub fn new(
|
||||
token_id: i64,
|
||||
signature: std::string::String,
|
||||
instruction_index: i64,
|
||||
slot: std::option::Option<u64>,
|
||||
authority_wallet: std::option::Option<std::string::String>,
|
||||
source_wallet: std::option::Option<std::string::String>,
|
||||
amount: std::string::String,
|
||||
supply_after: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
token_id,
|
||||
signature,
|
||||
instruction_index,
|
||||
slot,
|
||||
authority_wallet,
|
||||
source_wallet,
|
||||
amount,
|
||||
supply_after,
|
||||
executed_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbTokenBurnEventEntity> for KbTokenBurnEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(
|
||||
entity: crate::KbTokenBurnEventEntity,
|
||||
) -> Result<Self, Self::Error> {
|
||||
let executed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.executed_at);
|
||||
let executed_at = match executed_at_result {
|
||||
Ok(executed_at) => executed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse token burn event executed_at '{}': {}",
|
||||
entity.executed_at,
|
||||
error
|
||||
)));
|
||||
},
|
||||
};
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert token burn event slot '{}' to u64: {}",
|
||||
slot,
|
||||
error
|
||||
)));
|
||||
},
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
token_id: entity.token_id,
|
||||
signature: entity.signature,
|
||||
instruction_index: entity.instruction_index,
|
||||
slot,
|
||||
authority_wallet: entity.authority_wallet,
|
||||
source_wallet: entity.source_wallet,
|
||||
amount: entity.amount,
|
||||
supply_after: entity.supply_after,
|
||||
executed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
99
kb_lib/src/db/dtos/token_mint_event.rs
Normal file
99
kb_lib/src/db/dtos/token_mint_event.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
// file: kb_lib/src/db/dtos/token_mint_event.rs
|
||||
|
||||
//! Token mint event DTO.
|
||||
|
||||
/// Application-facing normalized token mint event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbTokenMintEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<u64>,
|
||||
/// Optional mint authority wallet.
|
||||
pub authority_wallet: std::option::Option<std::string::String>,
|
||||
/// Optional destination wallet.
|
||||
pub destination_wallet: std::option::Option<std::string::String>,
|
||||
/// Minted amount as decimal text.
|
||||
pub amount: std::string::String,
|
||||
/// Optional supply after mint as decimal text.
|
||||
pub supply_after: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp.
|
||||
pub executed_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbTokenMintEventDto {
|
||||
/// Creates a new token mint event DTO.
|
||||
pub fn new(
|
||||
token_id: i64,
|
||||
signature: std::string::String,
|
||||
instruction_index: i64,
|
||||
slot: std::option::Option<u64>,
|
||||
authority_wallet: std::option::Option<std::string::String>,
|
||||
destination_wallet: std::option::Option<std::string::String>,
|
||||
amount: std::string::String,
|
||||
supply_after: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: None,
|
||||
token_id,
|
||||
signature,
|
||||
instruction_index,
|
||||
slot,
|
||||
authority_wallet,
|
||||
destination_wallet,
|
||||
amount,
|
||||
supply_after,
|
||||
executed_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbTokenMintEventEntity> for KbTokenMintEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbTokenMintEventEntity) -> Result<Self, Self::Error> {
|
||||
let executed_at_result = chrono::DateTime::parse_from_rfc3339(&entity.executed_at);
|
||||
let executed_at = match executed_at_result {
|
||||
Ok(executed_at) => executed_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse token mint event executed_at '{}': {}",
|
||||
entity.executed_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let slot = match entity.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = u64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert token mint event slot '{}' to u64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
token_id: entity.token_id,
|
||||
signature: entity.signature,
|
||||
instruction_index: entity.instruction_index,
|
||||
slot,
|
||||
authority_wallet: entity.authority_wallet,
|
||||
destination_wallet: entity.destination_wallet,
|
||||
amount: entity.amount,
|
||||
supply_after: entity.supply_after,
|
||||
executed_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
153
kb_lib/src/db/dtos/trade_event.rs
Normal file
153
kb_lib/src/db/dtos/trade_event.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
// file: kb_lib/src/db/dtos/trade_event.rs
|
||||
|
||||
//! Trade-event DTO.
|
||||
|
||||
/// Application-facing trade-event DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbTradeEventDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Related transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional observed slot.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Stable trade side.
|
||||
pub trade_side: crate::KbSwapTradeSide,
|
||||
/// Related base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Related quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional raw base amount.
|
||||
pub base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional raw quote amount.
|
||||
pub quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional derived quote-per-base price.
|
||||
pub price_quote_per_base: std::option::Option<f64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Persisted payload JSON.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbTradeEventDto {
|
||||
/// Creates a new trade-event DTO.
|
||||
pub fn new(
|
||||
dex_id: i64,
|
||||
pool_id: i64,
|
||||
pair_id: i64,
|
||||
transaction_id: i64,
|
||||
decoded_event_id: i64,
|
||||
signature: std::string::String,
|
||||
slot: std::option::Option<i64>,
|
||||
trade_side: crate::KbSwapTradeSide,
|
||||
base_token_id: i64,
|
||||
quote_token_id: i64,
|
||||
base_amount_raw: std::option::Option<std::string::String>,
|
||||
quote_amount_raw: std::option::Option<std::string::String>,
|
||||
price_quote_per_base: std::option::Option<f64>,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
payload_json: std::string::String,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
dex_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
signature,
|
||||
slot,
|
||||
trade_side,
|
||||
base_token_id,
|
||||
quote_token_id,
|
||||
base_amount_raw,
|
||||
quote_amount_raw,
|
||||
price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
payload_json,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbTradeEventEntity> for KbTradeEventDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbTradeEventEntity) -> Result<Self, Self::Error> {
|
||||
let trade_side = kb_trade_side_from_string(entity.trade_side.as_str());
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse trade_event created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse trade_event updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
dex_id: entity.dex_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
transaction_id: entity.transaction_id,
|
||||
decoded_event_id: entity.decoded_event_id,
|
||||
signature: entity.signature,
|
||||
slot: entity.slot,
|
||||
trade_side,
|
||||
base_token_id: entity.base_token_id,
|
||||
quote_token_id: entity.quote_token_id,
|
||||
base_amount_raw: entity.base_amount_raw,
|
||||
quote_amount_raw: entity.quote_amount_raw,
|
||||
price_quote_per_base: entity.price_quote_per_base,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
payload_json: entity.payload_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_trade_side_from_string(value: &str) -> crate::KbSwapTradeSide {
|
||||
match value {
|
||||
"BuyBase" => crate::KbSwapTradeSide::BuyBase,
|
||||
"SellBase" => crate::KbSwapTradeSide::SellBase,
|
||||
_ => crate::KbSwapTradeSide::Unknown,
|
||||
}
|
||||
}
|
||||
69
kb_lib/src/db/dtos/wallet.rs
Normal file
69
kb_lib/src/db/dtos/wallet.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
// file: kb_lib/src/db/dtos/wallet.rs
|
||||
|
||||
//! Wallet DTO.
|
||||
|
||||
/// Application-facing wallet DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbWalletDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Stable wallet address.
|
||||
pub address: std::string::String,
|
||||
/// Optional user-defined label.
|
||||
pub label: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub first_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub last_seen_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbWalletDto {
|
||||
/// Creates a new wallet DTO.
|
||||
pub fn new(
|
||||
address: std::string::String,
|
||||
label: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
address,
|
||||
label,
|
||||
first_seen_at: now,
|
||||
last_seen_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbWalletEntity> for KbWalletDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbWalletEntity) -> Result<Self, Self::Error> {
|
||||
let first_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.first_seen_at);
|
||||
let first_seen_at = match first_seen_at_result {
|
||||
Ok(first_seen_at) => first_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet first_seen_at '{}': {}",
|
||||
entity.first_seen_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let last_seen_at_result = chrono::DateTime::parse_from_rfc3339(&entity.last_seen_at);
|
||||
let last_seen_at = match last_seen_at_result {
|
||||
Ok(last_seen_at) => last_seen_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet last_seen_at '{}': {}",
|
||||
entity.last_seen_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
address: entity.address,
|
||||
label: entity.label,
|
||||
first_seen_at,
|
||||
last_seen_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
124
kb_lib/src/db/dtos/wallet_holding.rs
Normal file
124
kb_lib/src/db/dtos/wallet_holding.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
// file: kb_lib/src/db/dtos/wallet_holding.rs
|
||||
|
||||
//! Wallet-holding DTO.
|
||||
|
||||
/// Application-facing wallet-holding DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbWalletHoldingDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related wallet id.
|
||||
pub wallet_id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// First transaction id that observed this wallet/token relationship.
|
||||
pub first_transaction_id: i64,
|
||||
/// Last transaction id that observed this wallet/token relationship.
|
||||
pub last_transaction_id: i64,
|
||||
/// Optional last decoded-event id.
|
||||
pub last_decoded_event_id: std::option::Option<i64>,
|
||||
/// Optional last related pool id.
|
||||
pub last_pool_id: std::option::Option<i64>,
|
||||
/// Optional last related pair id.
|
||||
pub last_pair_id: std::option::Option<i64>,
|
||||
/// Optional last observed role.
|
||||
pub last_role: std::option::Option<std::string::String>,
|
||||
/// Optional last observed raw balance-like value.
|
||||
pub balance_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot_observed: std::option::Option<i64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbWalletHoldingDto {
|
||||
/// Creates a new wallet-holding DTO.
|
||||
pub fn new(
|
||||
wallet_id: i64,
|
||||
token_id: i64,
|
||||
first_transaction_id: i64,
|
||||
last_transaction_id: i64,
|
||||
last_decoded_event_id: std::option::Option<i64>,
|
||||
last_pool_id: std::option::Option<i64>,
|
||||
last_pair_id: std::option::Option<i64>,
|
||||
last_role: std::option::Option<std::string::String>,
|
||||
balance_raw: std::option::Option<std::string::String>,
|
||||
last_slot_observed: std::option::Option<i64>,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
wallet_id,
|
||||
token_id,
|
||||
first_transaction_id,
|
||||
last_transaction_id,
|
||||
last_decoded_event_id,
|
||||
last_pool_id,
|
||||
last_pair_id,
|
||||
last_role,
|
||||
balance_raw,
|
||||
last_slot_observed,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbWalletHoldingEntity> for KbWalletHoldingDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbWalletHoldingEntity) -> Result<Self, Self::Error> {
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet_holding created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet_holding updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
wallet_id: entity.wallet_id,
|
||||
token_id: entity.token_id,
|
||||
first_transaction_id: entity.first_transaction_id,
|
||||
last_transaction_id: entity.last_transaction_id,
|
||||
last_decoded_event_id: entity.last_decoded_event_id,
|
||||
last_pool_id: entity.last_pool_id,
|
||||
last_pair_id: entity.last_pair_id,
|
||||
last_role: entity.last_role,
|
||||
balance_raw: entity.balance_raw,
|
||||
last_slot_observed: entity.last_slot_observed,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
134
kb_lib/src/db/dtos/wallet_participation.rs
Normal file
134
kb_lib/src/db/dtos/wallet_participation.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
// file: kb_lib/src/db/dtos/wallet_participation.rs
|
||||
|
||||
//! Wallet-participation DTO.
|
||||
|
||||
/// Application-facing wallet-participation DTO.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct KbWalletParticipationDto {
|
||||
/// Optional numeric primary key.
|
||||
pub id: std::option::Option<i64>,
|
||||
/// Related wallet id.
|
||||
pub wallet_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional related decoded event id.
|
||||
pub decoded_event_id: std::option::Option<i64>,
|
||||
/// Optional related pool id.
|
||||
pub pool_id: std::option::Option<i64>,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Stable participation role.
|
||||
pub role: std::string::String,
|
||||
/// Stable unique key used for idempotent upserts.
|
||||
pub unique_key: std::string::String,
|
||||
/// Observation source kind.
|
||||
pub source_kind: crate::KbObservationSourceKind,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
/// Update timestamp.
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl KbWalletParticipationDto {
|
||||
/// Creates a new wallet-participation DTO.
|
||||
pub fn new(
|
||||
wallet_id: i64,
|
||||
transaction_id: i64,
|
||||
decoded_event_id: std::option::Option<i64>,
|
||||
pool_id: std::option::Option<i64>,
|
||||
pair_id: std::option::Option<i64>,
|
||||
role: std::string::String,
|
||||
source_kind: crate::KbObservationSourceKind,
|
||||
source_endpoint_name: std::option::Option<std::string::String>,
|
||||
) -> Self {
|
||||
let now = chrono::Utc::now();
|
||||
let unique_key = kb_build_wallet_participation_unique_key(
|
||||
wallet_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
role.as_str(),
|
||||
);
|
||||
|
||||
Self {
|
||||
id: None,
|
||||
wallet_id,
|
||||
transaction_id,
|
||||
decoded_event_id,
|
||||
pool_id,
|
||||
pair_id,
|
||||
role,
|
||||
unique_key,
|
||||
source_kind,
|
||||
source_endpoint_name,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<crate::KbWalletParticipationEntity> for KbWalletParticipationDto {
|
||||
type Error = crate::KbError;
|
||||
|
||||
fn try_from(entity: crate::KbWalletParticipationEntity) -> Result<Self, Self::Error> {
|
||||
let source_kind_result = crate::KbObservationSourceKind::from_i16(entity.source_kind);
|
||||
let source_kind = match source_kind_result {
|
||||
Ok(source_kind) => source_kind,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
|
||||
let created_at = match created_at_result {
|
||||
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet_participation created_at '{}': {}",
|
||||
entity.created_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
|
||||
let updated_at = match updated_at_result {
|
||||
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot parse wallet_participation updated_at '{}': {}",
|
||||
entity.updated_at, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: Some(entity.id),
|
||||
wallet_id: entity.wallet_id,
|
||||
transaction_id: entity.transaction_id,
|
||||
decoded_event_id: entity.decoded_event_id,
|
||||
pool_id: entity.pool_id,
|
||||
pair_id: entity.pair_id,
|
||||
role: entity.role,
|
||||
unique_key: entity.unique_key,
|
||||
source_kind,
|
||||
source_endpoint_name: entity.source_endpoint_name,
|
||||
created_at,
|
||||
updated_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn kb_build_wallet_participation_unique_key(
|
||||
wallet_id: i64,
|
||||
transaction_id: i64,
|
||||
decoded_event_id: std::option::Option<i64>,
|
||||
pool_id: std::option::Option<i64>,
|
||||
pair_id: std::option::Option<i64>,
|
||||
role: &str,
|
||||
) -> std::string::String {
|
||||
let decoded_event_id_value = decoded_event_id.unwrap_or_default();
|
||||
let pool_id_value = pool_id.unwrap_or_default();
|
||||
let pair_id_value = pair_id.unwrap_or_default();
|
||||
format!(
|
||||
"{}:{}:{}:{}:{}:{}",
|
||||
wallet_id, transaction_id, decoded_event_id_value, pool_id_value, pair_id_value, role
|
||||
)
|
||||
}
|
||||
71
kb_lib/src/db/entities.rs
Normal file
71
kb_lib/src/db/entities.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
// file: kb_lib/src/db/entities.rs
|
||||
|
||||
//! Database entities.
|
||||
//!
|
||||
//! These types are close to persisted rows and SQL query results.
|
||||
|
||||
mod analysis_signal;
|
||||
mod chain_instruction;
|
||||
mod chain_slot;
|
||||
mod chain_transaction;
|
||||
mod db_metadata;
|
||||
mod db_runtime_event;
|
||||
mod dex;
|
||||
mod dex_decoded_event;
|
||||
mod known_http_endpoint;
|
||||
mod known_ws_endpoint;
|
||||
mod launch_attribution;
|
||||
mod launch_surface;
|
||||
mod launch_surface_key;
|
||||
mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_analytic_signal;
|
||||
mod pair_candle;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
mod pool_token;
|
||||
mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_holding;
|
||||
mod wallet_participation;
|
||||
|
||||
pub use analysis_signal::KbAnalysisSignalEntity;
|
||||
pub use chain_instruction::KbChainInstructionEntity;
|
||||
pub use chain_slot::KbChainSlotEntity;
|
||||
pub use chain_transaction::KbChainTransactionEntity;
|
||||
pub use db_metadata::KbDbMetadataEntity;
|
||||
pub use db_runtime_event::KbDbRuntimeEventEntity;
|
||||
pub use dex::KbDexEntity;
|
||||
pub use dex_decoded_event::KbDexDecodedEventEntity;
|
||||
pub use known_http_endpoint::KbKnownHttpEndpointEntity;
|
||||
pub use known_ws_endpoint::KbKnownWsEndpointEntity;
|
||||
pub use launch_attribution::KbLaunchAttributionEntity;
|
||||
pub use launch_surface::KbLaunchSurfaceEntity;
|
||||
pub use launch_surface_key::KbLaunchSurfaceKeyEntity;
|
||||
pub use liquidity_event::KbLiquidityEventEntity;
|
||||
pub use observed_token::KbObservedTokenEntity;
|
||||
pub use onchain_observation::KbOnchainObservationEntity;
|
||||
pub use pair::KbPairEntity;
|
||||
pub use pair_analytic_signal::KbPairAnalyticSignalEntity;
|
||||
pub use pair_candle::KbPairCandleEntity;
|
||||
pub use pair_metric::KbPairMetricEntity;
|
||||
pub use pool::KbPoolEntity;
|
||||
pub use pool_listing::KbPoolListingEntity;
|
||||
pub use pool_origin::KbPoolOriginEntity;
|
||||
pub use pool_token::KbPoolTokenEntity;
|
||||
pub use swap::KbSwapEntity;
|
||||
pub use token::KbTokenEntity;
|
||||
pub use token_burn_event::KbTokenBurnEventEntity;
|
||||
pub use token_mint_event::KbTokenMintEventEntity;
|
||||
pub use trade_event::KbTradeEventEntity;
|
||||
pub use wallet::KbWalletEntity;
|
||||
pub use wallet_holding::KbWalletHoldingEntity;
|
||||
pub use wallet_participation::KbWalletParticipationEntity;
|
||||
24
kb_lib/src/db/entities/analysis_signal.rs
Normal file
24
kb_lib/src/db/entities/analysis_signal.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// file: kb_lib/src/db/entities/analysis_signal.rs
|
||||
|
||||
//! Analysis signal entity.
|
||||
|
||||
/// Persisted analysis signal row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbAnalysisSignalEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Signal kind.
|
||||
pub signal_kind: std::string::String,
|
||||
/// Signal severity stored as stable integer.
|
||||
pub severity: i16,
|
||||
/// Logical object key, for example a mint, signature or pool address.
|
||||
pub object_key: std::string::String,
|
||||
/// Optional related on-chain observation id.
|
||||
pub related_observation_id: std::option::Option<i64>,
|
||||
/// Optional numeric score.
|
||||
pub score: std::option::Option<f64>,
|
||||
/// JSON-encoded payload.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
}
|
||||
34
kb_lib/src/db/entities/chain_instruction.rs
Normal file
34
kb_lib/src/db/entities/chain_instruction.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
// file: kb_lib/src/db/entities/chain_instruction.rs
|
||||
|
||||
//! Database entity for one normalized Solana instruction row.
|
||||
|
||||
/// Persisted Solana instruction row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbChainInstructionEntity {
|
||||
/// Internal row id.
|
||||
pub id: i64,
|
||||
/// Parent transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional parent instruction id for inner instructions.
|
||||
pub parent_instruction_id: std::option::Option<i64>,
|
||||
/// Top-level instruction index.
|
||||
pub instruction_index: i64,
|
||||
/// Optional inner instruction index.
|
||||
pub inner_instruction_index: std::option::Option<i64>,
|
||||
/// Optional program id.
|
||||
pub program_id: std::option::Option<std::string::String>,
|
||||
/// Optional program name.
|
||||
pub program_name: std::option::Option<std::string::String>,
|
||||
/// Optional stack height.
|
||||
pub stack_height: std::option::Option<i64>,
|
||||
/// Accounts JSON array.
|
||||
pub accounts_json: std::string::String,
|
||||
/// Optional data JSON.
|
||||
pub data_json: std::option::Option<std::string::String>,
|
||||
/// Optional parsed type.
|
||||
pub parsed_type: std::option::Option<std::string::String>,
|
||||
/// Optional parsed payload JSON.
|
||||
pub parsed_json: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: std::string::String,
|
||||
}
|
||||
19
kb_lib/src/db/entities/chain_slot.rs
Normal file
19
kb_lib/src/db/entities/chain_slot.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
|
||||
// file: kb_lib/src/db/entities/chain_slot.rs
|
||||
|
||||
//! Database entity for one observed Solana slot.
|
||||
|
||||
/// Persisted Solana slot row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbChainSlotEntity {
|
||||
/// Slot number.
|
||||
pub slot: i64,
|
||||
/// Optional parent slot number.
|
||||
pub parent_slot: std::option::Option<i64>,
|
||||
/// Optional block time in unix seconds.
|
||||
pub block_time_unix: std::option::Option<i64>,
|
||||
/// Creation timestamp.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
30
kb_lib/src/db/entities/chain_transaction.rs
Normal file
30
kb_lib/src/db/entities/chain_transaction.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
// file: kb_lib/src/db/entities/chain_transaction.rs
|
||||
|
||||
//! Database entity for one resolved Solana transaction.
|
||||
|
||||
/// Persisted Solana transaction row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbChainTransactionEntity {
|
||||
/// Internal row id.
|
||||
pub id: i64,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Optional block time in unix seconds.
|
||||
pub block_time_unix: std::option::Option<i64>,
|
||||
/// Optional logical endpoint name that resolved the transaction.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Optional version text.
|
||||
pub version_text: std::option::Option<std::string::String>,
|
||||
/// Optional transaction error JSON.
|
||||
pub err_json: std::option::Option<std::string::String>,
|
||||
/// Optional transaction meta JSON.
|
||||
pub meta_json: std::option::Option<std::string::String>,
|
||||
/// Full transaction JSON.
|
||||
pub transaction_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
14
kb_lib/src/db/entities/db_metadata.rs
Normal file
14
kb_lib/src/db/entities/db_metadata.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
// file: kb_lib/src/db/entities/db_metadata.rs
|
||||
|
||||
//! Metadata table entity.
|
||||
|
||||
/// Persisted metadata row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbDbMetadataEntity {
|
||||
/// Metadata key.
|
||||
pub key: std::string::String,
|
||||
/// Metadata value.
|
||||
pub value: std::string::String,
|
||||
/// Last update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
20
kb_lib/src/db/entities/db_runtime_event.rs
Normal file
20
kb_lib/src/db/entities/db_runtime_event.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
// file: kb_lib/src/db/entities/db_runtime_event.rs
|
||||
|
||||
//! Runtime event entity.
|
||||
|
||||
/// Persisted runtime event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbDbRuntimeEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Event kind.
|
||||
pub event_kind: std::string::String,
|
||||
/// Severity level stored as stable integer.
|
||||
pub level: i16,
|
||||
/// Event source.
|
||||
pub source: std::string::String,
|
||||
/// Human-readable message.
|
||||
pub message: std::string::String,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
}
|
||||
24
kb_lib/src/db/entities/dex.rs
Normal file
24
kb_lib/src/db/entities/dex.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// file: kb_lib/src/db/entities/dex.rs
|
||||
|
||||
//! DEX entity.
|
||||
|
||||
/// Persisted normalized DEX row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbDexEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Stable short code.
|
||||
pub code: std::string::String,
|
||||
/// Display name.
|
||||
pub name: std::string::String,
|
||||
/// Optional primary program id.
|
||||
pub program_id: std::option::Option<std::string::String>,
|
||||
/// Optional router program id.
|
||||
pub router_program_id: std::option::Option<std::string::String>,
|
||||
/// Whether this DEX is enabled.
|
||||
pub is_enabled: i64,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
34
kb_lib/src/db/entities/dex_decoded_event.rs
Normal file
34
kb_lib/src/db/entities/dex_decoded_event.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
// file: kb_lib/src/db/entities/dex_decoded_event.rs
|
||||
|
||||
//! Database entity for one decoded DEX event.
|
||||
|
||||
/// Persisted decoded DEX event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbDexDecodedEventEntity {
|
||||
/// Internal row id.
|
||||
pub id: i64,
|
||||
/// Parent transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional parent instruction id.
|
||||
pub instruction_id: std::option::Option<i64>,
|
||||
/// Decoded protocol name.
|
||||
pub protocol_name: std::string::String,
|
||||
/// Program id that produced the decoded event.
|
||||
pub program_id: std::string::String,
|
||||
/// Event kind.
|
||||
pub event_kind: std::string::String,
|
||||
/// Optional decoded pool account.
|
||||
pub pool_account: std::option::Option<std::string::String>,
|
||||
/// Optional decoded lp mint.
|
||||
pub lp_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded token A mint.
|
||||
pub token_a_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded token B mint.
|
||||
pub token_b_mint: std::option::Option<std::string::String>,
|
||||
/// Optional decoded market account.
|
||||
pub market_account: std::option::Option<std::string::String>,
|
||||
/// Serialized decoded payload.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp.
|
||||
pub created_at: std::string::String,
|
||||
}
|
||||
22
kb_lib/src/db/entities/known_http_endpoint.rs
Normal file
22
kb_lib/src/db/entities/known_http_endpoint.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
// file: kb_lib/src/db/entities/known_http_endpoint.rs
|
||||
|
||||
//! Known HTTP endpoint entity.
|
||||
|
||||
/// Persisted known HTTP endpoint row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbKnownHttpEndpointEntity {
|
||||
/// Logical endpoint name.
|
||||
pub name: std::string::String,
|
||||
/// Provider name.
|
||||
pub provider: std::string::String,
|
||||
/// Endpoint URL.
|
||||
pub url: std::string::String,
|
||||
/// Whether this endpoint is enabled.
|
||||
pub enabled: i64,
|
||||
/// JSON-encoded roles.
|
||||
pub roles_json: std::string::String,
|
||||
/// Optional last seen timestamp encoded as RFC3339 UTC text.
|
||||
pub last_seen_at: std::option::Option<std::string::String>,
|
||||
/// Last update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
22
kb_lib/src/db/entities/known_ws_endpoint.rs
Normal file
22
kb_lib/src/db/entities/known_ws_endpoint.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
// file: kb_lib/src/db/entities/known_ws_endpoint.rs
|
||||
|
||||
//! Known WebSocket endpoint entity.
|
||||
|
||||
/// Persisted known WebSocket endpoint row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbKnownWsEndpointEntity {
|
||||
/// Logical endpoint name.
|
||||
pub name: std::string::String,
|
||||
/// Provider name.
|
||||
pub provider: std::string::String,
|
||||
/// Endpoint URL.
|
||||
pub url: std::string::String,
|
||||
/// Whether this endpoint is enabled.
|
||||
pub enabled: i64,
|
||||
/// JSON-encoded roles.
|
||||
pub roles_json: std::string::String,
|
||||
/// Optional last seen timestamp encoded as RFC3339 UTC text.
|
||||
pub last_seen_at: std::option::Option<std::string::String>,
|
||||
/// Last update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
32
kb_lib/src/db/entities/launch_attribution.rs
Normal file
32
kb_lib/src/db/entities/launch_attribution.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
// file: kb_lib/src/db/entities/launch_attribution.rs
|
||||
|
||||
//! Launch attribution entity.
|
||||
|
||||
/// Persisted launch attribution row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbLaunchAttributionEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related launch surface id.
|
||||
pub launch_surface_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Optional related pool id.
|
||||
pub pool_id: std::option::Option<i64>,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Optional related matched key id.
|
||||
pub matched_key_id: std::option::Option<i64>,
|
||||
/// Decoded protocol name.
|
||||
pub protocol_name: std::string::String,
|
||||
/// Match kind used for attribution.
|
||||
pub match_kind: std::string::String,
|
||||
/// Matched value used for attribution.
|
||||
pub matched_value: std::string::String,
|
||||
/// Attribution timestamp encoded as RFC3339 UTC text.
|
||||
pub attributed_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
22
kb_lib/src/db/entities/launch_surface.rs
Normal file
22
kb_lib/src/db/entities/launch_surface.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
// file: kb_lib/src/db/entities/launch_surface.rs
|
||||
|
||||
//! Launch surface entity.
|
||||
|
||||
/// Persisted launch surface row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbLaunchSurfaceEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Stable short code.
|
||||
pub code: std::string::String,
|
||||
/// Display name.
|
||||
pub name: std::string::String,
|
||||
/// Optional protocol family hint.
|
||||
pub protocol_family: std::option::Option<std::string::String>,
|
||||
/// Whether the surface is enabled.
|
||||
pub is_enabled: i64,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
20
kb_lib/src/db/entities/launch_surface_key.rs
Normal file
20
kb_lib/src/db/entities/launch_surface_key.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
// file: kb_lib/src/db/entities/launch_surface_key.rs
|
||||
|
||||
//! Launch surface key entity.
|
||||
|
||||
/// Persisted launch surface matching key row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbLaunchSurfaceKeyEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related launch surface id.
|
||||
pub launch_surface_id: i64,
|
||||
/// Stable key kind, for example `config_account` or `creator`.
|
||||
pub match_kind: std::string::String,
|
||||
/// Stable key value.
|
||||
pub match_value: std::string::String,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
40
kb_lib/src/db/entities/liquidity_event.rs
Normal file
40
kb_lib/src/db/entities/liquidity_event.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
// file: kb_lib/src/db/entities/liquidity_event.rs
|
||||
|
||||
//! Liquidity event entity.
|
||||
|
||||
/// Persisted normalized liquidity event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbLiquidityEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Event kind stored as stable integer.
|
||||
pub event_kind: i16,
|
||||
/// Optional actor wallet.
|
||||
pub actor_wallet: std::option::Option<std::string::String>,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional LP token id.
|
||||
pub lp_token_id: std::option::Option<i64>,
|
||||
/// Base amount as decimal text.
|
||||
pub base_amount: std::string::String,
|
||||
/// Quote amount as decimal text.
|
||||
pub quote_amount: std::string::String,
|
||||
/// Optional LP amount as decimal text.
|
||||
pub lp_amount: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp encoded as RFC3339 UTC text.
|
||||
pub executed_at: std::string::String,
|
||||
}
|
||||
28
kb_lib/src/db/entities/observed_token.rs
Normal file
28
kb_lib/src/db/entities/observed_token.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
// file: kb_lib/src/db/entities/observed_token.rs
|
||||
|
||||
//! Observed token entity.
|
||||
|
||||
/// Persisted observed token row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbObservedTokenEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Token mint address.
|
||||
pub mint: std::string::String,
|
||||
/// Optional token symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// Optional token display name.
|
||||
pub name: std::option::Option<std::string::String>,
|
||||
/// Optional decimals value.
|
||||
pub decimals: std::option::Option<i64>,
|
||||
/// Token program id.
|
||||
pub token_program: std::string::String,
|
||||
/// Local status stored as stable integer.
|
||||
pub status: i16,
|
||||
/// First seen timestamp encoded as RFC3339 UTC text.
|
||||
pub first_seen_at: std::string::String,
|
||||
/// Last seen timestamp encoded as RFC3339 UTC text.
|
||||
pub last_seen_at: std::string::String,
|
||||
/// Last update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
24
kb_lib/src/db/entities/onchain_observation.rs
Normal file
24
kb_lib/src/db/entities/onchain_observation.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// file: kb_lib/src/db/entities/onchain_observation.rs
|
||||
|
||||
//! On-chain observation entity.
|
||||
|
||||
/// Persisted on-chain observation row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbOnchainObservationEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Observation kind.
|
||||
pub observation_kind: std::string::String,
|
||||
/// Observation source family stored as stable integer.
|
||||
pub source_kind: i16,
|
||||
/// Optional source endpoint logical name.
|
||||
pub endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Logical object key, for example a mint, signature or pool address.
|
||||
pub object_key: std::string::String,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// JSON-encoded raw payload.
|
||||
pub payload_json: std::string::String,
|
||||
/// Observation timestamp encoded as RFC3339 UTC text.
|
||||
pub observed_at: std::string::String,
|
||||
}
|
||||
24
kb_lib/src/db/entities/pair.rs
Normal file
24
kb_lib/src/db/entities/pair.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// file: kb_lib/src/db/entities/pair.rs
|
||||
|
||||
//! Normalized pair entity.
|
||||
|
||||
/// Persisted normalized pair row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPairEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional display symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// First seen timestamp encoded as RFC3339 UTC text.
|
||||
pub first_seen_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
32
kb_lib/src/db/entities/pair_analytic_signal.rs
Normal file
32
kb_lib/src/db/entities/pair_analytic_signal.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
// file: kb_lib/src/db/entities/pair_analytic_signal.rs
|
||||
|
||||
//! Pair-analytic-signal entity.
|
||||
|
||||
/// Persisted pair-analytic-signal row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPairAnalyticSignalEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Stable signal kind.
|
||||
pub signal_kind: std::string::String,
|
||||
/// Signal severity.
|
||||
pub severity: i16,
|
||||
/// Timeframe in seconds. Zero means non-bucketed signal.
|
||||
pub timeframe_seconds: i64,
|
||||
/// Inclusive bucket start in unix seconds. Zero means non-bucketed signal.
|
||||
pub bucket_start_unix: i64,
|
||||
/// Optional numeric score.
|
||||
pub score: std::option::Option<f64>,
|
||||
/// Signal value JSON encoded as text.
|
||||
pub signal_value_json: std::string::String,
|
||||
/// Optional first transaction id that produced this signal key.
|
||||
pub first_transaction_id: std::option::Option<i64>,
|
||||
/// Optional last transaction id that produced this signal key.
|
||||
pub last_transaction_id: std::option::Option<i64>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
44
kb_lib/src/db/entities/pair_candle.rs
Normal file
44
kb_lib/src/db/entities/pair_candle.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
// file: kb_lib/src/db/entities/pair_candle.rs
|
||||
|
||||
//! Pair-candle entity.
|
||||
|
||||
/// Persisted pair-candle row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPairCandleEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Candle timeframe in seconds.
|
||||
pub timeframe_seconds: i64,
|
||||
/// Inclusive bucket start in unix seconds.
|
||||
pub bucket_start_unix: i64,
|
||||
/// Exclusive bucket end in unix seconds.
|
||||
pub bucket_end_unix: i64,
|
||||
/// Open price in quote-per-base units.
|
||||
pub open_price_quote_per_base: f64,
|
||||
/// High price in quote-per-base units.
|
||||
pub high_price_quote_per_base: f64,
|
||||
/// Low price in quote-per-base units.
|
||||
pub low_price_quote_per_base: f64,
|
||||
/// Close price in quote-per-base units.
|
||||
pub close_price_quote_per_base: f64,
|
||||
/// Trade count inside the candle.
|
||||
pub trade_count: i64,
|
||||
/// Buy count inside the candle.
|
||||
pub buy_count: i64,
|
||||
/// Sell count inside the candle.
|
||||
pub sell_count: i64,
|
||||
/// Aggregated base volume as decimal text when available.
|
||||
pub base_volume_raw: std::option::Option<std::string::String>,
|
||||
/// Aggregated quote volume as decimal text when available.
|
||||
pub quote_volume_raw: std::option::Option<std::string::String>,
|
||||
/// Optional first trade signature inside the candle.
|
||||
pub first_trade_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last trade signature inside the candle.
|
||||
pub last_trade_signature: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
36
kb_lib/src/db/entities/pair_metric.rs
Normal file
36
kb_lib/src/db/entities/pair_metric.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
// file: kb_lib/src/db/entities/pair_metric.rs
|
||||
|
||||
//! Pair-metric entity.
|
||||
|
||||
/// Persisted pair-metric row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPairMetricEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Optional first observed slot.
|
||||
pub first_slot: std::option::Option<i64>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot: std::option::Option<i64>,
|
||||
/// Optional first observed signature.
|
||||
pub first_signature: std::option::Option<std::string::String>,
|
||||
/// Optional last observed signature.
|
||||
pub last_signature: std::option::Option<std::string::String>,
|
||||
/// Total trade count.
|
||||
pub trade_count: i64,
|
||||
/// Total buy count.
|
||||
pub buy_count: i64,
|
||||
/// Total sell count.
|
||||
pub sell_count: i64,
|
||||
/// Optional cumulative raw base volume.
|
||||
pub cumulative_base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional cumulative raw quote volume.
|
||||
pub cumulative_quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last derived quote-per-base price.
|
||||
pub last_price_quote_per_base: std::option::Option<f64>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
22
kb_lib/src/db/entities/pool.rs
Normal file
22
kb_lib/src/db/entities/pool.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
// file: kb_lib/src/db/entities/pool.rs
|
||||
|
||||
//! Normalized pool entity.
|
||||
|
||||
/// Persisted normalized pool row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPoolEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Pool address.
|
||||
pub address: std::string::String,
|
||||
/// Pool kind stored as stable integer.
|
||||
pub pool_kind: i16,
|
||||
/// Pool status stored as stable integer.
|
||||
pub status: i16,
|
||||
/// First seen timestamp encoded as RFC3339 UTC text.
|
||||
pub first_seen_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
30
kb_lib/src/db/entities/pool_listing.rs
Normal file
30
kb_lib/src/db/entities/pool_listing.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
// file: kb_lib/src/db/entities/pool_listing.rs
|
||||
|
||||
//! Pool listing entity.
|
||||
|
||||
/// Persisted normalized pool listing row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPoolListingEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Discovery source family stored as stable integer.
|
||||
pub source_kind: i16,
|
||||
/// Optional source endpoint logical name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Detection timestamp encoded as RFC3339 UTC text.
|
||||
pub detected_at: std::string::String,
|
||||
/// Optional initial base reserve estimate.
|
||||
pub initial_base_reserve: std::option::Option<f64>,
|
||||
/// Optional initial quote reserve estimate.
|
||||
pub initial_quote_reserve: std::option::Option<f64>,
|
||||
/// Optional initial price estimate in quote units.
|
||||
pub initial_price_quote: std::option::Option<f64>,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
38
kb_lib/src/db/entities/pool_origin.rs
Normal file
38
kb_lib/src/db/entities/pool_origin.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
// file: kb_lib/src/db/entities/pool_origin.rs
|
||||
|
||||
//! Pool origin entity.
|
||||
|
||||
/// Persisted pool-origin row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPoolOriginEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Optional related pool listing id.
|
||||
pub pool_listing_id: std::option::Option<i64>,
|
||||
/// Founding transaction id in the local model.
|
||||
pub founding_transaction_id: i64,
|
||||
/// Founding decoded-event id in the local model.
|
||||
pub founding_decoded_event_id: i64,
|
||||
/// Founding signature in the local model.
|
||||
pub founding_signature: std::string::String,
|
||||
/// Founding protocol name.
|
||||
pub founding_protocol_name: std::string::String,
|
||||
/// Founding event kind.
|
||||
pub founding_event_kind: std::string::String,
|
||||
/// Discovery source kind.
|
||||
pub source_kind: i16,
|
||||
/// Optional source endpoint logical name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Optional related launch attribution id.
|
||||
pub launch_attribution_id: std::option::Option<i64>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
24
kb_lib/src/db/entities/pool_token.rs
Normal file
24
kb_lib/src/db/entities/pool_token.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// file: kb_lib/src/db/entities/pool_token.rs
|
||||
|
||||
//! Pool token composition entity.
|
||||
|
||||
/// Persisted normalized pool token composition row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbPoolTokenEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Token role stored as stable integer.
|
||||
pub role: i16,
|
||||
/// Optional vault address.
|
||||
pub vault_address: std::option::Option<std::string::String>,
|
||||
/// Optional token order inside the pool.
|
||||
pub token_order: std::option::Option<i64>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
38
kb_lib/src/db/entities/swap.rs
Normal file
38
kb_lib/src/db/entities/swap.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
// file: kb_lib/src/db/entities/swap.rs
|
||||
|
||||
//! Swap entity.
|
||||
|
||||
/// Persisted normalized swap row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbSwapEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Optional trader wallet.
|
||||
pub trader_wallet: std::option::Option<std::string::String>,
|
||||
/// Base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Base amount as decimal text.
|
||||
pub base_amount: std::string::String,
|
||||
/// Quote amount as decimal text.
|
||||
pub quote_amount: std::string::String,
|
||||
/// Optional price in quote units as decimal text.
|
||||
pub price_quote: std::option::Option<std::string::String>,
|
||||
/// Trade side stored as stable integer.
|
||||
pub trade_side: i16,
|
||||
/// Execution timestamp encoded as RFC3339 UTC text.
|
||||
pub executed_at: std::string::String,
|
||||
}
|
||||
26
kb_lib/src/db/entities/token.rs
Normal file
26
kb_lib/src/db/entities/token.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
// file: kb_lib/src/db/entities/token.rs
|
||||
|
||||
//! Normalized token entity.
|
||||
|
||||
/// Persisted normalized token row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbTokenEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Mint address.
|
||||
pub mint: std::string::String,
|
||||
/// Optional token symbol.
|
||||
pub symbol: std::option::Option<std::string::String>,
|
||||
/// Optional token display name.
|
||||
pub name: std::option::Option<std::string::String>,
|
||||
/// Optional decimals value.
|
||||
pub decimals: std::option::Option<i64>,
|
||||
/// Token program id.
|
||||
pub token_program: std::string::String,
|
||||
/// Whether this token is typically used as quote token.
|
||||
pub is_quote_token: i64,
|
||||
/// First seen timestamp encoded as RFC3339 UTC text.
|
||||
pub first_seen_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
28
kb_lib/src/db/entities/token_burn_event.rs
Normal file
28
kb_lib/src/db/entities/token_burn_event.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
// file: kb_lib/src/db/entities/token_burn_event.rs
|
||||
|
||||
//! Token burn event entity.
|
||||
|
||||
/// Persisted normalized token burn event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbTokenBurnEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Optional authority wallet.
|
||||
pub authority_wallet: std::option::Option<std::string::String>,
|
||||
/// Optional source wallet.
|
||||
pub source_wallet: std::option::Option<std::string::String>,
|
||||
/// Burned amount as decimal text.
|
||||
pub amount: std::string::String,
|
||||
/// Optional supply after burn as decimal text.
|
||||
pub supply_after: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp encoded as RFC3339 UTC text.
|
||||
pub executed_at: std::string::String,
|
||||
}
|
||||
28
kb_lib/src/db/entities/token_mint_event.rs
Normal file
28
kb_lib/src/db/entities/token_mint_event.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
// file: kb_lib/src/db/entities/token_mint_event.rs
|
||||
|
||||
//! Token mint event entity.
|
||||
|
||||
/// Persisted normalized token mint event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbTokenMintEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// Transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Instruction index inside the transaction.
|
||||
pub instruction_index: i64,
|
||||
/// Optional slot number.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Optional mint authority wallet.
|
||||
pub authority_wallet: std::option::Option<std::string::String>,
|
||||
/// Optional destination wallet.
|
||||
pub destination_wallet: std::option::Option<std::string::String>,
|
||||
/// Minted amount as decimal text.
|
||||
pub amount: std::string::String,
|
||||
/// Optional supply after mint as decimal text.
|
||||
pub supply_after: std::option::Option<std::string::String>,
|
||||
/// Execution timestamp encoded as RFC3339 UTC text.
|
||||
pub executed_at: std::string::String,
|
||||
}
|
||||
46
kb_lib/src/db/entities/trade_event.rs
Normal file
46
kb_lib/src/db/entities/trade_event.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
// file: kb_lib/src/db/entities/trade_event.rs
|
||||
|
||||
//! Trade-event entity.
|
||||
|
||||
/// Persisted trade-event row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbTradeEventEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related DEX id.
|
||||
pub dex_id: i64,
|
||||
/// Related pool id.
|
||||
pub pool_id: i64,
|
||||
/// Related pair id.
|
||||
pub pair_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Related decoded event id.
|
||||
pub decoded_event_id: i64,
|
||||
/// Related transaction signature.
|
||||
pub signature: std::string::String,
|
||||
/// Optional observed slot.
|
||||
pub slot: std::option::Option<i64>,
|
||||
/// Stable trade side.
|
||||
pub trade_side: std::string::String,
|
||||
/// Related base token id.
|
||||
pub base_token_id: i64,
|
||||
/// Related quote token id.
|
||||
pub quote_token_id: i64,
|
||||
/// Optional raw base amount.
|
||||
pub base_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional raw quote amount.
|
||||
pub quote_amount_raw: std::option::Option<std::string::String>,
|
||||
/// Optional derived quote-per-base price.
|
||||
pub price_quote_per_base: std::option::Option<f64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: i16,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Persisted payload JSON.
|
||||
pub payload_json: std::string::String,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
18
kb_lib/src/db/entities/wallet.rs
Normal file
18
kb_lib/src/db/entities/wallet.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
// file: kb_lib/src/db/entities/wallet.rs
|
||||
|
||||
//! Wallet entity.
|
||||
|
||||
/// Persisted wallet row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbWalletEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Stable wallet address.
|
||||
pub address: std::string::String,
|
||||
/// Optional user-defined label.
|
||||
pub label: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub first_seen_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub last_seen_at: std::string::String,
|
||||
}
|
||||
38
kb_lib/src/db/entities/wallet_holding.rs
Normal file
38
kb_lib/src/db/entities/wallet_holding.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
// file: kb_lib/src/db/entities/wallet_holding.rs
|
||||
|
||||
//! Wallet-holding entity.
|
||||
|
||||
/// Persisted wallet-holding row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbWalletHoldingEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related wallet id.
|
||||
pub wallet_id: i64,
|
||||
/// Related token id.
|
||||
pub token_id: i64,
|
||||
/// First transaction id that observed this wallet/token relationship.
|
||||
pub first_transaction_id: i64,
|
||||
/// Last transaction id that observed this wallet/token relationship.
|
||||
pub last_transaction_id: i64,
|
||||
/// Optional last decoded-event id.
|
||||
pub last_decoded_event_id: std::option::Option<i64>,
|
||||
/// Optional last related pool id.
|
||||
pub last_pool_id: std::option::Option<i64>,
|
||||
/// Optional last related pair id.
|
||||
pub last_pair_id: std::option::Option<i64>,
|
||||
/// Optional last observed role.
|
||||
pub last_role: std::option::Option<std::string::String>,
|
||||
/// Optional last observed raw balance-like value.
|
||||
pub balance_raw: std::option::Option<std::string::String>,
|
||||
/// Optional last observed slot.
|
||||
pub last_slot_observed: std::option::Option<i64>,
|
||||
/// Observation source kind.
|
||||
pub source_kind: i16,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
32
kb_lib/src/db/entities/wallet_participation.rs
Normal file
32
kb_lib/src/db/entities/wallet_participation.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
// file: kb_lib/src/db/entities/wallet_participation.rs
|
||||
|
||||
//! Wallet-participation entity.
|
||||
|
||||
/// Persisted wallet-participation row.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
|
||||
pub struct KbWalletParticipationEntity {
|
||||
/// Numeric primary key.
|
||||
pub id: i64,
|
||||
/// Related wallet id.
|
||||
pub wallet_id: i64,
|
||||
/// Related transaction id.
|
||||
pub transaction_id: i64,
|
||||
/// Optional related decoded event id.
|
||||
pub decoded_event_id: std::option::Option<i64>,
|
||||
/// Optional related pool id.
|
||||
pub pool_id: std::option::Option<i64>,
|
||||
/// Optional related pair id.
|
||||
pub pair_id: std::option::Option<i64>,
|
||||
/// Stable participation role.
|
||||
pub role: std::string::String,
|
||||
/// Stable unique key used for idempotent upserts.
|
||||
pub unique_key: std::string::String,
|
||||
/// Observation source kind.
|
||||
pub source_kind: i16,
|
||||
/// Optional logical source endpoint name.
|
||||
pub source_endpoint_name: std::option::Option<std::string::String>,
|
||||
/// Creation timestamp encoded as RFC3339 UTC text.
|
||||
pub created_at: std::string::String,
|
||||
/// Update timestamp encoded as RFC3339 UTC text.
|
||||
pub updated_at: std::string::String,
|
||||
}
|
||||
130
kb_lib/src/db/queries.rs
Normal file
130
kb_lib/src/db/queries.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
// file: kb_lib/src/db/queries.rs
|
||||
|
||||
//! Database queries.
|
||||
|
||||
// file: kb_lib/src/db/queries.rs
|
||||
|
||||
//! Database queries.
|
||||
|
||||
mod analysis_signal;
|
||||
mod chain_instruction;
|
||||
mod chain_slot;
|
||||
mod chain_transaction;
|
||||
mod db_metadata;
|
||||
mod db_runtime_event;
|
||||
mod dex;
|
||||
mod dex_decoded_event;
|
||||
mod known_http_endpoint;
|
||||
mod known_ws_endpoint;
|
||||
mod launch_attribution;
|
||||
mod launch_surface;
|
||||
mod launch_surface_key;
|
||||
mod liquidity_event;
|
||||
mod observed_token;
|
||||
mod onchain_observation;
|
||||
mod pair;
|
||||
mod pair_analytic_signal;
|
||||
mod pair_candle;
|
||||
mod pair_metric;
|
||||
mod pool;
|
||||
mod pool_listing;
|
||||
mod pool_origin;
|
||||
mod pool_token;
|
||||
mod swap;
|
||||
mod token;
|
||||
mod token_burn_event;
|
||||
mod token_mint_event;
|
||||
mod trade_event;
|
||||
mod wallet;
|
||||
mod wallet_holding;
|
||||
mod wallet_participation;
|
||||
|
||||
pub use analysis_signal::insert_analysis_signal;
|
||||
pub use analysis_signal::list_recent_analysis_signals;
|
||||
pub use chain_instruction::delete_chain_instructions_by_transaction_id;
|
||||
pub use chain_instruction::insert_chain_instruction;
|
||||
pub use chain_instruction::list_chain_instructions_by_transaction_id;
|
||||
pub use chain_slot::get_chain_slot;
|
||||
pub use chain_slot::list_recent_chain_slots;
|
||||
pub use chain_slot::upsert_chain_slot;
|
||||
pub use chain_transaction::get_chain_transaction_by_signature;
|
||||
pub use chain_transaction::list_recent_chain_transactions;
|
||||
pub use chain_transaction::upsert_chain_transaction;
|
||||
pub use db_metadata::get_db_metadata;
|
||||
pub use db_metadata::list_db_metadata;
|
||||
pub use db_metadata::upsert_db_metadata;
|
||||
pub use db_runtime_event::insert_db_runtime_event;
|
||||
pub use db_runtime_event::list_recent_db_runtime_events;
|
||||
pub use dex::get_dex_by_code;
|
||||
pub use dex::list_dexes;
|
||||
pub use dex::upsert_dex;
|
||||
pub use dex_decoded_event::get_dex_decoded_event_by_key;
|
||||
pub use dex_decoded_event::list_dex_decoded_events_by_transaction_id;
|
||||
pub use dex_decoded_event::upsert_dex_decoded_event;
|
||||
pub use known_http_endpoint::get_known_http_endpoint;
|
||||
pub use known_http_endpoint::list_known_http_endpoints;
|
||||
pub use known_http_endpoint::upsert_known_http_endpoint;
|
||||
pub use known_ws_endpoint::get_known_ws_endpoint;
|
||||
pub use known_ws_endpoint::list_known_ws_endpoints;
|
||||
pub use known_ws_endpoint::upsert_known_ws_endpoint;
|
||||
pub use launch_attribution::get_launch_attribution_by_decoded_event_id;
|
||||
pub use launch_attribution::list_launch_attributions_by_pool_id;
|
||||
pub use launch_attribution::upsert_launch_attribution;
|
||||
pub use launch_surface::get_launch_surface_by_code;
|
||||
pub use launch_surface::list_launch_surfaces;
|
||||
pub use launch_surface::upsert_launch_surface;
|
||||
pub use launch_surface_key::get_launch_surface_key_by_match;
|
||||
pub use launch_surface_key::list_launch_surface_keys_by_surface_id;
|
||||
pub use launch_surface_key::upsert_launch_surface_key;
|
||||
pub use liquidity_event::list_recent_liquidity_events;
|
||||
pub use liquidity_event::upsert_liquidity_event;
|
||||
pub use observed_token::get_observed_token_by_mint;
|
||||
pub use observed_token::list_observed_tokens;
|
||||
pub use observed_token::upsert_observed_token;
|
||||
pub use onchain_observation::insert_onchain_observation;
|
||||
pub use onchain_observation::list_recent_onchain_observations;
|
||||
pub use pair::get_pair_by_pool_id;
|
||||
pub use pair::list_pairs;
|
||||
pub use pair::upsert_pair;
|
||||
pub use pair_analytic_signal::get_pair_analytic_signal_by_key;
|
||||
pub use pair_analytic_signal::list_pair_analytic_signals_by_pair_id;
|
||||
pub use pair_analytic_signal::upsert_pair_analytic_signal;
|
||||
pub use pair_candle::get_pair_candle_by_key;
|
||||
pub use pair_candle::list_pair_candles_by_pair_and_timeframe;
|
||||
pub use pair_candle::upsert_pair_candle;
|
||||
pub use pair_metric::get_pair_metric_by_pair_id;
|
||||
pub use pair_metric::list_pair_metrics;
|
||||
pub use pair_metric::upsert_pair_metric;
|
||||
pub use pool::get_pool_by_address;
|
||||
pub use pool::list_pools;
|
||||
pub use pool::upsert_pool;
|
||||
pub use pool_listing::get_pool_listing_by_pool_id;
|
||||
pub use pool_listing::list_pool_listings;
|
||||
pub use pool_listing::upsert_pool_listing;
|
||||
pub use pool_origin::get_pool_origin_by_pool_id;
|
||||
pub use pool_origin::list_pool_origins;
|
||||
pub use pool_origin::upsert_pool_origin;
|
||||
pub use pool_token::list_pool_tokens_by_pool_id;
|
||||
pub use pool_token::upsert_pool_token;
|
||||
pub use swap::list_recent_swaps;
|
||||
pub use swap::upsert_swap;
|
||||
pub use token::get_token_by_mint;
|
||||
pub use token::upsert_token;
|
||||
pub use token_burn_event::list_recent_token_burn_events;
|
||||
pub use token_burn_event::upsert_token_burn_event;
|
||||
pub use token_mint_event::list_recent_token_mint_events;
|
||||
pub use token_mint_event::upsert_token_mint_event;
|
||||
pub use trade_event::get_trade_event_by_decoded_event_id;
|
||||
pub use trade_event::list_trade_events_by_pair_id;
|
||||
pub use trade_event::list_trade_events_by_transaction_id;
|
||||
pub use trade_event::upsert_trade_event;
|
||||
pub use wallet::get_wallet_by_address;
|
||||
pub use wallet::list_wallets;
|
||||
pub use wallet::upsert_wallet;
|
||||
pub use wallet_holding::get_wallet_holding_by_wallet_and_token;
|
||||
pub use wallet_holding::list_wallet_holdings_by_wallet_id;
|
||||
pub use wallet_holding::upsert_wallet_holding;
|
||||
pub use wallet_participation::get_wallet_participation_by_unique_key;
|
||||
pub use wallet_participation::list_wallet_participations_by_pool_id;
|
||||
pub use wallet_participation::list_wallet_participations_by_wallet_id;
|
||||
pub use wallet_participation::upsert_wallet_participation;
|
||||
154
kb_lib/src/db/queries/analysis_signal.rs
Normal file
154
kb_lib/src/db/queries/analysis_signal.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
// file: kb_lib/src/db/queries/analysis_signal.rs
|
||||
|
||||
//! Queries for `kb_analysis_signals`.
|
||||
|
||||
/// Inserts one analysis signal row and returns its numeric id.
|
||||
pub async fn insert_analysis_signal(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbAnalysisSignalDto,
|
||||
) -> Result<i64, crate::KbError> {
|
||||
let payload_json_result = serde_json::to_string(&dto.payload);
|
||||
let payload_json = match payload_json_result {
|
||||
Ok(payload_json) => payload_json,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot serialize analysis signal payload: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_analysis_signals (
|
||||
signal_kind,
|
||||
severity,
|
||||
object_key,
|
||||
related_observation_id,
|
||||
score,
|
||||
payload_json,
|
||||
created_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
"#,
|
||||
)
|
||||
.bind(dto.signal_kind.clone())
|
||||
.bind(dto.severity.to_i16())
|
||||
.bind(dto.object_key.clone())
|
||||
.bind(dto.related_observation_id)
|
||||
.bind(dto.score)
|
||||
.bind(payload_json)
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
let query_result = match query_result {
|
||||
Ok(query_result) => query_result,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot insert kb_analysis_signals on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(query_result.last_insert_rowid())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists recent analysis signals ordered from newest to oldest.
|
||||
pub async fn list_recent_analysis_signals(
|
||||
database: &crate::KbDatabase,
|
||||
limit: u32,
|
||||
) -> Result<std::vec::Vec<crate::KbAnalysisSignalDto>, crate::KbError> {
|
||||
if limit == 0 {
|
||||
return Ok(std::vec::Vec::new());
|
||||
}
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbAnalysisSignalEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
signal_kind,
|
||||
severity,
|
||||
object_key,
|
||||
related_observation_id,
|
||||
score,
|
||||
payload_json,
|
||||
created_at
|
||||
FROM kb_analysis_signals
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
"#,
|
||||
)
|
||||
.bind(i64::from(limit))
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list analysis signals on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbAnalysisSignalDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[tokio::test]
|
||||
async fn analysis_signal_roundtrip_works() {
|
||||
let tempdir = tempfile::tempdir().expect("tempdir must succeed");
|
||||
let database_path = tempdir.path().join("analysis_signal.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
let database = crate::KbDatabase::connect_and_initialize(&config)
|
||||
.await
|
||||
.expect("database init must succeed");
|
||||
let dto = crate::KbAnalysisSignalDto::new(
|
||||
"candidate_token".to_string(),
|
||||
crate::KbAnalysisSignalSeverity::Medium,
|
||||
"So11111111111111111111111111111111111111112".to_string(),
|
||||
None,
|
||||
Some(0.72),
|
||||
serde_json::json!({
|
||||
"reason": "fresh_token_with_activity"
|
||||
}),
|
||||
);
|
||||
let inserted_id = crate::insert_analysis_signal(&database, &dto)
|
||||
.await
|
||||
.expect("insert must succeed");
|
||||
assert!(inserted_id > 0);
|
||||
let listed = crate::list_recent_analysis_signals(&database, 10)
|
||||
.await
|
||||
.expect("list must succeed");
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].signal_kind, "candidate_token");
|
||||
assert_eq!(listed[0].severity, crate::KbAnalysisSignalSeverity::Medium);
|
||||
assert_eq!(listed[0].score, Some(0.72));
|
||||
}
|
||||
}
|
||||
246
kb_lib/src/db/queries/chain_instruction.rs
Normal file
246
kb_lib/src/db/queries/chain_instruction.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
// file: kb_lib/src/db/queries/chain_instruction.rs
|
||||
|
||||
//! Queries for `kb_chain_instructions`.
|
||||
|
||||
/// Inserts one normalized chain instruction row.
|
||||
pub async fn insert_chain_instruction(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbChainInstructionDto,
|
||||
) -> Result<i64, crate::KbError> {
|
||||
let instruction_index_result = i64::from(dto.instruction_index);
|
||||
let inner_instruction_index = match dto.inner_instruction_index {
|
||||
Some(inner_instruction_index) => Some(i64::from(inner_instruction_index)),
|
||||
None => None,
|
||||
};
|
||||
let stack_height = match dto.stack_height {
|
||||
Some(stack_height) => Some(i64::from(stack_height)),
|
||||
None => None,
|
||||
};
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_chain_instructions (
|
||||
transaction_id,
|
||||
parent_instruction_id,
|
||||
instruction_index,
|
||||
inner_instruction_index,
|
||||
program_id,
|
||||
program_name,
|
||||
stack_height,
|
||||
accounts_json,
|
||||
data_json,
|
||||
parsed_type,
|
||||
parsed_json,
|
||||
created_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
"#,
|
||||
)
|
||||
.bind(dto.transaction_id)
|
||||
.bind(dto.parent_instruction_id)
|
||||
.bind(instruction_index_result)
|
||||
.bind(inner_instruction_index)
|
||||
.bind(dto.program_id.clone())
|
||||
.bind(dto.program_name.clone())
|
||||
.bind(stack_height)
|
||||
.bind(dto.accounts_json.clone())
|
||||
.bind(dto.data_json.clone())
|
||||
.bind(dto.parsed_type.clone())
|
||||
.bind(dto.parsed_json.clone())
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
let insert_result = match query_result {
|
||||
Ok(insert_result) => insert_result,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot insert kb_chain_instructions on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(insert_result.last_insert_rowid())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists instructions for one transaction ordered from outer to inner.
|
||||
pub async fn list_chain_instructions_by_transaction_id(
|
||||
database: &crate::KbDatabase,
|
||||
transaction_id: i64,
|
||||
) -> Result<std::vec::Vec<crate::KbChainInstructionDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbChainInstructionEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
transaction_id,
|
||||
parent_instruction_id,
|
||||
instruction_index,
|
||||
inner_instruction_index,
|
||||
program_id,
|
||||
program_name,
|
||||
stack_height,
|
||||
accounts_json,
|
||||
data_json,
|
||||
parsed_type,
|
||||
parsed_json,
|
||||
created_at
|
||||
FROM kb_chain_instructions
|
||||
WHERE transaction_id = ?
|
||||
ORDER BY instruction_index ASC, inner_instruction_index ASC, id ASC
|
||||
"#,
|
||||
)
|
||||
.bind(transaction_id)
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list kb_chain_instructions for transaction_id '{}' on sqlite: {}",
|
||||
transaction_id, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbChainInstructionDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes all instructions for one transaction id.
|
||||
pub async fn delete_chain_instructions_by_transaction_id(
|
||||
database: &crate::KbDatabase,
|
||||
transaction_id: i64,
|
||||
) -> Result<(), crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
DELETE FROM kb_chain_instructions
|
||||
WHERE transaction_id = ?
|
||||
"#,
|
||||
)
|
||||
.bind(transaction_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
if let Err(error) = query_result {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot delete kb_chain_instructions for transaction_id '{}' on sqlite: {}",
|
||||
transaction_id, error
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
async fn make_database() -> crate::KbDatabase {
|
||||
let tempdir = tempfile::tempdir().expect("tempdir must succeed");
|
||||
let database_path = tempdir.path().join("chain_instruction.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
crate::KbDatabase::connect_and_initialize(&config)
|
||||
.await
|
||||
.expect("database init must succeed")
|
||||
}
|
||||
|
||||
async fn make_transaction(database: &crate::KbDatabase) -> i64 {
|
||||
let dto = crate::KbChainTransactionDto::new(
|
||||
"sig-chain-instruction-1".to_string(),
|
||||
None,
|
||||
None,
|
||||
Some("mainnet_public_http".to_string()),
|
||||
Some("legacy".to_string()),
|
||||
None,
|
||||
None,
|
||||
r#"{"transaction":{"message":{"instructions":[]}}}"#.to_string(),
|
||||
);
|
||||
crate::upsert_chain_transaction(database, &dto)
|
||||
.await
|
||||
.expect("chain transaction upsert must succeed")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chain_instruction_insert_list_delete_works() {
|
||||
let database = make_database().await;
|
||||
let transaction_id = make_transaction(&database).await;
|
||||
let outer_dto = crate::KbChainInstructionDto::new(
|
||||
transaction_id,
|
||||
None,
|
||||
0,
|
||||
None,
|
||||
Some(crate::SPL_TOKEN_PROGRAM_ID.to_string()),
|
||||
Some("spl-token".to_string()),
|
||||
Some(1),
|
||||
r#"["AccountA","AccountB"]"#.to_string(),
|
||||
Some(r#""raw-data-outer""#.to_string()),
|
||||
Some("transfer".to_string()),
|
||||
Some(r#"{"type":"transfer","info":{"amount":"10"}}"#.to_string()),
|
||||
);
|
||||
let outer_instruction_id = crate::insert_chain_instruction(&database, &outer_dto)
|
||||
.await
|
||||
.expect("outer instruction insert must succeed");
|
||||
assert!(outer_instruction_id > 0);
|
||||
let inner_dto = crate::KbChainInstructionDto::new(
|
||||
transaction_id,
|
||||
Some(outer_instruction_id),
|
||||
0,
|
||||
Some(0),
|
||||
Some(crate::SPL_TOKEN_PROGRAM_ID.to_string()),
|
||||
Some("spl-token".to_string()),
|
||||
Some(2),
|
||||
r#"["InnerA","InnerB"]"#.to_string(),
|
||||
Some(r#""raw-data-inner""#.to_string()),
|
||||
Some("mintTo".to_string()),
|
||||
Some(r#"{"type":"mintTo","info":{"amount":"5"}}"#.to_string()),
|
||||
);
|
||||
let inner_instruction_id = crate::insert_chain_instruction(&database, &inner_dto)
|
||||
.await
|
||||
.expect("inner instruction insert must succeed");
|
||||
assert!(inner_instruction_id > outer_instruction_id);
|
||||
let listed = crate::list_chain_instructions_by_transaction_id(&database, transaction_id)
|
||||
.await
|
||||
.expect("chain instruction list must succeed");
|
||||
assert_eq!(listed.len(), 2);
|
||||
assert_eq!(listed[0].parent_instruction_id, None);
|
||||
assert_eq!(listed[0].instruction_index, 0);
|
||||
assert_eq!(listed[0].inner_instruction_index, None);
|
||||
assert_eq!(listed[0].parsed_type, Some("transfer".to_string()));
|
||||
assert_eq!(listed[1].parent_instruction_id, Some(outer_instruction_id));
|
||||
assert_eq!(listed[1].instruction_index, 0);
|
||||
assert_eq!(listed[1].inner_instruction_index, Some(0));
|
||||
assert_eq!(listed[1].parsed_type, Some("mintTo".to_string()));
|
||||
crate::delete_chain_instructions_by_transaction_id(&database, transaction_id)
|
||||
.await
|
||||
.expect("chain instruction delete must succeed");
|
||||
let listed_after_delete =
|
||||
crate::list_chain_instructions_by_transaction_id(&database, transaction_id)
|
||||
.await
|
||||
.expect("chain instruction list after delete must succeed");
|
||||
assert_eq!(listed_after_delete.len(), 0);
|
||||
}
|
||||
}
|
||||
221
kb_lib/src/db/queries/chain_slot.rs
Normal file
221
kb_lib/src/db/queries/chain_slot.rs
Normal file
@@ -0,0 +1,221 @@
|
||||
// file: kb_lib/src/db/queries/chain_slot.rs
|
||||
|
||||
//! Queries for `kb_chain_slots`.
|
||||
|
||||
/// Inserts or updates one normalized chain slot row.
|
||||
pub async fn upsert_chain_slot(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbChainSlotDto,
|
||||
) -> Result<u64, crate::KbError> {
|
||||
let slot_result = i64::try_from(dto.slot);
|
||||
let slot = match slot_result {
|
||||
Ok(slot) => slot,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain slot '{}' to i64: {}",
|
||||
dto.slot, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let parent_slot = match dto.parent_slot {
|
||||
Some(parent_slot) => {
|
||||
let parent_slot_result = i64::try_from(parent_slot);
|
||||
match parent_slot_result {
|
||||
Ok(parent_slot) => Some(parent_slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain parent_slot '{}' to i64: {}",
|
||||
parent_slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_chain_slots (
|
||||
slot,
|
||||
parent_slot,
|
||||
block_time_unix,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(slot) DO UPDATE SET
|
||||
parent_slot = excluded.parent_slot,
|
||||
block_time_unix = excluded.block_time_unix,
|
||||
updated_at = excluded.updated_at
|
||||
"#,
|
||||
)
|
||||
.bind(slot)
|
||||
.bind(parent_slot)
|
||||
.bind(dto.block_time_unix)
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.bind(dto.updated_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
if let Err(error) = query_result {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot upsert kb_chain_slots on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
Ok(dto.slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads one chain slot row by slot number.
|
||||
pub async fn get_chain_slot(
|
||||
database: &crate::KbDatabase,
|
||||
slot: u64,
|
||||
) -> Result<std::option::Option<crate::KbChainSlotDto>, crate::KbError> {
|
||||
let slot_result = i64::try_from(slot);
|
||||
let slot_i64 = match slot_result {
|
||||
Ok(slot_i64) => slot_i64,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert requested chain slot '{}' to i64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbChainSlotEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
slot,
|
||||
parent_slot,
|
||||
block_time_unix,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_chain_slots
|
||||
WHERE slot = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(slot_i64)
|
||||
.fetch_optional(pool)
|
||||
.await;
|
||||
let entity_option = match query_result {
|
||||
Ok(entity_option) => entity_option,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot fetch kb_chain_slots for slot '{}' on sqlite: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match entity_option {
|
||||
Some(entity) => {
|
||||
let dto_result = crate::KbChainSlotDto::try_from(entity);
|
||||
match dto_result {
|
||||
Ok(dto) => Ok(Some(dto)),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists recent chain slots ordered from newest to oldest.
|
||||
pub async fn list_recent_chain_slots(
|
||||
database: &crate::KbDatabase,
|
||||
limit: u32,
|
||||
) -> Result<std::vec::Vec<crate::KbChainSlotDto>, crate::KbError> {
|
||||
if limit == 0 {
|
||||
return Ok(std::vec::Vec::new());
|
||||
}
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbChainSlotEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
slot,
|
||||
parent_slot,
|
||||
block_time_unix,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_chain_slots
|
||||
ORDER BY slot DESC
|
||||
LIMIT ?
|
||||
"#,
|
||||
)
|
||||
.bind(i64::from(limit))
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list kb_chain_slots on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbChainSlotDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
async fn make_database() -> crate::KbDatabase {
|
||||
let tempdir = tempfile::tempdir().expect("tempdir must succeed");
|
||||
let database_path = tempdir.path().join("chain_slot.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
crate::KbDatabase::connect_and_initialize(&config)
|
||||
.await
|
||||
.expect("database init must succeed")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chain_slot_roundtrip_works() {
|
||||
let database = make_database().await;
|
||||
let dto = crate::KbChainSlotDto::new(424242, Some(424241), Some(1_777_777_777));
|
||||
let slot = crate::upsert_chain_slot(&database, &dto)
|
||||
.await
|
||||
.expect("chain slot upsert must succeed");
|
||||
assert_eq!(slot, 424242);
|
||||
let fetched = crate::get_chain_slot(&database, 424242)
|
||||
.await
|
||||
.expect("chain slot fetch must succeed")
|
||||
.expect("chain slot must exist");
|
||||
assert_eq!(fetched.slot, 424242);
|
||||
assert_eq!(fetched.parent_slot, Some(424241));
|
||||
assert_eq!(fetched.block_time_unix, Some(1_777_777_777));
|
||||
let listed = crate::list_recent_chain_slots(&database, 10)
|
||||
.await
|
||||
.expect("chain slot list must succeed");
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].slot, 424242);
|
||||
assert_eq!(listed[0].parent_slot, Some(424241));
|
||||
assert_eq!(listed[0].block_time_unix, Some(1_777_777_777));
|
||||
}
|
||||
}
|
||||
265
kb_lib/src/db/queries/chain_transaction.rs
Normal file
265
kb_lib/src/db/queries/chain_transaction.rs
Normal file
@@ -0,0 +1,265 @@
|
||||
// file: kb_lib/src/db/queries/chain_transaction.rs
|
||||
|
||||
//! Queries for `kb_chain_transactions`.
|
||||
|
||||
/// Inserts or updates one normalized chain transaction row.
|
||||
pub async fn upsert_chain_transaction(
|
||||
database: &crate::KbDatabase,
|
||||
dto: &crate::KbChainTransactionDto,
|
||||
) -> Result<i64, crate::KbError> {
|
||||
let slot_i64 = match dto.slot {
|
||||
Some(slot) => {
|
||||
let slot_result = i64::try_from(slot);
|
||||
match slot_result {
|
||||
Ok(slot) => Some(slot),
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot convert chain transaction slot '{}' to i64: {}",
|
||||
slot, error
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO kb_chain_transactions (
|
||||
signature,
|
||||
slot,
|
||||
block_time_unix,
|
||||
source_endpoint_name,
|
||||
version_text,
|
||||
err_json,
|
||||
meta_json,
|
||||
transaction_json,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(signature) DO UPDATE SET
|
||||
slot = excluded.slot,
|
||||
block_time_unix = excluded.block_time_unix,
|
||||
source_endpoint_name = excluded.source_endpoint_name,
|
||||
version_text = excluded.version_text,
|
||||
err_json = excluded.err_json,
|
||||
meta_json = excluded.meta_json,
|
||||
transaction_json = excluded.transaction_json,
|
||||
updated_at = excluded.updated_at
|
||||
"#,
|
||||
)
|
||||
.bind(dto.signature.clone())
|
||||
.bind(slot_i64)
|
||||
.bind(dto.block_time_unix)
|
||||
.bind(dto.source_endpoint_name.clone())
|
||||
.bind(dto.version_text.clone())
|
||||
.bind(dto.err_json.clone())
|
||||
.bind(dto.meta_json.clone())
|
||||
.bind(dto.transaction_json.clone())
|
||||
.bind(dto.created_at.to_rfc3339())
|
||||
.bind(dto.updated_at.to_rfc3339())
|
||||
.execute(pool)
|
||||
.await;
|
||||
if let Err(error) = query_result {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot upsert kb_chain_transactions on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
|
||||
r#"
|
||||
SELECT id
|
||||
FROM kb_chain_transactions
|
||||
WHERE signature = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(dto.signature.clone())
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
match id_result {
|
||||
Ok(id) => Ok(id),
|
||||
Err(error) => Err(crate::KbError::Db(format!(
|
||||
"cannot fetch kb_chain_transactions id for signature '{}' on sqlite: {}",
|
||||
dto.signature, error
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads one chain transaction row by signature.
|
||||
pub async fn get_chain_transaction_by_signature(
|
||||
database: &crate::KbDatabase,
|
||||
signature: &str,
|
||||
) -> Result<std::option::Option<crate::KbChainTransactionDto>, crate::KbError> {
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbChainTransactionEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
signature,
|
||||
slot,
|
||||
block_time_unix,
|
||||
source_endpoint_name,
|
||||
version_text,
|
||||
err_json,
|
||||
meta_json,
|
||||
transaction_json,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_chain_transactions
|
||||
WHERE signature = ?
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(signature.to_string())
|
||||
.fetch_optional(pool)
|
||||
.await;
|
||||
let entity_option = match query_result {
|
||||
Ok(entity_option) => entity_option,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot fetch kb_chain_transactions for signature '{}' on sqlite: {}",
|
||||
signature, error
|
||||
)));
|
||||
}
|
||||
};
|
||||
match entity_option {
|
||||
Some(entity) => {
|
||||
let dto_result = crate::KbChainTransactionDto::try_from(entity);
|
||||
match dto_result {
|
||||
Ok(dto) => Ok(Some(dto)),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists recent chain transactions ordered from newest to oldest.
|
||||
pub async fn list_recent_chain_transactions(
|
||||
database: &crate::KbDatabase,
|
||||
limit: u32,
|
||||
) -> Result<std::vec::Vec<crate::KbChainTransactionDto>, crate::KbError> {
|
||||
if limit == 0 {
|
||||
return Ok(std::vec::Vec::new());
|
||||
}
|
||||
match database.connection() {
|
||||
crate::KbDatabaseConnection::Sqlite(pool) => {
|
||||
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbChainTransactionEntity>(
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
signature,
|
||||
slot,
|
||||
block_time_unix,
|
||||
source_endpoint_name,
|
||||
version_text,
|
||||
err_json,
|
||||
meta_json,
|
||||
transaction_json,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM kb_chain_transactions
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
"#,
|
||||
)
|
||||
.bind(i64::from(limit))
|
||||
.fetch_all(pool)
|
||||
.await;
|
||||
let entities = match query_result {
|
||||
Ok(entities) => entities,
|
||||
Err(error) => {
|
||||
return Err(crate::KbError::Db(format!(
|
||||
"cannot list kb_chain_transactions on sqlite: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dtos = std::vec::Vec::new();
|
||||
for entity in entities {
|
||||
let dto_result = crate::KbChainTransactionDto::try_from(entity);
|
||||
let dto = match dto_result {
|
||||
Ok(dto) => dto,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
dtos.push(dto);
|
||||
}
|
||||
Ok(dtos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
async fn make_database() -> crate::KbDatabase {
|
||||
let tempdir = tempfile::tempdir().expect("tempdir must succeed");
|
||||
let database_path = tempdir.path().join("chain_transaction.sqlite3");
|
||||
let config = crate::KbDatabaseConfig {
|
||||
enabled: true,
|
||||
backend: crate::KbDatabaseBackend::Sqlite,
|
||||
sqlite: crate::KbSqliteDatabaseConfig {
|
||||
path: database_path.to_string_lossy().to_string(),
|
||||
create_if_missing: true,
|
||||
busy_timeout_ms: 5000,
|
||||
max_connections: 1,
|
||||
auto_initialize_schema: true,
|
||||
use_wal: true,
|
||||
},
|
||||
};
|
||||
crate::KbDatabase::connect_and_initialize(&config)
|
||||
.await
|
||||
.expect("database init must succeed")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chain_transaction_roundtrip_works() {
|
||||
let database = make_database().await;
|
||||
let slot_dto = crate::KbChainSlotDto::new(515151, Some(515150), Some(1_700_000_001));
|
||||
crate::upsert_chain_slot(&database, &slot_dto)
|
||||
.await
|
||||
.expect("chain slot upsert must succeed");
|
||||
let dto = crate::KbChainTransactionDto::new(
|
||||
"sig-chain-transaction-1".to_string(),
|
||||
Some(515151),
|
||||
Some(1_700_000_001),
|
||||
Some("helius_primary_http".to_string()),
|
||||
Some("0".to_string()),
|
||||
None,
|
||||
Some(r#"{"fee":5000}"#.to_string()),
|
||||
r#"{"slot":515151,"transaction":{"message":{"instructions":[]}}}"#.to_string(),
|
||||
);
|
||||
let transaction_id = crate::upsert_chain_transaction(&database, &dto)
|
||||
.await
|
||||
.expect("chain transaction upsert must succeed");
|
||||
assert!(transaction_id > 0);
|
||||
let fetched =
|
||||
crate::get_chain_transaction_by_signature(&database, "sig-chain-transaction-1")
|
||||
.await
|
||||
.expect("chain transaction fetch must succeed")
|
||||
.expect("chain transaction must exist");
|
||||
assert_eq!(fetched.id, Some(transaction_id));
|
||||
assert_eq!(fetched.signature, "sig-chain-transaction-1");
|
||||
assert_eq!(fetched.slot, Some(515151));
|
||||
assert_eq!(fetched.block_time_unix, Some(1_700_000_001));
|
||||
assert_eq!(
|
||||
fetched.source_endpoint_name,
|
||||
Some("helius_primary_http".to_string())
|
||||
);
|
||||
assert_eq!(fetched.version_text, Some("0".to_string()));
|
||||
assert_eq!(fetched.meta_json, Some(r#"{"fee":5000}"#.to_string()));
|
||||
let listed = crate::list_recent_chain_transactions(&database, 10)
|
||||
.await
|
||||
.expect("chain transaction list must succeed");
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].signature, "sig-chain-transaction-1");
|
||||
assert_eq!(listed[0].slot, Some(515151));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user