forked from Goldii-locks/escrow-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjobs.ts
More file actions
404 lines (374 loc) · 13.4 KB
/
Copy pathjobs.ts
File metadata and controls
404 lines (374 loc) · 13.4 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 { z } from "zod";
import { StrKey } from "@stellar/stellar-sdk";
import { isValidStellarContractId, isValidStellarAddress } from "../utils/stellar.js";
// ---------------------------------------------------------------------------
// Reusable field schemas
// ---------------------------------------------------------------------------
/**
* Validates a Soroban contract address: starts with 'C', 56 characters total,
* and passes the Stellar SDK StrKey check.
*/
export const contractIdSchema = z.unknown().superRefine((value, ctx) => {
if (value === undefined || value === null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "contractId is required",
});
return;
}
if (typeof value !== "string") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "contractId must be a valid Stellar contract address (C...)",
});
return;
}
if (!isValidStellarContractId(value)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "contractId must be a valid Stellar contract address (C...)",
});
}
});
/**
* Validates a Stellar account (G…) address: starts with 'G', 56 characters,
* passes StrKey.isValidEd25519PublicKey.
*/
export const stellarAddressSchema = z
.string({ required_error: "address is required" })
.refine((v) => StrKey.isValidEd25519PublicKey(v), {
message: "address must be a valid Stellar account address (G…, 56 chars)",
});
/**
* Milestone index: non-negative integer (supplied as a URL param string or number).
* Validated against the raw value before transforming, since parseInt() would
* otherwise silently truncate decimal strings like "1.5" down to 1.
*/
export const milestoneIndexSchema = z
.union([z.string(), z.number()])
.refine(
(v) => (typeof v === "number" ? Number.isInteger(v) && v >= 0 : /^\d+$/.test(v)),
{ message: "index must be a non-negative integer" },
)
.transform((v) => (typeof v === "number" ? v : parseInt(v, 10)));
/**
* Amount: a positive numeric string or integer that can be coerced to BigInt.
* Accepts strings like "100", "100000000", or plain numbers.
*/
export const amountSchema = z
.union([z.string(), z.number(), z.bigint()])
.refine(
(v) => {
try {
const n = BigInt(v as string | number | bigint);
return n > 0n;
} catch {
return false;
}
},
{ message: "amount must be a positive numeric value" },
);
/**
* Named Stellar account field (G…) with field-specific error messages.
*/
const stellarAccountField = (field: string) =>
z
.string({ required_error: `${field} is required` })
.refine(isValidStellarAddress, {
message: `${field} must be a valid Stellar account address (G...)`,
});
// ---------------------------------------------------------------------------
// Composed route schemas
// ---------------------------------------------------------------------------
/** Route params: /:contractId */
export const contractIdParamsSchema = z.object({
contractId: contractIdSchema,
});
/** Route params: /:contractId/whitelist */
export const whitelistParamsSchema = z.object({
contractId: contractIdSchema,
});
/** Route params: /:contractId/milestones/:index */
export const contractMilestoneParamsSchema = z.object({
contractId: contractIdSchema,
index: milestoneIndexSchema,
});
/** POST /build-tx body schema validation */
export const buildTxBodySchema = z.object({
// Must be a valid Soroban contract ID
contractId: contractIdSchema,
// The contract method name to call
method: z.string({ required_error: "method is required" }).min(1, "method cannot be empty"),
// Optional arguments for the method, defaults to an empty array
args: z.array(z.any()).optional().default([]),
// The Stellar address of the transaction source account
sourceAddress: stellarAccountField("sourceAddress"),
});
/** POST /submit body */
export const submitBodySchema = z.object({
signedXdr: z
.string({ required_error: "signedXdr is required", invalid_type_error: "signedXdr must be a string" })
.min(1, "signedXdr cannot be empty")
.refine((v) => !/\s/.test(v), {
message: "signedXdr must not contain whitespace",
})
.refine(
(v) => {
// Valid base64: only A-Z a-z 0-9 + / = characters, length divisible by 4
return /^[A-Za-z0-9+/]*={0,2}$/.test(v) && v.length % 4 === 0;
},
{ message: "signedXdr must be a valid base64-encoded XDR string" },
),
sourceAddress: stellarAccountField("sourceAddress").optional(),
});
/**
* POST /:contractId/milestones/:index/partial-release body.
* Keeps its pre-existing field-specific error wording (rather than the
* generic amountSchema/stellarAddressSchema messages) since __tests__/
* partial-release.test.ts asserts on these exact strings.
*/
export const partialReleaseBodySchema = z.object({
amount: z
.union([z.string(), z.number()])
.refine(
(val) => {
try {
return BigInt(String(val)) > 0n;
} catch {
return false;
}
},
{ message: "amount must be a positive integer" },
),
sourceAddress: z
.string({ required_error: "sourceAddress is required" })
.refine(isValidStellarAddress, {
message: "sourceAddress must be a valid Stellar account address (G...)",
}),
});
/** POST /:contractId/milestones/:index/claim-auto-release body */
export const claimAutoReleaseBodySchema = z.object({
sourceAddress: stellarAccountField("sourceAddress"),
}).strict();
/** Route params: /by-wallet/:address */
export const byWalletParamsSchema = z.object({
address: stellarAddressSchema,
});
/** Query params: ?page=&limit= for GET /by-wallet/:address */
export const byWalletQuerySchema = z.object({
page: z
.union([z.string(), z.number()])
.optional()
.default("1")
.refine(
(v) =>
typeof v === "number"
? Number.isInteger(v) && v >= 1
: /^\d+$/.test(v) && parseInt(v, 10) >= 1,
{ message: "page must be a positive integer" },
)
.transform((v) => (typeof v === "number" ? v : parseInt(v, 10))),
limit: z
.union([z.string(), z.number()])
.optional()
.default("10")
.refine(
(v) =>
typeof v === "number"
? Number.isInteger(v) && v >= 1 && v <= 100
: /^\d+$/.test(v) &&
parseInt(v, 10) >= 1 &&
parseInt(v, 10) <= 100,
{ message: "limit must be between 1 and 100" },
)
.transform((v) => (typeof v === "number" ? v : parseInt(v, 10))),
});
/**
* POST /create-job-draft body.
* Validates payload shape/types and Stellar address formats for all party/token fields.
*/
export const createJobDraftBodySchema = z.object({
client: stellarAccountField("client").optional(),
freelancer: stellarAccountField("freelancer"),
arbiter: stellarAccountField("arbiter"),
token: z
.string({ required_error: "token is required" })
.refine(isValidStellarContractId, {
message: "token must be a valid Stellar contract address (C...)",
}),
autoReleaseDays: z
.any({ required_error: "autoReleaseDays is required" })
.refine((v) => typeof v === "string" || typeof v === "number", {
message: "autoReleaseDays must be a number",
})
.refine(
(v) => {
const n = typeof v === "number" ? v : Number(v);
return Number.isInteger(n) && n >= 1 && n <= 365;
},
{ message: "autoReleaseDays must be an integer between 1 and 365" },
)
.transform((v) => (typeof v === "number" ? v : parseInt(String(v), 10))),
milestones: z
.array(
z.object({
amount: z
.union([z.string(), z.number()], {
invalid_type_error: "amount must be a positive integer",
})
.refine(
(val) => {
try {
return BigInt(String(val)) > 0n;
} catch {
return false;
}
},
{ message: "amount must be a positive integer" },
),
}),
{ required_error: "milestones is required", invalid_type_error: "milestones must be an array" },
)
.min(1, "milestones must contain at least one milestone"),
acceptedAssets: z.array(z.string()).optional().default([]),
requirements: z.array(z.string()).optional().default([]),
});
/**
* POST /create-job-draft body — `*Address` naming variant.
*
* Two PRs shipped this endpoint with different field names, response shapes,
* and token-validation strictness, and both were merged. This variant keeps a
* permissive `.min(1)` token rule (its own tests post a token that is not a
* valid 56-char contract id); the variant above enforces a real C… address.
* `createJobDraftRouteValidator` in routes/jobs.ts picks between them by shape.
*/
export const createJobDraftLegacyBodySchema = z.object({
clientAddress: stellarAddressSchema,
freelancerAddress: stellarAddressSchema,
arbiterAddress: stellarAddressSchema,
tokenAddress: z
.string({ required_error: "tokenAddress is required" })
.min(1, "tokenAddress cannot be empty"),
milestones: z
.array(
z.object({
amount: amountSchema,
}),
{ required_error: "milestones is required" },
)
.min(1, "milestones must contain at least one entry"),
});
/**
* POST /:contractId/whitelist/update body.
* Validates the token address and the action (add/remove).
*/
export const whitelistUpdateBodySchema = z.object({
token: z
.string({
required_error: "token is required",
invalid_type_error: "token must be a string",
})
.min(1, "token cannot be empty")
.refine(isValidStellarContractId, {
message: "token must be a valid Stellar contract address (C...)",
}),
action: z
.enum(["add", "remove"], {
required_error: "action is required",
invalid_type_error: "action must be one of: add, remove",
}),
adminAddress: stellarAccountField("adminAddress"),
}).strict();
export type WhitelistUpdateBody = z.infer<typeof whitelistUpdateBodySchema>;
export type CreateJobDraftLegacyBody = z.infer<typeof createJobDraftLegacyBodySchema>;
/**
* Validates a Stellar address that can be either a public key account address (G...)
* or a Soroban contract address (C...).
*/
export const stellarAddressOrContractSchema = z
.string({ required_error: "Address is required" })
.refine((v) => isValidStellarAddress(v) || isValidStellarContractId(v), {
message: "Invalid Stellar address",
});
/**
* POST /:contractId/whitelist/update body schema.
* Accepts `addresses` (or `tokens` fallback) array containing valid Stellar addresses.
*/
export const updateWhitelistBodySchema = z
.object({
addresses: z
.array(stellarAddressOrContractSchema, {
required_error: "addresses array is required",
invalid_type_error: "addresses must be an array",
})
.optional(),
tokens: z
.array(stellarAddressOrContractSchema, {
invalid_type_error: "tokens must be an array",
})
.optional(),
})
.superRefine((data, ctx) => {
const addresses = data.addresses ?? data.tokens;
if (!addresses) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "addresses array is required",
path: ["addresses"],
});
return;
}
if (addresses.length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "addresses array cannot be empty",
path: ["addresses"],
});
}
});
export type UpdateWhitelistBody = z.infer<typeof updateWhitelistBodySchema>;
/**
* POST /:contractId/whitelist/update accepts two historical body shapes:
*
* - the single-token form `{ token, action, adminAddress }`
* (`whitelistUpdateBodySchema`), and
* - the bulk form `{ addresses | tokens }` (`updateWhitelistBodySchema`).
*
* A plain `z.union` would collapse both branches into one `invalid_union`
* issue with an empty path, and the route's error responses are asserted
* field-by-field. So dispatch on the shape instead and forward the chosen
* branch's issues verbatim, which keeps `details[].field` populated.
*
* An ambiguous body (neither `addresses` nor `tokens` present) is reported
* against the single-token form, so an empty `{}` lists token/action/
* adminAddress as missing.
*/
export const whitelistUpdateRequestSchema = z
.object({})
.passthrough()
.superRefine((data, ctx) => {
const body = (data ?? {}) as Record<string, unknown>;
const isBulkForm = "addresses" in body || "tokens" in body;
const branch = isBulkForm
? updateWhitelistBodySchema
: whitelistUpdateBodySchema;
const result = branch.safeParse(body);
if (!result.success) {
for (const issue of result.error.issues) {
ctx.addIssue(issue);
}
}
});
export type WhitelistUpdateRequestBody =
| WhitelistUpdateBody
| UpdateWhitelistBody;
export type ContractIdParams = z.infer<typeof contractIdParamsSchema>;
export type ContractMilestoneParams = z.infer<typeof contractMilestoneParamsSchema>;
export type WhitelistParams = z.infer<typeof whitelistParamsSchema>;
export type BuildTxBody = z.infer<typeof buildTxBodySchema>;
export type SubmitBody = z.infer<typeof submitBodySchema>;
export type PartialReleaseBody = z.infer<typeof partialReleaseBodySchema>;
export type ClaimAutoReleaseBody = z.infer<typeof claimAutoReleaseBodySchema>;
export type ByWalletParams = z.infer<typeof byWalletParamsSchema>;
export type ByWalletQuery = z.infer<typeof byWalletQuerySchema>;
export type CreateJobDraftBody = z.infer<typeof createJobDraftBodySchema>;