forked from InsurNiffy/niff-Stellar-shurance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaims.service.ts
More file actions
404 lines (355 loc) · 12.6 KB
/
Copy pathclaims.service.ts
File metadata and controls
404 lines (355 loc) · 12.6 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
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Prisma } from '@prisma/client';
import { SorobanService } from '../rpc/soroban.service';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../cache/redis.service';
import { SanitizationService } from './sanitization.service';
import { TenantContextService } from '../tenant/tenant-context.service';
import { claimTenantWhere, assertTenantOwnership } from '../tenant/tenant-filter.helper';
import {
ClaimDetailResponseDto,
ClaimMetadataDto,
ClaimsListResponseDto,
ConsistencyMetadataDto,
DeadlineDto,
QuorumProgressDto,
SanitizedEvidenceDto,
VoteTalliesDto,
} from './dto/claim.dto';
import {
buildKeysetWhere,
buildNextCursor,
clampLimit,
} from '../helpers/pagination';
interface ListClaimsParams {
after?: string;
limit?: number;
status?: string;
}
const VOTE_WINDOW_LEDGERS = 120_960;
const SECONDS_PER_LEDGER = 5;
type ClaimWithVotes = Prisma.ClaimGetPayload<{
include: {
votes: { select: { vote: true } };
};
}>;
@Injectable()
export class ClaimsService {
private readonly logger = new Logger(ClaimsService.name);
private readonly cacheTtl: number;
private readonly ipfsGateway: string;
private readonly maxAcceptableLag = 5;
private readonly indexerNetwork: string;
constructor(
private readonly prisma: PrismaService,
private readonly redis: RedisService,
private readonly sanitization: SanitizationService,
private readonly config: ConfigService,
private readonly soroban: SorobanService,
private readonly tenantCtx: TenantContextService,
) {
this.cacheTtl = this.config.get<number>('CACHE_TTL_SECONDS', 60);
this.ipfsGateway = this.config.get<string>('IPFS_GATEWAY', 'https://ipfs.io');
this.indexerNetwork = this.config.get<string>('STELLAR_NETWORK', 'testnet');
}
async listClaims(params: ListClaimsParams): Promise<ClaimsListResponseDto> {
const { after, status } = params;
const limit = clampLimit(params.limit);
const tenantId = this.tenantCtx.tenantId;
const cacheKey = `claims:list:${tenantId ?? 'global'}:${after ?? 'start'}:${limit}:${status ?? 'all'}`;
const cached = await this.redis.get<ClaimsListResponseDto>(cacheKey);
if (cached) {
this.logger.debug(`Cache hit for ${cacheKey}`);
return cached;
}
const lastLedger = await this.getLastLedger();
const statusFilter = status
? { status: status.toUpperCase() as 'PENDING' | 'APPROVED' | 'PAID' | 'REJECTED' }
: {};
const keysetWhere = buildKeysetWhere(after);
const where: Prisma.ClaimWhereInput = claimTenantWhere(tenantId, {
...statusFilter,
...(keysetWhere ?? {}),
});
const [claims, total] = await Promise.all([
this.prisma.claim.findMany({
where,
include: { votes: { select: { vote: true } } },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: limit,
}),
this.prisma.claim.count({ where: claimTenantWhere(tenantId, statusFilter) }),
]);
const response: ClaimsListResponseDto = {
data: claims.map((claim) => this.transformClaim(claim, lastLedger)),
pagination: {
next_cursor: buildNextCursor(claims, limit, total),
total,
},
};
await this.redis.set(cacheKey, response, this.cacheTtl);
return response;
}
async getClaimsNeedingVote(
walletAddress: string,
params: ListClaimsParams,
): Promise<ClaimsListResponseDto> {
const { after } = params;
const limit = clampLimit(params.limit);
const tenantId = this.tenantCtx.tenantId;
const lastLedger = await this.getLastLedger();
const votedClaimIds = await this.prisma.vote.findMany({
where: { voterAddress: walletAddress.toLowerCase() },
select: { claimId: true },
});
const votedIds = votedClaimIds.map((v) => v.claimId);
const keysetWhere = buildKeysetWhere(after);
const baseWhere: Prisma.ClaimWhereInput = claimTenantWhere(tenantId, {
status: 'PENDING',
...(votedIds.length > 0 ? { id: { notIn: votedIds } } : {}),
});
const [allOpen, page] = await Promise.all([
this.prisma.claim.count({ where: baseWhere }),
this.prisma.claim.findMany({
where: { ...baseWhere, ...(keysetWhere ?? {}) },
include: { votes: { select: { vote: true } } },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: limit,
}),
]);
const openClaims = page.filter(
(claim) => this.getVotingDeadlineLedger(claim.createdAtLedger) > lastLedger,
);
return {
data: openClaims.map((claim) => this.transformClaim(claim, lastLedger)),
pagination: {
next_cursor: buildNextCursor(openClaims, limit, allOpen),
total: allOpen,
},
};
}
async getClaimById(id: number, walletAddress?: string): Promise<ClaimDetailResponseDto> {
const tenantId = this.tenantCtx.tenantId;
const cacheKey = `claims:detail:${tenantId ?? 'global'}:${id}`;
const cached = await this.redis.get<ClaimDetailResponseDto>(cacheKey);
if (cached && !walletAddress) {
this.logger.debug(`Cache hit for ${cacheKey}`);
return cached;
}
const lastLedger = await this.getLastLedger();
const claim = await this.prisma.claim.findUnique({
where: { id },
include: {
votes: {
select: { vote: true },
},
},
});
// Enforce tenant ownership — returns 404 for cross-tenant reads
assertTenantOwnership(claim, tenantId, `Claim ${id}`);
if (!claim) {
throw new NotFoundException(`Claim with ID ${id} not found`);
}
const response = this.transformClaim(claim, lastLedger);
if (!walletAddress) {
await this.redis.set(cacheKey, response, this.cacheTtl);
return response;
}
return this.enrichWithUserVote(response, walletAddress);
}
private async getLastLedger(): Promise<number> {
const cursor = await this.prisma.ledgerCursor.findUnique({
where: { network: this.indexerNetwork },
});
if (cursor) {
return cursor.lastProcessedLedger;
}
const legacy = await this.prisma.indexerState.findFirst({
orderBy: { lastLedger: 'desc' },
});
return legacy?.lastLedger ?? 0;
}
private transformClaim(claim: ClaimWithVotes, lastLedger: number): ClaimDetailResponseDto {
const yesVotes = claim.votes.filter((vote) => vote.vote === 'APPROVE').length;
const noVotes = claim.votes.filter((vote) => vote.vote === 'REJECT').length;
const totalVotes = yesVotes + noVotes;
const votingDeadlineLedger = this.getVotingDeadlineLedger(claim.createdAtLedger);
const votingDeadlineTime = new Date(
claim.createdAt.getTime() + VOTE_WINDOW_LEDGERS * SECONDS_PER_LEDGER * 1000,
);
const isOpen = votingDeadlineLedger > lastLedger;
const remainingSeconds = isOpen
? (votingDeadlineLedger - lastLedger) * SECONDS_PER_LEDGER
: undefined;
const requiredVotes = Math.max(1, Math.floor(totalVotes / 2) + 1);
const sanitizedHash = this.sanitization.sanitizeIpfsHash(
this.extractEvidenceHash(claim.imageUrls),
);
const indexerLag = Math.max(0, lastLedger - claim.updatedAtLedger);
return {
metadata: {
id: claim.id,
policyId: claim.policyId,
creatorAddress: this.sanitization.sanitizeWalletAddress(claim.creatorAddress),
status: claim.status.toLowerCase() as 'pending' | 'approved' | 'paid' | 'rejected',
amount: claim.amount,
description: claim.description
? this.sanitization.sanitizeDescription(claim.description)
: undefined,
evidenceHash: sanitizedHash,
createdAtLedger: claim.createdAtLedger,
createdAt: claim.createdAt,
updatedAt: claim.updatedAt,
} as ClaimMetadataDto,
votes: {
yesVotes,
noVotes,
totalVotes,
} as VoteTalliesDto,
quorum: {
required: requiredVotes,
current: totalVotes,
percentage: Math.min(100, Math.round((totalVotes / requiredVotes) * 100)),
reached: claim.isFinalized || Math.max(yesVotes, noVotes) >= requiredVotes,
} as QuorumProgressDto,
deadline: {
votingDeadlineLedger,
votingDeadlineTime,
isOpen,
remainingSeconds,
} as DeadlineDto,
evidence: {
gatewayUrl: sanitizedHash ? `${this.ipfsGateway}/ipfs/${sanitizedHash}` : '',
hash: sanitizedHash,
} as SanitizedEvidenceDto,
consistency: {
isFinalized: claim.isFinalized,
indexerLag,
lastIndexedLedger: lastLedger,
isStale: indexerLag > this.maxAcceptableLag,
} as ConsistencyMetadataDto,
};
}
private getVotingDeadlineLedger(createdAtLedger: number): number {
return createdAtLedger + VOTE_WINDOW_LEDGERS;
}
private extractEvidenceHash(imageUrls: string[]): string {
for (const imageUrl of imageUrls) {
const directHash = this.sanitization.sanitizeIpfsHash(imageUrl);
if (directHash) {
return directHash;
}
const match = imageUrl.match(/\/ipfs\/([^/?#]+)/i);
if (match?.[1]) {
return match[1];
}
}
return '';
}
private async enrichWithUserVote(
claim: ClaimDetailResponseDto,
walletAddress: string,
): Promise<ClaimDetailResponseDto> {
const userVote = await this.prisma.vote.findFirst({
where: {
claimId: claim.metadata.id,
voterAddress: walletAddress.toLowerCase(),
},
});
if (userVote) {
claim.userHasVoted = true;
claim.userVote = userVote.vote === 'APPROVE' ? 'yes' : 'no';
}
return claim;
}
async invalidateCache(claimId?: number): Promise<void> {
if (claimId) {
await this.redis.del(`claims:detail:${claimId}`);
}
await this.redis.delPattern('claims:list:*');
this.logger.log(`Cache invalidated for claim ${claimId || 'all'}`);
}
/**
* Build an unsigned file_claim transaction
*/
async buildTransaction(args: {
holder: string;
policyId: number;
amount: bigint;
details: string;
imageUrls: string[];
}) {
return this.soroban.buildFileClaimTransaction(args);
}
/**
* Submit a signed transaction
*/
async submitTransaction(transactionXdr: string) {
const result = await this.soroban.submitTransaction(transactionXdr);
// Invalidate claims list cache so the new claim appears
await this.invalidateCache();
return result;
}
// ── Claim status polling & SSE ───────────────────────────────────────────
/**
* Returns the current status for a set of claim IDs.
* Used by the frontend polling loop (GET /api/claims/status).
*/
async getClaimStatuses(
claimIds: string[],
): Promise<{ claimId: string; status: string; updatedAt: string }[]> {
const numericIds = claimIds.map(Number).filter((n) => !isNaN(n));
if (numericIds.length === 0) return [];
const claims = await this.prisma.claim.findMany({
where: { id: { in: numericIds } },
select: { id: true, status: true, updatedAt: true },
});
return claims.map((c) => ({
claimId: String(c.id),
status: c.status.toLowerCase(),
updatedAt: c.updatedAt.toISOString(),
}));
}
/**
* Subscribes a SSE client to status changes for the given claim IDs.
* Returns an unsubscribe function to call when the client disconnects.
*
* Implementation: lightweight in-process pub/sub via a Map of listeners.
* In a multi-instance deployment, replace with a Redis pub/sub channel.
*/
subscribeToStatusChanges(
claimIds: string[],
send: (data: object) => void,
): () => void {
const idSet = new Set(claimIds);
const listener = (update: { claimId: string; status: string; updatedAt: string }) => {
if (idSet.has(update.claimId)) {
send(update);
}
};
ClaimsService.statusListeners.add(listener);
return () => ClaimsService.statusListeners.delete(listener);
}
/**
* Publishes a status-change event to all active SSE subscribers.
* Call this from the indexer or queue consumer whenever a claim status changes.
*/
static publishStatusChange(update: {
claimId: string;
status: string;
updatedAt: string;
}): void {
for (const listener of ClaimsService.statusListeners) {
try {
listener(update);
} catch {
// Ignore errors from individual listeners (e.g. closed connections).
}
}
}
// In-process listener registry. Replace with Redis pub/sub for multi-instance.
private static readonly statusListeners = new Set<
(update: { claimId: string; status: string; updatedAt: string }) => void
>();
}