-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4822 lines (4315 loc) · 138 KB
/
Copy pathserver.js
File metadata and controls
4822 lines (4315 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const cors = require("cors");
const { Pool } = require("pg");
require("dotenv").config();
const { verifyFloSignature, rateLimitAuth } = require("./flo-auth");
const {
verifyFloPayment,
sendFloPayment,
sendUsdaiPayment,
MARKETPLACE_FLO_ADDRESS,
} = require("./flo-chain");
// Fail fast if the DB isn't configured
if (!process.env.DATABASE_URL) {
console.error("FATAL: DATABASE_URL is not set. Exiting.");
process.exit(1);
}
const app = express();
const port = process.env.PORT || 3000;
const sunoCache = new Map();
const flowCache = new Map();
const top100Cache = new Map();
const playTracking = new Map();
const CACHE_DURATION = 5 * 60 * 1000;
const MAX_CACHE_ENTRIES = 2000;
// ==================== SCRAPER HELPERS ====================
async function fetchSunoPlayCount(inputUrl) {
try {
const response = await fetch(inputUrl, {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
},
signal: AbortSignal.timeout(8000), // 8 second timeout
});
if (!response.ok) {
throw new Error(`Failed to fetch from Suno. Status: ${response.status}`);
}
const html = await response.text();
let playCount = null;
const playCountMatch = html.match(/play_count\\?["']?\s*:\s*(\d+)/i);
if (playCountMatch) {
playCount = parseInt(playCountMatch[1], 10);
} else {
console.warn("Could not find play_count in Suno HTML");
}
return playCount;
} catch (e) {
console.error("Suno scrape error:", e);
return null;
}
}
async function fetchGoogleFlowPlayCount(inputUrl) {
try {
const response = await fetch(inputUrl, {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
},
signal: AbortSignal.timeout(8000),
});
if (!response.ok) {
throw new Error(
`Failed to fetch Google Flow page. Status: ${response.status}`,
);
}
const html = await response.text();
const playCountMatch =
html.match(/"play_count"\s*:\s*(\d+)/i) ||
html.match(/"playCount"\s*:\s*(\d+)/i);
if (!playCountMatch) {
console.warn("Could not find play_count in Google Flow HTML");
return null;
}
const playCount = parseInt(playCountMatch[1], 10);
console.log(`Google Flow play count: ${playCount}`);
return playCount;
} catch (error) {
console.error("Google Flow play count error:", error);
return null;
}
}
// Pipeline lock
let pipelineRunning = false;
let pipelineLockTime = null;
let pipelineStartTime = null;
// Request idempotency - prevent replay attacks
const processedRequests = new Map();
function isRequestProcessed(signature, timestamp) {
const key = `${signature}:${timestamp}`;
if (processedRequests.has(key)) {
return true;
}
const now = Date.now();
for (const [k, ts] of processedRequests) {
if (now - ts > 5 * 60 * 1000) {
processedRequests.delete(k);
}
}
processedRequests.set(key, now);
return false;
}
function preventReplay(fields, floIdField = "floId") {
return (req, res, next) => {
const body = req.body || {};
const floId = body[floIdField];
const sign = body.sign;
const time = body.time;
if (!floId || !sign || !time) {
return next();
}
if (isRequestProcessed(sign, Number(time))) {
console.warn(
`Replay attack detected: ${floId} at ${new Date(time).toISOString()}`,
);
return res.status(409).json({
success: false,
error: "This request has already been processed",
});
}
next();
};
}
const cacheCleanupInterval = setInterval(() => {
const now = Date.now();
for (const [key, entry] of sunoCache.entries()) {
if (now - entry.timestamp > CACHE_DURATION) {
sunoCache.delete(key);
}
}
for (const [key, entry] of flowCache.entries()) {
if (now - entry.timestamp > CACHE_DURATION) {
flowCache.delete(key);
}
}
for (const [key, entry] of top100Cache.entries()) {
if (now - entry.timestamp > 60000) {
top100Cache.delete(key);
}
}
const cutoff = now - 3600000;
for (const [key, data] of playTracking) {
if (data.timestamp < cutoff) {
playTracking.delete(key);
}
}
for (const [key, ts] of processedRequests) {
if (now - ts > 5 * 60 * 1000) {
processedRequests.delete(key);
}
}
}, 60 * 1000);
function cacheSet(cache, key, value) {
if (cache.size >= MAX_CACHE_ENTRIES) {
const oldestKey = cache.keys().next().value;
cache.delete(oldestKey);
}
cache.set(key, value);
}
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(",").map((o) => o.trim())
: null;
app.use(
cors(
allowedOrigins
? {
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
}
: undefined,
),
);
app.use(express.json({ limit: "100kb" }));
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 10000,
});
pool.on("error", (err) => {
console.error("Unexpected error on idle PostgreSQL client:", err);
});
let dbReady = false;
pool
.connect()
.then(async (client) => {
console.log("Connected to Neon PostgreSQL");
client.release();
await ensureMarketplaceSchema();
await ensureAuditLogSchema();
await ensureLifecycleSchema();
await ensureComponentSchema();
dbReady = true;
})
.catch((err) => {
console.error("Database connection failed:", err);
});
// =====================================================================
// DATABASE MIGRATION HELPER - Fix existing duplicate payment_txid rows
// =====================================================================
async function fixDuplicatePaymentTxids() {
console.log(
"Checking for duplicate payment_txid rows in main_token_transactions...",
);
// Find duplicates
const duplicates = await pool.query(`
SELECT payment_txid, COUNT(*) as count, array_agg(id ORDER BY id ASC) as ids
FROM main_token_transactions
WHERE payment_txid IS NOT NULL
GROUP BY payment_txid
HAVING COUNT(*) > 1
`);
if (duplicates.rows.length === 0) {
console.log("No duplicate payment_txid rows found.");
return;
}
console.log(`Found ${duplicates.rows.length} duplicate payment_txid values.`);
for (const row of duplicates.rows) {
const ids = row.ids;
// Keep the first one (oldest), mark others as duplicate and set payment_txid to NULL
const keepId = ids[0];
const duplicateIds = ids.slice(1);
console.log(
` Payment txid ${row.payment_txid}: keeping id ${keepId}, removing ${duplicateIds.length} duplicates`,
);
// Set payment_txid to NULL for duplicates so they don't violate the unique constraint
await pool.query(
`UPDATE main_token_transactions
SET payment_txid = NULL
WHERE id = ANY($1)`,
[duplicateIds],
);
// Log the duplicates for audit
await pool.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('duplicate_payment_txid_fixed', $1, NOW())`,
[
JSON.stringify({
payment_txid: row.payment_txid,
kept_id: keepId,
duplicate_ids: duplicateIds,
}),
],
);
}
console.log("Duplicate payment_txid rows fixed.");
}
// =====================================================================
// ORPHAN PAYOUT RECONCILIATION
// =====================================================================
async function reconcileOrphanPayouts() {
console.log("Checking for orphan payouts (sent but not recorded)...");
// Check sell_queue for locked but unpaid rows (stuck after send)
const stuckSells = await pool.query(`
SELECT id, flo_id, token_amount, paid_amount, payout_txid, payout_locked_at
FROM sell_queue
WHERE payout_locked_at IS NOT NULL
AND status != 'paid'
AND paid_amount < token_amount
`);
if (stuckSells.rows.length > 0) {
console.log(`Found ${stuckSells.rows.length} stuck sell payouts.`);
for (const row of stuckSells.rows) {
console.log(
` Sell row ${row.id}: locked at ${row.payout_locked_at}, txid ${row.payout_txid || "unknown"}`,
);
// Log for manual review
await pool.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('stuck_sell_payout_detected', $1, NOW())`,
[
JSON.stringify({
queueRowId: row.id,
floId: row.flo_id,
amount: row.token_amount - row.paid_amount,
payoutTxid: row.payout_txid,
lockedAt: row.payout_locked_at,
}),
],
);
}
}
// Check property_payouts for sending but not paid rows
const stuckPropertyPayouts = await pool.query(`
SELECT id, property_id, recipient_flo_id, amount, flo_txid
FROM property_payouts
WHERE status = 'sending'
AND paid_at IS NULL
`);
if (stuckPropertyPayouts.rows.length > 0) {
console.log(
`Found ${stuckPropertyPayouts.rows.length} stuck property payouts.`,
);
for (const row of stuckPropertyPayouts.rows) {
console.log(
` Property payout ${row.id}: sending, txid ${row.flo_txid || "unknown"}`,
);
await pool.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('stuck_property_payout_detected', $1, NOW())`,
[
JSON.stringify({
payoutId: row.id,
propertyId: row.property_id,
recipient: row.recipient_flo_id,
amount: row.amount,
txid: row.flo_txid,
}),
],
);
}
}
return {
stuckSells: stuckSells.rows.length,
stuckPropertyPayouts: stuckPropertyPayouts.rows.length,
};
}
// Admin endpoint to resolve orphan payouts
app.post(
"/api/admin/resolve-orphan/:type/:id",
secureEndpoint({
fields: ["adminFloId", "resolution", "time"],
floIdField: "adminFloId",
requireAdmin: true,
rateLimitOpts: { max: 5, windowMs: 60000 },
}),
async (req, res) => {
const { type, id } = req.params;
const { resolution } = req.body; // 'confirm_paid' or 'revert'
if (!["confirm_paid", "revert"].includes(resolution)) {
return res.status(400).json({
success: false,
error: "resolution must be 'confirm_paid' or 'revert'",
});
}
const client = await pool.connect();
try {
await client.query("BEGIN");
if (type === "sell") {
const row = await client.query(
`SELECT * FROM sell_queue WHERE id = $1 AND payout_locked_at IS NOT NULL FOR UPDATE`,
[id],
);
if (!row.rows.length) {
await client.query("ROLLBACK");
return res.status(404).json({
success: false,
error: "Sell queue row not found or not locked",
});
}
if (resolution === "confirm_paid") {
await client.query(
`UPDATE sell_queue
SET paid_amount = released_amount,
status = CASE
WHEN released_amount >= token_amount THEN 'paid'
ELSE 'partially_released'
END,
payout_txid = $1
WHERE id = $2`,
[id],
);
await client.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('orphan_sell_resolved_paid', $1, NOW())`,
[JSON.stringify({ sellId: id, resolvedBy: req.verifiedFloId })],
);
} else {
// Revert: unlock and refund liquidity
const rowData = row.rows[0];
const amountToRefund =
Number(rowData.released_amount) - Number(rowData.paid_amount);
const tokenPrice = await getCurrentTokenPrice();
const usdaiAmount = amountToRefund * tokenPrice;
await client.query(
`UPDATE platform_liquidity SET balance = balance + $1, updated_at = now() WHERE id = 1`,
[usdaiAmount],
);
await client.query(
`UPDATE sell_queue SET payout_locked_at = NULL WHERE id = $1`,
[id],
);
await client.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('orphan_sell_resolved_reverted', $1, NOW())`,
[
JSON.stringify({
sellId: id,
resolvedBy: req.verifiedFloId,
refundedAmount: usdaiAmount,
}),
],
);
}
} else if (type === "property_payout") {
const row = await client.query(
`SELECT * FROM property_payouts WHERE id = $1 AND status = 'sending' FOR UPDATE`,
[id],
);
if (!row.rows.length) {
await client.query("ROLLBACK");
return res.status(404).json({
success: false,
error: "Property payout not found or not in sending state",
});
}
if (resolution === "confirm_paid") {
await client.query(
`UPDATE property_payouts
SET status = 'paid', paid_at = now()
WHERE id = $1`,
[id],
);
await client.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('orphan_property_payout_resolved_paid', $1, NOW())`,
[JSON.stringify({ payoutId: id, resolvedBy: req.verifiedFloId })],
);
} else {
// Revert: refund liquidity
const rowData = row.rows[0];
const usdaiAmount = Number(rowData.amount);
await client.query(
`UPDATE platform_liquidity SET balance = balance + $1, updated_at = now() WHERE id = 1`,
[usdaiAmount],
);
await client.query(
`UPDATE property_payouts SET status = 'pending' WHERE id = $1`,
[id],
);
await client.query(
`INSERT INTO audit_log (event_type, details, created_at)
VALUES ('orphan_property_payout_resolved_reverted', $1, NOW())`,
[
JSON.stringify({
payoutId: id,
resolvedBy: req.verifiedFloId,
refundedAmount: usdaiAmount,
}),
],
);
}
} else {
await client.query("ROLLBACK");
return res.status(400).json({
success: false,
error: "type must be 'sell' or 'property_payout'",
});
}
await client.query("COMMIT");
res.json({ success: true, message: "Orphan resolved" });
} catch (err) {
await client.query("ROLLBACK");
console.error("Failed to resolve orphan:", err);
res.status(500).json({ success: false, error: err.message });
} finally {
client.release();
}
},
);
// Admin endpoint to list orphans
app.get(
"/api/admin/orphans",
secureEndpoint({
fields: ["adminFloId", "time"],
floIdField: "adminFloId",
requireAdmin: true,
rateLimitOpts: { max: 5, windowMs: 60000 },
}),
async (req, res) => {
try {
const [stuckSells, stuckPropertyPayouts] = await Promise.all([
pool.query(`
SELECT id, flo_id, token_amount, paid_amount, released_amount,
payout_txid, payout_locked_at, requested_at
FROM sell_queue
WHERE payout_locked_at IS NOT NULL
AND status != 'paid'
AND paid_amount < token_amount
`),
pool.query(`
SELECT id, property_id, recipient_flo_id, amount, flo_txid
FROM property_payouts
WHERE status = 'sending'
AND paid_at IS NULL
`),
]);
res.json({
success: true,
orphans: {
sell_queue: stuckSells.rows,
property_payouts: stuckPropertyPayouts.rows,
},
});
} catch (err) {
console.error("Failed to list orphans:", err);
res.status(500).json({ success: false, error: err.message });
}
},
);
// =====================================================================
// SCHEMA SETUP
// =====================================================================
async function ensureMarketplaceSchema() {
await pool.query(`
CREATE TABLE IF NOT EXISTS plays (
track_id TEXT PRIMARY KEY,
play_count INT DEFAULT 0
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS likes (
track_id TEXT NOT NULL,
user_id TEXT NOT NULL,
PRIMARY KEY (track_id, user_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS categories (
id SERIAL PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
ALTER TABLE categories ADD COLUMN IF NOT EXISTS independent_ranking BOOLEAN DEFAULT false;
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS people (
flo_id TEXT PRIMARY KEY,
work_profile TEXT NOT NULL,
experience TEXT,
name TEXT,
cv_url TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS tracks_components (
id SERIAL PRIMARY KEY,
track_id TEXT NOT NULL,
category_id INT REFERENCES categories(id),
component_type TEXT NOT NULL,
contributor_flo_id TEXT NOT NULL,
metadata JSONB,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS properties (
id SERIAL PRIMARY KEY,
category_id INT REFERENCES categories(id),
status TEXT DEFAULT 'active',
total_slots INT DEFAULT 5,
scarcity_score NUMERIC DEFAULT 0,
utility_score NUMERIC DEFAULT 0,
current_price NUMERIC DEFAULT 0,
high_scarcity_streak INT DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS name TEXT;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS created_by_flo_id TEXT;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS category_rank INT;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS in_top_100 BOOLEAN DEFAULT false;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS consumption NUMERIC DEFAULT 0;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS base_price NUMERIC DEFAULT 0;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS valuation_updated_at TIMESTAMPTZ;`,
);
await pool.query(
`ALTER TABLE properties ADD COLUMN IF NOT EXISTS in_global_top_100 BOOLEAN DEFAULT false;`,
);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_valuation_history (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id),
consumption NUMERIC NOT NULL,
base_price NUMERIC NOT NULL,
formula_version TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS main_token_balances (
flo_id TEXT PRIMARY KEY,
balance NUMERIC DEFAULT 0,
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS main_token_transactions (
id SERIAL PRIMARY KEY,
flo_id TEXT NOT NULL,
type TEXT NOT NULL,
token_amount NUMERIC NOT NULL,
price_at_time NUMERIC NOT NULL,
payment_txid TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
// Fix duplicate payment_txid rows before creating unique index
await fixDuplicatePaymentTxids();
// Create unique index with IF NOT EXISTS
await pool.query(`
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_indexes
WHERE indexname = 'main_token_transactions_payment_txid_unique'
) THEN
CREATE UNIQUE INDEX main_token_transactions_payment_txid_unique
ON main_token_transactions (payment_txid) WHERE payment_txid IS NOT NULL;
END IF;
END $$;
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS main_token_price_history (
id SERIAL PRIMARY KEY,
price NUMERIC NOT NULL,
total_supply NUMERIC NOT NULL,
system_valuation NUMERIC NOT NULL,
recorded_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS platform_liquidity (
id SERIAL PRIMARY KEY,
balance NUMERIC DEFAULT 0,
expenses_taken NUMERIC DEFAULT 0,
liquidity_target NUMERIC,
last_payout_created_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS sell_queue (
id SERIAL PRIMARY KEY,
flo_id TEXT NOT NULL,
token_amount NUMERIC NOT NULL,
requested_at TIMESTAMPTZ DEFAULT now(),
released_amount NUMERIC DEFAULT 0,
status TEXT DEFAULT 'queued'
);
`);
await pool.query(
`ALTER TABLE sell_queue ADD COLUMN IF NOT EXISTS paid_amount NUMERIC DEFAULT 0;`,
);
await pool.query(
`ALTER TABLE sell_queue ADD COLUMN IF NOT EXISTS payout_txid TEXT;`,
);
await pool.query(
`ALTER TABLE sell_queue ADD COLUMN IF NOT EXISTS payout_locked_at TIMESTAMPTZ;`,
);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_payouts (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id),
component_id INT REFERENCES tracks_components(id),
recipient_flo_id TEXT NOT NULL,
amount NUMERIC NOT NULL,
status TEXT DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(
`ALTER TABLE property_payouts ADD COLUMN IF NOT EXISTS flo_txid TEXT;`,
);
await pool.query(
`ALTER TABLE property_payouts ADD COLUMN IF NOT EXISTS paid_at TIMESTAMPTZ;`,
);
await pool.query(`
CREATE TABLE IF NOT EXISTS portfolio_positions (
flo_id TEXT NOT NULL,
property_id INT NOT NULL REFERENCES properties(id),
token_amount NUMERIC NOT NULL DEFAULT 0,
allocation_pct NUMERIC NOT NULL DEFAULT 0,
value NUMERIC NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (flo_id, property_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS portfolio_snapshots (
id SERIAL PRIMARY KEY,
flo_id TEXT NOT NULL,
total_value NUMERIC NOT NULL,
token_price NUMERIC NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_components (
property_id INT REFERENCES properties(id),
component_id INT REFERENCES tracks_components(id),
added_by_flo_id TEXT,
added_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (property_id, component_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_people (
property_id INT REFERENCES properties(id),
person_flo_id TEXT REFERENCES people(flo_id),
role TEXT NOT NULL DEFAULT '',
added_by_flo_id TEXT,
added_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (property_id, person_flo_id, role)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_interest (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id),
flo_id TEXT NOT NULL,
intent TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_usage_events (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id),
component_id INT REFERENCES tracks_components(id),
usage_type TEXT NOT NULL,
actor_flo_id TEXT,
rights_duration_days INT,
value_type TEXT,
value_amount NUMERIC,
value_description TEXT,
metadata JSONB,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
requester_flo_id TEXT NOT NULL,
brief TEXT NOT NULL,
budget NUMERIC,
status TEXT DEFAULT 'open',
fulfilled_by_flo_id TEXT,
track_id TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(
`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS component_type TEXT;`,
);
await pool.query(
`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMPTZ;`,
);
await pool.query(
`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ;`,
);
await pool.query(
`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS delivery_link TEXT;`,
);
await pool.query(`
CREATE TABLE IF NOT EXISTS task_submissions (
id SERIAL PRIMARY KEY,
task_id INT REFERENCES tasks(id) NOT NULL,
submitter_flo_id TEXT NOT NULL,
delivery_link TEXT NOT NULL,
is_selected BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS task_claims (
id SERIAL PRIMARY KEY,
task_id INT REFERENCES tasks(id) NOT NULL,
claimer_flo_id TEXT NOT NULL,
claimed_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(task_id, claimer_flo_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_tasks (
property_id INT REFERENCES properties(id),
task_id INT REFERENCES tasks(id),
added_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (property_id, task_id)
);
`);
// FINANCE COMPONENTS
await pool.query(`
CREATE TABLE IF NOT EXISTS finance_components (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id) NOT NULL,
component_type TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT,
amount NUMERIC DEFAULT 0,
currency TEXT DEFAULT NULL,
terms TEXT,
created_by_flo_id TEXT NOT NULL,
metadata JSONB,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS royalty_splits (
id SERIAL PRIMARY KEY,
finance_component_id INT REFERENCES finance_components(id) NOT NULL,
recipient_flo_id TEXT NOT NULL,
share_percentage NUMERIC NOT NULL CHECK (share_percentage >= 0 AND share_percentage <= 100),
role TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS property_finance_allocations (
id SERIAL PRIMARY KEY,
property_id INT REFERENCES properties(id) NOT NULL,
category TEXT NOT NULL,
amount NUMERIC NOT NULL DEFAULT 0,
allocation_pct NUMERIC NOT NULL,
description TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_property_finance_allocations_property_category
ON property_finance_allocations (property_id, category);
`);
await pool.query(`
CREATE INDEX IF NOT EXISTS idx_property_finance_allocations_property
ON property_finance_allocations (property_id);
`);
await pool.query(`
CREATE INDEX IF NOT EXISTS idx_property_finance_allocations_category
ON property_finance_allocations (category);
`);
await pool.query(
`ALTER TABLE people ADD COLUMN IF NOT EXISTS profile_image_url TEXT;`,
);
await pool.query(
`ALTER TABLE people ADD COLUMN IF NOT EXISTS x_url TEXT;`,
);
await pool.query(
`ALTER TABLE people ADD COLUMN IF NOT EXISTS linkedin_url TEXT;`,
);
await pool.query(
`ALTER TABLE people ADD COLUMN IF NOT EXISTS website_url TEXT;`,
);
console.log("Marketplace v3 schema ready");
}
async function ensureAuditLogSchema() {
await pool.query(`
CREATE TABLE IF NOT EXISTS play_audit_log (
id SERIAL PRIMARY KEY,
track_id TEXT NOT NULL,
user_flo_id TEXT NOT NULL,
ip_address TEXT,
user_agent TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(`
CREATE INDEX IF NOT EXISTS idx_play_audit_track_user
ON play_audit_log (track_id, user_flo_id, created_at);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS audit_log (
id SERIAL PRIMARY KEY,
event_type TEXT NOT NULL,
flo_id TEXT,
ip_address TEXT,
user_agent TEXT,
details JSONB,
created_at TIMESTAMPTZ DEFAULT now()
);
`);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_audit_log_flo_id ON audit_log (flo_id);`,
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_audit_log_event_type ON audit_log (event_type);`,
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log (created_at);`,
);