@clarigen/cli 0.3.3 → 1.0.0-next.10

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,16 @@
1
+ import * as _oclif_parser_lib_flags from '@oclif/parser/lib/flags';
2
+ import { Command } from '@oclif/command';
3
+
4
+ declare class Generate extends Command {
5
+ static description: string;
6
+ static strict: boolean;
7
+ static hidden: boolean;
8
+ static flags: {
9
+ help: _oclif_parser_lib_flags.IBooleanFlag<void>;
10
+ watch: _oclif_parser_lib_flags.IBooleanFlag<boolean>;
11
+ };
12
+ static args: any[];
13
+ run(): Promise<void>;
14
+ }
15
+
16
+ export { Generate };
@@ -1,65 +1,74 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Generate = void 0;
4
- const command_1 = require("@oclif/command");
5
- const utils_1 = require("../utils");
6
- const config_1 = require("../config");
7
- const chokidar_1 = require("chokidar");
8
- const path_1 = require("path");
9
- const chalk_1 = require("chalk");
10
- // eslint-disable-next-line @typescript-eslint/no-var-requires
11
- const ora = require('ora');
12
- class Generate extends command_1.Command {
13
- async run() {
14
- const { flags } = this.parse(Generate);
15
- const cwd = process.cwd();
16
- if (flags.watch) {
17
- const spinner = ora('Generating files').start();
18
- const { contractsDir } = await config_1.getConfigFile(cwd);
19
- const watcher = chokidar_1.watch([contractsDir], {
20
- cwd,
21
- });
22
- try {
23
- await utils_1.generateProject(cwd);
24
- spinner.succeed(`Finished generating files. Watching for changes.`);
25
- }
26
- catch (error) {
27
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
28
- spinner.fail(`Error generating files.\n${error.message}`);
29
- }
30
- watcher.on('change', async (path) => {
31
- const file = path_1.basename(path);
32
- spinner.clear();
33
- spinner.start(`Change detected for ${chalk_1.green(file)}, generating.`);
34
- try {
35
- await utils_1.generateProject(cwd);
36
- spinner.succeed(`Finished generating files for ${chalk_1.green(file)}. Watching for changes.`);
37
- }
38
- catch (error) {
39
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
40
- const msg = error.message;
41
- spinner.fail(`Error after saving ${chalk_1.red(file)}.\n${msg}`);
42
- }
43
- });
44
- process.on('SIGINT', async () => {
45
- await watcher.close();
46
- process.exit();
47
- });
48
- }
49
- else {
50
- await utils_1.generateProject(cwd);
51
- }
52
- }
1
+ var P=Object.defineProperty,at=Object.defineProperties,lt=Object.getOwnPropertyDescriptor,ft=Object.getOwnPropertyDescriptors,pt=Object.getOwnPropertyNames,A=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var L=(t,n,r)=>n in t?P(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,x=(t,n)=>{for(var r in n||(n={}))v.call(n,r)&&L(t,r,n[r]);if(A)for(var r of A(n))R.call(n,r)&&L(t,r,n[r]);return t},T=(t,n)=>at(t,ft(n));var U=(t,n)=>{var r={};for(var e in t)v.call(t,e)&&n.indexOf(e)<0&&(r[e]=t[e]);if(t!=null&&A)for(var e of A(t))n.indexOf(e)<0&&R.call(t,e)&&(r[e]=t[e]);return r};var gt=(t,n)=>{for(var r in n)P(t,r,{get:n[r],enumerable:!0})},ut=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of pt(n))!v.call(t,o)&&o!==r&&P(t,o,{get:()=>n[o],enumerable:!(e=lt(n,o))||e.enumerable});return t};var mt=t=>ut(P({},"__esModule",{value:!0}),t);var Tt={};gt(Tt,{Generate:()=>C});module.exports=mt(Tt);var b=require("@oclif/command");var Y=require("@clarigen/native-bin"),d=require("@clarigen/core"),k=require("path");var Ft=require("@oclif/command");var y=require("path"),N=require("fs/promises"),H=require("fs");var D=require("@ltd/j-toml"),O=require("path"),_=require("fs/promises"),E=require("micro-stacks/wallet-sdk"),W=require("toposort"),V=require("micro-stacks/crypto");async function Ct(t){let n=(0,O.resolve)(t,"settings","Devnet.toml"),r=await(0,_.readFile)(n,{encoding:"utf-8"});return(0,D.parse)(r,1,`
2
+ `,!0,{longer:!0})}async function yt(t){let n=(0,O.resolve)(t,"Clarinet.toml"),r=await(0,_.readFile)(n,{encoding:"utf-8"});return(0,D.parse)(r,1,`
3
+ `,!0)}async function K(t,n){let r=await yt(t),e=n.deployer.address;return dt(r.contracts).map(c=>({file:r.contracts[c].path.replace(/^contracts\//,""),address:e,name:c}))}function dt(t){let n=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(c=>n.push([o,c]))}),(0,W.array)(r,n).reverse()}async function M(t){let n=await Ct(t),r=await Promise.all(Object.entries(n.accounts).map(async([o,i])=>{let c=await(0,E.generateWallet)(i.mnemonic,"password"),[s]=c.accounts,l=(0,E.getStxAddressFromAccount)(s,V.StacksNetworkVersion.testnetP2PKH);return[o,T(x({},i),{address:l})]}));return Object.fromEntries(r)}var q={outputDir:"src/clarigen",clarinet:"."};function $t(t){return(0,y.resolve)(t,"clarigen.config.json")}async function xt(t){try{return await(0,N.access)(t,H.constants.R_OK),!0}catch{return!1}}async function wt(t){let n=$t(t);if(await xt(n)){let e=await(0,N.readFile)(n,{encoding:"utf-8"}),o=JSON.parse(e);return x(x({},q),o)}return q}async function j(t){let n=await wt(t),r=(0,y.resolve)(t,n.clarinet||"."),e=await M(r),o=await K(r,e),i=(0,y.relative)(process.cwd(),(0,y.join)(n.clarinet,"contracts"));return T(x({},n),{contracts:o,contractsDir:i,accounts:e,clarinet:n.clarinet||"."})}var f=require("micro-stacks/transactions"),I=require("@clarigen/core"),Q=require("reserved-words"),g=(t,n=!1)=>{if((0,f.isClarityAbiPrimitive)(t)){if(t==="uint128")return n?"number | bigint":"bigint";if(t==="int128")return n?"number | bigint":"bigint";if(t==="bool")return"boolean";if(t==="principal")return"string";if(t==="none")return"null";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(t)}`)}else{if((0,f.isClarityAbiBuffer)(t))return"Uint8Array";if((0,f.isClarityAbiResponse)(t)){let r=g(t.response.ok),e=g(t.response.error);return`ClarityTypes.Response<${r}, ${e}>`}else{if((0,f.isClarityAbiOptional)(t))return`${g(t.optional)} | null`;if((0,f.isClarityAbiTuple)(t)){let r=[];return t.tuple.forEach(({name:e,type:o})=>{let i=g(o);r.push(`"${e}": ${i}`)}),`{
4
+ ${r.join(`;
5
+ `)}
6
+ }`}else{if((0,f.isClarityAbiList)(t))return`${g(t.list.type)}[]`;if((0,f.isClarityAbiStringAscii)(t))return"string";if((0,f.isClarityAbiStringUtf8)(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function bt(t){let n=(0,I.toCamelCase)(t);return`${(0,Q.check)(n,6)?"_":""}${n}`}var ht={public:"Public",read_only:"ReadOnly",private:"Private"};function X(t){let n="";return t.functions.forEach((r,e)=>{let o=`${(0,I.toCamelCase)(r.name)}: `;if(o+=`(${r.args.map(s=>`${bt(s.name)}: ${g(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${ht[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!(0,f.isClarityAbiResponse)(s))throw new Error("Expected response type for public function");let l=g(s.response.ok),a=g(s.response.error);o+=`${l}, ${a}>;`}else o+=`${g(r.outputs.type)}>;`;n+=`${e===0?"":`
7
+ `} ${o}`}),t.maps.forEach(r=>{let e=`${(0,I.toCamelCase)(r.name)}: `,o=g(r.key,!0),i=`key: ${o}`,c=g(r.value);e+=`(${i}) => ContractCalls.Map<${o}, ${c}>;`,n+=`
8
+ ${e}`}),n}var Z=async({provider:t,contractFile:n,contractAddress:r,contractName:e})=>{let o=await t.runCommand(["launch",`${r}.${e}`,n,t.dbFilePath,"--output_analysis","--costs","--assets"]);if((0,Y.hasStdErr)(o.stderr))throw new Error(`Error on ${n}:
9
+ ${o.stderr}
10
+ `);let i=JSON.parse(o.stdout);if(i.error){let{initialization:s}=i.error;if(s!=null&&s.includes(`
11
+ Near:
12
+ `)){let[l,a]=s.split(`
13
+ Near:
14
+ `),u="",F=/start_line: (\d+),/.exec(a);throw F&&(u=F[1]),new Error(`Error on ${n}:
15
+ ${l}
16
+ ${u?`Near line ${u}`:""}
17
+ Raw trace:
18
+ ${a}
19
+ `)}throw new Error(`Error on ${n}:
20
+ ${JSON.stringify(i.error,null,2)}
21
+ `)}return i.analysis},z=({contractName:t,abi:n})=>{let r=(0,d.toCamelCase)(t,!0),s=n,{clarity_version:e}=s,o=U(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
22
+
23
+ // prettier-ignore
24
+ export const ${r}Interface: ClarityAbi = ${i};
25
+ `},G=({contractFile:t,contractAddress:n,contractName:r})=>{let e=(0,d.toCamelCase)(r,!0),o=(0,d.toCamelCase)(r),i=`${e}Contract`,c=`${e}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
+ import type { ${i} } from './types';
27
+ import { ${c} } from './abi';
28
+ export type { ${i} } from './types';
29
+
30
+ export function ${o}Contract(contractAddress: string, contractName: string) {
31
+ return pureProxy<${i}>({
32
+ abi: ${c},
33
+ contractAddress,
34
+ contractName,
35
+ });
53
36
  }
54
- exports.Generate = Generate;
55
- Generate.description = `Generate project files`;
56
- Generate.strict = true;
57
- Generate.hidden = false;
58
- Generate.flags = {
59
- help: command_1.flags.help({ char: 'h' }),
60
- watch: command_1.flags.boolean({
61
- char: 'w',
62
- description: 'Watch for changes to your contracts',
63
- }),
37
+
38
+ export const ${o}Info: Contract<${i}> = {
39
+ contract: ${o}Contract,
40
+ address: '${n}',
41
+ contractFile: '${t}',
42
+ name: '${r}',
43
+ abi: ${c},
64
44
  };
65
- Generate.args = [];
45
+ `},tt=(t,n)=>{let r=(0,d.toCamelCase)(n,!0),e=X(t);return`import { ClarityTypes, ContractCalls } from '@clarigen/core';
46
+
47
+ // prettier-ignore
48
+ export interface ${r}Contract {
49
+ ${e}
50
+ }
51
+ `},rt=t=>{let n=["import type { ContractInstances } from '@clarigen/core';"],r=[],e=[],o="";"accounts"in t&&(o=`
52
+
53
+ // prettier-ignore
54
+ export const accounts = {
55
+ ${Object.keys(t.accounts).map(l=>{let a=t.accounts[l];return`"${l}": {
56
+ mnemonic: "${a.mnemonic}",
57
+ balance: ${a.balance.toString()}n,
58
+ address: "${a.address}",
59
+ },`}).join(`
60
+ `)}
61
+ };`),t.contracts.forEach(s=>{let l=s.name,a=(0,d.toCamelCase)(l),u=`${a}Info`,m=`${(0,d.toCamelCase)(l,!0)}Contract`,F=(0,k.dirname)(s.file),J=`'./${(0,k.join)(F||".",l)}'`,it=`import { ${u} } from ${J};`;n.push(it);let st=`export type { ${m} } from ${J};`;r.push(st);let ct=`${a}: ${u},`;e.push(ct)});let i=`
62
+ export type Contracts = ContractInstances<typeof contracts>;
63
+ `;return`${n.join(`
64
+ `)}
65
+ ${r.join(`
66
+ `)}
67
+ ${i}
68
+ export const contracts = {
69
+ ${e.join(`
70
+ `)}
71
+ };${o}
72
+ `};var nt=require("@clarigen/native-bin"),p=require("path"),$=require("fs/promises");var At=async({contractFile:t,outputFolder:n,provider:r,contractAddress:e,dirName:o,contractName:i})=>{let c=(0,p.resolve)(process.cwd(),t),s=await Z({contractFile:c,provider:r,contractAddress:e,contractName:i}),l=tt(s,i),a=G({contractFile:(0,p.relative)(process.cwd(),c),contractAddress:e,contractName:i}),u=z({contractName:i,abi:s}),m=(0,p.resolve)(n,o||".",i);await(0,$.mkdir)(m,{recursive:!0}),await(0,$.writeFile)((0,p.resolve)(m,"abi.ts"),u),await(0,$.writeFile)((0,p.resolve)(m,"index.ts"),a),await(0,$.writeFile)((0,p.resolve)(m,"types.ts"),l)},S=async t=>{let n=await j(t),{contractsDir:r,outputDir:e,contracts:o}=n,i=(0,p.resolve)(t,e),c=await(0,nt.createClarityBin)();for(let a of o){let u=(0,p.resolve)(t,r,a.file),m=(0,p.dirname)(a.file);await At({contractFile:u,outputFolder:i,provider:c,contractAddress:a.address,dirName:m,contractName:a.name})}let s=rt(n),l=(0,p.resolve)(i,"index.ts");await(0,$.writeFile)(l,s)};var et=require("chokidar"),ot=require("path"),h=require("chalk"),Pt=require("ora"),B=class extends b.Command{async run(){let{flags:n}=this.parse(B),r=process.cwd();if(n.watch){let e=Pt("Generating files").start(),{contractsDir:o}=await j(r),i=(0,et.watch)([o],{cwd:r});try{await S(r),e.succeed("Finished generating files. Watching for changes.")}catch(c){e.fail(`Error generating files.
73
+ ${c.message}`)}i.on("change",async c=>{let s=(0,ot.basename)(c);e.clear(),e.start(`Change detected for ${(0,h.green)(s)}, generating.`);try{await S(r),e.succeed(`Finished generating files for ${(0,h.green)(s)}. Watching for changes.`)}catch(l){let a=l.message;e.fail(`Error after saving ${(0,h.red)(s)}.
74
+ ${a}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await S(r)}},C=B;C.description="Generate project files",C.strict=!0,C.hidden=!1,C.flags={help:b.flags.help({char:"h"}),watch:b.flags.boolean({char:"w",description:"Watch for changes to your contracts"})},C.args=[];0&&(module.exports={Generate});
@@ -0,0 +1,74 @@
1
+ var Z=Object.defineProperty,z=Object.defineProperties;var G=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var N=(t,n,r)=>n in t?Z(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,C=(t,n)=>{for(var r in n||(n={}))j.call(n,r)&&N(t,r,n[r]);if(w)for(var r of w(n))I.call(n,r)&&N(t,r,n[r]);return t},b=(t,n)=>z(t,G(n));var tt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(n,r)=>(typeof require!="undefined"?require:n)[r]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var k=(t,n)=>{var r={};for(var e in t)j.call(t,e)&&n.indexOf(e)<0&&(r[e]=t[e]);if(t!=null&&w)for(var e of w(t))n.indexOf(e)<0&&I.call(t,e)&&(r[e]=t[e]);return r};import{Command as Dt,flags as q}from"@oclif/command";import{hasStdErr as Tt}from"@clarigen/native-bin";import{toCamelCase as $}from"@clarigen/core";import{dirname as Et,join as Nt}from"path";import{run as sr}from"@oclif/command";import{resolve as J,join as at,relative as lt}from"path";import{readFile as ft,access as pt}from"fs/promises";import{constants as gt}from"fs";import{parse as S}from"@ltd/j-toml";import{resolve as v}from"path";import{readFile as D}from"fs/promises";import{generateWallet as rt,getStxAddressFromAccount as nt}from"micro-stacks/wallet-sdk";import{array as et}from"toposort";import{StacksNetworkVersion as ot}from"micro-stacks/crypto";async function it(t){let n=v(t,"settings","Devnet.toml"),r=await D(n,{encoding:"utf-8"});return S(r,1,`
2
+ `,!0,{longer:!0})}async function st(t){let n=v(t,"Clarinet.toml"),r=await D(n,{encoding:"utf-8"});return S(r,1,`
3
+ `,!0)}async function O(t,n){let r=await st(t),e=n.deployer.address;return ct(r.contracts).map(c=>({file:r.contracts[c].path.replace(/^contracts\//,""),address:e,name:c}))}function ct(t){let n=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(c=>n.push([o,c]))}),et(r,n).reverse()}async function _(t){let n=await it(t),r=await Promise.all(Object.entries(n.accounts).map(async([o,i])=>{let c=await rt(i.mnemonic,"password"),[s]=c.accounts,l=nt(s,ot.testnetP2PKH);return[o,b(C({},i),{address:l})]}));return Object.fromEntries(r)}var B={outputDir:"src/clarigen",clarinet:"."};function ut(t){return J(t,"clarigen.config.json")}async function mt(t){try{return await pt(t,gt.R_OK),!0}catch{return!1}}async function Ct(t){let n=ut(t);if(await mt(n)){let e=await ft(n,{encoding:"utf-8"}),o=JSON.parse(e);return C(C({},B),o)}return B}async function h(t){let n=await Ct(t),r=J(t,n.clarinet||"."),e=await _(r),o=await O(r,e),i=lt(process.cwd(),at(n.clarinet,"contracts"));return b(C({},n),{contracts:o,contractsDir:i,accounts:e,clarinet:n.clarinet||"."})}import{isClarityAbiBuffer as yt,isClarityAbiList as dt,isClarityAbiOptional as $t,isClarityAbiPrimitive as xt,isClarityAbiResponse as L,isClarityAbiStringAscii as wt,isClarityAbiStringUtf8 as bt,isClarityAbiTuple as ht}from"micro-stacks/transactions";import{toCamelCase as P}from"@clarigen/core";import{check as Ft}from"reserved-words";var f=(t,n=!1)=>{if(xt(t)){if(t==="uint128")return n?"number | bigint":"bigint";if(t==="int128")return n?"number | bigint":"bigint";if(t==="bool")return"boolean";if(t==="principal")return"string";if(t==="none")return"null";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(t)}`)}else{if(yt(t))return"Uint8Array";if(L(t)){let r=f(t.response.ok),e=f(t.response.error);return`ClarityTypes.Response<${r}, ${e}>`}else{if($t(t))return`${f(t.optional)} | null`;if(ht(t)){let r=[];return t.tuple.forEach(({name:e,type:o})=>{let i=f(o);r.push(`"${e}": ${i}`)}),`{
4
+ ${r.join(`;
5
+ `)}
6
+ }`}else{if(dt(t))return`${f(t.list.type)}[]`;if(wt(t))return"string";if(bt(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function At(t){let n=P(t);return`${Ft(n,6)?"_":""}${n}`}var Pt={public:"Public",read_only:"ReadOnly",private:"Private"};function R(t){let n="";return t.functions.forEach((r,e)=>{let o=`${P(r.name)}: `;if(o+=`(${r.args.map(s=>`${At(s.name)}: ${f(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Pt[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!L(s))throw new Error("Expected response type for public function");let l=f(s.response.ok),a=f(s.response.error);o+=`${l}, ${a}>;`}else o+=`${f(r.outputs.type)}>;`;n+=`${e===0?"":`
7
+ `} ${o}`}),t.maps.forEach(r=>{let e=`${P(r.name)}: `,o=f(r.key,!0),i=`key: ${o}`,c=f(r.value);e+=`(${i}) => ContractCalls.Map<${o}, ${c}>;`,n+=`
8
+ ${e}`}),n}var U=async({provider:t,contractFile:n,contractAddress:r,contractName:e})=>{let o=await t.runCommand(["launch",`${r}.${e}`,n,t.dbFilePath,"--output_analysis","--costs","--assets"]);if(Tt(o.stderr))throw new Error(`Error on ${n}:
9
+ ${o.stderr}
10
+ `);let i=JSON.parse(o.stdout);if(i.error){let{initialization:s}=i.error;if(s!=null&&s.includes(`
11
+ Near:
12
+ `)){let[l,a]=s.split(`
13
+ Near:
14
+ `),p="",x=/start_line: (\d+),/.exec(a);throw x&&(p=x[1]),new Error(`Error on ${n}:
15
+ ${l}
16
+ ${p?`Near line ${p}`:""}
17
+ Raw trace:
18
+ ${a}
19
+ `)}throw new Error(`Error on ${n}:
20
+ ${JSON.stringify(i.error,null,2)}
21
+ `)}return i.analysis},W=({contractName:t,abi:n})=>{let r=$(t,!0),s=n,{clarity_version:e}=s,o=k(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
22
+
23
+ // prettier-ignore
24
+ export const ${r}Interface: ClarityAbi = ${i};
25
+ `},V=({contractFile:t,contractAddress:n,contractName:r})=>{let e=$(r,!0),o=$(r),i=`${e}Contract`,c=`${e}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
+ import type { ${i} } from './types';
27
+ import { ${c} } from './abi';
28
+ export type { ${i} } from './types';
29
+
30
+ export function ${o}Contract(contractAddress: string, contractName: string) {
31
+ return pureProxy<${i}>({
32
+ abi: ${c},
33
+ contractAddress,
34
+ contractName,
35
+ });
36
+ }
37
+
38
+ export const ${o}Info: Contract<${i}> = {
39
+ contract: ${o}Contract,
40
+ address: '${n}',
41
+ contractFile: '${t}',
42
+ name: '${r}',
43
+ abi: ${c},
44
+ };
45
+ `},K=(t,n)=>{let r=$(n,!0),e=R(t);return`import { ClarityTypes, ContractCalls } from '@clarigen/core';
46
+
47
+ // prettier-ignore
48
+ export interface ${r}Contract {
49
+ ${e}
50
+ }
51
+ `},M=t=>{let n=["import type { ContractInstances } from '@clarigen/core';"],r=[],e=[],o="";"accounts"in t&&(o=`
52
+
53
+ // prettier-ignore
54
+ export const accounts = {
55
+ ${Object.keys(t.accounts).map(l=>{let a=t.accounts[l];return`"${l}": {
56
+ mnemonic: "${a.mnemonic}",
57
+ balance: ${a.balance.toString()}n,
58
+ address: "${a.address}",
59
+ },`}).join(`
60
+ `)}
61
+ };`),t.contracts.forEach(s=>{let l=s.name,a=$(l),p=`${a}Info`,g=`${$(l,!0)}Contract`,x=Et(s.file),E=`'./${Nt(x||".",l)}'`,Q=`import { ${p} } from ${E};`;n.push(Q);let X=`export type { ${g} } from ${E};`;r.push(X);let Y=`${a}: ${p},`;e.push(Y)});let i=`
62
+ export type Contracts = ContractInstances<typeof contracts>;
63
+ `;return`${n.join(`
64
+ `)}
65
+ ${r.join(`
66
+ `)}
67
+ ${i}
68
+ export const contracts = {
69
+ ${e.join(`
70
+ `)}
71
+ };${o}
72
+ `};import{createClarityBin as jt}from"@clarigen/native-bin";import{resolve as u,relative as It,dirname as kt}from"path";import{mkdir as St,writeFile as F}from"fs/promises";var vt=async({contractFile:t,outputFolder:n,provider:r,contractAddress:e,dirName:o,contractName:i})=>{let c=u(process.cwd(),t),s=await U({contractFile:c,provider:r,contractAddress:e,contractName:i}),l=K(s,i),a=V({contractFile:It(process.cwd(),c),contractAddress:e,contractName:i}),p=W({contractName:i,abi:s}),g=u(n,o||".",i);await St(g,{recursive:!0}),await F(u(g,"abi.ts"),p),await F(u(g,"index.ts"),a),await F(u(g,"types.ts"),l)},A=async t=>{let n=await h(t),{contractsDir:r,outputDir:e,contracts:o}=n,i=u(t,e),c=await jt();for(let a of o){let p=u(t,r,a.file),g=kt(a.file);await vt({contractFile:p,outputFolder:i,provider:c,contractAddress:a.address,dirName:g,contractName:a.name})}let s=M(n),l=u(i,"index.ts");await F(l,s)};import{watch as Ot}from"chokidar";import{basename as _t}from"path";import{red as Bt,green as H}from"chalk";var Jt=tt("ora"),T=class extends Dt{async run(){let{flags:n}=this.parse(T),r=process.cwd();if(n.watch){let e=Jt("Generating files").start(),{contractsDir:o}=await h(r),i=Ot([o],{cwd:r});try{await A(r),e.succeed("Finished generating files. Watching for changes.")}catch(c){e.fail(`Error generating files.
73
+ ${c.message}`)}i.on("change",async c=>{let s=_t(c);e.clear(),e.start(`Change detected for ${H(s)}, generating.`);try{await A(r),e.succeed(`Finished generating files for ${H(s)}. Watching for changes.`)}catch(l){let a=l.message;e.fail(`Error after saving ${Bt(s)}.
74
+ ${a}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await A(r)}},m=T;m.description="Generate project files",m.strict=!0,m.hidden=!1,m.flags={help:q.help({char:"h"}),watch:q.boolean({char:"w",description:"Watch for changes to your contracts"})},m.args=[];export{m as Generate};
@@ -0,0 +1,62 @@
1
+ export { run } from '@oclif/command';
2
+ import { ClarityAbiType } from 'micro-stacks/clarity';
3
+ import { ClarityAbi } from '@clarigen/core';
4
+ import { NativeClarityBinProvider } from '@clarigen/native-bin';
5
+ export { Generate } from './commands/index.js';
6
+ import '@oclif/parser/lib/flags';
7
+
8
+ interface ClarinetConfigAccount {
9
+ mnemonic: string;
10
+ balance: bigint;
11
+ }
12
+ interface ClarinetAccount extends ClarinetConfigAccount {
13
+ address: string;
14
+ }
15
+ interface ClarinetAccounts {
16
+ deployer: ClarinetAccount;
17
+ [name: string]: ClarinetAccount;
18
+ }
19
+
20
+ interface ConfigContract {
21
+ address: string;
22
+ file: string;
23
+ name: string;
24
+ }
25
+ interface ConfigFileContents {
26
+ outputDir: string;
27
+ clarinet: string;
28
+ }
29
+ interface ConfigFile extends ConfigFileContents {
30
+ contractsDir: string;
31
+ contracts: ConfigContract[];
32
+ accounts: ClarinetAccounts;
33
+ clarinet: string;
34
+ }
35
+ declare const defaultConfigFile: ConfigFileContents;
36
+ declare function configFilePath(rootPath: string): string;
37
+ declare function configFileExists(configPath: string): Promise<boolean>;
38
+ declare function getConfigFile(rootPath: string): Promise<ConfigFileContents>;
39
+ declare function getProjectConfig(rootPath: string): Promise<ConfigFile>;
40
+
41
+ declare const jsTypeFromAbiType: (val: ClarityAbiType, isArgument?: boolean) => string;
42
+ declare function makePureTypes(abi: ClarityAbi): string;
43
+
44
+ declare const generateInterface: ({ provider, contractFile, contractAddress, contractName, }: {
45
+ contractFile: string;
46
+ provider: NativeClarityBinProvider;
47
+ contractAddress: string;
48
+ contractName: string;
49
+ }) => Promise<ClarityAbi>;
50
+ declare const generateInterfaceFile: ({ contractName, abi, }: {
51
+ contractName: string;
52
+ abi: ClarityAbi;
53
+ }) => string;
54
+ declare const generateIndexFile: ({ contractFile, contractAddress, contractName, }: {
55
+ contractFile: string;
56
+ contractAddress: string;
57
+ contractName: string;
58
+ }) => string;
59
+ declare const generateTypesFile: (abi: ClarityAbi, contractName: string) => string;
60
+ declare const generateProjectIndexFile: (config: ConfigFile) => string;
61
+
62
+ export { ConfigContract, ConfigFile, ConfigFileContents, configFileExists, configFilePath, defaultConfigFile, generateIndexFile, generateInterface, generateInterfaceFile, generateProjectIndexFile, generateTypesFile, getConfigFile, getProjectConfig, jsTypeFromAbiType, makePureTypes };
package/dist/index.js CHANGED
@@ -1,19 +1,74 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
1
+ var T=Object.defineProperty,gt=Object.defineProperties,ut=Object.getOwnPropertyDescriptor,mt=Object.getOwnPropertyDescriptors,Ct=Object.getOwnPropertyNames,P=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var q=(t,n,r)=>n in t?T(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,x=(t,n)=>{for(var r in n||(n={}))v.call(n,r)&&q(t,r,n[r]);if(P)for(var r of P(n))H.call(n,r)&&q(t,r,n[r]);return t},E=(t,n)=>gt(t,mt(n));var Q=(t,n)=>{var r={};for(var e in t)v.call(t,e)&&n.indexOf(e)<0&&(r[e]=t[e]);if(t!=null&&P)for(var e of P(t))n.indexOf(e)<0&&H.call(t,e)&&(r[e]=t[e]);return r};var yt=(t,n)=>{for(var r in n)T(t,r,{get:n[r],enumerable:!0})},dt=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Ct(n))!v.call(t,o)&&o!==r&&T(t,o,{get:()=>n[o],enumerable:!(e=ut(n,o))||e.enumerable});return t};var $t=t=>dt(T({},"__esModule",{value:!0}),t);var Tt={};yt(Tt,{Generate:()=>C,configFileExists:()=>rt,configFilePath:()=>tt,defaultConfigFile:()=>B,generateIndexFile:()=>U,generateInterface:()=>L,generateInterfaceFile:()=>R,generateProjectIndexFile:()=>V,generateTypesFile:()=>W,getConfigFile:()=>nt,getProjectConfig:()=>b,jsTypeFromAbiType:()=>g,makePureTypes:()=>J,run:()=>at.run});module.exports=$t(Tt);var at=require("@oclif/command");var y=require("path"),j=require("fs/promises"),G=require("fs");var D=require("@ltd/j-toml"),O=require("path"),_=require("fs/promises"),N=require("micro-stacks/wallet-sdk"),X=require("toposort"),Y=require("micro-stacks/crypto");async function xt(t){let n=(0,O.resolve)(t,"settings","Devnet.toml"),r=await(0,_.readFile)(n,{encoding:"utf-8"});return(0,D.parse)(r,1,`
2
+ `,!0,{longer:!0})}async function wt(t){let n=(0,O.resolve)(t,"Clarinet.toml"),r=await(0,_.readFile)(n,{encoding:"utf-8"});return(0,D.parse)(r,1,`
3
+ `,!0)}async function Z(t,n){let r=await wt(t),e=n.deployer.address;return bt(r.contracts).map(c=>({file:r.contracts[c].path.replace(/^contracts\//,""),address:e,name:c}))}function bt(t){let n=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(c=>n.push([o,c]))}),(0,X.array)(r,n).reverse()}async function z(t){let n=await xt(t),r=await Promise.all(Object.entries(n.accounts).map(async([o,i])=>{let c=await(0,N.generateWallet)(i.mnemonic,"password"),[s]=c.accounts,l=(0,N.getStxAddressFromAccount)(s,Y.StacksNetworkVersion.testnetP2PKH);return[o,E(x({},i),{address:l})]}));return Object.fromEntries(r)}var B={outputDir:"src/clarigen",clarinet:"."};function tt(t){return(0,y.resolve)(t,"clarigen.config.json")}async function rt(t){try{return await(0,j.access)(t,G.constants.R_OK),!0}catch{return!1}}async function nt(t){let n=tt(t);if(await rt(n)){let e=await(0,j.readFile)(n,{encoding:"utf-8"}),o=JSON.parse(e);return x(x({},B),o)}return B}async function b(t){let n=await nt(t),r=(0,y.resolve)(t,n.clarinet||"."),e=await z(r),o=await Z(r,e),i=(0,y.relative)(process.cwd(),(0,y.join)(n.clarinet,"contracts"));return E(x({},n),{contracts:o,contractsDir:i,accounts:e,clarinet:n.clarinet||"."})}var f=require("micro-stacks/transactions"),I=require("@clarigen/core"),et=require("reserved-words"),g=(t,n=!1)=>{if((0,f.isClarityAbiPrimitive)(t)){if(t==="uint128")return n?"number | bigint":"bigint";if(t==="int128")return n?"number | bigint":"bigint";if(t==="bool")return"boolean";if(t==="principal")return"string";if(t==="none")return"null";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(t)}`)}else{if((0,f.isClarityAbiBuffer)(t))return"Uint8Array";if((0,f.isClarityAbiResponse)(t)){let r=g(t.response.ok),e=g(t.response.error);return`ClarityTypes.Response<${r}, ${e}>`}else{if((0,f.isClarityAbiOptional)(t))return`${g(t.optional)} | null`;if((0,f.isClarityAbiTuple)(t)){let r=[];return t.tuple.forEach(({name:e,type:o})=>{let i=g(o);r.push(`"${e}": ${i}`)}),`{
4
+ ${r.join(`;
5
+ `)}
6
+ }`}else{if((0,f.isClarityAbiList)(t))return`${g(t.list.type)}[]`;if((0,f.isClarityAbiStringAscii)(t))return"string";if((0,f.isClarityAbiStringUtf8)(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function ht(t){let n=(0,I.toCamelCase)(t);return`${(0,et.check)(n,6)?"_":""}${n}`}var Ft={public:"Public",read_only:"ReadOnly",private:"Private"};function J(t){let n="";return t.functions.forEach((r,e)=>{let o=`${(0,I.toCamelCase)(r.name)}: `;if(o+=`(${r.args.map(s=>`${ht(s.name)}: ${g(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Ft[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!(0,f.isClarityAbiResponse)(s))throw new Error("Expected response type for public function");let l=g(s.response.ok),a=g(s.response.error);o+=`${l}, ${a}>;`}else o+=`${g(r.outputs.type)}>;`;n+=`${e===0?"":`
7
+ `} ${o}`}),t.maps.forEach(r=>{let e=`${(0,I.toCamelCase)(r.name)}: `,o=g(r.key,!0),i=`key: ${o}`,c=g(r.value);e+=`(${i}) => ContractCalls.Map<${o}, ${c}>;`,n+=`
8
+ ${e}`}),n}var ot=require("@clarigen/native-bin"),d=require("@clarigen/core"),k=require("path");var L=async({provider:t,contractFile:n,contractAddress:r,contractName:e})=>{let o=await t.runCommand(["launch",`${r}.${e}`,n,t.dbFilePath,"--output_analysis","--costs","--assets"]);if((0,ot.hasStdErr)(o.stderr))throw new Error(`Error on ${n}:
9
+ ${o.stderr}
10
+ `);let i=JSON.parse(o.stdout);if(i.error){let{initialization:s}=i.error;if(s!=null&&s.includes(`
11
+ Near:
12
+ `)){let[l,a]=s.split(`
13
+ Near:
14
+ `),u="",A=/start_line: (\d+),/.exec(a);throw A&&(u=A[1]),new Error(`Error on ${n}:
15
+ ${l}
16
+ ${u?`Near line ${u}`:""}
17
+ Raw trace:
18
+ ${a}
19
+ `)}throw new Error(`Error on ${n}:
20
+ ${JSON.stringify(i.error,null,2)}
21
+ `)}return i.analysis},R=({contractName:t,abi:n})=>{let r=(0,d.toCamelCase)(t,!0),s=n,{clarity_version:e}=s,o=Q(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
22
+
23
+ // prettier-ignore
24
+ export const ${r}Interface: ClarityAbi = ${i};
25
+ `},U=({contractFile:t,contractAddress:n,contractName:r})=>{let e=(0,d.toCamelCase)(r,!0),o=(0,d.toCamelCase)(r),i=`${e}Contract`,c=`${e}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
+ import type { ${i} } from './types';
27
+ import { ${c} } from './abi';
28
+ export type { ${i} } from './types';
29
+
30
+ export function ${o}Contract(contractAddress: string, contractName: string) {
31
+ return pureProxy<${i}>({
32
+ abi: ${c},
33
+ contractAddress,
34
+ contractName,
35
+ });
36
+ }
37
+
38
+ export const ${o}Info: Contract<${i}> = {
39
+ contract: ${o}Contract,
40
+ address: '${n}',
41
+ contractFile: '${t}',
42
+ name: '${r}',
43
+ abi: ${c},
11
44
  };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.run = void 0;
14
- var command_1 = require("@oclif/command");
15
- Object.defineProperty(exports, "run", { enumerable: true, get: function () { return command_1.run; } });
16
- __exportStar(require("./config"), exports);
17
- __exportStar(require("./generate/declaration"), exports);
18
- __exportStar(require("./generate/files"), exports);
19
- __exportStar(require("./commands"), exports);
45
+ `},W=(t,n)=>{let r=(0,d.toCamelCase)(n,!0),e=J(t);return`import { ClarityTypes, ContractCalls } from '@clarigen/core';
46
+
47
+ // prettier-ignore
48
+ export interface ${r}Contract {
49
+ ${e}
50
+ }
51
+ `},V=t=>{let n=["import type { ContractInstances } from '@clarigen/core';"],r=[],e=[],o="";"accounts"in t&&(o=`
52
+
53
+ // prettier-ignore
54
+ export const accounts = {
55
+ ${Object.keys(t.accounts).map(l=>{let a=t.accounts[l];return`"${l}": {
56
+ mnemonic: "${a.mnemonic}",
57
+ balance: ${a.balance.toString()}n,
58
+ address: "${a.address}",
59
+ },`}).join(`
60
+ `)}
61
+ };`),t.contracts.forEach(s=>{let l=s.name,a=(0,d.toCamelCase)(l),u=`${a}Info`,m=`${(0,d.toCamelCase)(l,!0)}Contract`,A=(0,k.dirname)(s.file),M=`'./${(0,k.join)(A||".",l)}'`,lt=`import { ${u} } from ${M};`;n.push(lt);let ft=`export type { ${m} } from ${M};`;r.push(ft);let pt=`${a}: ${u},`;e.push(pt)});let i=`
62
+ export type Contracts = ContractInstances<typeof contracts>;
63
+ `;return`${n.join(`
64
+ `)}
65
+ ${r.join(`
66
+ `)}
67
+ ${i}
68
+ export const contracts = {
69
+ ${e.join(`
70
+ `)}
71
+ };${o}
72
+ `};var h=require("@oclif/command");var it=require("@clarigen/native-bin"),p=require("path"),$=require("fs/promises");var At=async({contractFile:t,outputFolder:n,provider:r,contractAddress:e,dirName:o,contractName:i})=>{let c=(0,p.resolve)(process.cwd(),t),s=await L({contractFile:c,provider:r,contractAddress:e,contractName:i}),l=W(s,i),a=U({contractFile:(0,p.relative)(process.cwd(),c),contractAddress:e,contractName:i}),u=R({contractName:i,abi:s}),m=(0,p.resolve)(n,o||".",i);await(0,$.mkdir)(m,{recursive:!0}),await(0,$.writeFile)((0,p.resolve)(m,"abi.ts"),u),await(0,$.writeFile)((0,p.resolve)(m,"index.ts"),a),await(0,$.writeFile)((0,p.resolve)(m,"types.ts"),l)},S=async t=>{let n=await b(t),{contractsDir:r,outputDir:e,contracts:o}=n,i=(0,p.resolve)(t,e),c=await(0,it.createClarityBin)();for(let a of o){let u=(0,p.resolve)(t,r,a.file),m=(0,p.dirname)(a.file);await At({contractFile:u,outputFolder:i,provider:c,contractAddress:a.address,dirName:m,contractName:a.name})}let s=V(n),l=(0,p.resolve)(i,"index.ts");await(0,$.writeFile)(l,s)};var st=require("chokidar"),ct=require("path"),F=require("chalk"),Pt=require("ora"),K=class extends h.Command{async run(){let{flags:n}=this.parse(K),r=process.cwd();if(n.watch){let e=Pt("Generating files").start(),{contractsDir:o}=await b(r),i=(0,st.watch)([o],{cwd:r});try{await S(r),e.succeed("Finished generating files. Watching for changes.")}catch(c){e.fail(`Error generating files.
73
+ ${c.message}`)}i.on("change",async c=>{let s=(0,ct.basename)(c);e.clear(),e.start(`Change detected for ${(0,F.green)(s)}, generating.`);try{await S(r),e.succeed(`Finished generating files for ${(0,F.green)(s)}. Watching for changes.`)}catch(l){let a=l.message;e.fail(`Error after saving ${(0,F.red)(s)}.
74
+ ${a}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await S(r)}},C=K;C.description="Generate project files",C.strict=!0,C.hidden=!1,C.flags={help:h.flags.help({char:"h"}),watch:h.flags.boolean({char:"w",description:"Watch for changes to your contracts"})},C.args=[];0&&(module.exports={Generate,configFileExists,configFilePath,defaultConfigFile,generateIndexFile,generateInterface,generateInterfaceFile,generateProjectIndexFile,generateTypesFile,getConfigFile,getProjectConfig,jsTypeFromAbiType,makePureTypes,run});
package/dist/index.mjs ADDED
@@ -0,0 +1,74 @@
1
+ var Z=Object.defineProperty,z=Object.defineProperties;var G=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var N=(t,n,r)=>n in t?Z(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,C=(t,n)=>{for(var r in n||(n={}))j.call(n,r)&&N(t,r,n[r]);if(w)for(var r of w(n))I.call(n,r)&&N(t,r,n[r]);return t},b=(t,n)=>z(t,G(n));var tt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(n,r)=>(typeof require!="undefined"?require:n)[r]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var k=(t,n)=>{var r={};for(var e in t)j.call(t,e)&&n.indexOf(e)<0&&(r[e]=t[e]);if(t!=null&&w)for(var e of w(t))n.indexOf(e)<0&&I.call(t,e)&&(r[e]=t[e]);return r};import{run as Nr}from"@oclif/command";import{resolve as J,join as at,relative as lt}from"path";import{readFile as ft,access as pt}from"fs/promises";import{constants as gt}from"fs";import{parse as S}from"@ltd/j-toml";import{resolve as v}from"path";import{readFile as D}from"fs/promises";import{generateWallet as rt,getStxAddressFromAccount as nt}from"micro-stacks/wallet-sdk";import{array as et}from"toposort";import{StacksNetworkVersion as ot}from"micro-stacks/crypto";async function it(t){let n=v(t,"settings","Devnet.toml"),r=await D(n,{encoding:"utf-8"});return S(r,1,`
2
+ `,!0,{longer:!0})}async function st(t){let n=v(t,"Clarinet.toml"),r=await D(n,{encoding:"utf-8"});return S(r,1,`
3
+ `,!0)}async function O(t,n){let r=await st(t),e=n.deployer.address;return ct(r.contracts).map(c=>({file:r.contracts[c].path.replace(/^contracts\//,""),address:e,name:c}))}function ct(t){let n=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(c=>n.push([o,c]))}),et(r,n).reverse()}async function _(t){let n=await it(t),r=await Promise.all(Object.entries(n.accounts).map(async([o,i])=>{let c=await rt(i.mnemonic,"password"),[s]=c.accounts,l=nt(s,ot.testnetP2PKH);return[o,b(C({},i),{address:l})]}));return Object.fromEntries(r)}var B={outputDir:"src/clarigen",clarinet:"."};function ut(t){return J(t,"clarigen.config.json")}async function mt(t){try{return await pt(t,gt.R_OK),!0}catch{return!1}}async function Ct(t){let n=ut(t);if(await mt(n)){let e=await ft(n,{encoding:"utf-8"}),o=JSON.parse(e);return C(C({},B),o)}return B}async function h(t){let n=await Ct(t),r=J(t,n.clarinet||"."),e=await _(r),o=await O(r,e),i=lt(process.cwd(),at(n.clarinet,"contracts"));return b(C({},n),{contracts:o,contractsDir:i,accounts:e,clarinet:n.clarinet||"."})}import{isClarityAbiBuffer as yt,isClarityAbiList as dt,isClarityAbiOptional as $t,isClarityAbiPrimitive as xt,isClarityAbiResponse as L,isClarityAbiStringAscii as wt,isClarityAbiStringUtf8 as bt,isClarityAbiTuple as ht}from"micro-stacks/transactions";import{toCamelCase as P}from"@clarigen/core";import{check as Ft}from"reserved-words";var f=(t,n=!1)=>{if(xt(t)){if(t==="uint128")return n?"number | bigint":"bigint";if(t==="int128")return n?"number | bigint":"bigint";if(t==="bool")return"boolean";if(t==="principal")return"string";if(t==="none")return"null";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(t)}`)}else{if(yt(t))return"Uint8Array";if(L(t)){let r=f(t.response.ok),e=f(t.response.error);return`ClarityTypes.Response<${r}, ${e}>`}else{if($t(t))return`${f(t.optional)} | null`;if(ht(t)){let r=[];return t.tuple.forEach(({name:e,type:o})=>{let i=f(o);r.push(`"${e}": ${i}`)}),`{
4
+ ${r.join(`;
5
+ `)}
6
+ }`}else{if(dt(t))return`${f(t.list.type)}[]`;if(wt(t))return"string";if(bt(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function At(t){let n=P(t);return`${Ft(n,6)?"_":""}${n}`}var Pt={public:"Public",read_only:"ReadOnly",private:"Private"};function R(t){let n="";return t.functions.forEach((r,e)=>{let o=`${P(r.name)}: `;if(o+=`(${r.args.map(s=>`${At(s.name)}: ${f(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Pt[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!L(s))throw new Error("Expected response type for public function");let l=f(s.response.ok),a=f(s.response.error);o+=`${l}, ${a}>;`}else o+=`${f(r.outputs.type)}>;`;n+=`${e===0?"":`
7
+ `} ${o}`}),t.maps.forEach(r=>{let e=`${P(r.name)}: `,o=f(r.key,!0),i=`key: ${o}`,c=f(r.value);e+=`(${i}) => ContractCalls.Map<${o}, ${c}>;`,n+=`
8
+ ${e}`}),n}import{hasStdErr as Tt}from"@clarigen/native-bin";import{toCamelCase as $}from"@clarigen/core";import{dirname as Et,join as Nt}from"path";var U=async({provider:t,contractFile:n,contractAddress:r,contractName:e})=>{let o=await t.runCommand(["launch",`${r}.${e}`,n,t.dbFilePath,"--output_analysis","--costs","--assets"]);if(Tt(o.stderr))throw new Error(`Error on ${n}:
9
+ ${o.stderr}
10
+ `);let i=JSON.parse(o.stdout);if(i.error){let{initialization:s}=i.error;if(s!=null&&s.includes(`
11
+ Near:
12
+ `)){let[l,a]=s.split(`
13
+ Near:
14
+ `),p="",x=/start_line: (\d+),/.exec(a);throw x&&(p=x[1]),new Error(`Error on ${n}:
15
+ ${l}
16
+ ${p?`Near line ${p}`:""}
17
+ Raw trace:
18
+ ${a}
19
+ `)}throw new Error(`Error on ${n}:
20
+ ${JSON.stringify(i.error,null,2)}
21
+ `)}return i.analysis},W=({contractName:t,abi:n})=>{let r=$(t,!0),s=n,{clarity_version:e}=s,o=k(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
22
+
23
+ // prettier-ignore
24
+ export const ${r}Interface: ClarityAbi = ${i};
25
+ `},V=({contractFile:t,contractAddress:n,contractName:r})=>{let e=$(r,!0),o=$(r),i=`${e}Contract`,c=`${e}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
+ import type { ${i} } from './types';
27
+ import { ${c} } from './abi';
28
+ export type { ${i} } from './types';
29
+
30
+ export function ${o}Contract(contractAddress: string, contractName: string) {
31
+ return pureProxy<${i}>({
32
+ abi: ${c},
33
+ contractAddress,
34
+ contractName,
35
+ });
36
+ }
37
+
38
+ export const ${o}Info: Contract<${i}> = {
39
+ contract: ${o}Contract,
40
+ address: '${n}',
41
+ contractFile: '${t}',
42
+ name: '${r}',
43
+ abi: ${c},
44
+ };
45
+ `},K=(t,n)=>{let r=$(n,!0),e=R(t);return`import { ClarityTypes, ContractCalls } from '@clarigen/core';
46
+
47
+ // prettier-ignore
48
+ export interface ${r}Contract {
49
+ ${e}
50
+ }
51
+ `},M=t=>{let n=["import type { ContractInstances } from '@clarigen/core';"],r=[],e=[],o="";"accounts"in t&&(o=`
52
+
53
+ // prettier-ignore
54
+ export const accounts = {
55
+ ${Object.keys(t.accounts).map(l=>{let a=t.accounts[l];return`"${l}": {
56
+ mnemonic: "${a.mnemonic}",
57
+ balance: ${a.balance.toString()}n,
58
+ address: "${a.address}",
59
+ },`}).join(`
60
+ `)}
61
+ };`),t.contracts.forEach(s=>{let l=s.name,a=$(l),p=`${a}Info`,g=`${$(l,!0)}Contract`,x=Et(s.file),E=`'./${Nt(x||".",l)}'`,Q=`import { ${p} } from ${E};`;n.push(Q);let X=`export type { ${g} } from ${E};`;r.push(X);let Y=`${a}: ${p},`;e.push(Y)});let i=`
62
+ export type Contracts = ContractInstances<typeof contracts>;
63
+ `;return`${n.join(`
64
+ `)}
65
+ ${r.join(`
66
+ `)}
67
+ ${i}
68
+ export const contracts = {
69
+ ${e.join(`
70
+ `)}
71
+ };${o}
72
+ `};import{Command as Dt,flags as q}from"@oclif/command";import{createClarityBin as jt}from"@clarigen/native-bin";import{resolve as u,relative as It,dirname as kt}from"path";import{mkdir as St,writeFile as F}from"fs/promises";var vt=async({contractFile:t,outputFolder:n,provider:r,contractAddress:e,dirName:o,contractName:i})=>{let c=u(process.cwd(),t),s=await U({contractFile:c,provider:r,contractAddress:e,contractName:i}),l=K(s,i),a=V({contractFile:It(process.cwd(),c),contractAddress:e,contractName:i}),p=W({contractName:i,abi:s}),g=u(n,o||".",i);await St(g,{recursive:!0}),await F(u(g,"abi.ts"),p),await F(u(g,"index.ts"),a),await F(u(g,"types.ts"),l)},A=async t=>{let n=await h(t),{contractsDir:r,outputDir:e,contracts:o}=n,i=u(t,e),c=await jt();for(let a of o){let p=u(t,r,a.file),g=kt(a.file);await vt({contractFile:p,outputFolder:i,provider:c,contractAddress:a.address,dirName:g,contractName:a.name})}let s=M(n),l=u(i,"index.ts");await F(l,s)};import{watch as Ot}from"chokidar";import{basename as _t}from"path";import{red as Bt,green as H}from"chalk";var Jt=tt("ora"),T=class extends Dt{async run(){let{flags:n}=this.parse(T),r=process.cwd();if(n.watch){let e=Jt("Generating files").start(),{contractsDir:o}=await h(r),i=Ot([o],{cwd:r});try{await A(r),e.succeed("Finished generating files. Watching for changes.")}catch(c){e.fail(`Error generating files.
73
+ ${c.message}`)}i.on("change",async c=>{let s=_t(c);e.clear(),e.start(`Change detected for ${H(s)}, generating.`);try{await A(r),e.succeed(`Finished generating files for ${H(s)}. Watching for changes.`)}catch(l){let a=l.message;e.fail(`Error after saving ${Bt(s)}.
74
+ ${a}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await A(r)}},m=T;m.description="Generate project files",m.strict=!0,m.hidden=!1,m.flags={help:q.help({char:"h"}),watch:q.boolean({char:"w",description:"Watch for changes to your contracts"})},m.args=[];export{m as Generate,mt as configFileExists,ut as configFilePath,B as defaultConfigFile,V as generateIndexFile,U as generateInterface,W as generateInterfaceFile,M as generateProjectIndexFile,K as generateTypesFile,Ct as getConfigFile,h as getProjectConfig,f as jsTypeFromAbiType,R as makePureTypes,Nr as run};
package/package.json CHANGED
@@ -2,9 +2,10 @@
2
2
  "name": "@clarigen/cli",
3
3
  "description": "A CLI for generating a Typescript interface for a Clarity contract.",
4
4
  "author": "Hank Stoever",
5
- "version": "0.3.3",
5
+ "version": "1.0.0-next.10",
6
6
  "license": "MIT",
7
- "main": "dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "main": "./dist/index.js",
8
9
  "files": [
9
10
  "dist",
10
11
  "src",
@@ -14,14 +15,14 @@
14
15
  "node": ">=10"
15
16
  },
16
17
  "scripts": {
17
- "dev": "tsdx watch",
18
- "start": "ts-node-script src/start.ts",
18
+ "start": "tsup-node --watch",
19
+ "dev": "tsup-node --watch",
20
+ "build": "shx rm -rf ./dist && tsup-node src/index.ts src/commands/index.ts --splitting false",
19
21
  "compile": "ncc build src/index.ts --no-source-map-register -e @oclif/command -e @oclif/errors",
20
22
  "build-single-file": "yarn compile && oclif-dev readme",
21
- "build": "rm -rf dist && tsc -b",
22
- "test": "tsdx test",
23
- "lint": "tsdx lint",
24
- "typecheck": "tsc --noEmit",
23
+ "test": "jest",
24
+ "lint": "eslint \"src/**/*.{ts,tsx}\" && prettier --check src/**/*.ts",
25
+ "typecheck": "tsc --noEmit -p tsconfig-test.json",
25
26
  "prepublishOnly": "yarn build"
26
27
  },
27
28
  "bin": {
@@ -40,24 +41,28 @@
40
41
  "devDependencies": {
41
42
  "@oclif/dev-cli": "^1.26.0",
42
43
  "@oclif/errors": "^1.3.4",
44
+ "@types/reserved-words": "0.1.0",
45
+ "@types/toposort": "2.0.3",
43
46
  "@vercel/ncc": "0.27.0",
44
47
  "oclif": "^1.16.1",
45
48
  "ts-node": "^9.1.1"
46
49
  },
47
50
  "dependencies": {
48
- "@clarigen/core": "0.3.2",
49
- "@clarigen/native-bin": "0.3.3",
51
+ "@clarigen/core": "1.0.0-next.10",
52
+ "@clarigen/native-bin": "1.0.0-next.10",
50
53
  "@ltd/j-toml": "1.12.2",
51
54
  "@oclif/command": "^1.8.0",
52
55
  "@oclif/config": "^1.17.0",
53
56
  "@oclif/plugin-help": "3.2.3",
54
- "@stacks/wallet-sdk": "1.0.0-wallet-sdk.4",
55
57
  "chalk": "4.1.0",
56
58
  "chokidar": "3.5.1",
57
- "ora": "5.4.0"
59
+ "micro-stacks": "^0.2.0",
60
+ "ora": "5.4.0",
61
+ "reserved-words": "0.1.2",
62
+ "toposort": "2.0.2"
58
63
  },
59
64
  "publishConfig": {
60
65
  "access": "public"
61
66
  },
62
- "gitHead": "ac18d4209761b318dcb6770cceb1fc11817d53f6"
67
+ "gitHead": "7f0fe914649439236709140ddce39d8e81028dc3"
63
68
  }