-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathcampaignStore.ts
More file actions
1549 lines (1382 loc) · 48.9 KB
/
Copy pathcampaignStore.ts
File metadata and controls
1549 lines (1382 loc) · 48.9 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
import { getDb, initDb } from './db';
import { getCampaignHistory, recordEvent, BlockchainMetadata } from './eventHistory';
import { createNotification } from './notificationService';
import { dispatchWebhook } from './webhookService';
export type CampaignStatus = 'open' | 'funded' | 'claimed' | 'failed';
export interface CampaignInput {
creator: string;
title: string;
description: string;
acceptedTokens?: string[];
assetCode?: string; // Backward compatibility
targetAmount: number;
deadline: number;
metadata?: {
imageUrl?: string;
externalLink?: string;
};
maxPerContributor?: number;
}
export interface PledgeInput {
contributor: string;
amount: number;
assetCode?: string; // Optional for backward compatibility if only one token
tokenId?: string; // Canonical token identifier (code:issuer for classic; contract addr for native). Falls back to assetCode if missing.
}
export interface ReconciledPledgeInput extends PledgeInput {
transactionHash: string;
confirmedAt?: number;
}
export interface CampaignRecord {
id: string;
creator: string;
title: string;
description: string;
acceptedTokens: string[];
assetCode: string; // Backward compatibility (first token)
targetAmount: number;
pledgedAmount: number;
deadline: number;
createdAt: number;
claimedAt?: number;
failedAt?: number;
deletedAt?: number;
metadata?: {
imageUrl?: string;
externalLink?: string;
};
maxPerContributor?: number;
tokenBalances?: Record<string, number>;
}
export interface CampaignProgress {
status: CampaignStatus;
percentFunded: number;
remainingAmount: number;
pledgeCount: number;
hoursLeft: number;
canPledge: boolean;
canClaim: boolean;
canRefund: boolean;
}
export interface PledgeRecord {
id: number;
campaignId: string;
contributor: string;
amount: number;
assetCode: string;
tokenId?: string; // Canonical token identifier
createdAt: number;
refundedAt?: number;
transactionHash?: string;
}
export interface RefundReconciliationInput {
txHash: string;
contractId?: string;
networkPassphrase?: string;
rpcUrl?: string;
walletAddress?: string;
ledger?: number;
createdAt?: number;
latestLedger?: number;
source?: 'local' | 'soroban-contract';
}
interface CampaignRow {
id: string;
creator: string;
title: string;
description: string;
accepted_tokens_json: string; // JSON array of strings
target_amount: number;
pledged_amount: number;
deadline: number;
created_at: number;
claimed_at: number | null;
failed_at: number | null;
deleted_at: number | null;
metadata_json: string | null;
max_per_contributor: number | null;
}
interface PledgeRow {
id: number;
campaign_id: string;
contributor: string;
amount: number;
asset_code: string;
token_id: string | null;
created_at: number;
refunded_at: number | null;
transaction_hash: string | null;
}
type ServiceError = Error & {
statusCode?: number;
code?: string;
};
function toServiceError(message: string, statusCode: number, code = 'BAD_REQUEST'): ServiceError {
const error = new Error(message) as ServiceError;
error.statusCode = statusCode;
error.code = code;
return error;
}
function nowInSeconds(): number {
return Math.floor(Date.now() / 1000);
}
function nowInMilliseconds(): number {
return Date.now();
}
function round(value: number): number {
return Number(value.toFixed(2));
}
function rowToCampaign(row: CampaignRow): CampaignRecord {
const acceptedTokens = JSON.parse(row.accepted_tokens_json);
return {
id: row.id,
creator: row.creator,
title: row.title,
description: row.description,
acceptedTokens: acceptedTokens,
assetCode: acceptedTokens[0] || '',
targetAmount: row.target_amount,
pledgedAmount: row.pledged_amount,
deadline: row.deadline,
createdAt: row.created_at,
claimedAt: row.claimed_at ?? undefined,
failedAt: row.failed_at ?? undefined,
deletedAt: row.deleted_at ?? undefined,
metadata: row.metadata_json ? JSON.parse(row.metadata_json) : undefined,
maxPerContributor: row.max_per_contributor ?? undefined,
};
}
function rowToPledge(row: PledgeRow): PledgeRecord {
return {
id: row.id,
campaignId: row.campaign_id,
contributor: row.contributor,
amount: row.amount,
assetCode: row.asset_code,
tokenId: row.token_id ?? row.asset_code,
createdAt: row.created_at,
refundedAt: row.refunded_at ?? undefined,
transactionHash: row.transaction_hash ?? undefined,
};
}
function nextCampaignId(): string {
const db = getDb();
const row = db
.prepare(`SELECT COALESCE(MAX(CAST(id AS INTEGER)), 0) AS latest FROM campaigns`)
.get() as { latest: number };
return String(row.latest + 1);
}
function getActivePledgeCount(campaignId: string): number {
const db = getDb();
const row = db
.prepare(`SELECT COUNT(*) AS count FROM pledges WHERE campaign_id = ? AND refunded_at IS NULL`)
.get(campaignId) as { count: number };
return row.count;
}
export function getPledgeByTransactionHash(transactionHash: string): PledgeRecord | undefined {
const db = getDb();
const row = db
.prepare(`SELECT * FROM pledges WHERE transaction_hash = ?`)
.get(transactionHash) as PledgeRow | undefined;
return row ? rowToPledge(row) : undefined;
}
export function getPledgeById(campaignId: string, pledgeId: number): PledgeRecord | undefined {
const db = getDb();
const row = db
.prepare(`SELECT * FROM pledges WHERE campaign_id = ? AND id = ?`)
.get(campaignId, pledgeId) as PledgeRow | undefined;
return row ? rowToPledge(row) : undefined;
}
function getContributorPledgedTotal(campaignId: string, contributor: string): number {
export function getContributorPledgedTotal(campaignId: string, contributor: string): number {
const db = getDb();
const row = db
.prepare(
`SELECT COALESCE(SUM(amount), 0) AS total
FROM pledges
WHERE campaign_id = ? AND contributor = ? AND refunded_at IS NULL`,
)
.get(campaignId, contributor) as { total: number };
return row.total;
}
/**
* Initializes the campaign store by setting up the underlying SQLite database.
* Must be called once at application startup before any store functions are used.
*/
export function initCampaignStore(): void {
initDb();
}
function checkContributorLimit(
campaign: CampaignRecord,
contributor: string,
amount: number,
): void {
if (campaign.maxPerContributor !== undefined && campaign.maxPerContributor > 0) {
const existingPledged = getContributorPledgedTotal(campaign.id, contributor);
if (existingPledged + amount > campaign.maxPerContributor) {
throw toServiceError(
'Pledge exceeds maximum allowed per contributor.',
400,
'MAX_PER_CONTRIBUTOR_EXCEEDED',
);
}
}
}
/**
* Derives the current progress and lifecycle state of a campaign.
*
* @param campaign - The campaign record to evaluate.
* @param at - Unix timestamp (seconds) to evaluate state against; defaults to now.
* @param pledgeCountOverride - Optional pledge count to use instead of querying database.
* @returns A {@link CampaignProgress} object with status, funding percentages, and action flags.
*/
export function calculateProgress(
campaign: CampaignRecord,
at = nowInMilliseconds(),
pledgeCount?: number,
): CampaignProgress {
const deadlineAt = campaign.deadline * 1000;
const deadlineReached = at > deadlineAt;
const canClaim =
campaign.claimedAt === undefined &&
deadlineReached &&
campaign.pledgedAmount >= campaign.targetAmount;
const canRefund =
campaign.claimedAt === undefined &&
deadlineReached &&
campaign.pledgedAmount < campaign.targetAmount;
const canPledge = campaign.claimedAt === undefined && !deadlineReached;
let status: CampaignStatus = 'open';
if (campaign.claimedAt !== undefined) {
status = 'claimed';
} else if (campaign.pledgedAmount >= campaign.targetAmount) {
status = 'funded';
} else if (deadlineReached) {
status = 'failed';
}
return {
status,
percentFunded: round((campaign.pledgedAmount / campaign.targetAmount) * 100),
remainingAmount: round(Math.max(0, campaign.targetAmount - campaign.pledgedAmount)),
pledgeCount: pledgeCount ?? getActivePledgeCount(campaign.id),
hoursLeft: round(Math.max(0, deadlineAt - at) / 3600000),
canPledge,
canClaim,
canRefund,
};
}
export type CampaignSortField = 'createdAt' | 'deadline' | 'pledgedAmount' | 'targetAmount';
export type SortOrder = 'asc' | 'desc';
export interface ListCampaignsOptions {
searchQuery?: string;
assetCode?: string;
assetCodes?: string[];
status?: CampaignStatus;
includeDeleted?: boolean;
page?: number;
limit?: number;
sort?: CampaignSortField;
order?: SortOrder;
createdAfter?: number;
createdBefore?: number;
}
export interface ListCampaignsResult {
campaigns: CampaignRecord[];
totalCount: number;
pledgeCounts: Record<string, number>;
}
export interface ListCampaignPledgesOptions {
page: number;
limit: number;
}
export interface ListCampaignPledgesResult {
pledges: PledgeRecord[];
totalCount: number;
}
export interface ContributorSummary {
contributor: string;
totalPledged: number;
refundedAmount: number;
isFullyRefunded: boolean;
}
export interface GlobalStats {
totalCampaigns: number;
campaignCountByStatus: Record<CampaignStatus, number>;
totalPledgedAmount: number;
totalPledgedUsdc: number;
totalPledgedXlm: number;
totalContributors: number;
avgFundingRatePct: number;
onChainCampaignCount?: number; // Total campaigns from contract
}
export interface LeaderboardEntry {
rank: number;
contributor: string;
totalPledged: number;
campaignCount: number;
averagePledgeAmount: number;
}
const MAX_CAMPAIGN_DURATION_SECONDS = 60 * 60 * 24 * 180;
/**
* Retrieves a paginated, filtered list of campaigns from the database.
*
* @param options - Optional filters: `searchQuery`, `assetCode`, `status`, `includeDeleted`, `page`, `limit`.
* @returns A {@link ListCampaignsResult} with the matching campaign records and the total count.
*/
export function listCampaigns(options?: ListCampaignsOptions): ListCampaignsResult {
const db = getDb();
const paginate = options?.page !== undefined && options?.limit !== undefined;
const page = options?.page ?? 1;
const limit = options?.limit ?? 10;
const offset = paginate ? (page - 1) * limit : 0;
const whereClauses: string[] = [];
const params: (string | number)[] = [];
if (options?.searchQuery && options.searchQuery.trim()) {
const rawQuery = options.searchQuery.trim();
// Fixes CodeRabbit: Sanitize/escape special characters so FTS5 MATCH doesn't syntax crash
const cleanQuery = rawQuery.replace(/[^a-zA-Z0-9\s]/g, ' ').trim();
const ftsMatchTerm = cleanQuery ? `${cleanQuery}*` : '';
// Fixes CodeRabbit: Use exact matching for creator public key instead of a slow LIKE scan
const creatorExactTerm = rawQuery;
const exactTerm = rawQuery;
if (ftsMatchTerm) {
whereClauses.push(`(
campaigns.id IN (SELECT id FROM campaigns_fts WHERE campaigns_fts MATCH ?)
OR LOWER(campaigns.creator) = LOWER(?)
OR campaigns.id = ?
)`);
params.push(ftsMatchTerm, creatorExactTerm, exactTerm);
} else {
// Fallback if cleaning the query stripped all characters
whereClauses.push(`(LOWER(campaigns.creator) = LOWER(?) OR campaigns.id = ?)`);
params.push(creatorExactTerm, exactTerm);
}
}
if (options?.assetCode) {
whereClauses.push(`campaigns.accepted_tokens_json LIKE ?`);
params.push(`%${options.assetCode.toUpperCase()}%`);
}
if (options?.assetCodes && options.assetCodes.length > 0) {
const conditions = options.assetCodes
.map(() => `campaigns.accepted_tokens_json LIKE ?`)
.join(' OR ');
whereClauses.push(`(${conditions})`);
options.assetCodes.forEach((code) => {
params.push(`%${code.toUpperCase()}%`);
});
}
if (options?.status) {
const now = nowInMilliseconds();
switch (options.status) {
case 'claimed':
whereClauses.push(`claimed_at IS NOT NULL`);
break;
case 'funded':
whereClauses.push(`claimed_at IS NULL AND pledged_amount >= target_amount`);
break;
case 'failed':
whereClauses.push(
`campaigns.claimed_at IS NULL AND campaigns.pledged_amount < campaigns.target_amount AND campaigns.deadline * 1000 < ?`,
);
params.push(now);
break;
case 'open':
whereClauses.push(`claimed_at IS NULL AND pledged_amount < target_amount AND deadline * 1000 >= ?`);
params.push(now);
break;
}
}
if (options?.createdAfter !== undefined) {
whereClauses.push(`campaigns.created_at >= ?`);
params.push(options.createdAfter);
}
if (options?.createdBefore !== undefined) {
whereClauses.push(`campaigns.created_at <= ?`);
params.push(options.createdBefore);
}
if (!options?.includeDeleted) {
whereClauses.push(`campaigns.deleted_at IS NULL`);
}
let whereClause = '';
if (whereClauses.length > 0) {
whereClause = ` WHERE ${whereClauses.join(' AND ')}`;
}
const countQuery = `SELECT COUNT(DISTINCT campaigns.id) as total FROM campaigns LEFT JOIN pledges ON campaigns.id = pledges.campaign_id AND pledges.refunded_at IS NULL${whereClause}`;
const totalCount = (db.prepare(countQuery).get(...params) as { total: number }).total;
// Build ORDER BY clause from sort options
const sortField = options?.sort ?? 'createdAt';
const sortOrder = options?.order ?? 'desc';
const orderDir = sortOrder === 'asc' ? 'ASC' : 'DESC';
let orderByClause: string;
switch (sortField) {
case 'deadline':
orderByClause = `campaigns.deadline ${orderDir}`;
break;
case 'pledgedAmount':
orderByClause = `campaigns.pledged_amount ${orderDir}`;
break;
case 'targetAmount':
orderByClause = `campaigns.target_amount ${orderDir}`;
break;
case 'createdAt':
default:
orderByClause = `campaigns.created_at ${orderDir}`;
break;
}
const dataQuery = paginate
? `SELECT campaigns.*, COUNT(pledges.id) as pledge_count FROM campaigns LEFT JOIN pledges ON campaigns.id = pledges.campaign_id AND pledges.refunded_at IS NULL${whereClause} GROUP BY campaigns.id ORDER BY ${orderByClause} LIMIT ? OFFSET ?`
: `SELECT campaigns.*, COUNT(pledges.id) as pledge_count FROM campaigns LEFT JOIN pledges ON campaigns.id = pledges.campaign_id AND pledges.refunded_at IS NULL${whereClause} GROUP BY campaigns.id ORDER BY ${orderByClause}`;
const rows = (
paginate
? db.prepare(dataQuery).all(...params, limit, offset)
: db.prepare(dataQuery).all(...params)
) as Array<CampaignRow & { pledge_count: number }>;
const pledgeCounts: Record<string, number> = {};
const campaigns = rows.map((row) => {
pledgeCounts[row.id] = row.pledge_count;
const { pledge_count: _pledgeCount, ...campaignRow } = row;
void _pledgeCount;
const now = nowInMilliseconds();
const failResult = db.prepare(
`UPDATE campaigns SET failed_at = ? WHERE id = ? AND failed_at IS NULL AND claimed_at IS NULL AND pledged_amount < target_amount AND deadline * 1000 < ?`,
).run(campaignRow.deadline, campaignRow.id, now);
if (failResult.changes === 1) {
campaignRow.failed_at = campaignRow.deadline;
void dispatchWebhook('campaign_failed', campaignRow.id, {
pledgedAmount: campaignRow.pledged_amount,
targetAmount: campaignRow.target_amount,
deadline: campaignRow.deadline,
});
}
return rowToCampaign(campaignRow as CampaignRow);
});
return {
campaigns,
totalCount,
pledgeCounts,
};
}
/**
* Fetches a single campaign by its ID.
*
* @param campaignId - The unique campaign identifier.
* @returns The {@link CampaignRecord} if found, or `undefined` if it does not exist.
*/
export function getCampaign(campaignId: string): CampaignRecord | undefined {
const db = getDb();
const row = db.prepare(`SELECT * FROM campaigns WHERE id = ?`).get(campaignId) as
CampaignRow | undefined;
if (row) {
const now = nowInMilliseconds();
const failResult = db.prepare(
`UPDATE campaigns SET failed_at = ? WHERE id = ? AND failed_at IS NULL AND claimed_at IS NULL AND pledged_amount < target_amount AND deadline * 1000 < ?`,
).run(row.deadline, row.id, now);
if (failResult.changes === 1) {
row.failed_at = row.deadline;
void dispatchWebhook('campaign_failed', row.id, {
pledgedAmount: row.pledged_amount,
targetAmount: row.target_amount,
deadline: row.deadline,
});
}
const campaign = rowToCampaign(row);
campaign.tokenBalances = getCampaignTokenBalances(campaignId);
return campaign;
}
return undefined;
}
/**
* Returns all pledges for a campaign, ordered by most recent first.
*
* @param campaignId - The unique campaign identifier.
* @returns An array of {@link PledgeRecord} objects (may be empty).
*/
export function getPledges(campaignId: string): PledgeRecord[] {
const db = getDb();
const rows = db
.prepare(`SELECT * FROM pledges WHERE campaign_id = ? ORDER BY created_at DESC, id DESC`)
.all(campaignId) as PledgeRow[];
return rows.map(rowToPledge);
}
/**
* Returns a paginated list of pledges for a specific campaign.
*
* @param campaignId - The unique campaign identifier.
* @param options - Pagination options: `page` (1-based) and `limit` (records per page).
* @returns A {@link ListCampaignPledgesResult} with pledge records and the total count.
*/
export function listCampaignPledges(
campaignId: string,
options: ListCampaignPledgesOptions,
): ListCampaignPledgesResult {
const db = getDb();
const offset = (options.page - 1) * options.limit;
const totalCount = (
db.prepare(`SELECT COUNT(*) AS total FROM pledges WHERE campaign_id = ?`).get(campaignId) as {
total: number;
}
).total;
const rows = db
.prepare(
`SELECT *
FROM pledges
WHERE campaign_id = ?
ORDER BY created_at DESC, id DESC
LIMIT ? OFFSET ?`,
)
.all(campaignId, options.limit, offset) as PledgeRow[];
return {
pledges: rows.map(rowToPledge),
totalCount,
};
}
/**
* Aggregates pledge totals per contributor for a campaign, including refunded amounts.
*
* @param campaignId - The unique campaign identifier.
* @returns An array of {@link ContributorSummary} objects sorted by total pledged (descending),
* or an empty array if the campaign does not exist.
*/
export function getContributorSummary(campaignId: string): ContributorSummary[] {
const db = getDb();
const rows = db
.prepare(
`
SELECT
contributor,
COALESCE(SUM(CASE WHEN refunded_at IS NULL THEN amount ELSE 0 END), 0) as totalPledged,
COALESCE(SUM(CASE WHEN refunded_at IS NOT NULL THEN amount ELSE 0 END), 0) as refundedAmount
FROM pledges
WHERE campaign_id = ?
GROUP BY contributor
ORDER BY totalPledged DESC
`,
)
.all(campaignId) as Array<{
contributor: string;
totalPledged: number;
refundedAmount: number;
}>;
const campaign = getCampaign(campaignId);
if (!campaign) {
return [];
}
return rows.map((row) => ({
contributor: row.contributor,
totalPledged: Number(row.totalPledged),
refundedAmount: Number(row.refundedAmount),
isFullyRefunded: row.refundedAmount > 0 && row.totalPledged === 0,
}));
}
/**
* Fetches a campaign enriched with its calculated progress, recent pledges, and event history.
*
* @param campaignId - The unique campaign identifier.
* @param pledgePreviewLimit - Maximum number of recent pledges to include (default: 5).
* @returns The enriched campaign object, or `undefined` if the campaign does not exist.
*/
export function getCampaignWithProgress(campaignId: string, pledgePreviewLimit = 5) {
const campaign = getCampaign(campaignId);
if (!campaign) {
return undefined;
}
return {
...campaign,
progress: calculateProgress(campaign),
pledges: getPledges(campaignId).slice(0, pledgePreviewLimit),
history: getCampaignHistory(campaignId),
};
}
/**
* Creates a new campaign and records a "created" lifecycle event.
*
* @param input - The campaign creation payload (see {@link CampaignInput}).
* @returns The newly created {@link CampaignRecord}.
* @throws {ServiceError} 400 `MAX_CAMPAIGN_DURATION_EXCEEDED` if the deadline is too far in the future.
* @throws {ServiceError} 400 `INVALID_INPUT` if no accepted tokens are provided.
*/
export function createCampaign(input: CampaignInput): CampaignRecord {
const db = getDb();
const now = nowInSeconds();
if (input.deadline - now > MAX_CAMPAIGN_DURATION_SECONDS) {
throw toServiceError(
`Campaign duration exceeds maximum of ${MAX_CAMPAIGN_DURATION_SECONDS} seconds.`,
400,
'MAX_CAMPAIGN_DURATION_EXCEEDED',
);
}
const acceptedTokens = input.acceptedTokens
? input.acceptedTokens.map((code) => code.trim().toUpperCase())
: input.assetCode
? [input.assetCode.trim().toUpperCase()]
: [];
if (acceptedTokens.length === 0) {
throw toServiceError('At least one accepted token is required.', 400, 'INVALID_INPUT');
}
const campaign: CampaignRecord = {
id: nextCampaignId(),
creator: input.creator,
title: input.title.trim(),
description: input.description.trim(),
acceptedTokens,
assetCode: acceptedTokens[0] || '',
targetAmount: round(input.targetAmount),
pledgedAmount: 0,
deadline: input.deadline,
createdAt: now,
metadata: input.metadata,
maxPerContributor: input.maxPerContributor,
};
db.prepare(
`INSERT INTO campaigns (
id, creator, title, description, accepted_tokens_json, target_amount, pledged_amount, deadline, created_at, claimed_at, failed_at, metadata_json, max_per_contributor
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)`,
).run(
campaign.id,
campaign.creator,
campaign.title,
campaign.description,
JSON.stringify(campaign.acceptedTokens),
campaign.targetAmount,
campaign.pledgedAmount,
campaign.deadline,
campaign.createdAt,
null,
null,
campaign.metadata ? JSON.stringify(campaign.metadata) : null,
campaign.maxPerContributor ?? null,
);
recordEvent(
campaign.id,
'created',
campaign.createdAt,
campaign.creator,
undefined,
{
title: campaign.title,
acceptedTokens: campaign.acceptedTokens,
targetAmount: campaign.targetAmount,
deadline: campaign.deadline,
},
{ source: 'local' } as BlockchainMetadata,
);
return campaign;
}
/**
* Records an off-chain pledge for a campaign and updates the pledged total.
*
* @param campaignId - The ID of the campaign to pledge to.
* @param input - The pledge payload (contributor address, amount, optional asset code).
* @returns The updated {@link CampaignRecord} after the pledge is applied.
* @throws {ServiceError} 404 `NOT_FOUND` if the campaign does not exist.
* @throws {ServiceError} 400 `INVALID_ASSET` if the token is not accepted by the campaign.
* @throws {ServiceError} 400 `INVALID_CAMPAIGN_STATE` if the campaign is no longer accepting pledges.
* @throws {ServiceError} 400 `MAX_PER_CONTRIBUTOR_EXCEEDED` if the contributor limit is breached.
* @throws {ServiceError} 400 `CAMPAIGN_FUNDING_CAP_EXCEEDED` if the pledge would exceed the target amount.
*/
export function addPledge(campaignId: string, input: PledgeInput): CampaignRecord {
const db = getDb();
const campaign = getCampaign(campaignId);
if (!campaign) {
throw toServiceError('Campaign not found.', 404, 'NOT_FOUND');
}
const assetCode = (input.assetCode || campaign.assetCode).toUpperCase();
const tokenId = input.tokenId || assetCode;
const isTokenAccepted = campaign.acceptedTokens.some((accepted) => {
// Direct canonical token ID match (CODE:ISSUER or contract address)
if (accepted === tokenId) return true;
// If accepted entry has no issuer component (legacy asset-code-only), fall back to assetCode
if (!accepted.includes(':')) {
return accepted === assetCode;
}
// Match by asset code portion of canonical ID for backward compatibility
return accepted.split(':')[0] === assetCode;
});
if (!isTokenAccepted) {
throw toServiceError(
`Token ${tokenId} is not accepted by this campaign.`,
400,
'INVALID_ASSET',
);
}
const progress = calculateProgress(campaign);
if (!progress.canPledge) {
throw toServiceError('Campaign is no longer accepting pledges.', 400, 'INVALID_CAMPAIGN_STATE');
}
const createdAt = nowInSeconds();
const roundedAmount = round(input.amount);
db.transaction(() => {
// Re-check contributor limit within transaction to prevent race conditions
const existingPledged = getContributorPledgedTotal(campaignId, input.contributor);
if (campaign.maxPerContributor !== undefined && campaign.maxPerContributor > 0) {
if (existingPledged + roundedAmount > campaign.maxPerContributor) {
throw toServiceError(
'Pledge exceeds maximum allowed per contributor.',
400,
'MAX_PER_CONTRIBUTOR_EXCEEDED',
);
}
}
// Re-check campaign funding cap within transaction
const currentPledgedAmount = db
.prepare(`SELECT pledged_amount FROM campaigns WHERE id = ?`)
.get(campaignId) as { pledged_amount: number };
const nextPledgedAmount = round(currentPledgedAmount.pledged_amount + roundedAmount);
if (nextPledgedAmount > campaign.targetAmount) {
throw toServiceError(
'Pledge exceeds campaign funding cap.',
400,
'CAMPAIGN_FUNDING_CAP_EXCEEDED',
);
}
db.prepare(
`INSERT INTO pledges (campaign_id, contributor, amount, asset_code, created_at, refunded_at, transaction_hash)
VALUES (?, ?, ?, ?, ?, NULL, NULL)`,
).run(campaignId, input.contributor, roundedAmount, assetCode, createdAt);
db.prepare(`UPDATE campaigns SET pledged_amount = pledged_amount + ? WHERE id = ?`).run(
roundedAmount,
campaignId,
);
recordEvent(
campaignId,
'pledged',
createdAt,
input.contributor,
roundedAmount,
{
newTotalPledged: nextPledgedAmount,
assetCode,
source: 'backend-mvp',
},
{ source: 'local' } as BlockchainMetadata,
);
// Check if contributor has reached their limit and record event
if (
campaign.maxPerContributor !== undefined &&
campaign.maxPerContributor > 0
) {
const newContributorTotal = round(
getContributorPledgedTotal(campaignId, input.contributor),
);
if (newContributorTotal >= campaign.maxPerContributor) {
recordEvent(
campaignId,
"pledge_limit_reached",
createdAt,
input.contributor,
newContributorTotal,
{
maxPerContributor: campaign.maxPerContributor,
assetCode,
},
{ source: "local" } as BlockchainMetadata,
);
}
}
})();
return getCampaign(campaignId)!;
}
/**
* Reconciles an on-chain Soroban pledge into the local database, deduplicating by transaction hash.
*
* @param campaignId - The ID of the campaign the pledge belongs to.
* @param input - The reconciled pledge payload including a mandatory `transactionHash`.
* @returns The updated {@link CampaignRecord} after the pledge is applied (or the existing record if already reconciled).
* @throws {ServiceError} 409 `TRANSACTION_HASH_CONFLICT` if the tx hash belongs to a different campaign.
* @throws {ServiceError} 404 `NOT_FOUND` if the campaign does not exist.
* @throws {ServiceError} 400 `INVALID_CAMPAIGN_STATE` if the campaign is no longer accepting pledges.
* @throws {ServiceError} 400 `MAX_PER_CONTRIBUTOR_EXCEEDED` if the contributor limit is breached.
* @throws {ServiceError} 400 `CAMPAIGN_FUNDING_CAP_EXCEEDED` if the pledge would exceed the target amount.
*/
export interface ReconcileOnChainPledgeResult {
campaign: CampaignRecord;
existing: boolean;
}
export function reconcileOnChainPledge(
campaignId: string,
input: ReconciledPledgeInput,
): ReconcileOnChainPledgeResult {
const existingPledge = getPledgeByTransactionHash(input.transactionHash);
if (existingPledge) {
if (existingPledge.campaignId !== campaignId) {
throw toServiceError(
'transactionHash already belongs to a different campaign.',
409,
'TRANSACTION_HASH_CONFLICT',
);
}
return { campaign: getCampaign(campaignId)!, existing: true };
}
const campaign = getCampaign(campaignId);
if (!campaign) {
throw toServiceError('Campaign not found.', 404, 'NOT_FOUND');
}
const db = getDb();
const createdAt = input.confirmedAt ?? nowInSeconds();
const roundedAmount = round(input.amount);
const assetCode = (input.assetCode || campaign.assetCode).toUpperCase();
const tokenId = input.tokenId || assetCode;
const isTokenAccepted = campaign.acceptedTokens.some((accepted) => {
if (accepted === tokenId) return true;
if (!accepted.includes(':')) {
return accepted === assetCode;
}
return accepted.split(':')[0] === assetCode;
});
if (!isTokenAccepted) {
throw toServiceError(
`Token ${tokenId} is not accepted by this campaign.`,
400,
'INVALID_ASSET',
);
}
const progress = calculateProgress(campaign);
if (!progress.canPledge) {
throw toServiceError('Campaign is no longer accepting pledges.', 400, 'INVALID_CAMPAIGN_STATE');
}
const insertedNewPledge = db.transaction(() => {
// Re-check contributor limit within transaction to prevent race conditions
const existingPledged = getContributorPledgedTotal(campaignId, input.contributor);
if (campaign.maxPerContributor !== undefined && campaign.maxPerContributor > 0) {
if (existingPledged + roundedAmount > campaign.maxPerContributor) {
throw toServiceError(
'Pledge exceeds maximum allowed per contributor.',
400,
'MAX_PER_CONTRIBUTOR_EXCEEDED',
);
}
}
// Re-check campaign funding cap within transaction
const currentPledgedAmount = db
.prepare(`SELECT pledged_amount FROM campaigns WHERE id = ?`)
.get(campaignId) as { pledged_amount: number };
const nextPledgedAmount = round(currentPledgedAmount.pledged_amount + roundedAmount);
if (nextPledgedAmount > campaign.targetAmount) {
throw toServiceError(
'Pledge exceeds campaign funding cap.',
400,
'CAMPAIGN_FUNDING_CAP_EXCEEDED',
);
}
const result = db
.prepare(
`INSERT OR IGNORE INTO pledges (
campaign_id, contributor, amount, asset_code, token_id, created_at, refunded_at, transaction_hash
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,
)
.run(
campaignId,
input.contributor,
roundedAmount,
assetCode,
tokenId,
createdAt,
input.transactionHash,
);
if (result.changes === 0) {
const duplicatePledge = getPledgeByTransactionHash(input.transactionHash);
if (!duplicatePledge) {
throw toServiceError(
'Failed to reconcile pledge due to database conflict.',
500,
'DB_CONFLICT',
);
}
if (duplicatePledge.campaignId !== campaignId) {
throw toServiceError(
'transactionHash already belongs to a different campaign.',
409,
'TRANSACTION_HASH_CONFLICT',
);
}