-
Notifications
You must be signed in to change notification settings - Fork 664
Expand file tree
/
Copy pathbuilder.ts
More file actions
357 lines (303 loc) · 10.1 KB
/
builder.ts
File metadata and controls
357 lines (303 loc) · 10.1 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
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { parseAbiItem } from "abitype";
import open from "open";
import ora, { type Ora } from "ora";
import prompts from "prompts";
import { parse } from "toml";
import { createThirdwebClient } from "../../../client/client.js";
import { upload } from "../../../storage/upload.js";
import { checkPrerequisites } from "./check-prerequisites.js";
const THIRDWEB_URL = "https://thirdweb.com";
export async function publishStylus(secretKey?: string) {
const spinner = ora("Checking if this is a Stylus project...").start();
checkPrerequisites(spinner, "cargo", ["--version"], "Rust (cargo)");
checkPrerequisites(spinner, "rustc", ["--version"], "Rust compiler (rustc)");
const uri = await buildStylus(spinner, secretKey);
const url = getUrl(uri, "publish").toString();
spinner.succeed(`Upload complete, navigate to ${url}`);
await open(url);
}
export async function deployStylus(secretKey?: string) {
const spinner = ora("Checking if this is a Stylus project...").start();
checkPrerequisites(spinner, "cargo", ["--version"], "Rust (cargo)");
checkPrerequisites(spinner, "rustc", ["--version"], "Rust compiler (rustc)");
const uri = await buildStylus(spinner, secretKey);
const url = getUrl(uri, "deploy").toString();
spinner.succeed(`Upload complete, navigate to ${url}`);
await open(url);
}
async function buildStylus(spinner: Ora, secretKey?: string) {
if (!secretKey) {
spinner.fail(
"Error: Secret key is required. Please pass it via the -k parameter.",
);
process.exit(1);
}
try {
// Step 1: Validate stylus project
const root = process.cwd();
if (!root) {
spinner.fail("Error: No package directory found.");
process.exit(1);
}
const cargoTomlPath = join(root, "Cargo.toml");
if (!existsSync(cargoTomlPath)) {
spinner.fail("Error: No Cargo.toml found. Not a Stylus/Rust project.");
process.exit(1);
}
const cargoToml = readFileSync(cargoTomlPath, "utf8");
const parsedCargoToml = parse(cargoToml);
if (!parsedCargoToml.dependencies?.["stylus-sdk"]) {
spinner.fail(
"Error: Not a Stylus project. Missing stylus-sdk dependency.",
);
process.exit(1);
}
spinner.succeed("Stylus project detected.");
// Step 2: Run stylus command to generate initcode
spinner.start("Generating initcode...");
const initcodeResult = spawnSync("cargo", ["stylus", "get-initcode"], {
encoding: "utf-8",
});
if (initcodeResult.status !== 0) {
spinner.fail("Failed to generate initcode.");
process.exit(1);
}
const initcode = extractBytecode(initcodeResult.stdout);
if (!initcode) {
spinner.fail("Failed to generate initcode.");
process.exit(1);
}
spinner.succeed("Initcode generated.");
// Step 3: Run stylus command to generate abi (plain Solidity, no solc needed)
spinner.start("Generating ABI...");
const abiResult = spawnSync("cargo", ["stylus", "export-abi"], {
encoding: "utf-8",
});
if (abiResult.status !== 0) {
spinner.fail("Failed to generate ABI.");
process.exit(1);
}
const solidityOutput = abiResult.stdout.trim();
if (!solidityOutput) {
spinner.fail("Failed to generate ABI.");
process.exit(1);
}
const interfaces = parseSolidityInterfaces(solidityOutput);
if (interfaces.length === 0) {
spinner.fail("No interfaces found in ABI output.");
process.exit(1);
}
spinner.succeed("ABI generated.");
// Step 3.5: detect the constructor
spinner.start("Detecting constructor\u2026");
const constructorResult = spawnSync("cargo", ["stylus", "constructor"], {
encoding: "utf-8",
});
if (constructorResult.status !== 0) {
spinner.fail("Failed to get constructor signature.");
process.exit(1);
}
const constructorSigRaw = constructorResult.stdout.trim();
spinner.succeed(`Constructor found: ${constructorSigRaw || "none"}`);
// Step 4: Process the output
let selectedIndex = 0;
if (interfaces.length > 1) {
const response = await prompts({
choices: interfaces.map((iface, idx) => ({
title: iface.name,
value: idx,
})),
message: "Select entrypoint:",
name: "contract",
type: "select",
});
if (typeof response.contract !== "number") {
spinner.fail("No contract selected.");
process.exit(1);
}
selectedIndex = response.contract;
}
const selectedInterface = interfaces[selectedIndex];
if (!selectedInterface) {
spinner.fail("No interface found.");
process.exit(1);
}
const selectedContractName = selectedInterface.name.replace(/^I/, "");
// biome-ignore lint/suspicious/noExplicitAny: ABI is untyped JSON from parseAbiItem
const abiArray: any[] = selectedInterface.abi;
const constructorAbi = constructorSigToAbi(constructorSigRaw);
if (
constructorAbi &&
// biome-ignore lint/suspicious/noExplicitAny: ABI entries have varying shapes
!abiArray.some((e: any) => e.type === "constructor")
) {
abiArray.unshift(constructorAbi);
}
const metadata = {
compiler: {},
language: "rust",
output: {
abi: abiArray,
devdoc: {},
userdoc: {},
},
settings: {
compilationTarget: {
"src/main.rs": selectedContractName,
},
},
sources: {},
};
spinner.succeed("Stylus contract exported successfully.");
// Step 5: Upload to IPFS
spinner.start("Uploading to IPFS...");
const client = createThirdwebClient({
secretKey,
});
const metadataUri = await upload({
client,
files: [metadata],
});
const bytecodeUri = await upload({
client,
files: [initcode],
});
const uri = await upload({
client,
files: [
{
analytics: {
cli_version: "",
command: "publish-stylus",
contract_name: selectedContractName,
project_type: "stylus",
},
bytecodeUri,
compilers: {
stylus: [
{ bytecodeUri, compilerVersion: "", evmVersion: "", metadataUri },
],
},
metadataUri,
name: selectedContractName,
},
],
});
spinner.succeed("Upload complete");
return uri;
} catch (error) {
spinner.fail(`Error: ${error}`);
process.exit(1);
}
}
// biome-ignore lint/suspicious/noExplicitAny: ABI items from parseAbiItem are untyped
type AbiEntry = any;
type ParsedInterface = { name: string; abi: AbiEntry[] };
function parseSolidityInterfaces(source: string): ParsedInterface[] {
const results: ParsedInterface[] = [];
const ifaceRegex = /interface\s+(I?[A-Za-z0-9_]+)\s*\{([\s\S]*?)\n\}/g;
for (
let ifaceMatch = ifaceRegex.exec(source);
ifaceMatch !== null;
ifaceMatch = ifaceRegex.exec(source)
) {
const name = ifaceMatch[1] ?? "";
const body = ifaceMatch[2] ?? "";
const abi: AbiEntry[] = [];
// Build struct lookup: name -> tuple type string
const structs = new Map<string, string>();
const structRegex = /struct\s+(\w+)\s*\{([^}]*)\}/g;
for (
let structMatch = structRegex.exec(body);
structMatch !== null;
structMatch = structRegex.exec(body)
) {
const fields = (structMatch[2] ?? "")
.split(";")
.map((f) => f.trim())
.filter(Boolean)
.map((f) => f.split(/\s+/)[0] ?? "");
structs.set(structMatch[1] ?? "", `(${fields.join(",")})`);
}
// Resolve struct references in a type string (iterative for nested structs)
const resolveStructs = (sig: string): string => {
let resolved = sig;
for (let i = 0; i < 10; i++) {
let changed = false;
for (const [sName, sTuple] of structs) {
const re = new RegExp(`\\b${sName}\\b(\\[\\])?`, "g");
const next = resolved.replace(
re,
(_, arr) => `${sTuple}${arr ?? ""}`,
);
if (next !== resolved) {
resolved = next;
changed = true;
}
}
if (!changed) break;
}
return resolved;
};
// Extract each statement (function/error/event) delimited by ;
const statements = body
.split(";")
.map((s) => s.replace(/\n/g, " ").trim())
.filter(
(s) =>
s.startsWith("function ") ||
s.startsWith("error ") ||
s.startsWith("event "),
);
for (const stmt of statements) {
// Strip Solidity qualifiers that abitype doesn't expect
let cleaned = stmt
.replace(/\b(external|public|internal|private)\b/g, "")
.replace(/\b(memory|calldata|storage)\b/g, "")
.replace(/\s+/g, " ")
.trim();
// Resolve struct type names to tuple types
cleaned = resolveStructs(cleaned);
try {
const parsed = parseAbiItem(cleaned);
abi.push(parsed);
} catch {
// Skip unparseable items
}
}
results.push({ abi, name });
}
return results;
}
function getUrl(hash: string, command: string) {
const url = new URL(
`${THIRDWEB_URL}/contracts/${command}/${encodeURIComponent(hash.replace("ipfs://", ""))}`,
);
return url;
}
function extractBytecode(rawOutput: string): string {
const hexStart = rawOutput.indexOf("7f000000");
if (hexStart === -1) {
throw new Error("Could not find start of bytecode");
}
return rawOutput.slice(hexStart).trim();
}
function constructorSigToAbi(sig: string) {
if (!sig || !sig.startsWith("constructor")) return undefined;
const sigClean = sig
.replace(/^constructor\s*\(?/, "")
.replace(/\)\s*$/, "")
.replace(/\s+(payable|nonpayable)\s*$/, "");
const mutability = sig.includes("payable") ? "payable" : "nonpayable";
const inputs =
sigClean === ""
? []
: sigClean.split(",").map((p) => {
const [type, name = ""] = p.trim().split(/\s+/);
return { internalType: type, name, type };
});
return { inputs, stateMutability: mutability, type: "constructor" };
}