feat: migration Ğ1v2 — Subsquid + Cesium+ g1.data.e-is.pro

Sources de données réelles Ğ1v2 (vérifiées par introspection) :
- SubsquidAdapter : https://squidv2s.syoul.fr/v1/graphql
  transfers(filter: timestamp >= since, orderBy: TIMESTAMP_DESC)
  with from.linkedIdentity.name pour jointure géo
- CesiumAdapter : https://g1.data.e-is.pro (59 841 profils)
  recherche batch par nom d'identité (title.keyword)
  g1.data.duniter.fr hors ligne depuis arrêt Ğ1v1

Schémas Zod mis à jour pour Ğ1v2 :
- G1v2KeySchema : SS58 "g1" + 47 chars = 49 chars (mesuré sur données réelles)
- SubsquidTransferSchema : id, blockNumber, timestamp ISO, amount BigInt string
- parseSubsquidAmount : BigInt string centimes → Ğ1 flottant

Activation : VITE_USE_LIVE_API=true dans .env.local
Badge "● live Ğ1v2 / ○ mock" ajouté dans l'UI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
syoul
2026-03-22 16:01:36 +01:00
parent d20d042bca
commit 2f813c5fdf
8 changed files with 392 additions and 259 deletions

View File

@@ -1,12 +1,18 @@
/**
* DataService — abstraction layer between the UI and data sources.
* DataService — couche d'abstraction entre l'UI et les sources de données.
*
* Currently backed by mock data. To switch to the Subsquid GraphQL API:
* 1. Set `USE_LIVE_API = true` (or read from env: import.meta.env.VITE_USE_LIVE_API)
* 2. Fill in SUBSQUID_ENDPOINT with your indexer URL
* 3. Implement `fetchLiveTransactions` with a proper GraphQL query
* Mode mock (USE_LIVE_API = false) : données simulées, aucun appel réseau.
* Mode live (USE_LIVE_API = true) : données réelles Ğ1v2.
* - Transactions : Subsquid indexer https://squidv2s.syoul.fr/v1/graphql
* - Géolocalisation : Cesium+ https://g1.data.e-is.pro
* → recherche par nom d'identité (identity.name depuis le graphe Subsquid)
* → les transactions sans profil Cesium+ reçoivent des coordonnées approx.
*
* Pour activer : définir VITE_USE_LIVE_API=true dans .env.local
*/
import { fetchTransfers } from './adapters/SubsquidAdapter';
import { resolveGeoByNames } from './adapters/CesiumAdapter';
import {
getTransactionsForPeriod,
computeStats,
@@ -16,76 +22,48 @@ import {
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
const USE_LIVE_API = false;
const SUBSQUID_ENDPOINT = 'https://squid.subsquid.io/g1-indexer/graphql'; // placeholder
const USE_LIVE_API = import.meta.env.VITE_USE_LIVE_API === 'true';
// Centroïde France — fallback géo quand Cesium+ n'a pas le profil
const FRANCE_CENTER = { lat: 46.2276, lng: 2.2137 };
// ---------------------------------------------------------------------------
// GraphQL helpers (used when USE_LIVE_API = true)
// Pipeline données live Ğ1v2
// ---------------------------------------------------------------------------
interface GqlTransactionEdge {
node: {
id: string;
blockTimestamp: string;
amount: string;
issuer: string;
recipient: string;
issuerlat?: number;
issuerlng?: number;
city?: string;
};
}
async function fetchLiveTransactions(periodDays: number): Promise<Transaction[]> {
const since = new Date(Date.now() - periodDays * 24 * 60 * 60 * 1000).toISOString();
// 1. Récupère les transferts depuis Subsquid
const rawTransfers = await fetchTransfers(periodDays);
const query = `
query GetTransactions($since: DateTime!) {
transfers(
where: { blockTimestamp_gte: $since }
orderBy: blockTimestamp_DESC
limit: 5000
) {
edges {
node {
id
blockTimestamp
amount
issuer
recipient
issuerlat
issuerlng
city
}
}
}
if (rawTransfers.length === 0) return [];
// 2. Collecte les noms d'identité uniques pour la recherche Cesium+
const names = rawTransfers.map((t) => t.fromName).filter(Boolean);
// 3. Résout les coordonnées via Cesium+ (une seule requête batch)
let geoMap = new Map<string, { lat: number; lng: number; city: string }>();
try {
const profiles = await resolveGeoByNames(names);
for (const [name, p] of profiles) {
geoMap.set(name, { lat: p.lat, lng: p.lng, city: p.city });
}
`;
} catch (err) {
console.warn('Cesium+ indisponible, fallback coordonnées France :', err);
}
const response = await fetch(SUBSQUID_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables: { since } }),
// 4. Assemble les transactions avec coordonnées
return rawTransfers.map((t): Transaction => {
const geo = geoMap.get(t.fromName) ?? FRANCE_CENTER;
return {
id: t.id,
timestamp: t.timestamp,
lat: geo.lat,
lng: geo.lng,
amount: t.amount,
city: ('city' in geo ? geo.city : undefined) ?? 'Inconnue',
fromKey: t.fromId,
toKey: t.toId,
};
});
if (!response.ok) {
throw new Error(`GraphQL request failed: ${response.statusText}`);
}
const { data, errors } = await response.json();
if (errors?.length) {
throw new Error(`GraphQL errors: ${JSON.stringify(errors)}`);
}
return (data.transfers.edges as GqlTransactionEdge[]).map((edge) => ({
id: edge.node.id,
timestamp: new Date(edge.node.blockTimestamp).getTime(),
lat: edge.node.issuerlat ?? 46.2276, // fallback: France centroid
lng: edge.node.issuerlng ?? 2.2137,
amount: parseFloat(edge.node.amount) / 100, // Ğ1 uses centimes
city: edge.node.city ?? 'Inconnue',
fromKey: edge.node.issuer,
toKey: edge.node.recipient,
}));
}
// ---------------------------------------------------------------------------
@@ -100,19 +78,22 @@ export interface PeriodStats {
export interface DataResult {
transactions: Transaction[];
stats: PeriodStats;
source: 'live' | 'mock';
}
export async function fetchData(periodDays: number): Promise<DataResult> {
let transactions: Transaction[];
let source: 'live' | 'mock';
if (USE_LIVE_API) {
transactions = await fetchLiveTransactions(periodDays);
source = 'live';
} else {
// Simulate async for drop-in replacement compatibility
await new Promise((r) => setTimeout(r, 120));
await new Promise((r) => setTimeout(r, 80));
transactions = getTransactionsForPeriod(periodDays);
source = 'mock';
}
const stats = computeStats(transactions);
return { transactions, stats };
return { transactions, stats, source };
}