Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
use {
    super::*,
    badges::{
        AUCTION_BIDDER_BADGE_ID, AUCTION_WINNER_BADGE_ID, BADGES_VERSION, BLOCK_BADGE_ID,
        BLOCK_WINNER_BADGE_ID, BRAVOCADO_ASSET, BRAVOCADO_BADGE_ID, BadgeLookup, BadgesPayload,
        DISPENSER_BADGE_ID, ExternalBadgeSources, LOYALTY_BADGE_ID, LOYALTY_BLOCKS_PER_INSTANCE,
        MINER_ASSET, MINER_BADGE_ID, REFINERY_BADGE_ID, build_block_badge_type, build_bucket_badge,
        build_unique_badge, payload_is_fresh, payload_within_max_age,
    },
    rounds::{Round, RoundParticipant},
};

#[derive(sqlx::FromRow, Debug, Clone, PartialEq)]
pub struct BestEverDelta {
    /// Highest snapshotted round seen in this read
    pub latest_round: Option<i32>,
    pub history_best: Option<f64>,
    pub current_best: Option<f64>,
}

#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct HighestDiff {
    pub blockheight: i32,
    pub username: String,
    pub diff: f64,
}

#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct TeraShare {
    pub username: String,
    pub tera_shares: i64,
}

#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub(crate) struct Split {
    pub(crate) worker_name: String,
    pub(crate) worker_total: i64,
    pub(crate) percentage: f64,
}

