-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathapi.test.ts
More file actions
177 lines (153 loc) · 5.68 KB
/
Copy pathapi.test.ts
File metadata and controls
177 lines (153 loc) · 5.68 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
import fs from 'fs';
import { Server } from 'http';
import path from 'path';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { app } from './index';
import { initCampaignStore } from './services/campaignStore';
import { getDb, resetDbForTests } from './services/db';
// Mock sorobanRpc to avoid real network calls during tests
vi.mock('./services/sorobanRpc', () => ({
ensureSorobanRefundConfig: vi.fn(),
verifyRefundTransaction: vi.fn().mockResolvedValue({
txHash: 'mock-tx-hash',
status: 'SUCCESS',
ledger: 100,
createdAt: Math.floor(Date.now() / 1000),
latestLedger: 100,
}),
}));
const TEST_DB_PATH = path.join('/tmp', `stellar-goal-vault-api-${process.pid}.db`);
process.env.DB_PATH = TEST_DB_PATH;
process.env.CONTRACT_ID = 'mock-contract';
let server: Server;
let baseUrl: string;
beforeAll(async () => {
fs.rmSync(TEST_DB_PATH, { force: true });
initCampaignStore();
await new Promise<void>((resolve) => {
server = app.listen(0, () => {
const address = server.address() as any;
baseUrl = `http://localhost:${address.port}`;
resolve();
});
});
});
afterAll(() => {
server.close();
resetDbForTests();
fs.rmSync(TEST_DB_PATH, { force: true });
});
beforeEach(() => {
const db = getDb();
db.prepare(`DELETE FROM campaign_events`).run();
db.prepare(`DELETE FROM pledges`).run();
db.prepare(`DELETE FROM campaigns`).run();
});
const CREATOR = `G${'A'.repeat(55)}`;
const CONTRIBUTOR = `G${'B'.repeat(55)}`;
async function post(apiPath: string, body: any) {
const response = await fetch(`${baseUrl}${apiPath}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await response.json().catch(() => null);
return { status: response.status, data };
}
describe('Campaign Lifecycle API', () => {
it('covers create, pledge, claim end-to-end', async () => {
// 1. Create Campaign
const createRes = await post('/api/campaigns', {
creator: CREATOR,
targetAmount: 100,
deadline: Math.floor(Date.now() / 1000) + 3600,
});
expect(createRes.status).toBe(201);
const campaignId = createRes.data.data.id;
expect(campaignId).toBeDefined();
// 2. Pledge to reach target
const pledgeRes = await post(`/api/campaigns/${campaignId}/pledges`, {
contributor: CONTRIBUTOR,
amount: 100,
assetCode: "USDC",
});
expect(pledgeRes.status).toBe(201);
expect(pledgeRes.data.data.progress.status).toBe('funded');
expect(pledgeRes.data.data.progress.canClaim).toBe(false); // Deadline not reached yet
// Move deadline to past in DB to allow claim
getDb()
.prepare(`UPDATE campaigns SET deadline = ? WHERE id = ?`)
.run(Math.floor(Date.now() / 1000) - 3600, campaignId);
// 3. Claim
const claimRes = await post(`/api/campaigns/${campaignId}/claim`, {
creator: CREATOR,
transactionHash: 'a'.repeat(64),
confirmedAt: Math.floor(Date.now() / 1000),
});
expect(claimRes.status).toBe(200);
expect(claimRes.data.data.progress.status).toBe('claimed');
// Duplicate Claim is idempotent (returns 200 with the same status)
const duplicateClaimRes = await post(`/api/campaigns/${campaignId}/claim`, {
creator: CREATOR,
transactionHash: 'a'.repeat(64),
confirmedAt: Math.floor(Date.now() / 1000),
});
expect(duplicateClaimRes.status).toBe(200);
});
it('covers create, pledge, failed, refund end-to-end', async () => {
// 1. Create Campaign
const createRes = await post('/api/campaigns', {
creator: CREATOR,
targetAmount: 100,
deadline: Math.floor(Date.now() / 1000) + 3600,
});
expect(createRes.status).toBe(201);
const campaignId = createRes.data.data.id;
// 2. Pledge partial amount
const pledgeRes = await post(`/api/campaigns/${campaignId}/pledges`, {
contributor: CONTRIBUTOR,
amount: 50,
assetCode: "XLM",
});
expect(pledgeRes.status).toBe(201);
const mockSorobanData = {
txHash: 'a'.repeat(64),
contractId: 'C' + 'A'.repeat(55),
networkPassphrase: 'Test SDF Network ; September 2015',
rpcUrl: 'http://localhost:8000/soroban/rpc',
walletAddress: CONTRIBUTOR,
};
// Attempt early refund (should fail)
const earlyRefundRes = await post(`/api/campaigns/${campaignId}/refund`, {
contributor: CONTRIBUTOR,
soroban: mockSorobanData,
});
expect(earlyRefundRes.status).toBe(400);
expect(earlyRefundRes.data.error.code).toBe('INVALID_CAMPAIGN_STATE');
// Move deadline to past in DB to fail the campaign
getDb()
.prepare(`UPDATE campaigns SET deadline = ? WHERE id = ?`)
.run(Math.floor(Date.now() / 1000) - 3600, campaignId);
// 3. Refund
const refundRes = await post(`/api/campaigns/${campaignId}/refund`, {
contributor: CONTRIBUTOR,
soroban: mockSorobanData,
});
expect(refundRes.status).toBe(200);
expect(refundRes.data.data.refundedAmount).toBe(50);
expect(refundRes.data.data.pledgedAmount).toBe(0); // Pledged amount reduces to 0
});
it("sanitizes HTML tags in title and description during campaign creation", async () => {
const createRes = await post("/api/campaigns", {
creator: CREATOR,
title: "<h1>Test</h1>",
description: "<h1>Test</h1> with at least 20 characters",
acceptedTokens: ["USDC"],
targetAmount: 100,
deadline: Math.floor(Date.now() / 1000) + 3600,
});
expect(createRes.status).toBe(201);
expect(createRes.data.data.title).toBe("<h1>Test</h1>");
expect(createRes.data.data.description).toBe("<h1>Test</h1> with at least 20 characters");
});
});