@secondlayer/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2578 @@
1
+ // src/core/plugin-manager.ts
2
+ import { format } from "prettier";
3
+ import { promises as fs } from "fs";
4
+ import path from "path";
5
+ import { validateStacksAddress } from "@stacks/transactions";
6
+ var PluginManager = class {
7
+ constructor() {
8
+ this.plugins = [];
9
+ this.logger = this.createLogger();
10
+ this.utils = this.createUtils();
11
+ this.executionContext = {
12
+ phase: "config",
13
+ startTime: Date.now(),
14
+ results: /* @__PURE__ */ new Map()
15
+ };
16
+ }
17
+ /**
18
+ * Register a plugin
19
+ */
20
+ register(plugin) {
21
+ if (!plugin.name || !plugin.version) {
22
+ throw new Error("Plugin must have a name and version");
23
+ }
24
+ const existing = this.plugins.find((p) => p.name === plugin.name);
25
+ if (existing) {
26
+ throw new Error(
27
+ `Plugin "${plugin.name}" is already registered (version ${existing.version})`
28
+ );
29
+ }
30
+ this.plugins.push(plugin);
31
+ this.logger.debug(`Registered plugin: ${plugin.name}@${plugin.version}`);
32
+ }
33
+ /**
34
+ * Get all registered plugins
35
+ */
36
+ getPlugins() {
37
+ return [...this.plugins];
38
+ }
39
+ /**
40
+ * Transform user config through all plugins
41
+ */
42
+ async transformConfig(config) {
43
+ this.executionContext.phase = "config";
44
+ let transformedConfig = { ...config };
45
+ for (const plugin of this.plugins) {
46
+ if (plugin.transformConfig) {
47
+ this.executionContext.currentPlugin = plugin;
48
+ try {
49
+ const result = await plugin.transformConfig(transformedConfig);
50
+ transformedConfig = result;
51
+ this.recordHookResult(plugin.name, "transformConfig", {
52
+ success: true
53
+ });
54
+ } catch (error) {
55
+ const err = error;
56
+ this.recordHookResult(plugin.name, "transformConfig", {
57
+ success: false,
58
+ error: err
59
+ });
60
+ throw new Error(
61
+ `Plugin "${plugin.name}" failed during config transformation: ${err.message}`
62
+ );
63
+ }
64
+ }
65
+ }
66
+ const resolvedConfig = {
67
+ ...transformedConfig,
68
+ plugins: this.plugins
69
+ };
70
+ return resolvedConfig;
71
+ }
72
+ /**
73
+ * Transform contracts through all plugins
74
+ */
75
+ async transformContracts(contracts, _config) {
76
+ const processedContracts = [];
77
+ for (let contract of contracts) {
78
+ if (contract._clarinetSource && contract.abi) {
79
+ const address = typeof contract.address === "string" ? contract.address : "";
80
+ const [contractAddress, contractName] = address.split(".");
81
+ const processed = {
82
+ name: contract.name || contractName,
83
+ address: contractAddress,
84
+ contractName,
85
+ abi: contract.abi,
86
+ source: "local",
87
+ metadata: { source: "clarinet" }
88
+ };
89
+ processedContracts.push(processed);
90
+ continue;
91
+ }
92
+ for (const plugin of this.plugins) {
93
+ if (plugin.transformContract) {
94
+ this.executionContext.currentPlugin = plugin;
95
+ try {
96
+ contract = await plugin.transformContract(contract);
97
+ this.recordHookResult(plugin.name, "transformContract", {
98
+ success: true
99
+ });
100
+ } catch (error) {
101
+ const err = error;
102
+ this.recordHookResult(plugin.name, "transformContract", {
103
+ success: false,
104
+ error: err
105
+ });
106
+ this.logger.warn(
107
+ `Plugin "${plugin.name}" failed to transform contract: ${err.message}`
108
+ );
109
+ }
110
+ }
111
+ }
112
+ if (contract.abi) {
113
+ const processed = {
114
+ name: contract.name || "unknown",
115
+ address: typeof contract.address === "string" ? contract.address.split(".")[0] : "unknown",
116
+ contractName: contract.name || "unknown",
117
+ abi: contract.abi,
118
+ source: "api",
119
+ // Use "api" as default for plugin-processed contracts
120
+ metadata: contract.metadata
121
+ };
122
+ processedContracts.push(processed);
123
+ }
124
+ }
125
+ return processedContracts;
126
+ }
127
+ /**
128
+ * Execute lifecycle hooks
129
+ */
130
+ async executeHook(hookName, context) {
131
+ for (const plugin of this.plugins) {
132
+ const hook = plugin[hookName];
133
+ if (typeof hook === "function") {
134
+ this.executionContext.currentPlugin = plugin;
135
+ try {
136
+ await hook.call(plugin, context);
137
+ this.recordHookResult(plugin.name, hookName, {
138
+ success: true
139
+ });
140
+ } catch (error) {
141
+ const err = error;
142
+ this.recordHookResult(plugin.name, hookName, {
143
+ success: false,
144
+ error: err
145
+ });
146
+ this.logger.error(
147
+ `Plugin "${plugin.name}" failed during ${hookName}: ${err.message}`
148
+ );
149
+ }
150
+ }
151
+ }
152
+ }
153
+ /**
154
+ * Execute generation phase with full context
155
+ */
156
+ async executeGeneration(contracts, config) {
157
+ this.executionContext.phase = "generate";
158
+ const outputs = /* @__PURE__ */ new Map();
159
+ const context = {
160
+ config,
161
+ logger: this.logger,
162
+ utils: this.utils,
163
+ contracts,
164
+ outputs,
165
+ augment: (outputKey, contractName, content) => {
166
+ this.augmentOutput(outputs, outputKey, contractName, content);
167
+ },
168
+ addOutput: (key, output) => {
169
+ outputs.set(key, output);
170
+ }
171
+ };
172
+ await this.executeHook("beforeGenerate", context);
173
+ await this.executeHook("generate", context);
174
+ await this.executeHook("afterGenerate", context);
175
+ return outputs;
176
+ }
177
+ /**
178
+ * Transform outputs through plugins
179
+ */
180
+ async transformOutputs(outputs) {
181
+ this.executionContext.phase = "output";
182
+ const transformedOutputs = /* @__PURE__ */ new Map();
183
+ for (const [key, output] of outputs) {
184
+ let transformedContent = output.content;
185
+ for (const plugin of this.plugins) {
186
+ if (plugin.transformOutput) {
187
+ this.executionContext.currentPlugin = plugin;
188
+ try {
189
+ transformedContent = await plugin.transformOutput(
190
+ transformedContent,
191
+ output.type || "other"
192
+ );
193
+ this.recordHookResult(plugin.name, "transformOutput", {
194
+ success: true
195
+ });
196
+ } catch (error) {
197
+ const err = error;
198
+ this.recordHookResult(plugin.name, "transformOutput", {
199
+ success: false,
200
+ error: err
201
+ });
202
+ this.logger.warn(
203
+ `Plugin "${plugin.name}" failed to transform output: ${err.message}`
204
+ );
205
+ }
206
+ }
207
+ }
208
+ transformedOutputs.set(key, {
209
+ ...output,
210
+ content: transformedContent
211
+ });
212
+ }
213
+ return transformedOutputs;
214
+ }
215
+ /**
216
+ * Write outputs to disk
217
+ */
218
+ async writeOutputs(outputs) {
219
+ for (const [, output] of outputs) {
220
+ try {
221
+ const resolvedPath = path.resolve(process.cwd(), output.path);
222
+ await this.utils.ensureDir(path.dirname(resolvedPath));
223
+ await this.utils.writeFile(resolvedPath, output.content);
224
+ } catch (error) {
225
+ const err = error;
226
+ this.logger.error(`Failed to write ${output.path}: ${err.message}`);
227
+ throw err;
228
+ }
229
+ }
230
+ }
231
+ /**
232
+ * Get execution results for debugging
233
+ */
234
+ getExecutionResults() {
235
+ return new Map(this.executionContext.results);
236
+ }
237
+ /**
238
+ * Augment existing output with additional content
239
+ */
240
+ augmentOutput(outputs, outputKey, contractName, content) {
241
+ const existing = outputs.get(outputKey);
242
+ if (!existing) {
243
+ this.logger.warn(`Cannot augment non-existent output: ${outputKey}`);
244
+ return;
245
+ }
246
+ const augmentedContent = `${existing.content}
247
+
248
+ // Augmented by plugin for ${contractName}
249
+ ${JSON.stringify(content, null, 2)}`;
250
+ outputs.set(outputKey, {
251
+ ...existing,
252
+ content: augmentedContent
253
+ });
254
+ }
255
+ /**
256
+ * Record hook execution result
257
+ */
258
+ recordHookResult(pluginName, hookName, result) {
259
+ const key = `${pluginName}:${hookName}`;
260
+ const existing = this.executionContext.results.get(key) || [];
261
+ existing.push({ ...result, plugin: pluginName });
262
+ this.executionContext.results.set(key, existing);
263
+ }
264
+ /**
265
+ * Create logger instance
266
+ */
267
+ createLogger() {
268
+ return {
269
+ info: (message) => console.log(`\u2139\uFE0F ${message}`),
270
+ warn: (message) => console.warn(`\u26A0\uFE0F ${message}`),
271
+ error: (message) => console.error(`\u274C ${message}`),
272
+ debug: (message) => {
273
+ if (process.env.DEBUG) {
274
+ console.log(`\u{1F41B} ${message}`);
275
+ }
276
+ },
277
+ success: (message) => console.log(`\u2705 ${message}`)
278
+ };
279
+ }
280
+ /**
281
+ * Create utils instance
282
+ */
283
+ createUtils() {
284
+ return {
285
+ toCamelCase: (str) => {
286
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
287
+ },
288
+ toKebabCase: (str) => {
289
+ return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
290
+ },
291
+ validateAddress: (address) => {
292
+ return validateStacksAddress(address.split(".")[0]);
293
+ },
294
+ parseContractId: (contractId) => {
295
+ const [address, contractName] = contractId.split(".");
296
+ return { address, contractName };
297
+ },
298
+ formatCode: async (code) => {
299
+ return format(code, {
300
+ parser: "typescript",
301
+ singleQuote: true,
302
+ semi: true,
303
+ printWidth: 100,
304
+ trailingComma: "es5"
305
+ });
306
+ },
307
+ resolvePath: (relativePath) => {
308
+ return path.resolve(process.cwd(), relativePath);
309
+ },
310
+ fileExists: async (filePath) => {
311
+ try {
312
+ await fs.access(filePath);
313
+ return true;
314
+ } catch {
315
+ return false;
316
+ }
317
+ },
318
+ readFile: async (filePath) => {
319
+ return fs.readFile(filePath, "utf-8");
320
+ },
321
+ writeFile: async (filePath, content) => {
322
+ await fs.writeFile(filePath, content, "utf-8");
323
+ },
324
+ ensureDir: async (dirPath) => {
325
+ await fs.mkdir(dirPath, { recursive: true });
326
+ }
327
+ };
328
+ }
329
+ };
330
+
331
+ // src/plugins/clarinet/index.ts
332
+ import { initSimnet } from "@hirosystems/clarinet-sdk";
333
+
334
+ // src/generators/contract.ts
335
+ import { format as format2 } from "prettier";
336
+ async function generateContractInterface(contracts) {
337
+ const imports = `import { Cl, validateStacksAddress } from '@stacks/transactions'`;
338
+ const header = `/**
339
+ * Generated by @stacks/codegen
340
+ * DO NOT EDIT MANUALLY
341
+ */`;
342
+ const contractsCode = contracts.map((contract) => generateContract(contract)).join("\n\n");
343
+ const code = `${imports}
344
+
345
+ ${header}
346
+
347
+ ${contractsCode}`;
348
+ const formatted = await format2(code, {
349
+ parser: "typescript",
350
+ singleQuote: true,
351
+ semi: true,
352
+ printWidth: 100,
353
+ trailingComma: "es5"
354
+ });
355
+ return formatted;
356
+ }
357
+ function generateContract(contract) {
358
+ const { name, address, contractName, abi } = contract;
359
+ const abiCode = generateAbiConstant(name, abi);
360
+ const methods = abi.functions.filter((func) => func.access !== "private").map((func) => generateMethod(func, address, contractName)).join(",\n\n ");
361
+ const contractCode = `export const ${name} = {
362
+ address: '${address}',
363
+ contractAddress: '${address}',
364
+ contractName: '${contractName}',
365
+
366
+ ${methods}
367
+ } as const`;
368
+ return `${abiCode}
369
+
370
+ ${contractCode}`;
371
+ }
372
+ function generateAbiConstant(name, abi) {
373
+ const abiJson = JSON.stringify(abi, null, 2).replace(/"([a-zA-Z_$][a-zA-Z0-9_$]*)":/g, "$1:").replace(/"/g, "'");
374
+ return `export const ${name}Abi = ${abiJson} as const`;
375
+ }
376
+ function generateMethod(func, address, contractName) {
377
+ const methodName = toCamelCase(func.name);
378
+ if (func.args.length === 0) {
379
+ return `${methodName}() {
380
+ return {
381
+ contractAddress: '${address}',
382
+ contractName: '${contractName}',
383
+ functionName: '${func.name}',
384
+ functionArgs: []
385
+ }
386
+ }`;
387
+ }
388
+ if (func.args.length === 1) {
389
+ const originalArgName = func.args[0].name;
390
+ const argName = toCamelCase(originalArgName);
391
+ const argType = getTypeForArg(func.args[0]);
392
+ const clarityConversion = generateClarityConversion(argName, func.args[0]);
393
+ return `${methodName}(...args: [{ ${argName}: ${argType} }] | [${argType}]) {
394
+ const ${argName} = args.length === 1 && typeof args[0] === 'object' && args[0] !== null && '${argName}' in args[0]
395
+ ? args[0].${argName}
396
+ : args[0] as ${argType}
397
+
398
+ return {
399
+ contractAddress: '${address}',
400
+ contractName: '${contractName}',
401
+ functionName: '${func.name}',
402
+ functionArgs: [${clarityConversion}]
403
+ }
404
+ }`;
405
+ }
406
+ const argsList = func.args.map((arg) => toCamelCase(arg.name)).join(", ");
407
+ const argsTypes = func.args.map((arg) => {
408
+ const camelName = toCamelCase(arg.name);
409
+ return `${camelName}: ${getTypeForArg(arg)}`;
410
+ }).join("; ");
411
+ const argsArray = func.args.map((arg) => {
412
+ const argName = toCamelCase(arg.name);
413
+ return generateClarityConversion(argName, arg);
414
+ }).join(", ");
415
+ const objectAccess = func.args.map((arg) => {
416
+ const camelName = toCamelCase(arg.name);
417
+ return `args[0].${camelName}`;
418
+ }).join(", ");
419
+ const positionTypes = func.args.map((arg) => getTypeForArg(arg)).join(", ");
420
+ return `${methodName}(...args: [{ ${argsTypes} }] | [${positionTypes}]) {
421
+ const [${argsList}] = args.length === 1 && typeof args[0] === 'object' && args[0] !== null
422
+ ? [${objectAccess}]
423
+ : args as [${positionTypes}]
424
+
425
+ return {
426
+ contractAddress: '${address}',
427
+ contractName: '${contractName}',
428
+ functionName: '${func.name}',
429
+ functionArgs: [${argsArray}]
430
+ }
431
+ }`;
432
+ }
433
+ function getTypeForArg(arg) {
434
+ const type = arg.type;
435
+ if (typeof type === "string") {
436
+ switch (type) {
437
+ case "uint128":
438
+ case "int128":
439
+ return "bigint";
440
+ case "bool":
441
+ return "boolean";
442
+ case "principal":
443
+ case "trait_reference":
444
+ return "string";
445
+ default:
446
+ return "any";
447
+ }
448
+ }
449
+ if (type["string-ascii"] || type["string-utf8"]) {
450
+ return "string";
451
+ }
452
+ if (type.buff) {
453
+ return "Uint8Array | string | { type: 'ascii' | 'utf8' | 'hex'; value: string }";
454
+ }
455
+ if (type.optional) {
456
+ const innerType = getTypeForArg({ type: type.optional });
457
+ return `${innerType} | null`;
458
+ }
459
+ if (type.list) {
460
+ const innerType = getTypeForArg({ type: type.list.type });
461
+ return `${innerType}[]`;
462
+ }
463
+ if (type.tuple) {
464
+ const fields = type.tuple.map(
465
+ (field) => `${toCamelCase(field.name)}: ${getTypeForArg({ type: field.type })}`
466
+ ).join("; ");
467
+ return `{ ${fields} }`;
468
+ }
469
+ if (type.response) {
470
+ const okType = getTypeForArg({ type: type.response.ok });
471
+ const errType = getTypeForArg({ type: type.response.error });
472
+ return `{ ok: ${okType} } | { err: ${errType} }`;
473
+ }
474
+ return "any";
475
+ }
476
+ function toCamelCase(str) {
477
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "");
478
+ }
479
+ function generateClarityConversion(argName, argType) {
480
+ const type = argType.type;
481
+ if (typeof type === "string") {
482
+ switch (type) {
483
+ case "uint128":
484
+ return `Cl.uint(${argName})`;
485
+ case "int128":
486
+ return `Cl.int(${argName})`;
487
+ case "bool":
488
+ return `Cl.bool(${argName})`;
489
+ case "principal":
490
+ case "trait_reference":
491
+ return `(() => {
492
+ const [address, contractName] = ${argName}.split(".") as [string, string];
493
+ if (!validateStacksAddress(address)) {
494
+ throw new Error("Invalid Stacks address format");
495
+ }
496
+ if (${argName}.includes(".")) {
497
+ return Cl.contractPrincipal(address, contractName);
498
+ } else {
499
+ return Cl.standardPrincipal(${argName});
500
+ }
501
+ })()`;
502
+ default:
503
+ return `${argName}`;
504
+ }
505
+ }
506
+ if (type["string-ascii"]) {
507
+ return `Cl.stringAscii(${argName})`;
508
+ }
509
+ if (type["string-utf8"]) {
510
+ return `Cl.stringUtf8(${argName})`;
511
+ }
512
+ if (type.buff) {
513
+ return `(() => {
514
+ const value = ${argName};
515
+ // Direct Uint8Array
516
+ if (value instanceof Uint8Array) {
517
+ return Cl.buffer(value);
518
+ }
519
+ // Object notation with explicit type
520
+ if (typeof value === 'object' && value !== null && value.type && value.value) {
521
+ switch (value.type) {
522
+ case 'ascii':
523
+ return Cl.bufferFromAscii(value.value);
524
+ case 'utf8':
525
+ return Cl.bufferFromUtf8(value.value);
526
+ case 'hex':
527
+ return Cl.bufferFromHex(value.value);
528
+ default:
529
+ throw new Error(\`Unsupported buffer type: \${value.type}\`);
530
+ }
531
+ }
532
+ // Auto-detect string type
533
+ if (typeof value === 'string') {
534
+ // Check for hex (0x prefix or pure hex pattern)
535
+ if (value.startsWith('0x') || /^[0-9a-fA-F]+$/.test(value)) {
536
+ return Cl.bufferFromHex(value);
537
+ }
538
+ // Check for non-ASCII characters (UTF-8)
539
+ if (!/^[\\x00-\\x7F]*$/.test(value)) {
540
+ return Cl.bufferFromUtf8(value);
541
+ }
542
+ // Default to ASCII for simple ASCII strings
543
+ return Cl.bufferFromAscii(value);
544
+ }
545
+ throw new Error(\`Invalid buffer value: \${value}\`);
546
+ })()`;
547
+ }
548
+ if (type.optional) {
549
+ const innerConversion = generateClarityConversion(argName, {
550
+ type: type.optional
551
+ });
552
+ return `${argName} !== null ? Cl.some(${innerConversion.replace(argName, `${argName}`)}) : Cl.none()`;
553
+ }
554
+ if (type.list) {
555
+ const innerConversion = generateClarityConversion("item", {
556
+ type: type.list.type
557
+ });
558
+ return `Cl.list(${argName}.map(item => ${innerConversion}))`;
559
+ }
560
+ if (type.tuple) {
561
+ const fields = type.tuple.map((field) => {
562
+ const camelFieldName = toCamelCase(field.name);
563
+ const fieldConversion = generateClarityConversion(
564
+ `${argName}.${camelFieldName}`,
565
+ { type: field.type }
566
+ );
567
+ return `"${field.name}": ${fieldConversion}`;
568
+ }).join(", ");
569
+ return `Cl.tuple({ ${fields} })`;
570
+ }
571
+ if (type.response) {
572
+ const okConversion = generateClarityConversion(`${argName}.ok`, {
573
+ type: type.response.ok
574
+ });
575
+ const errConversion = generateClarityConversion(`${argName}.err`, {
576
+ type: type.response.error
577
+ });
578
+ return `'ok' in ${argName} ? Cl.ok(${okConversion.replace(`${argName}.ok`, `${argName}.ok`)}) : Cl.error(${errConversion.replace(`${argName}.err`, `${argName}.err`)})`;
579
+ }
580
+ return `${argName}`;
581
+ }
582
+
583
+ // src/plugins/clarinet/index.ts
584
+ function toCamelCase2(str) {
585
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
586
+ }
587
+ function sanitizeContractName(name) {
588
+ return toCamelCase2(name);
589
+ }
590
+ async function isUserDefinedContract(contractId, manifestPath) {
591
+ const [address, contractName] = contractId.split(".");
592
+ try {
593
+ const { promises: fs2 } = await import("fs");
594
+ const tomlContent = await fs2.readFile(manifestPath, "utf-8");
595
+ const contractSectionRegex = /^\[contracts\.([^\]]+)\]/gm;
596
+ const userContracts = /* @__PURE__ */ new Set();
597
+ let match;
598
+ while ((match = contractSectionRegex.exec(tomlContent)) !== null) {
599
+ userContracts.add(match[1]);
600
+ }
601
+ if (userContracts.has(contractName)) {
602
+ return true;
603
+ }
604
+ } catch (error) {
605
+ }
606
+ const systemContractPatterns = [
607
+ /^pox-\d+$/,
608
+ // pox-2, pox-3, etc.
609
+ /^bns$/,
610
+ // Blockchain Name System
611
+ /^costs-\d+$/,
612
+ // costs-2, costs-3, etc.
613
+ /^lockup$/
614
+ // lockup contract
615
+ ];
616
+ if (systemContractPatterns.some((pattern) => pattern.test(contractName))) {
617
+ return false;
618
+ }
619
+ const systemAddresses = [
620
+ "SP000000000000000000002Q6VF78",
621
+ // Boot contracts address
622
+ "ST000000000000000000002AMW42H"
623
+ // Boot contracts address (testnet)
624
+ ];
625
+ if (systemAddresses.includes(address)) {
626
+ return false;
627
+ }
628
+ return true;
629
+ }
630
+ var clarinet = (options = {}) => {
631
+ const manifestPath = options.path || "./Clarinet.toml";
632
+ let simnet;
633
+ return {
634
+ name: "@stacks/codegen/plugin-clarinet",
635
+ version: "1.0.0",
636
+ async transformConfig(config) {
637
+ try {
638
+ simnet = await initSimnet(manifestPath);
639
+ const contractInterfaces = simnet.getContractsInterfaces();
640
+ const contracts = [];
641
+ for (const [contractId, abi] of contractInterfaces) {
642
+ const [_, contractName] = contractId.split(".");
643
+ if (!await isUserDefinedContract(contractId, manifestPath)) {
644
+ if (options.debug) {
645
+ console.log(`\u{1F6AB} Skipping system contract: ${contractId}`);
646
+ }
647
+ continue;
648
+ }
649
+ if (options.include && !options.include.includes(contractName)) {
650
+ continue;
651
+ }
652
+ if (options.exclude && options.exclude.includes(contractName)) {
653
+ continue;
654
+ }
655
+ const sanitizedName = sanitizeContractName(contractName);
656
+ contracts.push({
657
+ name: sanitizedName,
658
+ address: contractId,
659
+ abi,
660
+ // Remove source field - this was causing the path resolution issue
661
+ _clarinetSource: true
662
+ // Internal flag for our plugin
663
+ });
664
+ }
665
+ if (options.debug) {
666
+ console.log(
667
+ `\u{1F50D} Clarinet plugin found ${contracts.length} user-defined contracts`
668
+ );
669
+ }
670
+ return {
671
+ ...config,
672
+ contracts: [...config.contracts || [], ...contracts]
673
+ };
674
+ } catch (error) {
675
+ const err = error;
676
+ if (options.debug) {
677
+ console.warn(
678
+ `\u26A0\uFE0F Clarinet plugin failed to load contracts: ${err.message}`
679
+ );
680
+ }
681
+ return config;
682
+ }
683
+ },
684
+ async generate(context) {
685
+ const clarinetContracts = context.contracts.filter(
686
+ (contract) => contract.metadata?.source === "clarinet"
687
+ );
688
+ if (clarinetContracts.length === 0) {
689
+ return;
690
+ }
691
+ if (options.debug) {
692
+ context.logger.debug(
693
+ `Generating interfaces for ${clarinetContracts.length} Clarinet contracts`
694
+ );
695
+ }
696
+ const contractsCode = await generateContractInterface(clarinetContracts);
697
+ context.addOutput("contracts", {
698
+ path: context.config.out,
699
+ content: contractsCode,
700
+ type: "contracts"
701
+ });
702
+ }
703
+ };
704
+ };
705
+ async function hasClarinetProject(path2 = "./Clarinet.toml") {
706
+ try {
707
+ const { promises: fs2 } = await import("fs");
708
+ await fs2.access(path2);
709
+ return true;
710
+ } catch {
711
+ return false;
712
+ }
713
+ }
714
+
715
+ // src/plugins/actions/generators.ts
716
+ function toCamelCase3(str) {
717
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
718
+ }
719
+ function getTypeForArg2(arg) {
720
+ const type = arg.type;
721
+ if (typeof type === "string") {
722
+ switch (type) {
723
+ case "uint128":
724
+ case "int128":
725
+ return "bigint";
726
+ case "bool":
727
+ return "boolean";
728
+ case "principal":
729
+ case "trait_reference":
730
+ return "string";
731
+ default:
732
+ return "any";
733
+ }
734
+ }
735
+ if (type["string-ascii"] || type["string-utf8"]) {
736
+ return "string";
737
+ }
738
+ if (type.buff) {
739
+ return "Uint8Array | string | { type: 'ascii' | 'utf8' | 'hex'; value: string }";
740
+ }
741
+ if (type.optional) {
742
+ const innerType = getTypeForArg2({ type: type.optional });
743
+ return `${innerType} | null`;
744
+ }
745
+ if (type.list) {
746
+ const innerType = getTypeForArg2({ type: type.list.type });
747
+ return `${innerType}[]`;
748
+ }
749
+ if (type.tuple) {
750
+ const fields = type.tuple.map(
751
+ (field) => `${toCamelCase3(field.name)}: ${getTypeForArg2({ type: field.type })}`
752
+ ).join("; ");
753
+ return `{ ${fields} }`;
754
+ }
755
+ if (type.response) {
756
+ const okType = getTypeForArg2({ type: type.response.ok });
757
+ const errType = getTypeForArg2({ type: type.response.error });
758
+ return `{ ok: ${okType} } | { err: ${errType} }`;
759
+ }
760
+ return "any";
761
+ }
762
+ function generateArgsSignature(args) {
763
+ if (args.length === 0) return "";
764
+ const argsTypes = args.map((arg) => {
765
+ const camelName = toCamelCase3(arg.name);
766
+ return `${camelName}: ${getTypeForArg2(arg)}`;
767
+ }).join("; ");
768
+ return `args: { ${argsTypes} }, `;
769
+ }
770
+ function generateClarityArgs(args, contractName) {
771
+ if (args.length === 0) return "";
772
+ return args.map((arg) => {
773
+ const argName = `args.${toCamelCase3(arg.name)}`;
774
+ return generateClarityConversion2(argName, arg);
775
+ }).join(", ");
776
+ }
777
+ function generateClarityConversion2(argName, argType) {
778
+ const type = argType.type;
779
+ if (typeof type === "string") {
780
+ switch (type) {
781
+ case "uint128":
782
+ return `Cl.uint(${argName})`;
783
+ case "int128":
784
+ return `Cl.int(${argName})`;
785
+ case "bool":
786
+ return `Cl.bool(${argName})`;
787
+ case "principal":
788
+ case "trait_reference":
789
+ return `(() => {
790
+ const [address, contractName] = ${argName}.split(".") as [string, string];
791
+ if (!validateStacksAddress(address)) {
792
+ throw new Error("Invalid Stacks address format");
793
+ }
794
+ if (${argName}.includes(".")) {
795
+ return Cl.contractPrincipal(address, contractName);
796
+ } else {
797
+ return Cl.standardPrincipal(${argName});
798
+ }
799
+ })()`;
800
+ default:
801
+ return `${argName}`;
802
+ }
803
+ }
804
+ if (type["string-ascii"]) {
805
+ return `Cl.stringAscii(${argName})`;
806
+ }
807
+ if (type["string-utf8"]) {
808
+ return `Cl.stringUtf8(${argName})`;
809
+ }
810
+ if (type.buff) {
811
+ return `(() => {
812
+ const value = ${argName};
813
+ if (value instanceof Uint8Array) {
814
+ return Cl.buffer(value);
815
+ }
816
+ if (typeof value === 'object' && value !== null && value.type && value.value) {
817
+ switch (value.type) {
818
+ case 'ascii':
819
+ return Cl.bufferFromAscii(value.value);
820
+ case 'utf8':
821
+ return Cl.bufferFromUtf8(value.value);
822
+ case 'hex':
823
+ return Cl.bufferFromHex(value.value);
824
+ default:
825
+ throw new Error(\`Unsupported buffer type: \${value.type}\`);
826
+ }
827
+ }
828
+ if (typeof value === 'string') {
829
+ if (value.startsWith('0x') || /^[0-9a-fA-F]+$/.test(value)) {
830
+ return Cl.bufferFromHex(value);
831
+ }
832
+ if (!/^[\\x00-\\x7F]*$/.test(value)) {
833
+ return Cl.bufferFromUtf8(value);
834
+ }
835
+ return Cl.bufferFromAscii(value);
836
+ }
837
+ throw new Error(\`Invalid buffer value: \${value}\`);
838
+ })()`;
839
+ }
840
+ if (type.optional) {
841
+ const innerConversion = generateClarityConversion2(argName, {
842
+ type: type.optional
843
+ });
844
+ return `${argName} !== null ? Cl.some(${innerConversion.replace(argName, `${argName}`)}) : Cl.none()`;
845
+ }
846
+ if (type.list) {
847
+ const innerConversion = generateClarityConversion2("item", {
848
+ type: type.list.type
849
+ });
850
+ return `Cl.list(${argName}.map(item => ${innerConversion}))`;
851
+ }
852
+ if (type.tuple) {
853
+ const fields = type.tuple.map((field) => {
854
+ const camelFieldName = toCamelCase3(field.name);
855
+ const fieldConversion = generateClarityConversion2(
856
+ `${argName}.${camelFieldName}`,
857
+ { type: field.type }
858
+ );
859
+ return `"${field.name}": ${fieldConversion}`;
860
+ }).join(", ");
861
+ return `Cl.tuple({ ${fields} })`;
862
+ }
863
+ if (type.response) {
864
+ const okConversion = generateClarityConversion2(`${argName}.ok`, {
865
+ type: type.response.ok
866
+ });
867
+ const errConversion = generateClarityConversion2(`${argName}.err`, {
868
+ type: type.response.error
869
+ });
870
+ return `'ok' in ${argName} ? Cl.ok(${okConversion.replace(`${argName}.ok`, `${argName}.ok`)}) : Cl.error(${errConversion.replace(`${argName}.err`, `${argName}.err`)})`;
871
+ }
872
+ return `${argName}`;
873
+ }
874
+ function generateReadHelpers(contract, options) {
875
+ const { abi, name } = contract;
876
+ const functions = abi.functions || [];
877
+ const readOnlyFunctions = functions.filter(
878
+ (f) => f.access === "read_only" || f.access === "read-only"
879
+ );
880
+ if (readOnlyFunctions.length === 0) {
881
+ return "";
882
+ }
883
+ const filteredFunctions = readOnlyFunctions.filter(
884
+ (func) => {
885
+ if (options.includeFunctions && !options.includeFunctions.includes(func.name)) {
886
+ return false;
887
+ }
888
+ if (options.excludeFunctions && options.excludeFunctions.includes(func.name)) {
889
+ return false;
890
+ }
891
+ return true;
892
+ }
893
+ );
894
+ if (filteredFunctions.length === 0) {
895
+ return "";
896
+ }
897
+ const helpers = filteredFunctions.map((func) => {
898
+ const methodName = toCamelCase3(func.name);
899
+ const argsSignature = generateArgsSignature(func.args);
900
+ const clarityArgs = generateClarityArgs(func.args, name);
901
+ return `async ${methodName}(${argsSignature}options?: {
902
+ network?: 'mainnet' | 'testnet' | 'devnet';
903
+ senderAddress?: string;
904
+ }) {
905
+ return await fetchCallReadOnlyFunction({
906
+ contractAddress: '${contract.address}',
907
+ contractName: '${contract.contractName}',
908
+ functionName: '${func.name}',
909
+ functionArgs: [${clarityArgs}],
910
+ network: options?.network || 'mainnet',
911
+ senderAddress: options?.senderAddress || 'SP000000000000000000002Q6VF78'
912
+ });
913
+ }`;
914
+ });
915
+ return `read: {
916
+ ${helpers.join(",\n\n ")}
917
+ }`;
918
+ }
919
+ function generateWriteHelpers(contract, options) {
920
+ const { abi, name } = contract;
921
+ const functions = abi.functions || [];
922
+ const publicFunctions = functions.filter(
923
+ (f) => f.access === "public"
924
+ );
925
+ if (publicFunctions.length === 0) {
926
+ return "";
927
+ }
928
+ const filteredFunctions = publicFunctions.filter((func) => {
929
+ if (options.includeFunctions && !options.includeFunctions.includes(func.name)) {
930
+ return false;
931
+ }
932
+ if (options.excludeFunctions && options.excludeFunctions.includes(func.name)) {
933
+ return false;
934
+ }
935
+ return true;
936
+ });
937
+ if (filteredFunctions.length === 0) {
938
+ return "";
939
+ }
940
+ const helpers = filteredFunctions.map((func) => {
941
+ const methodName = toCamelCase3(func.name);
942
+ const argsSignature = generateArgsSignature(func.args);
943
+ const clarityArgs = generateClarityArgs(func.args, name);
944
+ return `async ${methodName}(${argsSignature}options: {
945
+ senderKey: string;
946
+ network?: 'mainnet' | 'testnet' | 'devnet';
947
+ fee?: string | number | undefined;
948
+ nonce?: bigint;
949
+ anchorMode?: 1 | 2 | 3; // AnchorMode: OnChainOnly = 1, OffChainOnly = 2, Any = 3
950
+ postConditions?: any[]; // TODO: Add proper PostCondition types
951
+ validateWithAbi?: boolean;
952
+ }) {
953
+ const { senderKey, network = 'mainnet', ...txOptions } = options;
954
+
955
+ return await makeContractCall({
956
+ contractAddress: '${contract.address}',
957
+ contractName: '${contract.contractName}',
958
+ functionName: '${func.name}',
959
+ functionArgs: [${clarityArgs}],
960
+ senderKey,
961
+ network,
962
+ validateWithAbi: true,
963
+ ...txOptions
964
+ });
965
+ }`;
966
+ });
967
+ return `write: {
968
+ ${helpers.join(",\n\n ")}
969
+ }`;
970
+ }
971
+ async function generateActionHelpers(contract, options) {
972
+ const readHelpers = generateReadHelpers(contract, options);
973
+ const writeHelpers = generateWriteHelpers(contract, options);
974
+ if (!readHelpers && !writeHelpers) {
975
+ return "";
976
+ }
977
+ const helpers = [readHelpers, writeHelpers].filter(Boolean);
978
+ return helpers.join(",\n\n");
979
+ }
980
+
981
+ // src/plugins/actions/index.ts
982
+ var actions = (options = {}) => {
983
+ return {
984
+ name: "@stacks/codegen/plugin-actions",
985
+ version: "1.0.0",
986
+ async generate(context) {
987
+ const { contracts } = context;
988
+ const filteredContracts = contracts.filter((contract) => {
989
+ if (options.include && !options.include.includes(contract.name)) {
990
+ return false;
991
+ }
992
+ if (options.exclude && options.exclude.includes(contract.name)) {
993
+ return false;
994
+ }
995
+ return true;
996
+ });
997
+ if (filteredContracts.length === 0) {
998
+ if (options.debug) {
999
+ context.logger.debug("Actions plugin: No contracts to process");
1000
+ }
1001
+ return;
1002
+ }
1003
+ if (options.debug) {
1004
+ context.logger.debug(
1005
+ `Actions plugin: Generating read/write helpers for ${filteredContracts.length} contracts`
1006
+ );
1007
+ }
1008
+ const contractHelpers = /* @__PURE__ */ new Map();
1009
+ for (const contract of filteredContracts) {
1010
+ const actionsCode = await generateActionHelpers(contract, options);
1011
+ if (actionsCode) {
1012
+ contractHelpers.set(contract.name, actionsCode);
1013
+ }
1014
+ }
1015
+ if (contractHelpers.size > 0) {
1016
+ const existingOutput = context.outputs.get("contracts");
1017
+ if (existingOutput) {
1018
+ let modifiedContent = addRequiredImports(existingOutput.content);
1019
+ for (const [contractName, helpersCode] of contractHelpers) {
1020
+ modifiedContent = injectHelpersIntoContract(
1021
+ modifiedContent,
1022
+ contractName,
1023
+ helpersCode
1024
+ );
1025
+ }
1026
+ context.outputs.set("contracts", {
1027
+ ...existingOutput,
1028
+ content: modifiedContent
1029
+ });
1030
+ }
1031
+ }
1032
+ }
1033
+ };
1034
+ };
1035
+ function addRequiredImports(content) {
1036
+ if (content.includes("fetchCallReadOnlyFunction") && content.includes("makeContractCall")) {
1037
+ return content;
1038
+ }
1039
+ const transactionsImportRegex = /import\s+\{([^}]+)\}\s+from\s+['"]@stacks\/transactions['"];/;
1040
+ const match = content.match(transactionsImportRegex);
1041
+ if (match) {
1042
+ const existingImports = match[1].trim();
1043
+ const newImports = ["fetchCallReadOnlyFunction", "makeContractCall"].filter((imp) => !existingImports.includes(imp)).join(", ");
1044
+ if (newImports) {
1045
+ const updatedImport = `import { ${existingImports}, ${newImports} } from '@stacks/transactions';`;
1046
+ return content.replace(transactionsImportRegex, updatedImport);
1047
+ }
1048
+ }
1049
+ return content;
1050
+ }
1051
+ function injectHelpersIntoContract(content, contractName, helpersCode) {
1052
+ const contractPattern = new RegExp(
1053
+ `(export const ${contractName} = \\{[\\s\\S]*?)\\n\\} as const;`,
1054
+ "g"
1055
+ );
1056
+ return content.replace(contractPattern, (_, contractBody) => {
1057
+ const cleanBody = contractBody.replace(/,\s*$/, "");
1058
+ const indentedHelpersCode = helpersCode.split("\n").map((line) => {
1059
+ if (line.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/)) {
1060
+ return ` ${line}`;
1061
+ }
1062
+ return line;
1063
+ }).join("\n");
1064
+ return `${cleanBody},
1065
+
1066
+ ${indentedHelpersCode}
1067
+ } as const;`;
1068
+ });
1069
+ }
1070
+
1071
+ // src/plugins/react/provider/index.ts
1072
+ import { format as format3 } from "prettier";
1073
+ async function generateProvider() {
1074
+ const code = `/**
1075
+ * Generated Stacks React Provider
1076
+ * DO NOT EDIT MANUALLY
1077
+ */
1078
+
1079
+ import React, { createContext, useContext } from 'react'
1080
+
1081
+ /**
1082
+ * Stacks configuration interface
1083
+ */
1084
+ export interface StacksReactConfig {
1085
+ /**
1086
+ * Network to use for API calls
1087
+ */
1088
+ network: 'mainnet' | 'testnet' | 'devnet'
1089
+
1090
+ /**
1091
+ * API key for Stacks API (optional)
1092
+ */
1093
+ apiKey?: string
1094
+
1095
+ /**
1096
+ * Base URL for Stacks API (optional override)
1097
+ */
1098
+ apiUrl?: string
1099
+
1100
+ /**
1101
+ * Default sender address for read-only calls
1102
+ */
1103
+ senderAddress?: string
1104
+ }
1105
+
1106
+ /**
1107
+ * Provider component props
1108
+ */
1109
+ export interface StacksProviderProps {
1110
+ children: React.ReactNode
1111
+ config: StacksReactConfig
1112
+ }
1113
+
1114
+ /**
1115
+ * React context for Stacks configuration
1116
+ */
1117
+ const StacksContext = createContext<StacksReactConfig | undefined>(undefined)
1118
+ StacksContext.displayName = 'StacksContext'
1119
+
1120
+ /**
1121
+ * Create a Stacks React configuration with defaults
1122
+ */
1123
+ export function createStacksConfig(config: StacksReactConfig): StacksReactConfig {
1124
+ return {
1125
+ network: config.network,
1126
+ apiKey: config.apiKey,
1127
+ apiUrl: config.apiUrl,
1128
+ senderAddress: config.senderAddress || 'SP000000000000000000002Q6VF78'
1129
+ }
1130
+ }
1131
+
1132
+ /**
1133
+ * Provider component that makes Stacks configuration available to hooks
1134
+ */
1135
+ export function StacksProvider({ children, config }: StacksProviderProps) {
1136
+ const resolvedConfig = createStacksConfig(config)
1137
+
1138
+ return (
1139
+ <StacksContext.Provider value={resolvedConfig}>
1140
+ {children}
1141
+ </StacksContext.Provider>
1142
+ )
1143
+ }
1144
+
1145
+ /**
1146
+ * Hook to access the Stacks configuration
1147
+ */
1148
+ export function useStacksConfig(): StacksReactConfig {
1149
+ const context = useContext(StacksContext)
1150
+
1151
+ if (context === undefined) {
1152
+ throw new Error(
1153
+ 'useStacksConfig must be used within a StacksProvider. ' +
1154
+ 'Make sure to wrap your app with <StacksProvider config={{...}}>'
1155
+ )
1156
+ }
1157
+
1158
+ return context
1159
+ }`;
1160
+ const formatted = await format3(code, {
1161
+ parser: "typescript",
1162
+ singleQuote: true,
1163
+ semi: false,
1164
+ printWidth: 100,
1165
+ trailingComma: "es5"
1166
+ });
1167
+ return formatted;
1168
+ }
1169
+
1170
+ // src/plugins/react/generators/generic.ts
1171
+ import { format as format4 } from "prettier";
1172
+ var GENERIC_HOOKS = [
1173
+ "useAccount",
1174
+ "useConnect",
1175
+ "useDisconnect",
1176
+ "useNetwork",
1177
+ "useContract",
1178
+ "useOpenSTXTransfer",
1179
+ "useSignMessage",
1180
+ "useDeployContract",
1181
+ "useReadContract",
1182
+ "useTransaction",
1183
+ "useBlock",
1184
+ "useAccountTransactions",
1185
+ "useWaitForTransaction"
1186
+ ];
1187
+ async function generateGenericHooks(excludeList = []) {
1188
+ const hooksToGenerate = GENERIC_HOOKS.filter(
1189
+ (hookName) => !excludeList.includes(hookName)
1190
+ );
1191
+ const imports = `import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
1192
+ import { useState, useCallback } from 'react'
1193
+ import { useStacksConfig } from './provider'
1194
+ import { connect, disconnect, isConnected, request, openContractCall as stacksOpenContractCall } from '@stacks/connect'
1195
+ import { Cl, validateStacksAddress } from '@stacks/transactions'
1196
+ import type { ExtractFunctionArgs, ExtractFunctionNames, ClarityContract } from '@secondlayer/clarity-types'`;
1197
+ const header = `/**
1198
+ * Generated generic Stacks React hooks
1199
+ * DO NOT EDIT MANUALLY
1200
+ */`;
1201
+ const hooksCode = hooksToGenerate.map((hookName) => generateGenericHook(hookName)).filter(Boolean).join("\n\n");
1202
+ const code = `${imports}
1203
+
1204
+ ${header}
1205
+
1206
+ ${hooksCode}`;
1207
+ const formatted = await format4(code, {
1208
+ parser: "typescript",
1209
+ singleQuote: true,
1210
+ semi: false,
1211
+ printWidth: 100,
1212
+ trailingComma: "es5"
1213
+ });
1214
+ return formatted;
1215
+ }
1216
+ function generateGenericHook(hookName) {
1217
+ switch (hookName) {
1218
+ case "useAccount":
1219
+ return `export function useAccount() {
1220
+ const config = useStacksConfig()
1221
+
1222
+ return useQuery({
1223
+ queryKey: ['stacks-account', config.network],
1224
+ queryFn: async () => {
1225
+ try {
1226
+ // Check if already connected using @stacks/connect v8
1227
+ const connected = isConnected()
1228
+
1229
+ if (!connected) {
1230
+ return {
1231
+ address: undefined,
1232
+ addresses: undefined,
1233
+ isConnected: false,
1234
+ isConnecting: false,
1235
+ isDisconnected: true,
1236
+ status: 'disconnected' as const
1237
+ }
1238
+ }
1239
+
1240
+ // Get addresses using @stacks/connect v8 request method (SIP-030)
1241
+ const result = await request('stx_getAddresses')
1242
+
1243
+ if (!result || !result.addresses || result.addresses.length === 0) {
1244
+ return {
1245
+ address: undefined,
1246
+ addresses: undefined,
1247
+ isConnected: false,
1248
+ isConnecting: false,
1249
+ isDisconnected: true,
1250
+ status: 'disconnected' as const
1251
+ }
1252
+ }
1253
+
1254
+ // Extract STX addresses from the response
1255
+ const stxAddresses = result.addresses
1256
+ .filter((addr: any) => addr.address.startsWith('SP') || addr.address.startsWith('ST'))
1257
+ .map((addr: any) => addr.address)
1258
+
1259
+ return {
1260
+ address: stxAddresses[0] || undefined,
1261
+ addresses: stxAddresses,
1262
+ isConnected: true,
1263
+ isConnecting: false,
1264
+ isDisconnected: false,
1265
+ status: 'connected' as const
1266
+ }
1267
+ } catch (error) {
1268
+ // Handle case where wallet is not available or user rejected
1269
+ return {
1270
+ address: undefined,
1271
+ addresses: undefined,
1272
+ isConnected: false,
1273
+ isConnecting: false,
1274
+ isDisconnected: true,
1275
+ status: 'disconnected' as const
1276
+ }
1277
+ }
1278
+ },
1279
+ refetchOnWindowFocus: false,
1280
+ retry: false,
1281
+ staleTime: 1000 * 60 * 5, // 5 minutes
1282
+ refetchInterval: 1000 * 30, // Refetch every 30 seconds to detect wallet changes
1283
+ })
1284
+ }`;
1285
+ case "useConnect":
1286
+ return `export function useConnect() {
1287
+ const queryClient = useQueryClient()
1288
+
1289
+ const mutation = useMutation({
1290
+ mutationFn: async (options: { forceWalletSelect?: boolean } = {}) => {
1291
+ // Use @stacks/connect v8 connect method
1292
+ return await connect(options)
1293
+ },
1294
+ onSuccess: () => {
1295
+ // Invalidate account queries to refetch connection state
1296
+ queryClient.invalidateQueries({ queryKey: ['stacks-account'] })
1297
+ },
1298
+ onError: (error) => {
1299
+ console.error('Connection failed:', error)
1300
+ }
1301
+ })
1302
+
1303
+ return {
1304
+ // Custom connect function that works without arguments
1305
+ connect: (options?: { forceWalletSelect?: boolean }) => {
1306
+ return mutation.mutate(options || {})
1307
+ },
1308
+ connectAsync: async (options?: { forceWalletSelect?: boolean }) => {
1309
+ return mutation.mutateAsync(options || {})
1310
+ },
1311
+ // Expose all the mutation state
1312
+ isPending: mutation.isPending,
1313
+ isError: mutation.isError,
1314
+ isSuccess: mutation.isSuccess,
1315
+ error: mutation.error,
1316
+ data: mutation.data,
1317
+ reset: mutation.reset,
1318
+ // Keep the original mutate/mutateAsync for advanced users
1319
+ mutate: mutation.mutate,
1320
+ mutateAsync: mutation.mutateAsync
1321
+ }
1322
+ }`;
1323
+ case "useDisconnect":
1324
+ return `export function useDisconnect() {
1325
+ const queryClient = useQueryClient()
1326
+
1327
+ const mutation = useMutation({
1328
+ mutationFn: async () => {
1329
+ // Use @stacks/connect v8 disconnect method
1330
+ return await disconnect()
1331
+ },
1332
+ onSuccess: () => {
1333
+ // Clear all cached data on disconnect
1334
+ queryClient.clear()
1335
+ },
1336
+ onError: (error) => {
1337
+ console.error('Disconnect failed:', error)
1338
+ }
1339
+ })
1340
+
1341
+ return {
1342
+ // Custom disconnect function
1343
+ disconnect: () => {
1344
+ return mutation.mutate()
1345
+ },
1346
+ disconnectAsync: async () => {
1347
+ return mutation.mutateAsync()
1348
+ },
1349
+ // Expose all the mutation state
1350
+ isPending: mutation.isPending,
1351
+ isError: mutation.isError,
1352
+ isSuccess: mutation.isSuccess,
1353
+ error: mutation.error,
1354
+ data: mutation.data,
1355
+ reset: mutation.reset,
1356
+ // Keep the original mutate/mutateAsync for advanced users
1357
+ mutate: mutation.mutate,
1358
+ mutateAsync: mutation.mutateAsync
1359
+ }
1360
+ }`;
1361
+ case "useNetwork":
1362
+ return `export function useNetwork() {
1363
+ const config = useStacksConfig()
1364
+
1365
+ return useQuery({
1366
+ queryKey: ['stacks-network', config.network],
1367
+ queryFn: async () => {
1368
+ // Currently read-only from config
1369
+ // Future: Use request('stx_getNetworks') when wallet support improves
1370
+ const network = config.network
1371
+
1372
+ return {
1373
+ network,
1374
+ isMainnet: network === 'mainnet',
1375
+ isTestnet: network === 'testnet',
1376
+ isDevnet: network === 'devnet',
1377
+ // Future: Add switchNetwork when wallets support stx_networkChange
1378
+ // switchNetwork: async (newNetwork: string) => {
1379
+ // return await request('wallet_changeNetwork', { network: newNetwork })
1380
+ // }
1381
+ }
1382
+ },
1383
+ staleTime: Infinity, // Network config rarely changes
1384
+ refetchOnWindowFocus: false,
1385
+ retry: false
1386
+ })
1387
+ }`;
1388
+ case "useContract":
1389
+ return `export function useContract() {
1390
+ const config = useStacksConfig()
1391
+ const queryClient = useQueryClient()
1392
+ const [isRequestPending, setIsRequestPending] = useState(false)
1393
+
1394
+ // Helper function to convert JS values to Clarity values based on ABI
1395
+ const convertArgsWithAbi = (args: any, abiArgs: any[]): any[] => {
1396
+ if (!abiArgs || abiArgs.length === 0) return []
1397
+
1398
+ return abiArgs.map((abiArg, index) => {
1399
+ const argValue = Array.isArray(args)
1400
+ ? args[index]
1401
+ : args[abiArg.name] || args[abiArg.name.replace(/-/g, '').replace(/_/g, '')]
1402
+ return convertJSValueToClarityValue(argValue, abiArg.type)
1403
+ })
1404
+ }
1405
+
1406
+ // Helper function to convert buffer values with auto-detection
1407
+ const convertBufferValue = (value: any): any => {
1408
+ // Direct Uint8Array
1409
+ if (value instanceof Uint8Array) {
1410
+ return Cl.buffer(value)
1411
+ }
1412
+
1413
+ // Object notation with explicit type
1414
+ if (typeof value === 'object' && value !== null && value.type && value.value) {
1415
+ switch (value.type) {
1416
+ case 'ascii':
1417
+ return Cl.bufferFromAscii(value.value)
1418
+ case 'utf8':
1419
+ return Cl.bufferFromUtf8(value.value)
1420
+ case 'hex':
1421
+ return Cl.bufferFromHex(value.value)
1422
+ default:
1423
+ throw new Error(\`Unsupported buffer type: \${value.type}\`)
1424
+ }
1425
+ }
1426
+
1427
+ // Auto-detect string type
1428
+ if (typeof value === 'string') {
1429
+ // 1. Check for hex (0x prefix or pure hex pattern)
1430
+ if (value.startsWith('0x') || /^[0-9a-fA-F]+$/.test(value)) {
1431
+ return Cl.bufferFromHex(value)
1432
+ }
1433
+
1434
+ // 2. Check for non-ASCII characters (UTF-8)
1435
+ if (!/^[\\x00-\\x7F]*$/.test(value)) {
1436
+ return Cl.bufferFromUtf8(value)
1437
+ }
1438
+
1439
+ // 3. Default to ASCII for simple ASCII strings
1440
+ return Cl.bufferFromAscii(value)
1441
+ }
1442
+
1443
+ throw new Error(\`Invalid buffer value: \${value}\`)
1444
+ }
1445
+
1446
+ // Helper function to convert a single JS value to ClarityValue
1447
+ const convertJSValueToClarityValue = (value: any, type: any): any => {
1448
+ if (typeof type === 'string') {
1449
+ switch (type) {
1450
+ case 'uint128':
1451
+ return Cl.uint(value)
1452
+ case 'int128':
1453
+ return Cl.int(value)
1454
+ case 'bool':
1455
+ return Cl.bool(value)
1456
+ case 'principal':
1457
+ if (!validateStacksAddress(value.split('.')[0])) {
1458
+ throw new Error('Invalid Stacks address format')
1459
+ }
1460
+ if (value.includes('.')) {
1461
+ const [address, contractName] = value.split('.')
1462
+ return Cl.contractPrincipal(address, contractName)
1463
+ } else {
1464
+ return Cl.standardPrincipal(value)
1465
+ }
1466
+ default:
1467
+ return value
1468
+ }
1469
+ }
1470
+
1471
+ if (type['string-ascii']) {
1472
+ return Cl.stringAscii(value)
1473
+ }
1474
+
1475
+ if (type['string-utf8']) {
1476
+ return Cl.stringUtf8(value)
1477
+ }
1478
+
1479
+ if (type.buff) {
1480
+ return convertBufferValue(value)
1481
+ }
1482
+
1483
+ if (type.optional) {
1484
+ return value !== null ? Cl.some(convertJSValueToClarityValue(value, type.optional)) : Cl.none()
1485
+ }
1486
+
1487
+ if (type.list) {
1488
+ return Cl.list(value.map((item: any) => convertJSValueToClarityValue(item, type.list.type)))
1489
+ }
1490
+
1491
+ if (type.tuple) {
1492
+ const tupleData = type.tuple.reduce((acc: any, field: any) => {
1493
+ acc[field.name] = convertJSValueToClarityValue(value[field.name], field.type)
1494
+ return acc
1495
+ }, {})
1496
+ return Cl.tuple(tupleData)
1497
+ }
1498
+
1499
+ if (type.response) {
1500
+ return 'ok' in value
1501
+ ? Cl.ok(convertJSValueToClarityValue(value.ok, type.response.ok))
1502
+ : Cl.error(convertJSValueToClarityValue(value.err, type.response.error))
1503
+ }
1504
+
1505
+ return value
1506
+ }
1507
+
1508
+ // Helper function to find a function in an ABI by name
1509
+ const findFunctionInAbi = (abi: any, functionName: string): any => {
1510
+ if (!abi || !abi.functions) return null
1511
+ return abi.functions.find((func: any) => func.name === functionName)
1512
+ }
1513
+
1514
+ // Legacy function - unchanged, backward compatible
1515
+ const legacyOpenContractCall = useCallback(async (params: {
1516
+ contractAddress: string;
1517
+ contractName: string;
1518
+ functionName: string;
1519
+ functionArgs: any[]; // Pre-converted Clarity values
1520
+ network?: string;
1521
+ postConditions?: any[];
1522
+ attachment?: string;
1523
+ onFinish?: (data: any) => void;
1524
+ onCancel?: () => void;
1525
+ }) => {
1526
+ setIsRequestPending(true)
1527
+
1528
+ try {
1529
+ const { contractAddress, contractName, functionName, functionArgs, onFinish, onCancel, ...options } = params
1530
+ const network = params.network || config.network || 'mainnet'
1531
+ const contract = \`\${contractAddress}.\${contractName}\`
1532
+
1533
+ // Try @stacks/connect v8 stx_callContract first (SIP-030)
1534
+ try {
1535
+ const result = await request('stx_callContract', {
1536
+ contract,
1537
+ functionName,
1538
+ functionArgs,
1539
+ network,
1540
+ ...options
1541
+ })
1542
+
1543
+ // Invalidate relevant queries on success
1544
+ queryClient.invalidateQueries({
1545
+ queryKey: ['stacks-account']
1546
+ })
1547
+
1548
+ onFinish?.(result)
1549
+ return result
1550
+ } catch (connectError) {
1551
+ // Fallback to openContractCall for broader wallet compatibility
1552
+ console.warn('stx_callContract not supported, falling back to openContractCall:', connectError)
1553
+
1554
+ return new Promise((resolve, reject) => {
1555
+ stacksOpenContractCall({
1556
+ contractAddress,
1557
+ contractName,
1558
+ functionName,
1559
+ functionArgs,
1560
+ network,
1561
+ ...options,
1562
+ onFinish: (data: any) => {
1563
+ // Invalidate relevant queries on success
1564
+ queryClient.invalidateQueries({
1565
+ queryKey: ['stacks-account']
1566
+ })
1567
+
1568
+ onFinish?.(data)
1569
+ resolve(data)
1570
+ },
1571
+ onCancel: () => {
1572
+ onCancel?.()
1573
+ reject(new Error('User cancelled transaction'))
1574
+ }
1575
+ })
1576
+ })
1577
+ }
1578
+ } catch (error) {
1579
+ console.error('Contract call failed:', error)
1580
+ throw error instanceof Error ? error : new Error('Contract call failed')
1581
+ } finally {
1582
+ setIsRequestPending(false)
1583
+ }
1584
+ }, [config.network, queryClient])
1585
+
1586
+ // Enhanced function - requires ABI, auto-converts JS values
1587
+ const openContractCall = useCallback(async <
1588
+ T extends ClarityContract,
1589
+ FN extends ExtractFunctionNames<T>
1590
+ >(params: {
1591
+ contractAddress: string;
1592
+ contractName: string;
1593
+ functionName: FN;
1594
+ abi: T;
1595
+ functionArgs: ExtractFunctionArgs<T, FN>;
1596
+ network?: string;
1597
+ postConditions?: any[];
1598
+ attachment?: string;
1599
+ onFinish?: (data: any) => void;
1600
+ onCancel?: () => void;
1601
+ }) => {
1602
+ setIsRequestPending(true)
1603
+
1604
+ try {
1605
+ const { contractAddress, contractName, functionName, functionArgs, abi, onFinish, onCancel, ...options } = params
1606
+ const network = params.network || config.network || 'mainnet'
1607
+ const contract = \`\${contractAddress}.\${contractName}\`
1608
+
1609
+ // Find the function in the ABI and convert args
1610
+ const abiFunction = findFunctionInAbi(abi, functionName)
1611
+ if (!abiFunction) {
1612
+ throw new Error(\`Function '\${functionName}' not found in ABI\`)
1613
+ }
1614
+
1615
+ const processedArgs = convertArgsWithAbi(functionArgs, abiFunction.args || [])
1616
+
1617
+ // Try @stacks/connect v8 stx_callContract first (SIP-030)
1618
+ try {
1619
+ const result = await request('stx_callContract', {
1620
+ contract,
1621
+ functionName,
1622
+ functionArgs: processedArgs,
1623
+ network,
1624
+ ...options
1625
+ })
1626
+
1627
+ // Invalidate relevant queries on success
1628
+ queryClient.invalidateQueries({
1629
+ queryKey: ['stacks-account']
1630
+ })
1631
+
1632
+ onFinish?.(result)
1633
+ return result
1634
+ } catch (connectError) {
1635
+ // Fallback to openContractCall for broader wallet compatibility
1636
+ console.warn('stx_callContract not supported, falling back to openContractCall:', connectError)
1637
+
1638
+ return new Promise((resolve, reject) => {
1639
+ stacksOpenContractCall({
1640
+ contractAddress,
1641
+ contractName,
1642
+ functionName,
1643
+ functionArgs: processedArgs,
1644
+ network,
1645
+ ...options,
1646
+ onFinish: (data: any) => {
1647
+ // Invalidate relevant queries on success
1648
+ queryClient.invalidateQueries({
1649
+ queryKey: ['stacks-account']
1650
+ })
1651
+
1652
+ onFinish?.(data)
1653
+ resolve(data)
1654
+ },
1655
+ onCancel: () => {
1656
+ onCancel?.()
1657
+ reject(new Error('User cancelled transaction'))
1658
+ }
1659
+ })
1660
+ })
1661
+ }
1662
+ } catch (error) {
1663
+ console.error('Contract call failed:', error)
1664
+ throw error instanceof Error ? error : new Error('Contract call failed')
1665
+ } finally {
1666
+ setIsRequestPending(false)
1667
+ }
1668
+ }, [config.network, queryClient])
1669
+
1670
+ return {
1671
+ legacyOpenContractCall,
1672
+ openContractCall,
1673
+ isRequestPending
1674
+ }
1675
+ }`;
1676
+ case "useReadContract":
1677
+ return `export function useReadContract<TArgs = any, TResult = any>(params: {
1678
+ contractAddress: string;
1679
+ contractName: string;
1680
+ functionName: string;
1681
+ args?: TArgs;
1682
+ network?: 'mainnet' | 'testnet' | 'devnet';
1683
+ enabled?: boolean;
1684
+ }) {
1685
+ const config = useStacksConfig()
1686
+
1687
+ return useQuery<TResult>({
1688
+ queryKey: ['read-contract', params.contractAddress, params.contractName, params.functionName, params.args, params.network || config.network],
1689
+ queryFn: async () => {
1690
+ const { fetchCallReadOnlyFunction } = await import('@stacks/transactions')
1691
+
1692
+ // For now, we'll need to handle the args conversion here
1693
+ // In the future, we could integrate with the contract interface for automatic conversion
1694
+ let functionArgs: any[] = []
1695
+
1696
+ if (params.args) {
1697
+ // This is a simplified conversion - in practice, we'd need the ABI to do proper conversion
1698
+ // For now, we'll assume the args are already in the correct format or simple types
1699
+ if (Array.isArray(params.args)) {
1700
+ functionArgs = params.args
1701
+ } else if (typeof params.args === 'object') {
1702
+ // Convert object args to array (this is a basic implementation)
1703
+ functionArgs = Object.values(params.args)
1704
+ } else {
1705
+ functionArgs = [params.args]
1706
+ }
1707
+ }
1708
+
1709
+ return await fetchCallReadOnlyFunction({
1710
+ contractAddress: params.contractAddress,
1711
+ contractName: params.contractName,
1712
+ functionName: params.functionName,
1713
+ functionArgs,
1714
+ network: params.network || config.network || 'mainnet',
1715
+ senderAddress: config.senderAddress || 'SP000000000000000000002Q6VF78'
1716
+ }) as TResult
1717
+ },
1718
+ enabled: params.enabled ?? true
1719
+ })
1720
+ }`;
1721
+ case "useTransaction":
1722
+ return `export function useTransaction(txId?: string) {
1723
+ const config = useStacksConfig()
1724
+
1725
+ return useQuery({
1726
+ queryKey: ['transaction', txId, config.network],
1727
+ queryFn: () => fetchTransaction({
1728
+ txId: txId!,
1729
+ network: config.network,
1730
+ apiUrl: config.apiUrl
1731
+ }),
1732
+ enabled: !!txId
1733
+ })
1734
+ }`;
1735
+ case "useBlock":
1736
+ return `export function useBlock(height?: number) {
1737
+ const config = useStacksConfig()
1738
+
1739
+ return useQuery({
1740
+ queryKey: ['block', height, config.network],
1741
+ queryFn: () => fetchBlock({
1742
+ height: height!,
1743
+ network: config.network,
1744
+ apiUrl: config.apiUrl
1745
+ }),
1746
+ enabled: typeof height === 'number'
1747
+ })
1748
+ }`;
1749
+ case "useAccountTransactions":
1750
+ return `export function useAccountTransactions(address?: string) {
1751
+ const config = useStacksConfig()
1752
+
1753
+ return useQuery({
1754
+ queryKey: ['account-transactions', address, config.network],
1755
+ queryFn: () => fetchAccountTransactions({
1756
+ address: address!,
1757
+ network: config.network,
1758
+ apiUrl: config.apiUrl
1759
+ }),
1760
+ enabled: !!address
1761
+ })
1762
+ }`;
1763
+ case "useWaitForTransaction":
1764
+ return `export function useWaitForTransaction(txId?: string) {
1765
+ const config = useStacksConfig()
1766
+
1767
+ return useQuery({
1768
+ queryKey: ['wait-for-transaction', txId, config.network],
1769
+ queryFn: () => fetchTransaction({
1770
+ txId: txId!,
1771
+ network: config.network,
1772
+ apiUrl: config.apiUrl
1773
+ }),
1774
+ enabled: !!txId,
1775
+ refetchInterval: (data) => {
1776
+ // Stop polling when transaction is complete
1777
+ if (data?.tx_status === 'success' ||
1778
+ data?.tx_status === 'abort_by_response' ||
1779
+ data?.tx_status === 'abort_by_post_condition') {
1780
+ return false
1781
+ }
1782
+ return 2000 // Poll every 2 seconds
1783
+ },
1784
+ staleTime: 0 // Always refetch
1785
+ })
1786
+ }`;
1787
+ case "useOpenSTXTransfer":
1788
+ return `export function useOpenSTXTransfer() {
1789
+ const config = useStacksConfig()
1790
+ const queryClient = useQueryClient()
1791
+
1792
+ const mutation = useMutation({
1793
+ mutationFn: async (params: {
1794
+ recipient: string;
1795
+ amount: string | number;
1796
+ memo?: string;
1797
+ network?: string;
1798
+ onFinish?: (data: any) => void;
1799
+ onCancel?: () => void;
1800
+ }) => {
1801
+ const { recipient, amount, memo, onFinish, onCancel, ...options } = params
1802
+ const network = params.network || config.network || 'mainnet'
1803
+
1804
+ return new Promise((resolve, reject) => {
1805
+ openSTXTransfer({
1806
+ recipient,
1807
+ amount: amount.toString(),
1808
+ memo,
1809
+ network,
1810
+ ...options,
1811
+ onFinish: (data: any) => {
1812
+ onFinish?.(data)
1813
+ resolve(data)
1814
+ },
1815
+ onCancel: () => {
1816
+ onCancel?.()
1817
+ reject(new Error('User cancelled transaction'))
1818
+ }
1819
+ })
1820
+ })
1821
+ },
1822
+ onSuccess: () => {
1823
+ // Invalidate relevant queries on success
1824
+ queryClient.invalidateQueries({ queryKey: ['stacks-account'] })
1825
+ },
1826
+ onError: (error) => {
1827
+ console.error('STX transfer failed:', error)
1828
+ }
1829
+ })
1830
+
1831
+ const openSTXTransfer = useCallback(async (params: {
1832
+ recipient: string;
1833
+ amount: string | number;
1834
+ memo?: string;
1835
+ network?: string;
1836
+ onFinish?: (data: any) => void;
1837
+ onCancel?: () => void;
1838
+ }) => {
1839
+ return mutation.mutateAsync(params)
1840
+ }, [mutation])
1841
+
1842
+ return {
1843
+ openSTXTransfer,
1844
+ // Expose mutation state
1845
+ isPending: mutation.isPending,
1846
+ isError: mutation.isError,
1847
+ isSuccess: mutation.isSuccess,
1848
+ error: mutation.error,
1849
+ data: mutation.data,
1850
+ reset: mutation.reset
1851
+ }
1852
+ }`;
1853
+ case "useSignMessage":
1854
+ return `export function useSignMessage() {
1855
+ const config = useStacksConfig()
1856
+
1857
+ const mutation = useMutation({
1858
+ mutationFn: async (params: {
1859
+ message: string;
1860
+ network?: string;
1861
+ onFinish?: (data: any) => void;
1862
+ onCancel?: () => void;
1863
+ }) => {
1864
+ const { message, onFinish, onCancel, ...options } = params
1865
+ const network = params.network || config.network || 'mainnet'
1866
+
1867
+ return new Promise((resolve, reject) => {
1868
+ openSignatureRequestPopup({
1869
+ message,
1870
+ network,
1871
+ ...options,
1872
+ onFinish: (data: any) => {
1873
+ onFinish?.(data)
1874
+ resolve(data)
1875
+ },
1876
+ onCancel: () => {
1877
+ onCancel?.()
1878
+ reject(new Error('User cancelled message signing'))
1879
+ }
1880
+ })
1881
+ })
1882
+ },
1883
+ onError: (error) => {
1884
+ console.error('Message signing failed:', error)
1885
+ }
1886
+ })
1887
+
1888
+ const signMessage = useCallback(async (params: {
1889
+ message: string;
1890
+ network?: string;
1891
+ onFinish?: (data: any) => void;
1892
+ onCancel?: () => void;
1893
+ }) => {
1894
+ return mutation.mutateAsync(params)
1895
+ }, [mutation])
1896
+
1897
+ return {
1898
+ signMessage,
1899
+ // Expose mutation state
1900
+ isPending: mutation.isPending,
1901
+ isError: mutation.isError,
1902
+ isSuccess: mutation.isSuccess,
1903
+ error: mutation.error,
1904
+ data: mutation.data,
1905
+ reset: mutation.reset
1906
+ }
1907
+ }`;
1908
+ case "useDeployContract":
1909
+ return `export function useDeployContract() {
1910
+ const config = useStacksConfig()
1911
+ const queryClient = useQueryClient()
1912
+
1913
+ const mutation = useMutation({
1914
+ mutationFn: async (params: {
1915
+ contractName: string;
1916
+ codeBody: string;
1917
+ network?: string;
1918
+ postConditions?: any[];
1919
+ onFinish?: (data: any) => void;
1920
+ onCancel?: () => void;
1921
+ }) => {
1922
+ const { contractName, codeBody, onFinish, onCancel, ...options } = params
1923
+ const network = params.network || config.network || 'mainnet'
1924
+
1925
+ return new Promise((resolve, reject) => {
1926
+ openContractDeploy({
1927
+ contractName,
1928
+ codeBody,
1929
+ network,
1930
+ ...options,
1931
+ onFinish: (data: any) => {
1932
+ onFinish?.(data)
1933
+ resolve(data)
1934
+ },
1935
+ onCancel: () => {
1936
+ onCancel?.()
1937
+ reject(new Error('User cancelled contract deployment'))
1938
+ }
1939
+ })
1940
+ })
1941
+ },
1942
+ onSuccess: () => {
1943
+ // Invalidate relevant queries on success
1944
+ queryClient.invalidateQueries({ queryKey: ['stacks-account'] })
1945
+ },
1946
+ onError: (error) => {
1947
+ console.error('Contract deployment failed:', error)
1948
+ }
1949
+ })
1950
+
1951
+ const deployContract = useCallback(async (params: {
1952
+ contractName: string;
1953
+ codeBody: string;
1954
+ network?: string;
1955
+ postConditions?: any[];
1956
+ onFinish?: (data: any) => void;
1957
+ onCancel?: () => void;
1958
+ }) => {
1959
+ return mutation.mutateAsync(params)
1960
+ }, [mutation])
1961
+
1962
+ return {
1963
+ deployContract,
1964
+ // Expose mutation state
1965
+ isPending: mutation.isPending,
1966
+ isError: mutation.isError,
1967
+ isSuccess: mutation.isSuccess,
1968
+ error: mutation.error,
1969
+ data: mutation.data,
1970
+ reset: mutation.reset
1971
+ }
1972
+ }`;
1973
+ default:
1974
+ return "";
1975
+ }
1976
+ }
1977
+
1978
+ // src/plugins/react/generators/contract.ts
1979
+ import { format as format5 } from "prettier";
1980
+
1981
+ // src/plugins/react/generators/utils.ts
1982
+ function toCamelCase4(str) {
1983
+ return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
1984
+ }
1985
+ function capitalize(str) {
1986
+ return str.charAt(0).toUpperCase() + str.slice(1);
1987
+ }
1988
+ function generateHookArgsSignature(args) {
1989
+ if (args.length === 0) return "";
1990
+ const argsList = args.map((arg) => `${toCamelCase4(arg.name)}: ${mapClarityTypeToTS(arg.type)}`).join(", ");
1991
+ return `${argsList}`;
1992
+ }
1993
+ function generateArgsType(args) {
1994
+ if (args.length === 0) return "void";
1995
+ const argsList = args.map((arg) => `${toCamelCase4(arg.name)}: ${mapClarityTypeToTS(arg.type)}`).join("; ");
1996
+ return `{ ${argsList} }`;
1997
+ }
1998
+ function generateQueryKeyArgs(args) {
1999
+ if (args.length === 0) return "";
2000
+ return args.map((arg) => toCamelCase4(arg.name)).join(", ");
2001
+ }
2002
+ function generateFunctionCallArgs(args) {
2003
+ if (args.length === 0) return "";
2004
+ return args.map((arg) => toCamelCase4(arg.name)).join(", ");
2005
+ }
2006
+ function generateEnabledCondition(args) {
2007
+ return args.map((arg) => {
2008
+ const camelName = toCamelCase4(arg.name);
2009
+ const type = mapClarityTypeToTS(arg.type);
2010
+ if (type === "string") return `!!${camelName}`;
2011
+ if (type === "bigint") return `${camelName} !== undefined`;
2012
+ return `${camelName} !== undefined`;
2013
+ }).join(" && ");
2014
+ }
2015
+ function mapClarityTypeToTS(clarityType) {
2016
+ if (typeof clarityType !== "string") {
2017
+ if (clarityType?.uint || clarityType?.int) return "bigint";
2018
+ if (clarityType?.principal) return "string";
2019
+ if (clarityType?.bool) return "boolean";
2020
+ if (clarityType?.string || clarityType?.ascii) return "string";
2021
+ if (clarityType?.buff) return "Uint8Array";
2022
+ if (clarityType?.optional) {
2023
+ const innerType = mapClarityTypeToTS(clarityType.optional);
2024
+ return `${innerType} | null`;
2025
+ }
2026
+ if (clarityType?.response) return "any";
2027
+ if (clarityType?.tuple) return "any";
2028
+ if (clarityType?.list) return "any[]";
2029
+ return "any";
2030
+ }
2031
+ if (clarityType.includes("uint") || clarityType.includes("int"))
2032
+ return "bigint";
2033
+ if (clarityType.includes("principal")) return "string";
2034
+ if (clarityType.includes("bool")) return "boolean";
2035
+ if (clarityType.includes("string") || clarityType.includes("ascii"))
2036
+ return "string";
2037
+ if (clarityType.includes("buff")) return "Uint8Array";
2038
+ if (clarityType.includes("optional")) {
2039
+ const innerType = clarityType.replace(/optional\s*/, "").trim();
2040
+ return `${mapClarityTypeToTS(innerType)} | null`;
2041
+ }
2042
+ if (clarityType.includes("response")) return "any";
2043
+ if (clarityType.includes("tuple")) return "any";
2044
+ if (clarityType.includes("list")) return "any[]";
2045
+ return "any";
2046
+ }
2047
+ function generateObjectArgs(args) {
2048
+ if (args.length === 0) return "";
2049
+ return args.map((arg) => `${arg.name}: ${toCamelCase4(arg.name)}`).join(", ");
2050
+ }
2051
+
2052
+ // src/plugins/react/generators/contract.ts
2053
+ async function generateContractHooks(contracts, excludeList = []) {
2054
+ const imports = `import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
2055
+ import { useCallback } from 'react'
2056
+ import { useStacksConfig } from './provider'
2057
+ import { request, openContractCall as stacksOpenContractCall } from '@stacks/connect'
2058
+ import { ${contracts.map((c) => c.name).join(", ")} } from './contracts'`;
2059
+ const header = `/**
2060
+ * Generated contract-specific React hooks
2061
+ * DO NOT EDIT MANUALLY
2062
+ */`;
2063
+ const hooksCode = contracts.map((contract) => generateContractHookMethods(contract, excludeList)).filter(Boolean).join("\n\n");
2064
+ const code = `${imports}
2065
+
2066
+ ${header}
2067
+
2068
+ ${hooksCode}`;
2069
+ const formatted = await format5(code, {
2070
+ parser: "typescript",
2071
+ singleQuote: true,
2072
+ semi: false,
2073
+ printWidth: 100,
2074
+ trailingComma: "es5"
2075
+ });
2076
+ return formatted;
2077
+ }
2078
+ function generateContractHookMethods(contract, excludeList) {
2079
+ const { abi, name } = contract;
2080
+ const functions = abi.functions || [];
2081
+ const readOnlyFunctions = functions.filter(
2082
+ (f) => f.access === "read_only" || f.access === "read-only"
2083
+ );
2084
+ const publicFunctions = functions.filter(
2085
+ (f) => f.access === "public"
2086
+ );
2087
+ const readHooks = readOnlyFunctions.map((func) => {
2088
+ const hookName = `use${capitalize(name)}${capitalize(toCamelCase4(func.name))}`;
2089
+ if (excludeList.includes(hookName)) {
2090
+ return null;
2091
+ }
2092
+ return generateReadHook(func, name);
2093
+ }).filter(Boolean);
2094
+ const writeHooks = publicFunctions.map((func) => {
2095
+ const hookName = `use${capitalize(name)}${capitalize(toCamelCase4(func.name))}`;
2096
+ if (excludeList.includes(hookName)) {
2097
+ return null;
2098
+ }
2099
+ return generateWriteHook(func, name);
2100
+ }).filter(Boolean);
2101
+ const allHooks = [...readHooks, ...writeHooks];
2102
+ if (allHooks.length === 0) {
2103
+ return "";
2104
+ }
2105
+ return allHooks.join("\n\n");
2106
+ }
2107
+ function generateReadHook(func, contractName) {
2108
+ const hookName = `use${capitalize(contractName)}${capitalize(toCamelCase4(func.name))}`;
2109
+ const argsSignature = generateHookArgsSignature(func.args);
2110
+ const enabledParam = func.args.length > 0 ? ", options?: { enabled?: boolean }" : "options?: { enabled?: boolean }";
2111
+ return `export function ${hookName}(${argsSignature}${enabledParam}) {
2112
+ const config = useStacksConfig()
2113
+
2114
+ return useQuery({
2115
+ queryKey: ['${func.name}', ${contractName}.address, ${generateQueryKeyArgs(func.args)}],
2116
+ queryFn: () => ${contractName}.read.${toCamelCase4(func.name)}(${generateFunctionCallArgs(func.args) ? `{ ${generateObjectArgs(func.args)} }, ` : ""}{
2117
+ network: config.network,
2118
+ senderAddress: config.senderAddress || 'SP000000000000000000002Q6VF78'
2119
+ }),
2120
+ ${func.args.length > 0 ? `enabled: ${generateEnabledCondition(func.args)} && (options?.enabled ?? true),` : ""}
2121
+ ...options
2122
+ })
2123
+ }`;
2124
+ }
2125
+ function generateWriteHook(func, contractName) {
2126
+ const hookName = `use${capitalize(contractName)}${capitalize(toCamelCase4(func.name))}`;
2127
+ const argsType = generateArgsType(func.args);
2128
+ return `export function ${hookName}() {
2129
+ const config = useStacksConfig()
2130
+ const queryClient = useQueryClient()
2131
+
2132
+ const mutation = useMutation({
2133
+ mutationFn: async (params: {
2134
+ args: ${argsType};
2135
+ options?: {
2136
+ postConditions?: any[];
2137
+ attachment?: string;
2138
+ onFinish?: (data: any) => void;
2139
+ onCancel?: () => void;
2140
+ };
2141
+ }) => {
2142
+ const { args, options = {} } = params
2143
+ const contractCallData = ${contractName}.${toCamelCase4(func.name)}(args)
2144
+ const { contractAddress, contractName: name, functionName, functionArgs } = contractCallData
2145
+ const network = config.network || 'mainnet'
2146
+ const contract = \`\${contractAddress}.\${name}\`
2147
+
2148
+ // Try @stacks/connect v8 stx_callContract first (SIP-030)
2149
+ try {
2150
+ const result = await request('stx_callContract', {
2151
+ contract,
2152
+ functionName,
2153
+ functionArgs,
2154
+ network,
2155
+ ...options
2156
+ })
2157
+
2158
+ options.onFinish?.(result)
2159
+ return result
2160
+ } catch (connectError) {
2161
+ // Fallback to openContractCall for broader wallet compatibility
2162
+ console.warn('stx_callContract not supported, falling back to openContractCall:', connectError)
2163
+
2164
+ return new Promise((resolve, reject) => {
2165
+ stacksOpenContractCall({
2166
+ contractAddress,
2167
+ contractName: name,
2168
+ functionName,
2169
+ functionArgs,
2170
+ network,
2171
+ ...options,
2172
+ onFinish: (data: any) => {
2173
+ options.onFinish?.(data)
2174
+ resolve(data)
2175
+ },
2176
+ onCancel: () => {
2177
+ options.onCancel?.()
2178
+ reject(new Error('User cancelled transaction'))
2179
+ }
2180
+ })
2181
+ })
2182
+ }
2183
+ },
2184
+ onSuccess: () => {
2185
+ // Invalidate relevant queries on success
2186
+ queryClient.invalidateQueries({ queryKey: ['stacks-account'] })
2187
+ },
2188
+ onError: (error) => {
2189
+ console.error('Contract call failed:', error)
2190
+ }
2191
+ })
2192
+
2193
+ const ${toCamelCase4(func.name)} = useCallback(async (
2194
+ args: ${argsType},
2195
+ options?: {
2196
+ postConditions?: any[];
2197
+ attachment?: string;
2198
+ onFinish?: (data: any) => void;
2199
+ onCancel?: () => void;
2200
+ }
2201
+ ) => {
2202
+ return mutation.mutateAsync({ args, options })
2203
+ }, [mutation])
2204
+
2205
+ return {
2206
+ ${toCamelCase4(func.name)},
2207
+ // Expose mutation state
2208
+ isPending: mutation.isPending,
2209
+ isError: mutation.isError,
2210
+ isSuccess: mutation.isSuccess,
2211
+ error: mutation.error,
2212
+ data: mutation.data,
2213
+ reset: mutation.reset
2214
+ }
2215
+ }`;
2216
+ }
2217
+
2218
+ // src/plugins/react/index.ts
2219
+ var react = (options = {}) => {
2220
+ const excludeList = options.exclude || [];
2221
+ return {
2222
+ name: "@stacks/codegen/plugin-react",
2223
+ version: "1.0.0",
2224
+ async generate(context) {
2225
+ if (options.debug) {
2226
+ context.logger.debug(
2227
+ `React plugin generating hooks (excluding: ${excludeList.join(", ") || "none"})`
2228
+ );
2229
+ }
2230
+ const provider = await generateProvider();
2231
+ context.addOutput("provider", {
2232
+ path: "./src/generated/provider.tsx",
2233
+ content: provider,
2234
+ type: "config"
2235
+ });
2236
+ const genericHooks = await generateGenericHooks(excludeList);
2237
+ context.addOutput("generic-hooks", {
2238
+ path: "./src/generated/hooks.ts",
2239
+ content: genericHooks,
2240
+ type: "hooks"
2241
+ });
2242
+ if (context.contracts.length > 0) {
2243
+ const contractHooks = await generateContractHooks(
2244
+ context.contracts,
2245
+ excludeList
2246
+ );
2247
+ if (contractHooks.trim()) {
2248
+ context.addOutput("contract-hooks", {
2249
+ path: "./src/generated/contract-hooks.ts",
2250
+ content: contractHooks,
2251
+ type: "hooks"
2252
+ });
2253
+ }
2254
+ }
2255
+ if (options.debug) {
2256
+ context.logger.success(
2257
+ `React plugin generated ${context.contracts.length} contract hook sets`
2258
+ );
2259
+ }
2260
+ }
2261
+ };
2262
+ };
2263
+
2264
+ // src/utils/api.ts
2265
+ import got from "got";
2266
+ var API_URLS = {
2267
+ mainnet: "https://api.hiro.so",
2268
+ testnet: "https://api.testnet.hiro.so",
2269
+ devnet: "http://localhost:3999"
2270
+ };
2271
+ var StacksApiClient = class {
2272
+ constructor(network = "mainnet", apiKey, apiUrl) {
2273
+ this.baseUrl = apiUrl || API_URLS[network];
2274
+ this.headers = apiKey ? { "x-api-key": apiKey } : {};
2275
+ }
2276
+ async getContractInfo(contractId) {
2277
+ const [address, contractName] = contractId.split(".");
2278
+ if (!address || !contractName) {
2279
+ throw new Error(
2280
+ `Invalid contract ID format: ${contractId}. Expected format: ADDRESS.CONTRACT_NAME`
2281
+ );
2282
+ }
2283
+ const url = `${this.baseUrl}/v2/contracts/interface/${address}/${contractName}`;
2284
+ try {
2285
+ const response = await got(url, {
2286
+ headers: this.headers,
2287
+ responseType: "json"
2288
+ });
2289
+ return response.body;
2290
+ } catch (error) {
2291
+ if (error.response?.statusCode === 404) {
2292
+ throw new Error(`Contract not found: ${contractId}`);
2293
+ }
2294
+ if (error.response?.statusCode === 429) {
2295
+ throw new Error(
2296
+ "Rate limited. Please provide an API key in your config."
2297
+ );
2298
+ }
2299
+ throw new Error(`Failed to fetch contract: ${error.message}`);
2300
+ }
2301
+ }
2302
+ async getContractSource(contractId) {
2303
+ const [address, contractName] = contractId.split(".");
2304
+ if (!address || !contractName) {
2305
+ throw new Error(
2306
+ `Invalid contract ID format: ${contractId}. Expected format: ADDRESS.CONTRACT_NAME`
2307
+ );
2308
+ }
2309
+ const url = `${this.baseUrl}/v2/contracts/source/${address}/${contractName}`;
2310
+ try {
2311
+ const response = await got(url, {
2312
+ headers: this.headers,
2313
+ responseType: "json"
2314
+ });
2315
+ const data = response.body;
2316
+ return data.source;
2317
+ } catch (error) {
2318
+ return "";
2319
+ }
2320
+ }
2321
+ };
2322
+
2323
+ // src/parsers/clarity.ts
2324
+ function parseType(typeStr) {
2325
+ typeStr = typeStr.replace(/[()]/g, "").trim();
2326
+ switch (typeStr) {
2327
+ case "uint":
2328
+ case "uint128":
2329
+ return "uint128";
2330
+ case "int":
2331
+ case "int128":
2332
+ return "int128";
2333
+ case "bool":
2334
+ return "bool";
2335
+ case "principal":
2336
+ return "principal";
2337
+ case "trait_reference":
2338
+ return "principal";
2339
+ default:
2340
+ if (typeStr.startsWith("string-ascii")) {
2341
+ return { "string-ascii": { length: 256 } };
2342
+ }
2343
+ if (typeStr.startsWith("string-utf8")) {
2344
+ return { "string-utf8": { length: 256 } };
2345
+ }
2346
+ if (typeStr.startsWith("buff")) {
2347
+ return { buff: { length: 32 } };
2348
+ }
2349
+ return "uint128";
2350
+ }
2351
+ }
2352
+ function parseApiResponse(apiResponse) {
2353
+ try {
2354
+ const functions = [];
2355
+ if (apiResponse.functions) {
2356
+ for (const func of apiResponse.functions) {
2357
+ const access = func.access === "read_only" ? "read-only" : func.access;
2358
+ functions.push({
2359
+ name: func.name,
2360
+ access,
2361
+ args: func.args.map((arg) => ({
2362
+ name: arg.name,
2363
+ type: convertApiType(arg.type)
2364
+ })),
2365
+ outputs: convertApiType(func.outputs.type)
2366
+ });
2367
+ }
2368
+ }
2369
+ return { functions };
2370
+ } catch (error) {
2371
+ throw new Error(`Failed to parse API response: ${error}`);
2372
+ }
2373
+ }
2374
+ function convertApiType(apiType) {
2375
+ if (typeof apiType === "string") {
2376
+ if (apiType === "trait_reference") {
2377
+ return "trait_reference";
2378
+ }
2379
+ return parseType(apiType) || "uint128";
2380
+ }
2381
+ if (apiType.response) {
2382
+ return {
2383
+ response: {
2384
+ ok: convertApiType(apiType.response.ok),
2385
+ error: convertApiType(apiType.response.error)
2386
+ }
2387
+ };
2388
+ }
2389
+ if (apiType.optional) {
2390
+ return {
2391
+ optional: convertApiType(apiType.optional)
2392
+ };
2393
+ }
2394
+ if (apiType.list) {
2395
+ return {
2396
+ list: {
2397
+ type: convertApiType(apiType.list.type),
2398
+ length: apiType.list.length || 100
2399
+ }
2400
+ };
2401
+ }
2402
+ if (apiType.tuple) {
2403
+ return {
2404
+ tuple: apiType.tuple.map((field) => ({
2405
+ name: field.name,
2406
+ type: convertApiType(field.type)
2407
+ }))
2408
+ };
2409
+ }
2410
+ if (apiType.buffer) {
2411
+ return {
2412
+ buff: {
2413
+ length: apiType.buffer.length || 32
2414
+ }
2415
+ };
2416
+ }
2417
+ if (apiType["string-ascii"]) {
2418
+ return {
2419
+ "string-ascii": {
2420
+ length: apiType["string-ascii"].length || 256
2421
+ }
2422
+ };
2423
+ }
2424
+ if (apiType["string-utf8"]) {
2425
+ return {
2426
+ "string-utf8": {
2427
+ length: apiType["string-utf8"].length || 256
2428
+ }
2429
+ };
2430
+ }
2431
+ if (apiType === "none") {
2432
+ return "uint128";
2433
+ }
2434
+ return "uint128";
2435
+ }
2436
+
2437
+ // src/plugins/hiro/index.ts
2438
+ var hiro = (options) => {
2439
+ if (!options?.apiKey) {
2440
+ throw new Error(
2441
+ "Hiro plugin requires an API key. Get one for free at https://platform.hiro.so/"
2442
+ );
2443
+ }
2444
+ if (!options.network) {
2445
+ throw new Error("Hiro plugin requires a network ('mainnet' or 'testnet')");
2446
+ }
2447
+ if (!options.contracts || options.contracts.length === 0) {
2448
+ throw new Error(
2449
+ "Hiro plugin requires a contracts array with contract IDs to fetch"
2450
+ );
2451
+ }
2452
+ return {
2453
+ name: "@stacks/codegen/plugin-hiro",
2454
+ version: "1.0.0",
2455
+ async transformConfig(config) {
2456
+ if (options.debug) {
2457
+ console.log(
2458
+ `\u{1F504} Hiro plugin: Fetching ABIs for ${options.contracts.length} contracts from ${options.network}`
2459
+ );
2460
+ }
2461
+ const apiClient = new StacksApiClient(options.network, options.apiKey);
2462
+ const fetchedContracts = [];
2463
+ for (const contractId of options.contracts) {
2464
+ const result = await fetchContractABI(
2465
+ contractId,
2466
+ apiClient,
2467
+ options.debug
2468
+ );
2469
+ if (result.success && result.abi) {
2470
+ const [address, contractName] = contractId.split(".");
2471
+ const name = contractName ? contractName.replace(/-/g, "_").replace(/^\d/, "_$&") : address.replace(/^SP|^ST/, "").toLowerCase();
2472
+ fetchedContracts.push({
2473
+ name,
2474
+ address: contractId,
2475
+ abi: result.abi,
2476
+ metadata: {
2477
+ source: "hiro-api",
2478
+ network: options.network,
2479
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
2480
+ }
2481
+ });
2482
+ if (options.debug) {
2483
+ console.log(
2484
+ `\u2705 Hiro plugin: Successfully fetched ABI for ${contractId}`
2485
+ );
2486
+ }
2487
+ } else {
2488
+ if (options.debug) {
2489
+ console.warn(
2490
+ `\u26A0\uFE0F Hiro plugin: Failed to fetch ${contractId}: ${result.error}`
2491
+ );
2492
+ }
2493
+ }
2494
+ }
2495
+ if (options.debug) {
2496
+ console.log(
2497
+ `\u{1F50D} Hiro plugin: Successfully fetched ${fetchedContracts.length}/${options.contracts.length} contracts`
2498
+ );
2499
+ }
2500
+ return {
2501
+ ...config,
2502
+ contracts: [...config.contracts || [], ...fetchedContracts]
2503
+ };
2504
+ }
2505
+ };
2506
+ };
2507
+ async function fetchContractABI(contractId, apiClient, debug) {
2508
+ try {
2509
+ if (debug) {
2510
+ console.log(`\u{1F504} Fetching ABI for ${contractId}`);
2511
+ }
2512
+ const contractInfo = await apiClient.getContractInfo(contractId);
2513
+ const abi = parseApiResponse(contractInfo);
2514
+ return {
2515
+ success: true,
2516
+ contractId,
2517
+ abi
2518
+ };
2519
+ } catch (error) {
2520
+ if (error.message?.includes("Contract not found") || error.response?.statusCode === 404) {
2521
+ return {
2522
+ success: false,
2523
+ contractId,
2524
+ error: `Contract not found: ${contractId}`
2525
+ };
2526
+ }
2527
+ if (error.message?.includes("Rate limited") || error.response?.statusCode === 429) {
2528
+ return {
2529
+ success: false,
2530
+ contractId,
2531
+ error: `Rate limited when fetching ${contractId}. Consider using an API key.`
2532
+ };
2533
+ }
2534
+ return {
2535
+ success: false,
2536
+ contractId,
2537
+ error: error.message || "Unknown error"
2538
+ };
2539
+ }
2540
+ }
2541
+
2542
+ // src/plugins/index.ts
2543
+ function filterByOptions(items, options = {}) {
2544
+ let filtered = items;
2545
+ if (options.include && options.include.length > 0) {
2546
+ filtered = filtered.filter(
2547
+ (item) => options.include.some(
2548
+ (pattern) => item.name.includes(pattern) || item.name.match(new RegExp(pattern))
2549
+ )
2550
+ );
2551
+ }
2552
+ if (options.exclude && options.exclude.length > 0) {
2553
+ filtered = filtered.filter(
2554
+ (item) => !options.exclude.some(
2555
+ (pattern) => item.name.includes(pattern) || item.name.match(new RegExp(pattern))
2556
+ )
2557
+ );
2558
+ }
2559
+ return filtered;
2560
+ }
2561
+ function createPlugin(name, version, implementation) {
2562
+ return {
2563
+ name,
2564
+ version,
2565
+ ...implementation
2566
+ };
2567
+ }
2568
+ export {
2569
+ PluginManager,
2570
+ actions,
2571
+ clarinet,
2572
+ createPlugin,
2573
+ filterByOptions,
2574
+ hasClarinetProject,
2575
+ hiro,
2576
+ react
2577
+ };
2578
+ //# sourceMappingURL=index.js.map