#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct Payout {
    pub(crate) worker_name: String,
    pub btcaddress: Option<String>,
    pub(crate) lnurl: Option<String>,
    pub payable_shares: i64,
    pub total_shares: i64,
    pub percentage: f64,
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct PendingPayout {
    pub ln_address: String,
    pub btc_address: String,
    pub amount_sats: i64,
    pub payout_ids: Vec<i64>,
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct FailedPayout {
    pub btc_address: String,
    pub amount_sats: i64,
    pub payout_ids: Vec<i64>,
}

#[derive(Deserialize, Serialize, Debug, Clone, ToSchema)]
pub struct UpdatePayoutStatusRequest {
    pub payout_ids: Vec<i64>,
    pub status: String,
    pub failure_reason: Option<String>,
}

#[derive(Deserialize, Serialize, Debug, Clone, ToSchema)]
pub struct TransferDiffRequest {
    pub from: String,
    pub to: String,
    pub diff: i64,
}

#[derive(Debug)]
pub enum TransferDiffError {
    UnknownAccount(String),
    InsufficientDiff { username: String, unpaid: i64 },
    Database(Error),
}

impl From<sqlx::Error> for TransferDiffError {
    fn from(err: sqlx::Error) -> Self {
        Self::Database(anyhow!(err))
    }
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct TransferDiffResponse {
    pub from_payout_id: i64,
    pub to_payout_id: i64,
    pub diff: i64,
}

#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone, PartialEq, ToSchema)]
pub struct HistoricalPayout {
    pub id: i64,
    pub username: String,
    pub ln_address: String,
    pub amount_sats: i64,
    pub status: String,
    pub failure_reason: Option<String>,
    pub updated_at: String,
}

#[derive(Debug, Clone)]
pub struct Database {
    pub(crate) pool: Pool<Postgres>,
    /// External HTTP badge sources (Refinery / dispenser). Empty by default;
    /// populated for the badge-serving server via [`Database::with_external`].
    pub(crate) external: ExternalBadgeSources,
}

impl Database {
    pub async fn new(database_url: String) -> Result<Self> {
        Ok(Self {
            // The pool is shared across every DB-backed route (sync ingestion,
            // rounds, payouts, account migration) plus the aggregator bestshare
            // overlays, so 5 connections starves under concurrent load. Postgres
            // defaults to max_connections = 100, leaving ample headroom here.
            pool: PgPoolOptions::new()
                .max_connections(20)
                .acquire_timeout(Duration::from_secs(5))
                .connect(&database_url)
                .await
                .with_context(|| format!("failed to connect to database at `{database_url}`"))?,
            external: ExternalBadgeSources::default(),
        })
    }

    /// Attach external badge sources (Refinery / dispenser HTTP endpoints).
    pub(crate) fn with_external(mut self, external: ExternalBadgeSources) -> Self {
        self.external = external;
        self
    }

    pub(crate) async fn get_split(&self) -> Result<Vec<Split>> {
        sqlx::query_as::<_, Split>(
            "
            WITH worker_sums AS (
                SELECT
                    workername,
                    SUM(diff) AS worker_total
                FROM
                    remote_shares
                GROUP BY
                    workername
            ),
                 total_sum AS (
                     SELECT
                         SUM(worker_total) AS grand_total
                     FROM
                         worker_sums
                 )
            SELECT
                ws.workername AS worker_name,
                CAST(ws.worker_total AS INT8),
                ROUND((ws.worker_total / ts.grand_total)::numeric, 8)::FLOAT8 AS percentage
            FROM
                worker_sums ws
                    CROSS JOIN
                total_sum ts
            ORDER BY
                percentage DESC;
            ",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn get_total_coinbase(
        &self,
        blockheight: i32,
    ) -> Result<Option<(i32, String, i64, String, String)>> {
        sqlx::query_as::<_, (i32, String, i64, String, String)>(
            "
            SELECT blockheight, blockhash, coinbasevalue, workername, username
            FROM blocks
            WHERE blockheight = $1
            ",
        )
        .bind(blockheight)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn get_payouts(
        &self,
        blockheight: i32,
        btcaddress: String,
    ) -> Result<Vec<Payout>> {
        sqlx::query_as::<_, Payout>(
            "
            WITH target_block AS (
                SELECT id, blockheight
                FROM blocks
                WHERE blockheight = $1
                ORDER BY id
                LIMIT 1
            ),
            previous_block AS (
                SELECT MAX(b.blockheight) AS prev_height
                FROM blocks b
                JOIN target_block tb ON b.blockheight < tb.blockheight
            ),
            qualified_shares AS (
                SELECT s.workername, s.lnurl, s.username AS btcaddress, SUM(s.diff) as total_diff
                FROM remote_shares s, target_block tb, previous_block pb
                WHERE s.blockheight <= tb.blockheight
                    AND s.blockheight > pb.prev_height
                    AND s.username != $2
                    AND s.reject_reason IS NULL
                GROUP BY s.lnurl, s.username, s.workername
            ),
            sum_shares AS (
                SELECT SUM(total_diff) as grand_total
                FROM qualified_shares
            )
            SELECT
                qs.workername AS worker_name,
                qs.btcaddress,
                qs.lnurl,
                CAST(qs.total_diff as INT8) AS payable_shares,
                CAST(ss.grand_total as INT8) AS total_shares,
                ROUND((qs.total_diff / ss.grand_total)::numeric, 8)::FLOAT8 as percentage
            FROM qualified_shares qs
            CROSS JOIN sum_shares ss
            ORDER BY qs.total_diff DESC;
            ",
        )
        .bind(blockheight)
        .bind(btcaddress)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn get_payouts_range(
        &self,
        start_blockheight: i32,
        end_blockheight: i32,
        excluded_usernames: Vec<String>,
    ) -> Result<Vec<Payout>> {
        let exclusion_list = if excluded_usernames.is_empty() {
            vec!["".to_string()]
        } else {
            excluded_usernames
        };

        sqlx::query_as::<_, Payout>(
            "
            WITH qualified_shares AS (
                SELECT
                    s.workername,
                    s.lnurl,
                    s.username AS btcaddress,
                    SUM(s.diff) as total_diff
                FROM remote_shares s
                WHERE s.blockheight >= $1
                    AND s.blockheight < $2
                    AND s.username != ALL($3)
                    AND s.reject_reason IS NULL
                GROUP BY s.lnurl, s.username, s.workername
            ),
            sum_shares AS (
                SELECT SUM(total_diff) as grand_total
                FROM qualified_shares
            )
            SELECT
                qs.workername AS worker_name,
                qs.btcaddress,
                qs.lnurl,
                CAST(qs.total_diff as INT8) AS payable_shares,
                CAST(ss.grand_total as INT8) AS total_shares,
                ROUND((qs.total_diff / NULLIF(ss.grand_total, 0))::numeric, 8)::FLOAT8 as percentage
            FROM qualified_shares qs
            CROSS JOIN sum_shares ss
            WHERE ss.grand_total > 0
            ORDER BY qs.total_diff DESC;
        ",
        )
        .bind(start_blockheight)
        .bind(end_blockheight)
        .bind(&exclusion_list)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn get_user_payout_range(
        &self,
        start_blockheight: i32,
        end_blockheight: i32,
        target_username: String,
        excluded_usernames: Vec<String>,
    ) -> Result<Vec<Payout>> {
        if excluded_usernames.contains(&target_username) {
            return Ok(vec![]);
        }

        let exclusion_list = if excluded_usernames.is_empty() {
            vec!["".to_string()]
        } else {
            excluded_usernames
        };

        sqlx::query_as::<_, Payout>(
            "
        WITH qualified_shares AS (
            SELECT
                s.workername,
                s.lnurl,
                s.username AS btcaddress,
                SUM(s.diff) as total_diff
            FROM remote_shares s
            WHERE s.blockheight >= $1
                AND s.blockheight < $2
                AND s.username != ALL($4)
                AND s.reject_reason IS NULL
            GROUP BY s.lnurl, s.username, s.workername
        ),
        sum_shares AS (
            SELECT SUM(total_diff) as grand_total
            FROM qualified_shares
        ),
        user_shares AS (
            SELECT
                s.workername,
                s.lnurl,
                s.username AS btcaddress,
                SUM(s.diff) as total_diff
            FROM remote_shares s
            WHERE s.blockheight >= $1
                AND s.blockheight < $2
                AND s.username = $3
                AND s.reject_reason IS NULL
            GROUP BY s.lnurl, s.username, s.workername
        )
        SELECT
            us.workername AS worker_name,
            us.btcaddress,
            us.lnurl,
            CAST(us.total_diff as INT8) AS payable_shares,
            CAST(ss.grand_total as INT8) AS total_shares,
            ROUND((us.total_diff / NULLIF(ss.grand_total, 0))::numeric, 8)::FLOAT8 as percentage
        FROM user_shares us
        CROSS JOIN sum_shares ss
        WHERE ss.grand_total > 0
        ORDER BY us.total_diff DESC;
        ",
        )
        .bind(start_blockheight)
        .bind(end_blockheight)
        .bind(&target_username)
        .bind(&exclusion_list)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub async fn get_account(&self, username: &str) -> Result<Option<Account>> {
        #[derive(sqlx::FromRow)]
        pub struct AccountRaw {
            pub username: String,
            pub lnurl: Option<String>,
            pub past_lnurls: sqlx::types::Json<Vec<String>>,
            pub total_diff: i64,
            pub last_updated: Option<String>,
            pub metadata: Option<serde_json::Value>,
        }

        let Some(raw) = sqlx::query_as::<_, AccountRaw>(
            "
            SELECT
                a.username,
                a.lnurl,
                a.past_lnurls,
                a.total_diff,
                a.lnurl_updated_at::text as last_updated,
                m.data as metadata
            FROM accounts a
            LEFT JOIN account_metadata m ON a.id = m.account_id
            WHERE a.username = $1
            ",
        )
        .bind(username)
        .fetch_optional(&self.pool)
        .await?
        else {
            return Ok(None);
        };

        Ok(Some(Account {
            btc_address: raw.username,
            ln_address: raw.lnurl,
            past_ln_addresses: raw.past_lnurls.0,
            total_diff: raw.total_diff,
            last_updated: raw.last_updated,
            metadata: raw.metadata,
        }))
    }

    pub async fn update_account_lnurl(
        &self,
        username: &str,
        new_lnurl: &str,
    ) -> Result<Option<Account>> {
        if let Some(account) = self.get_account(username).await? {
            if let Some(old_lnurl) = &account.ln_address
                && old_lnurl == new_lnurl
            {
                return Err(anyhow!(
                    "New lightning address matches existing lightning address"
                ));
            }
            let mut past_lnurls = account.past_ln_addresses.clone();

            if let Some(current_lnurl) = &account.ln_address
                && !current_lnurl.is_empty()
                && !past_lnurls.contains(current_lnurl)
            {
                past_lnurls.insert(0, current_lnurl.clone());
            }

            past_lnurls.truncate(10);

            let past_lnurls_json = serde_json::to_value(past_lnurls)
                .map_err(|err| anyhow!("Failed to serialize past_lnurls: {}", err))?;

            let rows_affected = sqlx::query(
                "
                UPDATE accounts
                SET lnurl = $1, past_lnurls = $2, lnurl_updated_at = NOW(), updated_at = NOW()
                WHERE username = $3
                ",
            )
            .bind(new_lnurl)
            .bind(past_lnurls_json)
            .bind(username)
            .execute(&self.pool)
            .await
            .map_err(|err| anyhow!(err))?
            .rows_affected();

            if rows_affected == 0 {
                return Err(anyhow!(
                    "Expected to update existing account but no rows affected"
                ));
            }
        } else {
            sqlx::query(
                "
                INSERT INTO accounts (username, lnurl, past_lnurls, total_diff, lnurl_updated_at, created_at, updated_at)
                VALUES ($1, $2, '[]'::jsonb, 0, NOW(), NOW(), NOW())
                ",
            )
                .bind(username)
                .bind(new_lnurl)
                .execute(&self.pool)
                .await
                .map_err(|err| anyhow!(err))?;
        };

        self.get_account(username).await
    }

    pub async fn update_account_metadata(
        &self,
        username: &str,
        metadata: &serde_json::Value,
    ) -> Result<Option<Account>> {
        let account_id: Option<i64> =
            sqlx::query_scalar("SELECT id FROM accounts WHERE username = $1")
                .bind(username)
                .fetch_optional(&self.pool)
                .await?;

        let Some(account_id) = account_id else {
            return Ok(None);
        };

        sqlx::query(
            "
            INSERT INTO account_metadata (account_id, data, created_at, updated_at)
            VALUES ($1, $2, NOW(), NOW())
            ON CONFLICT (account_id) DO UPDATE
            SET data = account_metadata.data || $2, updated_at = NOW()
            ",
        )
        .bind(account_id)
        .bind(metadata)
        .execute(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        self.get_account(username).await
    }

    pub async fn migrate_accounts(&self) -> Result<u64> {
        let result = sqlx::query_scalar::<_, i64>("SELECT refresh_accounts()")
            .fetch_one(&self.pool)
            .await
            .map_err(|err| anyhow!(err))?;

        Ok(result as u64)
    }

    pub async fn get_highestdiff(&self, blockheight: i32) -> Result<Option<HighestDiff>> {
        sqlx::query_as::<_, HighestDiff>(
            "
            SELECT
                blockheight,
                COALESCE(username, '') AS username,
                sdiff as diff
            FROM remote_shares
            WHERE blockheight = $1
            ORDER BY sdiff DESC
            LIMIT 1
            ",
        )
        .bind(blockheight)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub async fn get_highestdiff_by_user(
        &self,
        blockheight: i32,
        username: &str,
    ) -> Result<Option<HighestDiff>> {
        sqlx::query_as::<_, HighestDiff>(
            "
            SELECT
                blockheight,
                COALESCE(username, '') AS username,
                sdiff as diff
            FROM remote_shares
            WHERE blockheight = $1 AND username = $2
            ORDER BY sdiff DESC
            LIMIT 1
            ",
        )
        .bind(blockheight)
        .bind(username)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub async fn get_highestdiff_all_users(&self, blockheight: i32) -> Result<Vec<HighestDiff>> {
        sqlx::query_as::<_, HighestDiff>(
            "
            SELECT DISTINCT ON (username)
                blockheight,
                COALESCE(username, '') AS username,
                sdiff as diff
            FROM remote_shares
            WHERE blockheight = $1
            ORDER BY username, sdiff DESC
            ",
        )
        .bind(blockheight)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    /// Highest difficulty share submitted since the last found block, across all
    /// nodes. Read from the `round_participation_current` materialized view
    /// (`top_diff` = `MAX(sdiff)` per user for the current round), so it is immune
    /// to individual ckpool instances failing to reset their `pool.status`
    /// `bestshare` on a block. Freshness tracks the matview refresh cadence.
    pub async fn get_current_round_bestshare(&self) -> Result<Option<f64>> {
        sqlx::query_scalar::<_, Option<f64>>(
            "SELECT MAX(top_diff) FROM round_participation_current",
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    /// Highest difficulty share submitted by a single user since the last found
    /// block. Round-scoped counterpart to the per-user `bestshare` reported in
    /// the ckpool user flatfile. Indexed lookup on the
    /// `round_participation_current` materialized view.
    pub async fn get_current_round_bestshare_by_user(&self, username: &str) -> Result<Option<f64>> {
        sqlx::query_scalar::<_, f64>(
            "SELECT top_diff FROM round_participation_current WHERE username = $1",
        )
        .bind(username)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    /// Read of a user's best-ever share difficulty
    pub async fn get_bestever_delta_by_user(
        &self,
        username: &str,
        after: i32,
    ) -> Result<BestEverDelta> {
        sqlx::query_as::<_, BestEverDelta>(
            "
            WITH new_rounds AS (
                SELECT MAX(blockheight) AS latest_round, MAX(top_diff) AS history_best
                FROM round_participation_history
                WHERE username = $1 AND blockheight > $2
            )
            SELECT
                nr.latest_round,
                nr.history_best,
                (SELECT top_diff FROM round_participation_current WHERE username = $1)
                    AS current_best
            FROM new_rounds nr
            ",
        )
        .bind(username)
        .bind(after)
        .fetch_one(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub async fn get_tera_shares(
        &self,
        min_blockheight: Option<i32>,
        max_blockheight: Option<i32>,
        min_diff: i64,
    ) -> Result<Vec<TeraShare>> {
        sqlx::query_as::<_, TeraShare>(
            "
            SELECT rs.username,
                   COUNT(rs.sdiff) as tera_shares
            FROM remote_shares rs
            WHERE rs.sdiff >= $3
              AND ($1::INTEGER IS NULL OR rs.blockheight >= $1)
              AND ($2::INTEGER IS NULL OR rs.blockheight < $2)
            GROUP BY rs.username
            ORDER BY tera_shares DESC
            ",
        )
        .bind(min_blockheight)
        .bind(max_blockheight)
        .bind(min_diff)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub async fn get_pending_payouts(&self) -> Result<Vec<PendingPayout>> {
        #[derive(sqlx::FromRow)]
        struct PayoutRow {
            payout_id: i64,
            ln_address: String,
            username: String,
            amount: i64,
        }

        let rows = sqlx::query_as::<_, PayoutRow>(
            "
            SELECT
                p.id as payout_id,
                COALESCE(a.lnurl, '') as ln_address,
                a.username as username,
                p.amount
            FROM payouts p
            JOIN accounts a ON p.account_id = a.id
            WHERE p.status IN ('pending', 'failure')
                AND a.lnurl IS NOT NULL
                AND a.lnurl != ''
            ORDER BY a.lnurl, p.id
            ",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let mut grouped: HashMap<String, PendingPayout> = HashMap::new();
        for row in rows {
            let entry = grouped
                .entry(row.ln_address.clone())
                .or_insert_with(|| PendingPayout {
                    ln_address: row.ln_address.clone(),
                    btc_address: row.username.clone(),
                    amount_sats: 0,
                    payout_ids: Vec::new(),
                });
            entry.amount_sats += row.amount;
            entry.payout_ids.push(row.payout_id);
        }

        let mut result: Vec<PendingPayout> = grouped.into_values().collect();
        result.sort_by_key(|b| Reverse(b.amount_sats));

        Ok(result)
    }

    pub async fn get_failed_payouts(&self) -> Result<Vec<FailedPayout>> {
        #[derive(sqlx::FromRow)]
        struct FailedPayoutRow {
            payout_id: i64,
            btc_address: String,
            amount: i64,
        }

        let rows = sqlx::query_as::<_, FailedPayoutRow>(
            "
            SELECT
                p.id as payout_id,
                a.username as btc_address,
                p.amount
            FROM payouts p
            JOIN accounts a ON p.account_id = a.id
            WHERE p.status IN ('failure')
            ORDER BY a.lnurl, p.id
            ",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let mut grouped: HashMap<String, (i64, Vec<i64>)> = HashMap::new();

        for row in rows {
            let entry = grouped
                .entry(row.btc_address.clone())
                .or_insert((0, Vec::new()));
            entry.0 += row.amount;
            entry.1.push(row.payout_id);
        }

        let mut result = Vec::new();
        for (btc_address, (amount_sats, payout_ids)) in grouped {
            result.push(FailedPayout {
                btc_address,
                amount_sats,
                payout_ids,
            });
        }

        result.sort_by_key(|b| Reverse(b.amount_sats));

        Ok(result)
    }

    /// All payouts across every status
    pub async fn get_all_payouts(&self, status: Option<&str>) -> Result<Vec<HistoricalPayout>> {
        let rows = sqlx::query_as::<_, HistoricalPayout>(
            "
            SELECT
                p.id as id,
                a.username as username,
                COALESCE(a.lnurl, '') as ln_address,
                p.amount as amount_sats,
                p.status as status,
                p.failure_reason as failure_reason,
                p.updated_at::text as updated_at
            FROM payouts p
            JOIN accounts a ON p.account_id = a.id
            WHERE ($1::text IS NULL OR p.status = $1)
            ORDER BY p.updated_at DESC, p.id DESC
            ",
        )
        .bind(status)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        Ok(rows)
    }

    pub async fn get_simulated_payouts(
        &self,
        total_reward: i64,
        block_winner: &str,
    ) -> Result<Vec<PendingPayout>> {
        if total_reward <= 100_000_000 {
            // 1 BTC of coinbase value is reserved for miner who found the block
            return Ok(Vec::new());
        }
        #[derive(sqlx::FromRow)]
        struct PayoutRow {
            username: String,
            ln_address: String,
            amount: i64,
        }

        let rows = sqlx::query_as::<_, PayoutRow>(
            "
            WITH eligible_accounts AS (
                SELECT
                    a.id as account_id,
                    a.username,
                    COALESCE(a.lnurl, '') as lnurl,
                    a.total_diff,
                    COALESCE(SUM(p.diff_paid), 0) as already_paid_diff
                FROM accounts a
                LEFT JOIN payouts p ON p.account_id = a.id
                    AND p.status != 'cancelled'
                GROUP BY a.id, a.username, a.lnurl, a.total_diff
            ),
            payable_accounts AS (
                SELECT
                    account_id,
                    username,
                    lnurl,
                    total_diff - already_paid_diff as unpaid_diff
                FROM eligible_accounts
                WHERE total_diff - already_paid_diff > 0
                    AND username != COALESCE($2, '')
            ),
            total_unpaid AS (
                SELECT SUM(unpaid_diff) as total_diff
                FROM payable_accounts
            )
            SELECT
                pa.username,
                pa.lnurl as ln_address,
                CASE
                    WHEN tu.total_diff > 0
                    THEN FLOOR((pa.unpaid_diff::NUMERIC / tu.total_diff::NUMERIC) * $1)::BIGINT
                    ELSE 0
                END as amount,
                CASE
                    WHEN tu.total_diff > 0
                    THEN ROUND((pa.unpaid_diff::NUMERIC / tu.total_diff::NUMERIC), 8)::FLOAT8
                    ELSE 0
                END as percentage
            FROM payable_accounts pa
            CROSS JOIN total_unpaid tu
            WHERE tu.total_diff > 0
            ORDER BY pa.unpaid_diff DESC
            ",
        )
        .bind(total_reward)
        .bind(block_winner)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        // Accounts sharing a lightning address are paid together. Accounts
        // without one are kept apart by username, otherwise every account
        // with no lnurl would collapse into a single payout credited to
        // whichever account came first.
        let mut grouped: HashMap<String, PendingPayout> = HashMap::new();
        for (payout_id, row) in (1i64..).zip(rows) {
            let key = if row.ln_address.is_empty() {
                format!("username:{}", row.username)
            } else {
                row.ln_address.clone()
            };
            let entry = grouped.entry(key).or_insert_with(|| PendingPayout {
                ln_address: row.ln_address.clone(),
                btc_address: row.username.clone(),
                amount_sats: 0,
                payout_ids: Vec::new(),
            });
            entry.amount_sats += row.amount;
            entry.payout_ids.push(payout_id);
        }

        let mut result: Vec<PendingPayout> = grouped.into_values().collect();
        result.sort_by_key(|b| Reverse(b.amount_sats));

        Ok(result)
    }

    /// Move unpaid diff between accounts via a zero-amount payout pair
    pub async fn transfer_diff(
        &self,
        from: &str,
        to: &str,
        diff: i64,
    ) -> Result<TransferDiffResponse, TransferDiffError> {
        // Negative heights keyed on id avoid unique_payout_per_block collisions
        const INSERT: &str = "
            INSERT INTO payouts
                (id, account_id, amount, diff_paid, blockheight_start, blockheight_end, status, failure_reason)
            SELECT nid, $1, 0, $2, (-nid)::INTEGER, (-nid)::INTEGER, 'success', $3
            FROM nextval(pg_get_serial_sequence('payouts', 'id')) AS nid
            RETURNING id
        ";

        let mut tx = self.pool.begin().await?;

        // Lock both accounts in id order so concurrent transfers serialize without deadlocks
        let locked = sqlx::query_as::<_, (i64, String)>(
            "SELECT id, username FROM accounts WHERE username IN ($1, $2) ORDER BY id FOR UPDATE",
        )
        .bind(from)
        .bind(to)
        .fetch_all(&mut *tx)
        .await?;

        let account_id = |username: &str| {
            locked
                .iter()
                .find(|(_, name)| name == username)
                .map(|(id, _)| *id)
                .ok_or_else(|| TransferDiffError::UnknownAccount(username.into()))
        };
        let from_id = account_id(from)?;
        let to_id = account_id(to)?;

        // Read under the lock so every committed transfer is counted
        let unpaid = sqlx::query_scalar::<_, i64>(
            "
            SELECT (COALESCE(a.total_diff, 0) - COALESCE(SUM(p.diff_paid), 0))::BIGINT
            FROM accounts a
            LEFT JOIN payouts p ON p.account_id = a.id AND p.status != 'cancelled'
            WHERE a.id = $1
            GROUP BY a.id, a.total_diff
            ",
        )
        .bind(from_id)
        .fetch_one(&mut *tx)
        .await?;

        if diff > unpaid {
            return Err(TransferDiffError::InsufficientDiff {
                username: from.into(),
                unpaid,
            });
        }

        let from_payout_id = sqlx::query_scalar::<_, i64>(INSERT)
            .bind(from_id)
            .bind(diff)
            .bind(format!("diff transfer to {to}"))
            .fetch_one(&mut *tx)
            .await?;

        let to_payout_id = sqlx::query_scalar::<_, i64>(INSERT)
            .bind(to_id)
            .bind(-diff)
            .bind(format!("diff transfer from {from}"))
            .fetch_one(&mut *tx)
            .await?;

        tx.commit().await?;

        Ok(TransferDiffResponse {
            from_payout_id,
            to_payout_id,
            diff,
        })
    }

    pub async fn update_payout_status(
        &self,
        payout_ids: &[i64],
        status: &str,
        failure_reason: Option<&str>,
    ) -> Result<u64> {
        if payout_ids.is_empty() {
            return Ok(0);
        }

        let valid_statuses = ["pending", "processing", "success", "failure", "cancelled"];
        if !valid_statuses.contains(&status) {
            return Err(anyhow!("Invalid status: {}", status));
        }

        let rows_affected = sqlx::query(
            "
            UPDATE payouts
            SET status = $1,
                failure_reason = $2,
                updated_at = NOW()
            WHERE id = ANY($3)
            ",
        )
        .bind(status)
        .bind(failure_reason)
        .bind(payout_ids)
        .execute(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?
        .rows_affected();

        Ok(rows_affected)
    }

    pub(crate) async fn get_rounds(&self) -> Result<Vec<Round>> {
        sqlx::query_as::<_, Round>(
            "
            SELECT blockheight, blockhash, username, diff, coinbasevalue
            FROM blocks
            ORDER BY blockheight ASC
            ",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn get_round_participation(
        &self,
        blockheight: Option<i32>,
    ) -> Result<Vec<RoundParticipant>> {
        match blockheight {
            None => {
                // 'current' round comes from matview
                match sqlx::query_as::<_, RoundParticipant>(
                    "
                    SELECT username, blocks_participated, top_diff, total_work
                    FROM round_participation_current
                    ORDER BY top_diff DESC
                    ",
                )
                .fetch_all(&self.pool)
                .await
                {
                    Ok(result) => Ok(result),
                    Err(e) => {
                        warn!("Materialized view query failed, falling back to direct query: {e}");
                        self.query_round_participation(None).await
                    }
                }
            }
            Some(h) => {
                // Historical round ending on blockheight 'h' comes from the history
                // table, which persists total_work (populated at snapshot time and
                // by the startup backfill). This is a cheap indexed read — the
                // expensive per-round aggregation happens once, out of band, not on
                // every request. On a miss we snapshot once, then read.
                match self.get_round_participation_history(h).await {
                    Ok(result) if !result.is_empty() => Ok(result),
                    Ok(_) => {
                        if let Err(e) = self.snapshot_round_participation(h).await {
                            warn!("Failed to snapshot round {h}: {e}");
                        }
                        self.get_round_participation_history(h)
                            .await
                            .map_err(|err| anyhow!(err))
                    }
                    // Dynamic fallback already computes total_work inline.
                    Err(_) => self.query_round_participation(Some(h)).await,
                }
            }
        }
    }

    async fn get_round_participation_history(
        &self,
        blockheight: i32,
    ) -> Result<Vec<RoundParticipant>, sqlx::Error> {
        sqlx::query_as::<_, RoundParticipant>(
            "
            SELECT username, blocks_participated, top_diff, total_work
            FROM round_participation_history
            WHERE blockheight = $1
            ORDER BY top_diff DESC
            ",
        )
        .bind(blockheight)
        .fetch_all(&self.pool)
        .await
    }

    /// Snapshot every completed round that hasn't had its `total_work` populated
    /// yet (missing history rows, or rows left at 0 by an older schema). Run once
    /// out of band on startup: it does the heavy per-round aggregation off the
    /// request path, then self-limits on subsequent runs since backfilled rounds
    /// no longer match. Rounds are processed oldest-first, one at a time.
    pub(crate) async fn backfill_round_participation(&self) -> Result<()> {
        let rounds: Vec<i32> = sqlx::query_scalar::<_, i32>(
            "
            SELECT b.blockheight
            FROM blocks b
            WHERE b.blockheight > 0
              AND NOT EXISTS (
                  SELECT 1 FROM round_participation_history h
                  WHERE h.blockheight = b.blockheight AND h.total_work > 0
              )
            ORDER BY b.blockheight
            ",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        if rounds.is_empty() {
            return Ok(());
        }

        info!(
            "Backfilling round total_work for {} round(s)...",
            rounds.len()
        );
        for h in &rounds {
            if let Err(e) = self.snapshot_round_participation(*h).await {
                warn!("Backfill snapshot failed for round {h}: {e}");
            }
        }
        info!("Round total_work backfill complete");

        Ok(())
    }

    async fn query_round_participation(
        &self,
        blockheight: Option<i32>,
    ) -> Result<Vec<RoundParticipant>> {
        sqlx::query_as::<_, RoundParticipant>(
            "
            WITH previous_block AS (
                SELECT COALESCE(MAX(blockheight), 0) AS prev_height
                FROM blocks
                WHERE ($1::INTEGER IS NULL OR blockheight < $1)
            )
            SELECT
                COALESCE(rs.username, '') AS username,
                COUNT(DISTINCT rs.blockheight) AS blocks_participated,
                COALESCE(MAX(rs.sdiff), 0) AS top_diff,
                COALESCE(SUM(rs.diff), 0) AS total_work
            FROM remote_shares rs, previous_block pb
            WHERE rs.blockheight > pb.prev_height
                AND ($1::INTEGER IS NULL OR rs.blockheight <= $1)
                AND rs.reject_reason IS NULL
            GROUP BY rs.username
            ORDER BY top_diff DESC
            ",
        )
        .bind(blockheight)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    pub(crate) async fn snapshot_round_participation(&self, blockheight: i32) -> Result<()> {
        sqlx::query(
            "
            INSERT INTO round_participation_history (blockheight, username, blocks_participated, top_diff, total_work)
            WITH previous_block AS (
                SELECT COALESCE(MAX(b.blockheight), 0) AS prev_height
                FROM blocks b
                WHERE b.blockheight < $1
            )
            SELECT
                $1,
                COALESCE(rs.username, ''),
                COUNT(DISTINCT rs.blockheight),
                COALESCE(MAX(rs.sdiff), 0),
                COALESCE(SUM(rs.diff), 0)
            FROM remote_shares rs, previous_block pb
            WHERE rs.blockheight > pb.prev_height
                AND rs.blockheight <= $1
                AND rs.reject_reason IS NULL
            GROUP BY rs.username
            ON CONFLICT (blockheight, username) DO UPDATE SET
                blocks_participated = EXCLUDED.blocks_participated,
                top_diff = EXCLUDED.top_diff,
                total_work = EXCLUDED.total_work
            ",
        )
        .bind(blockheight)
        .execute(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        Ok(())
    }

    /// Compute the `block` badge state for a user: one badge per pool-found
    /// block where they submitted an accepted share at that exact height. The
    /// earliest `BLOCK_UNIQUE_CAP` become individual medals and the rest stack.
    pub(crate) async fn compute_block_badges(&self, username: &str) -> Result<badges::BadgeType> {
        // "Mined on block X" means a share was submitted at the exact height the
        // block was found
        let heights: Vec<i32> = sqlx::query_scalar(
            "
            SELECT b.blockheight
            FROM blocks b
            WHERE b.blockheight > 0
              AND EXISTS (
                  SELECT 1 FROM remote_shares rs
                  WHERE rs.blockheight = b.blockheight
                    AND rs.username = $1
                    AND rs.reject_reason IS NULL
              )
            ORDER BY b.blockheight ASC
            ",
        )
        .bind(username)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let total = heights.len() as i64;
        Ok(build_block_badge_type(total, heights))
    }

    /// Block heights this user won (their share solved the block). Sourced from
    /// the `blocks` table where `username` is the winning address.
    pub(crate) async fn compute_block_winner_heights(&self, username: &str) -> Result<Vec<i32>> {
        sqlx::query_scalar::<_, i32>(
            "
            SELECT blockheight
            FROM blocks
            WHERE username = $1 AND blockheight > 0
            ORDER BY blockheight ASC
            ",
        )
        .bind(username)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }

    /// Number of loyalty instances: one per `LOYALTY_BLOCKS_PER_INSTANCE` blocks
    /// the user has submitted a share in (`account_metadata.data.block_count`).
    pub(crate) async fn compute_loyalty_count(&self, username: &str) -> Result<i64> {
        let block_count: Option<i64> = sqlx::query_scalar(
            "
            SELECT (m.data->>'block_count')::bigint
            FROM accounts a
            LEFT JOIN account_metadata m ON a.id = m.account_id
            WHERE a.username = $1
            ",
        )
        .bind(username)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?
        .flatten();

        Ok(block_count.unwrap_or(0) / LOYALTY_BLOCKS_PER_INSTANCE)
    }

    /// Compute the full badge payload for a user and cache it into
    /// `account_metadata.data.badges`. Returns `None` when the account does not
    /// exist. The shallow JSONB `||` merge preserves sibling keys such as
    /// `block_count`/`highest_blockheight`. Externally-sourced badges (refinery,
    /// dispenser) are best-effort: on a fetch failure the previously cached
    /// value for that badge is carried forward, so a transient outage of the
    /// Router/guac never makes an earned badge disappear from a profile.
    pub(crate) async fn compute_and_store_badges(
        &self,
        username: &str,
    ) -> Result<Option<BadgesPayload>> {
        let row: Option<(i64, Option<serde_json::Value>)> = sqlx::query_as(
            "
            SELECT a.id, m.data->'badges' AS badges
            FROM accounts a
            LEFT JOIN account_metadata m ON a.id = m.account_id
            WHERE a.username = $1
            ",
        )
        .bind(username)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let Some((account_id, previous_raw)) = row else {
            return Ok(None);
        };

        // Best-effort: an unparseable or absent previous payload just means
        // there is nothing to carry forward.
        let previous: Option<BadgesPayload> =
            previous_raw.and_then(|raw| serde_json::from_value(raw).ok());

        let mut types = std::collections::HashMap::new();

        types.insert(
            BLOCK_BADGE_ID.to_string(),
            self.compute_block_badges(username).await?,
        );
        types.insert(
            BLOCK_WINNER_BADGE_ID.to_string(),
            build_unique_badge(self.compute_block_winner_heights(username).await?),
        );
        types.insert(
            LOYALTY_BADGE_ID.to_string(),
            build_bucket_badge(self.compute_loyalty_count(username).await?),
        );

        // Carry the last known value forward when an external source is
        // unreachable, so an outage degrades to "stale" rather than "missing".
        let carry_forward = |id: &str, types: &mut std::collections::HashMap<String, _>| {
            if let Some(prev) = previous.as_ref().and_then(|p| p.types.get(id)) {
                types.insert(id.to_string(), prev.clone());
            }
        };

        match self.external.refinery_count(username).await {
            Ok(Some(count)) => {
                types.insert(REFINERY_BADGE_ID.to_string(), build_bucket_badge(count));
            }
            Ok(None) => {}
            Err(e) => {
                if !ExternalBadgeSources::is_not_found(&e) {
                    warn!("Refinery badge fetch failed for {username}, keeping cached value: {e}");
                }
                carry_forward(REFINERY_BADGE_ID, &mut types);
            }
        }

        match self.external.dispenser_assets(username).await {
            Ok(Some(assets)) => {
                types.insert(
                    DISPENSER_BADGE_ID.to_string(),
                    build_bucket_badge(assets.len() as i64),
                );
                // Per-asset badges for the collections that have one of their
                // own. These are earned-or-not: collecting a second Bravocado
                // does not stack a second medal, so the count is capped at one.
                for (badge_id, asset) in [
                    (BRAVOCADO_BADGE_ID, BRAVOCADO_ASSET),
                    (MINER_BADGE_ID, MINER_ASSET),
                ] {
                    let earned = i64::from(assets.contains_key(asset));
                    types.insert(badge_id.to_string(), build_bucket_badge(earned));
                }
            }
            Ok(None) => {}
            Err(e) => {
                if !ExternalBadgeSources::is_not_found(&e) {
                    warn!("Dispenser badge fetch failed for {username}, keeping cached value: {e}");
                }
                for id in [DISPENSER_BADGE_ID, BRAVOCADO_BADGE_ID, MINER_BADGE_ID] {
                    carry_forward(id, &mut types);
                }
            }
        }

        match self.external.auction_bids(username).await {
            Ok(Some(count)) => {
                types.insert(
                    AUCTION_BIDDER_BADGE_ID.to_string(),
                    build_bucket_badge(count),
                );
            }
            Ok(None) => {}
            Err(e) => {
                if !ExternalBadgeSources::is_not_found(&e) {
                    warn!(
                        "Auction bidder badge fetch failed for {username}, keeping cached value: {e}"
                    );
                }
                carry_forward(AUCTION_BIDDER_BADGE_ID, &mut types);
            }
        }

        match self.external.auction_wins(username).await {
            Ok(Some(count)) => {
                types.insert(
                    AUCTION_WINNER_BADGE_ID.to_string(),
                    build_bucket_badge(count),
                );
            }
            Ok(None) => {}
            Err(e) => {
                if !ExternalBadgeSources::is_not_found(&e) {
                    warn!(
                        "Auction winner badge fetch failed for {username}, keeping cached value: {e}"
                    );
                }
                carry_forward(AUCTION_WINNER_BADGE_ID, &mut types);
            }
        }

        let (source_tip, source_blocks): (i64, i64) = sqlx::query_as(
            "SELECT COALESCE(MAX(blockheight), 0)::bigint, COUNT(*)::bigint FROM blocks",
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let payload = BadgesPayload {
            version: BADGES_VERSION,
            computed_at: chrono::Utc::now().to_rfc3339(),
            source_tip,
            source_blocks,
            types,
        };

        let data = serde_json::json!({ "badges": serde_json::to_value(&payload)? });

        sqlx::query(
            "
            INSERT INTO account_metadata (account_id, data, created_at, updated_at)
            VALUES ($1, $2, NOW(), NOW())
            ON CONFLICT (account_id) DO UPDATE
            SET data = account_metadata.data || $2, updated_at = NOW()
            ",
        )
        .bind(account_id)
        .bind(&data)
        .execute(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        Ok(Some(payload))
    }

    /// Read the cached badge payload for an account, distinguishing a missing
    /// account (404) from a missing/stale cache (recompute on demand).
    ///
    /// The cache is considered fresh only when nothing that feeds it has
    /// changed: same schema version, same found-block fingerprint (tip + row
    /// count, so block/winner can't have changed), same loyalty count, within
    /// the backstop max age, and — only if external sources are configured —
    /// within the external re-poll TTL. This avoids re-checking unchanged data
    /// on a short timer while still bounding staleness.
    pub(crate) async fn get_account_badges(&self, username: &str) -> Result<BadgeLookup> {
        let row: Option<(i64, Option<serde_json::Value>, i64, i64, i64)> = sqlx::query_as(
            "
            SELECT
                a.id,
                m.data->'badges' AS badges,
                COALESCE((m.data->>'block_count')::bigint, 0) AS block_count,
                (SELECT COALESCE(MAX(blockheight), 0)::bigint FROM blocks) AS tip,
                (SELECT COUNT(*)::bigint FROM blocks) AS blocks
            FROM accounts a
            LEFT JOIN account_metadata m ON a.id = m.account_id
            WHERE a.username = $1
            ",
        )
        .bind(username)
        .fetch_optional(&self.pool)
        .await
        .map_err(|err| anyhow!(err))?;

        let Some((_id, badges, block_count, tip, blocks)) = row else {
            return Ok(BadgeLookup::NoAccount);
        };

        let Some(badges) = badges else {
            return Ok(BadgeLookup::Stale);
        };

        let external_configured = self.external.is_configured();
        let current_loyalty = block_count / LOYALTY_BLOCKS_PER_INSTANCE;

        match serde_json::from_value::<BadgesPayload>(badges) {
            Ok(payload)
                if payload.version == BADGES_VERSION
                    && payload.source_tip == tip
                    && payload.source_blocks == blocks
                    && payload.types.get(LOYALTY_BADGE_ID).map(|t| t.total)
                        == Some(current_loyalty)
                    && payload_within_max_age(&payload.computed_at)
                    && (!external_configured || payload_is_fresh(&payload.computed_at)) =>
            {
                Ok(BadgeLookup::Cached(payload))
            }
            _ => Ok(BadgeLookup::Stale),
        }
    }

    pub(crate) async fn refresh_current_round_participation(&self) -> Result<()> {
        let mut conn = self.pool.acquire().await.map_err(|err| anyhow!(err))?;

        let acquired: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock(8675309)")
            .fetch_one(&mut *conn)
            .await
            .map_err(|err| anyhow!(err))?;

        if !acquired {
            return Ok(());
        }

        let result =
            sqlx::query("REFRESH MATERIALIZED VIEW CONCURRENTLY round_participation_current")
                .execute(&mut *conn)
                .await;

        let _ = sqlx::query("SELECT pg_advisory_unlock(8675309)")
            .execute(&mut *conn)
            .await;

        result.map_err(|err| anyhow!(err))?;
        Ok(())
    }

    pub(crate) async fn get_participants(&self, blockheight: i32) -> Result<Vec<String>> {
        sqlx::query_scalar::<_, String>(
            "
            SELECT DISTINCT COALESCE(username, '')
            FROM remote_shares
            WHERE blockheight = $1
                AND reject_reason IS NULL
            ORDER BY 1
            ",
        )
        .bind(blockheight)
        .fetch_all(&self.pool)
        .await
        .map_err(|err| anyhow!(err))
    }
}