-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBlueprintController.ts
More file actions
394 lines (370 loc) · 10.9 KB
/
Copy pathBlueprintController.ts
File metadata and controls
394 lines (370 loc) · 10.9 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
import {
Body,
Controller,
Delete,
Path,
Post,
Response,
Route,
SuccessResponse,
Tags,
} from "tsoa";
import { isAddress } from "viem";
import { z } from "zod";
import { EvmClientFactory } from "../client/evmClient.js";
import { SupabaseDataService } from "../services/SupabaseDataService.js";
import type {
BaseResponse,
BlueprintCreateRequest,
BlueprintDeleteRequest,
BlueprintQueueMintRequest,
BlueprintResponse,
} from "../types/api.js";
import { Json } from "../types/supabaseData.js";
import { verifyAuthSignedData } from "../utils/verifyAuthSignedData.js";
import { waitForTxThenMintBlueprint } from "../utils/waitForTxThenMintBlueprint.js";
@Route("v1/blueprints")
@Tags("Blueprints")
export class BlueprintController extends Controller {
@Post()
@SuccessResponse(201, "Blueprint created successfully")
@Response<BlueprintResponse>(422, "Unprocessable content", {
success: false,
message: "Validation failed",
errors: { blueprint: "Invalid blueprint." },
})
public async createBlueprint(
@Body() requestBody: BlueprintCreateRequest,
): Promise<BlueprintResponse> {
const inputSchema = z.object({
form_values: z.object({
title: z
.string()
.trim()
.min(1, "We need a title for your hypercert")
.max(100, "Max 100 characters"),
logo: z.string().url("Logo URL is not valid"),
banner: z.string().url("Banner URL is not valid"),
cardImage: z
.string()
.url("Card image could not be generated")
.optional(),
description: z
.string()
.trim()
.min(10, {
message: "We need a longer description for your hypercert",
})
.max(5000, "max 5000 characters"),
link: z
.string()
.url("Please enter a valid link")
.optional()
.or(z.literal("")),
tags: z
.array(z.string())
.min(1, "We need at least one tag")
.max(20, "Maximum 20 tags allowed")
.refine(
(data) =>
data.every((tag) => tag.trim() !== "" && tag.length <= 50),
{
message:
"Please ensure all tags are filled in and no longer than 50 characters",
},
),
projectDates: z
.object(
{
from: z.date({ coerce: true }).refine((date) => date !== null, {
message: "Please enter a start date",
}),
to: z.date({ coerce: true }).refine((date) => date !== null, {
message: "Please enter an end date",
}),
},
{
required_error: "Please select a date range",
},
)
.refine((data) => data.from && data.to && data.from <= data.to, {
path: ["projectDates"],
message: "From date must be before to date",
}),
contributors: z
.array(z.string())
.refine(
(data) =>
data.filter((contributor) => contributor !== "").length > 0,
{
message: "We need at least one contributor",
},
)
.refine(
(data) => data.every((contributor) => contributor.length <= 50),
{
message: "Each contributor must be 50 characters or less",
},
),
allowlistEntries: z
.array(z.object({ address: z.string(), units: z.string() }))
.optional(),
allowlistURL: z
.string()
.trim()
.refine((input) => input && !input?.endsWith("/"), {
message: "URI cannot end with a trailing slash",
})
.optional()
.or(z.literal("")),
}),
signature: z.string(),
chain_id: z.number(),
admin_address: z
.string()
.refine((value) => isAddress(value), "Invalid admin address"),
minter_address: z
.string()
.refine((value) => isAddress(value), "Invalid minter address"),
});
const parsedBody = inputSchema.safeParse(requestBody);
if (!parsedBody.success) {
this.setStatus(400);
return {
success: false,
message: "Invalid input",
errors: JSON.parse(parsedBody.error.toString()),
};
}
const { signature, chain_id, admin_address, form_values, minter_address } =
parsedBody.data;
const verified = verifyAuthSignedData({
types: { Message: [{ name: "message", type: "string" }] },
primaryType: "Message",
message: {
message: `Create blueprint for ${admin_address}`,
},
address: admin_address,
signature: signature as `0x${string}`,
requiredChainId: chain_id,
});
if (!verified) {
this.setStatus(422);
return {
success: false,
message: "Validation failed",
errors: { signature: "Invalid signature." },
};
}
const dataService = new SupabaseDataService();
let blueprintId: number;
try {
const blueprint = await dataService.upsertBlueprints([
{
form_values: form_values as unknown as Json,
minter_address,
},
]);
blueprintId = blueprint[0].id;
} catch (error) {
this.setStatus(500);
return {
success: false,
message: "Failed to create blueprint",
errors: { blueprint: "Failed to create blueprint" },
};
}
if (!blueprintId) {
this.setStatus(500);
return {
success: false,
message: "Failed to create blueprint",
errors: { blueprint: "Failed to create blueprint" },
};
}
try {
await dataService.addAdminToBlueprint(
blueprintId,
admin_address,
chain_id,
);
} catch (error) {
this.setStatus(500);
return {
success: false,
message: "Failed to add admin to blueprint",
errors: { blueprint: "Failed to add admin to blueprint" },
};
}
this.setStatus(201);
return {
success: true,
data: { blueprint_id: blueprintId },
};
}
// Delete blueprint method
@Delete("{blueprintId}")
@SuccessResponse(200, "Blueprint deleted successfully")
@Response<BaseResponse>(422, "Unprocessable content", {
success: false,
message: "Validation failed",
errors: { blueprint: "Invalid blueprint." },
})
public async deleteBlueprint(
@Path() blueprintId: number,
@Body() requestBody: BlueprintDeleteRequest,
) {
const inputSchema = z.object({
signature: z.string(),
chain_id: z.number(),
admin_address: z
.string()
.refine((value) => isAddress(value), "Invalid admin address"),
});
const parsedBody = inputSchema.safeParse(requestBody);
if (!parsedBody.success) {
this.setStatus(400);
return {
success: false,
message: "Invalid input",
data: null,
errors: JSON.parse(parsedBody.error.toString()),
};
}
const { signature, admin_address, chain_id } = parsedBody.data;
const dataService = new SupabaseDataService();
const blueprint = await dataService.getBlueprintById(blueprintId);
if (!blueprint) {
this.setStatus(404);
return {
success: false,
message: "Blueprint not found",
errors: { blueprint: "Blueprint not found" },
};
}
const isAdmin = blueprint.admins.some(
(admin) => admin.address === admin_address && admin.chain_id === chain_id,
);
if (!isAdmin) {
this.setStatus(403);
return {
success: false,
message: "Unauthorized",
errors: { blueprint: "Unauthorized" },
};
}
const verified = verifyAuthSignedData({
types: {
Blueprint: [{ name: "id", type: "uint256" }],
BlueprintDeleteRequest: [{ name: "blueprint", type: "Blueprint" }],
},
primaryType: "BlueprintDeleteRequest",
message: {
blueprint: { id: blueprintId },
},
address: admin_address,
signature: signature as `0x${string}`,
requiredChainId: chain_id,
});
if (!verified) {
this.setStatus(422);
return {
success: false,
message: "Validation failed",
errors: { signature: "Invalid signature." },
};
}
try {
await dataService.deleteBlueprint(blueprintId);
} catch (error) {
this.setStatus(500);
return {
success: false,
message: "Failed to delete blueprint",
errors: { blueprint: "Failed to delete blueprint" },
};
}
this.setStatus(200);
return {
success: true,
message: "Blueprint deleted successfully",
};
}
@Post("mint/{blueprintId}")
@SuccessResponse(201, "Blueprint minted successfully")
@Response<BaseResponse>(422, "Unprocessable content", {
success: false,
message: "Validation failed",
errors: { blueprint: "Invalid blueprint." },
})
public async mintBlueprint(
@Path() blueprintId: number,
@Body() requestBody: BlueprintQueueMintRequest,
): Promise<BlueprintResponse> {
const inputSchema = z.object({
signature: z.string(),
chain_id: z.number(),
minter_address: z
.string()
.refine((value) => isAddress(value), "Invalid minter address"),
tx_hash: z.string(),
});
const parsedBody = inputSchema.safeParse(requestBody);
if (!parsedBody.success) {
this.setStatus(400);
return {
success: false,
message: "Invalid input",
errors: JSON.parse(parsedBody.error.toString()),
};
}
const { signature, chain_id, minter_address, tx_hash } = parsedBody.data;
const verified = verifyAuthSignedData({
types: {
Blueprint: [
{ name: "id", type: "uint256" },
{
name: "tx_hash",
type: "string",
},
],
BlueprintQueueMintRequest: [{ name: "blueprint", type: "Blueprint" }],
},
primaryType: "BlueprintQueueMintRequest",
message: {
blueprint: { id: blueprintId, tx_hash },
},
address: minter_address,
signature: signature as `0x${string}`,
requiredChainId: chain_id,
});
if (!verified) {
this.setStatus(422);
return {
success: false,
message: "Validation failed",
errors: { signature: "Invalid signature." },
};
}
const client = EvmClientFactory.createViemClient(chain_id);
const transaction = await client.getTransaction({
hash: tx_hash as `0x${string}`,
});
if (!transaction) {
this.setStatus(404);
return {
success: false,
message: "Transaction not found",
errors: { transaction: "Transaction not found" },
};
}
// Do not await
waitForTxThenMintBlueprint(tx_hash, chain_id, blueprintId);
this.setStatus(201);
return {
success: true,
data: { blueprint_id: blueprintId },
message: "Blueprint mint queued",
};
}
}