-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathintents.ts
More file actions
403 lines (351 loc) · 12.6 KB
/
Copy pathintents.ts
File metadata and controls
403 lines (351 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
import { Intent, IntentStatus, User, UserRole } from '@auto-drive/models'
import { intentsRepository } from '../../infrastructure/repositories/users/intents.js'
import { EventRouter } from '../../infrastructure/eventRouter/index.js'
import { MAX_RETRIES } from '../../infrastructure/eventRouter/tasks.js'
import {
ConflictError,
ForbiddenError,
GoneError,
ObjectNotFoundError,
} from '../../errors/index.js'
import { err, ok } from 'neverthrow'
import { config } from '../../config.js'
import { randomBytes } from 'crypto'
import { createLogger } from '../../infrastructure/drivers/logger.js'
import { AccountsUseCases } from './accounts.js'
import { transactionByteFee } from '@autonomys/auto-consensus'
import { ApiPromise, WsProvider } from '@polkadot/api'
const logger = createLogger('IntentsUseCases')
// Singleton API instance for price queries to prevent memory leaks
// Each ApiPromise creates WebSocket connections and WASM modules that are never garbage collected
let priceApiPromise: Promise<ApiPromise> | null = null
const getPriceApi = async (): Promise<ApiPromise> => {
if (!priceApiPromise) {
logger.debug('Creating singleton Polkadot API for price queries')
const provider = new WsProvider(config.chain.endpoint)
priceApiPromise = ApiPromise.create({ provider })
// Handle disconnection - reset the singleton so it reconnects on next call
priceApiPromise
.then((api) => {
api.on('disconnected', () => {
logger.warn('Price API disconnected, will reconnect on next query')
priceApiPromise = null
})
api.on('error', (error) => {
logger.error(error, 'Price API error, resetting connection')
priceApiPromise = null
})
})
.catch((error) => {
// Reset on initial connection failure to allow recovery on next call
logger.error(error, 'Price API failed to connect, resetting for retry')
priceApiPromise = null
})
}
return priceApiPromise
}
const randomBytes32 = () => {
return '0x' + randomBytes(32).toString('hex')
}
// Returns true if the intent has passed its price-lock window.
// Only PENDING intents can expire — once an intent is CONFIRMED or COMPLETED
// the expiry window is irrelevant.
// Intents with a txHash are actively being watched on-chain and must not be
// treated as expired — their resolution comes from markIntentAsConfirmed.
// Intents without an expiresAt (pre-feature rows) are considered expired.
const isIntentExpired = (intent: Intent): boolean => {
if (intent.status === IntentStatus.EXPIRED) return true
if (intent.status !== IntentStatus.PENDING) return false
if (intent.txHash) return false
if (!intent.expiresAt) return true
return intent.expiresAt < new Date()
}
const createIntent = async (executor: User): Promise<Intent> => {
const { price } = await IntentsUseCases.getPrice()
const expiresAt = new Date(
Date.now() + config.credits.intentExpiryMinutes * 60 * 1000,
)
const intent = await intentsRepository.createIntent({
id: randomBytes32(),
userPublicId: executor.publicId,
status: IntentStatus.PENDING,
paymentAmount: undefined,
shannonsPerByte: BigInt(price),
expiresAt,
})
return intent
}
const getIntent = async (user: User, id: string) => {
const intent = await intentsRepository.getById(id)
if (!intent) {
return err(new ObjectNotFoundError('Intent not found'))
}
if (user.publicId !== intent.userPublicId) {
return err(new ForbiddenError('Intent not found'))
}
if (isIntentExpired(intent)) {
return err(new GoneError('Intent has expired'))
}
return ok(intent)
}
const updateIntent = async (intent: Intent) => {
return intentsRepository.updateIntent(intent)
}
const triggerWatchIntent = async ({
executor,
txHash,
intentId,
}: {
executor: User
txHash: string
intentId: string
}) => {
const result = await getIntent(executor, intentId)
if (result.isErr()) {
return err(result.error)
}
const intent = result.value
if (intent?.userPublicId !== executor.publicId) {
return err(new ForbiddenError('Intent not found'))
}
EventRouter.publish({
id: 'watch-intent-tx',
retriesLeft: MAX_RETRIES,
params: {
txHash,
},
})
await intentsRepository.updateIntent({
...intent,
txHash,
})
return ok()
}
const markIntentAsConfirmed = async ({
intentId,
paymentAmount,
fromAddress,
}: {
intentId: string
paymentAmount: bigint
fromAddress?: string
}) => {
const intent = await intentsRepository.getById(intentId)
if (!intent) {
return err(new ObjectNotFoundError('Intent not found'))
}
// Idempotency guard — do not overwrite an intent that is already in a
// post-PENDING state. Duplicate calls arise from:
// • chain reorgs causing the same event to be re-emitted
// • the payment manager reconnecting and re-processing already-seen logs
// • watchTransaction and the _checkConfirmedIntents polling loop racing
//
// We return ok() rather than an error so the caller does not treat a
// duplicate as a failure and does not retry indefinitely.
if (
intent.status === IntentStatus.CONFIRMED ||
intent.status === IntentStatus.COMPLETED ||
intent.status === IntentStatus.OVER_CAP ||
intent.status === IntentStatus.FAILED ||
intent.status === IntentStatus.EXPIRED
) {
logger.info('markIntentAsConfirmed: intent already processed — skipping', {
intentId,
currentStatus: intent.status,
})
return ok(intent)
}
return ok(
await intentsRepository.updateIntent({
...intent,
status: IntentStatus.CONFIRMED,
paymentAmount,
fromAddress: fromAddress ?? intent.fromAddress,
}),
)
}
const getIntentCredits = (intent: Intent): bigint => {
if (!intent.paymentAmount) {
return BigInt(0)
}
return BigInt(intent.paymentAmount) / BigInt(intent.shannonsPerByte)
}
const onConfirmedIntent = async (intentId: string) => {
const intent = await intentsRepository.getById(intentId)
if (!intent) {
return err(new ObjectNotFoundError('Intent not found'))
}
if (intent.status === IntentStatus.COMPLETED) {
return err(new Error('Intent should be not completed'))
}
if (!intent.paymentAmount) {
logger.warn('Intent has no deposit amount', {
intentId,
})
return err(new Error('Intent has no deposit amount'))
}
// Guard: reject payments whose value is too small to purchase even a single
// byte of storage. getIntentCredits divides paymentAmount by shannonsPerByte
// using BigInt integer division, so a dust payment (paymentAmount <
// shannonsPerByte) yields 0 credits. Granting 0 credits would mark the
// intent COMPLETED while giving the user nothing — a misleading outcome that
// wastes a DB row and silently discards the payment.
//
// Both paymentAmount and shannonsPerByte are immutable on a confirmed intent,
// so this condition is permanent. We mark the intent FAILED (terminal) so
// the polling loop stops retrying. The on-chain payment is irreversible;
// resolution requires admin review (similar to OVER_CAP handling).
const creditBytes = IntentsUseCases.getIntentCredits(intent)
if (creditBytes === BigInt(0)) {
logger.warn(
'onConfirmedIntent: payment too small to yield any credits — marking FAILED',
{
intentId,
paymentAmount: intent.paymentAmount.toString(),
shannonsPerByte: intent.shannonsPerByte.toString(),
},
)
await intentsRepository.updateIntent({
...intent,
status: IntentStatus.FAILED,
})
return ok()
}
const addResult = await AccountsUseCases.addCreditsToAccount(
intent.userPublicId,
creditBytes,
intentId,
)
if (addResult.isErr()) {
if (addResult.error instanceof ForbiddenError) {
// The user's purchased credit balance is at or above the per-user cap.
// Mark the intent OVER_CAP (terminal) so the polling loop stops retrying
// and an admin can review. The payment is on-chain; resolution requires
// a manual decision (adjust cap + reprocess, or arrange a refund).
logger.warn('Intent blocked by per-user cap — marking OVER_CAP', {
intentId,
userPublicId: intent.userPublicId,
paymentAmount: intent.paymentAmount.toString(),
})
await intentsRepository.updateIntent({
...intent,
status: IntentStatus.OVER_CAP,
})
return ok()
}
return err(addResult.error)
}
await intentsRepository.updateIntent({
...intent,
status: IntentStatus.COMPLETED,
})
return ok()
}
const getConfirmedIntents = async () => {
return intentsRepository.getByStatus(IntentStatus.CONFIRMED)
}
// Returns all intents stuck in OVER_CAP for admin review.
// Only accessible to admin users — returns ForbiddenError for everyone else.
const getOverCapIntents = async (executor: User) => {
if (executor.role !== UserRole.Admin) {
return err(new ForbiddenError('Admin access required'))
}
const intents = await intentsRepository.getOverCapIntents()
return ok(intents)
}
// Resets an OVER_CAP intent back to CONFIRMED so the payment manager polling
// loop will attempt to grant credits on its next tick.
//
// Intended admin workflow:
// 1. Admin calls POST /accounts/update to raise the user's credit cap.
// 2. Admin calls POST /intents/:id/reprocess to re-queue this intent.
// 3. The polling loop picks it up within 30 seconds and calls onConfirmedIntent.
//
// Returns ConflictError if the intent is not in OVER_CAP status — this guards
// against accidentally re-queuing an already COMPLETED or PENDING intent.
const reprocessOverCapIntent = async (executor: User, intentId: string) => {
if (executor.role !== UserRole.Admin) {
return err(new ForbiddenError('Admin access required'))
}
const intent = await intentsRepository.getById(intentId)
if (!intent) {
return err(new ObjectNotFoundError('Intent not found'))
}
if (intent.status !== IntentStatus.OVER_CAP) {
return err(
new ConflictError(
`Intent is not in OVER_CAP status (current: ${intent.status})`,
),
)
}
await intentsRepository.updateIntent({
...intent,
status: IntentStatus.CONFIRMED,
})
logger.info('Admin requeued OVER_CAP intent for reprocessing', {
intentId,
adminPublicId: executor.publicId,
})
return ok()
}
// Marks all PENDING intents whose price-lock window has expired.
// Called periodically by the background job so that stale PENDING rows do not
// accumulate. CONFIRMED intents are not touched — once payment is confirmed
// the intent must be processed regardless of the original expiry window.
//
// Uses expireIntentIfPending (atomic conditional UPDATE with
// WHERE status = 'pending') instead of a read-then-write to avoid a TOCTOU
// race: if markIntentAsConfirmed promotes the intent to CONFIRMED between our
// SELECT and UPDATE, the conditional UPDATE simply no-ops instead of
// overwriting the CONFIRMED status and paymentAmount with stale data.
const cleanupExpiredIntents = async (): Promise<void> => {
const expired = await intentsRepository.getExpiredPendingIntents()
if (expired.length === 0) return
logger.info('Marking expired intents', { count: expired.length })
const results = await Promise.all(
expired.map((intent) =>
intentsRepository.expireIntentIfPending(intent.id),
),
)
const actuallyExpired = results.filter(Boolean).length
if (actuallyExpired < expired.length) {
logger.info(
'Some intents were not expired (status changed concurrently)',
{ attempted: expired.length, expired: actuallyExpired },
)
}
}
const BYTES_PER_GB = 1024 * 1024 * 1024
const SHANNONS_PER_AI3 = 1e18
const getPrice = async (): Promise<{ price: number; pricePerGB: number }> => {
const api = await getPriceApi()
const { current: currentPricePerByte } = await transactionByteFee(api)
const price = Math.floor(
currentPricePerByte * config.paymentManager.priceMultiplier,
)
return {
price,
pricePerGB: Math.round((price * BYTES_PER_GB) / SHANNONS_PER_AI3 * 100) / 100,
}
}
// Returns PENDING intents that already have a tx_hash — used by the payment
// manager startup sweep to re-watch transactions that were submitted but never
// confirmed due to a service restart or RPC outage.
const getPendingWithTxHash = async (): Promise<Intent[]> => {
return intentsRepository.getPendingWithTxHash()
}
export const IntentsUseCases = {
createIntent,
getIntent,
updateIntent,
triggerWatchIntent,
onConfirmedIntent,
markIntentAsConfirmed,
getConfirmedIntents,
getOverCapIntents,
getPendingWithTxHash,
reprocessOverCapIntent,
getIntentCredits,
getPrice,
cleanupExpiredIntents,
}