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
314 lines (275 loc) · 9.32 KB
/
Copy pathclaims.service.ts
File metadata and controls
314 lines (275 loc) · 9.32 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
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Prisma } from '@prisma/client';
import { SorobanService } from '../rpc/soroban.service';
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;
constructor(
private readonly prisma: PrismaService,
private readonly redis: RedisService,
private readonly sanitization: SanitizationService,
private readonly config: ConfigService,
private readonly soroban: SorobanService,
) {
this.cacheTtl = this.config.get<number>('CACHE_TTL_SECONDS', 60);
this.ipfsGateway = this.config.get<string>('IPFS_GATEWAY', 'https://ipfs.io');
}
async listClaims(params: ListClaimsParams): Promise<ClaimsListResponseDto> {
const { after, status } = params;
const limit = clampLimit(params.limit);
const cacheKey = `claims:list:${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 = {
...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: 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 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 = {
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 cacheKey = `claims:detail:${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 },
},
},
});
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 indexerState = await this.prisma.indexerState.findFirst({
orderBy: { lastLedger: 'desc' },
});
return indexerState?.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;
}
}