@clarigen/cli 1.0.0-next.18 → 1.0.0-next.19

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.
package/package.json CHANGED
@@ -2,7 +2,7 @@
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": "1.0.0-next.18",
5
+ "version": "1.0.0-next.19",
6
6
  "license": "MIT",
7
7
  "types": "./dist/index.d.ts",
8
8
  "main": "./dist/index.js",
@@ -50,9 +50,9 @@
50
50
  "ts-node": "^9.1.1"
51
51
  },
52
52
  "dependencies": {
53
- "@clarigen/claridocs": "1.0.0-next.18",
54
- "@clarigen/core": "1.0.0-next.18",
55
- "@clarigen/native-bin": "1.0.0-next.18",
53
+ "@clarigen/claridocs": "1.0.0-next.19",
54
+ "@clarigen/core": "1.0.0-next.19",
55
+ "@clarigen/native-bin": "1.0.0-next.19",
56
56
  "@ltd/j-toml": "1.12.2",
57
57
  "@oclif/command": "^1.8.0",
58
58
  "@oclif/config": "^1.17.0",
@@ -68,5 +68,5 @@
68
68
  "publishConfig": {
69
69
  "access": "public"
70
70
  },
71
- "gitHead": "597b4b53e6c876336126bf40b4b8850d1385af8f"
71
+ "gitHead": "d6b6fc199e367698d566f38ee3343b04a418c829"
72
72
  }
@@ -2,7 +2,6 @@ import { toCamelCase } from '@clarigen/core';
2
2
  import type { ConfigFile } from '../config';
3
3
  import { getArgName, jsTypeFromAbiType } from './declaration';
4
4
  import type { ContractMeta } from '../utils';
5
- import { resolveConfig, format } from 'prettier';
6
5
  import { relative, resolve } from 'path';
7
6
  import { readFile } from 'fs/promises';
8
7
  import { inspect } from 'util';
@@ -79,7 +78,7 @@ export async function generateSingleFile(
79
78
  const file = `
80
79
  ${types}
81
80
 
82
- export const contracts: Record<string, TypedAbi> = {
81
+ export const contracts = {
83
82
  ${contractDefs.join(',\n')}
84
83
  } as const;
85
84
 
@@ -111,8 +110,14 @@ Uint8Array.prototype[inspect.custom] = function (this: Uint8Array) {
111
110
  return `Uint8Array.from([${this.join(',')}])`;
112
111
  };
113
112
 
114
- function serialize(obj: any) {
115
- return inspect(obj, false, null, false);
113
+ export function serialize(obj: any) {
114
+ return inspect(obj, {
115
+ showHidden: false,
116
+ maxArrayLength: null,
117
+ maxStringLength: null,
118
+ depth: null,
119
+ colors: false,
120
+ });
116
121
  }
117
122
 
118
123
  function serializeLines(key: string, lines: string[]) {
@@ -122,7 +127,8 @@ function serializeLines(key: string, lines: string[]) {
122
127
  }
123
128
 
124
129
  export async function getSingleTypes() {
125
- const typesPath = resolve(__dirname, '../../../core/src/abi-types.ts');
130
+ // 🤔 weird stuff with tsup shims
131
+ const typesPath = resolve(__dirname, '../../dist/abi-types.ts.txt');
126
132
  const typesFile = await readFile(typesPath, { encoding: 'utf-8' });
127
133
  return typesFile;
128
134
  }
@@ -1,16 +0,0 @@
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,92 +0,0 @@
1
- var lt=Object.defineProperty,pt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var N=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var M=(t,r,e)=>r in t?lt(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,C=(t,r)=>{for(var e in r||(r={}))R.call(r,e)&&M(t,e,r[e]);if(N)for(var e of N(r))B.call(r,e)&&M(t,e,r[e]);return t},x=(t,r)=>pt(t,ft(r));var mt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(r,e)=>(typeof require!="undefined"?require:r)[e]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var j=(t,r)=>{var e={};for(var n in t)R.call(t,n)&&r.indexOf(n)<0&&(e[n]=t[n]);if(t!=null&&N)for(var n of N(t))r.indexOf(n)<0&&B.call(t,n)&&(e[n]=t[n]);return e};import{fileURLToPath as ut}from"url";import gt from"path";var Ct=()=>ut(import.meta.url),yt=()=>gt.dirname(Ct()),u=yt();import{Command as be,flags as st}from"@oclif/command";import{hasStdErr as rr}from"@clarigen/native-bin";import{toCamelCase as F}from"@clarigen/core";import{dirname as Bt,join as Jt}from"path";import{run as Qe}from"@oclif/command";import{resolve as H,join as Ft,relative as Tt}from"path";import{readFile as vt,access as Pt}from"fs/promises";import{constants as Nt}from"fs";import{parse as J}from"@ltd/j-toml";import{resolve as U}from"path";import{readFile as W}from"fs/promises";import{generateWallet as dt,getStxAddressFromAccount as $t}from"micro-stacks/wallet-sdk";import{array as bt}from"toposort";import{StacksNetworkVersion as xt}from"micro-stacks/crypto";async function wt(t){let r=U(t,"settings","Devnet.toml"),e=await W(r,{encoding:"utf-8"});return J(e,1,`
2
- `,!0,{longer:!0})}async function At(t){let r=U(t,"Clarinet.toml"),e=await W(r,{encoding:"utf-8"});return J(e,1,`
3
- `,!0)}async function z(t,r){let e=await At(t),n=r.deployer.address;return ht(e.contracts).map(a=>({file:e.contracts[a].path.replace(/^contracts\//,""),address:n,name:a}))}function ht(t){let r=[],e=[];return Object.entries(t).forEach(([o,i])=>{e.push(o),i.depends_on.forEach(a=>r.push([o,a]))}),bt(e,r).reverse()}async function K(t){let r=await wt(t),e=await Promise.all(Object.entries(r.accounts).map(async([o,i])=>{let a=await dt(i.mnemonic,"password"),[s]=a.accounts,l=$t(s,xt.testnetP2PKH);return[o,x(C({},i),{address:l})]}));return Object.fromEntries(e)}var q={outputDir:"src/clarigen",clarinet:"."};function jt(t){return H(t,"clarigen.config.json")}async function Et(t){try{return await Pt(t,Nt.R_OK),!0}catch{return!1}}async function It(t){let r=jt(t);if(await Et(r)){let n=await vt(r,{encoding:"utf-8"}),o=JSON.parse(n);return C(C({},q),o)}return q}async function E(t){let r=await It(t),e=H(t,r.clarinet||"."),n=await K(e),o=await z(e,n),i=Tt(process.cwd(),Ft(r.clarinet,"contracts"));return x(C({},r),{contracts:o,contractsDir:i,accounts:n,clarinet:r.clarinet||"."})}import{isClarityAbiBuffer as kt,isClarityAbiList as St,isClarityAbiOptional as Dt,isClarityAbiPrimitive as Vt,isClarityAbiResponse as Q,isClarityAbiStringAscii as Ot,isClarityAbiStringUtf8 as Lt,isClarityAbiTuple as _t}from"micro-stacks/transactions";import{toCamelCase as S}from"@clarigen/core";import{check as Mt}from"reserved-words";var f=(t,r=!1)=>{if(Vt(t)){if(t==="uint128")return r?"number | bigint":"bigint";if(t==="int128")return r?"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(kt(t))return"Uint8Array";if(Q(t)){let e=f(t.response.ok),n=f(t.response.error);return`Response<${e}, ${n}>`}else{if(Dt(t))return`${f(t.optional)} | null`;if(_t(t)){let e=[];return t.tuple.forEach(({name:n,type:o})=>{let i=f(o);e.push(`"${n}": ${i}`)}),`{
4
- ${e.join(`;
5
- `)}
6
- }`}else{if(St(t))return`${f(t.list.type)}[]`;if(Ot(t))return"string";if(Lt(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function D(t){let r=S(t);return`${Mt(r,6)?"_":""}${r}`}var Rt={public:"Public",read_only:"ReadOnly",private:"Private"};function X(t){let r="";return t.functions.forEach((e,n)=>{let o=`${S(e.name)}: `;if(o+=`(${e.args.map(s=>`${D(s.name)}: ${f(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Rt[e.access]}<`,e.access==="public"){let{type:s}=e.outputs;if(!Q(s))throw new Error("Expected response type for public function");let l=f(s.response.ok),p=f(s.response.error);o+=`${l}, ${p}>;`}else o+=`${f(e.outputs.type)}>;`;r+=`${n===0?"":`
7
- `} ${o}`}),t.maps.forEach(e=>{let n=`${S(e.name)}: `,o=f(e.key,!0),i=`key: ${o}`,a=f(e.value);n+=`(${i}) => ContractCalls.Map<${o}, ${a}>;`,r+=`
8
- ${n}`}),r}var Y=({contractName:t,abi:r})=>{let e=F(t,!0),s=r,{clarity_version:n}=s,o=j(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
9
-
10
- // prettier-ignore
11
- export const ${e}Interface: ClarityAbi = ${i};
12
- `},Z=({contractFile:t,contractAddress:r,contractName:e})=>{let n=F(e,!0),o=F(e),i=`${n}Contract`,a=`${n}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
13
- import type { ${i} } from './types';
14
- import { ${a} } from './abi';
15
- export type { ${i} } from './types';
16
-
17
- export function ${o}Contract(contractAddress: string, contractName: string) {
18
- return pureProxy<${i}>({
19
- abi: ${a},
20
- contractAddress,
21
- contractName,
22
- });
23
- }
24
-
25
- export const ${o}Info: Contract<${i}> = {
26
- contract: ${o}Contract,
27
- address: '${r}',
28
- contractFile: '${t}',
29
- name: '${e}',
30
- abi: ${a},
31
- };
32
- `},G=(t,r)=>{let e=F(r,!0),n=X(t);return`import { Response, ContractCalls } from '@clarigen/core';
33
-
34
- // prettier-ignore
35
- export interface ${e}Contract {
36
- ${n}
37
- }
38
- `},tt=t=>{let r=["import type { ContractInstances } from '@clarigen/core';"],e=[],n=[],o="";"accounts"in t&&(o=`
39
-
40
- // prettier-ignore
41
- export const accounts = {
42
- ${Object.keys(t.accounts).map(l=>{let p=t.accounts[l];return`"${l}": {
43
- mnemonic: "${p.mnemonic}",
44
- balance: ${p.balance.toString()}n,
45
- address: "${p.address}",
46
- },`}).join(`
47
- `)}
48
- };`),t.contracts.forEach(s=>{let l=s.name,p=F(l),b=`${p}Info`,w=`${F(l,!0)}Contract`,g=Bt(s.file),d=`'./${Jt(g||".",l)}'`,c=`import { ${b} } from ${d};`;r.push(c);let m=`export type { ${w} } from ${d};`;e.push(m);let h=`${p}: ${b},`;n.push(h)});let i=`
49
- export type Contracts = ContractInstances<typeof contracts>;
50
- `;return`${r.join(`
51
- `)}
52
- ${e.join(`
53
- `)}
54
- ${i}
55
- export const contracts = {
56
- ${n.join(`
57
- `)}
58
- };${o}
59
- `};import{createClarityBin as ue,deployContract as ge}from"@clarigen/native-bin";import{resolve as $,relative as Ce,dirname as ye}from"path";import{mkdir as de}from"fs/promises";import{createContractDocInfo as Ut,generateMarkdown as Wt}from"@clarigen/claridocs";import{mkdir as zt,readFile as Kt,writeFile as et}from"fs/promises";import{relative as qt,resolve as V}from"path";async function rt({contractFile:t,contractName:r,docsPath:e,abi:n,dirName:o}){let i=await Kt(t,{encoding:"utf-8"}),a=Ut({contractSrc:i,abi:n}),s=V(process.cwd(),e,o||"."),l=V(s,`${r}.md`),p=Wt({contract:a,contractFile:qt(s,t),contractName:r,abi:n});await zt(s,{recursive:!0}),await et(l,p)}async function nt(t){if(!t.docs)return;let e=`# Contracts
60
-
61
- ${t.contracts.map(o=>{let i=o.file.replace(".clar",".md");return`- [\`${o.name}\`](${i})`}).join(`
62
- `)}
63
- `,n=V(process.cwd(),t.docs,"README.md");await et(n,e)}import{toCamelCase as v}from"@clarigen/core";import{relative as Ht,resolve as Qt}from"path";import{readFile as Xt}from"fs/promises";import{inspect as O}from"util";function Yt(t){let{abi:r}=t,e=[],d=r,{functions:n,variables:o,maps:i}=d,a=j(d,["functions","variables","maps"]);n.forEach(c=>{let m=`${v(c.name)}: `,P=`[${c.args.map(_=>`${D(_.name)}: ${f(_.type,!0)}`).join(", ")}]`;m+=JSON.stringify(c);let ct=f(c.outputs.type);m+=` as TypedAbiFunction<${P}, ${ct}>`,e.push(m)});let s=t.variables.map(c=>{let m=`${v(c.name)}: `,h=f(c.type);return m+=`${O(c,!1,null,!1)} as TypedAbiVariable<${h}>`,m}),p=t.variables.filter(c=>c.access==="constant").map(c=>`"${v(c.name)}": ${Gt(c.defaultValue)}`),b=i.map(c=>{let m=`${v(c.name)}: `,h=f(c.key),P=f(c.value);return m+=JSON.stringify(c),m+=` as TypedAbiMap<${h}, ${P}>`,m}),w=JSON.stringify(a),g=Ht(process.cwd(),t.contractFile);return`{
64
- ${I("functions",e)}
65
- ${I("variables",s)}
66
- ${I("maps",b)}
67
- ${I("constants",p)}
68
- ${w.slice(1,-1)},
69
- contractName: '${t.contractName}',
70
- contractFile: '${g}',
71
- }`}async function ot(t,r){let e=r.map(a=>{let s=Yt(a);return`${v(a.contractName)}: ${s}`}),n=await te(),o=Zt(t);return`
72
- ${n}
73
-
74
- export const contracts: Record<string, TypedAbi> = {
75
- ${e.join(`,
76
- `)}
77
- } as const;
78
-
79
- ${o}
80
- `}function Zt(t){let r="";return"accounts"in t&&(r=`export const accounts = {
81
- ${Object.keys(t.accounts).map(n=>{let o=t.accounts[n];return`"${n}": {
82
- mnemonic: "${o.mnemonic}",
83
- balance: ${o.balance.toString()}n,
84
- address: "${o.address}",
85
- },`}).join(`
86
- `)}
87
- } as const;`),r}Uint8Array.prototype[O.custom]=function(){return`Uint8Array.from([${this.join(",")}])`};function Gt(t){return O(t,!1,null,!1)}function I(t,r){return`"${t}": {
88
- ${r.join(`,
89
- `)}
90
- },`}async function te(){let t=Qt(u,"../../../core/src/abi-types.ts");return await Xt(t,{encoding:"utf-8"})}import{writeFile as ee}from"fs/promises";import{basename as re}from"path";import{resolveConfig as ne,format as oe}from"prettier";var ie={printWidth:80,semi:!0,singleQuote:!0,trailingComma:"es5"};async function se(){try{let t=await ne(process.cwd());if(t)return t}catch{}return ie}async function ae(t,r){try{let e=re(r),n=await se();return oe(t,x(C({},n),{filepath:e}))}catch{}return t}async function T(t,r){let e=await ae(r,t);await ee(t,e)}import{cvToValue as ce}from"@clarigen/core";import{evalRaw as le}from"@clarigen/native-bin";import{hexToCV as pe}from"micro-stacks/clarity";async function it({abi:t,contractIdentifier:r,provider:e}){let n=t.variables.map(i=>fe({variable:i,provider:e,contractIdentifier:r}));return await Promise.all(n)}async function fe({contractIdentifier:t,variable:r,provider:e}){let n=me(r),o=await le({contractAddress:t,code:n,provider:e}),i=pe(o.output_serialized),a=ce(i,!0);return x(C({},r),{defaultValue:a})}function me(t){let{access:r}=t;return r==="variable"?`(var-get ${t.name})`:t.name}var $e=async({contractFile:t,outputFolder:r,provider:e,contractAddress:n,dirName:o,contractName:i,docsPath:a})=>{let s=$(process.cwd(),t),l=`${n}.${i}`,p=await ge({contractIdentifier:l,contractFilePath:s,provider:e}),b=await it({abi:p,contractIdentifier:l,provider:e}),w=G(p,i),g=Z({contractFile:Ce(process.cwd(),s),contractAddress:n,contractName:i}),d=Y({contractName:i,abi:p});typeof a<"u"&&await rt({contractFile:s,contractName:i,abi:p,docsPath:a,dirName:o});let c=$(r,o||".",i);return await de(c,{recursive:!0}),await T($(c,"abi.ts"),d),await T($(c,"index.ts"),g),await T($(c,"types.ts"),w),{abi:p,contractFile:s,contractName:i,dirName:o,contractAddress:n,variables:b}},k=async t=>{let r=await E(t),{contractsDir:e,outputDir:n,contracts:o}=r,i=$(t,n),a=await ue(),s=[];for(let g of o){let d=$(t,e,g.file),c=ye(g.file),m=await $e({contractFile:d,outputFolder:i,provider:a,contractAddress:g.address,dirName:c,contractName:g.name,docsPath:r.docs});s.push(m)}let l=tt(r);await nt(r);let p=$(i,"index.ts");await T(p,l);let b=await ot(r,s),w=$(i,"single.ts");await T(w,b)};import{watch as xe}from"chokidar";import{basename as we}from"path";import{red as Ae,green as at}from"chalk";var he=mt("ora"),L=class extends be{async run(){let{flags:r}=this.parse(L),e=process.cwd();if(r.watch){let n=he("Generating files").start(),{contractsDir:o}=await E(e),i=xe([o],{cwd:e});try{await k(e),n.succeed("Finished generating files. Watching for changes.")}catch(a){n.fail(`Error generating files.
91
- ${a.message}`)}i.on("change",async a=>{let s=we(a);n.clear(),n.start(`Change detected for ${at(s)}, generating.`);try{await k(e),n.succeed(`Finished generating files for ${at(s)}. Watching for changes.`)}catch(l){let p=l.message;n.fail(`Error after saving ${Ae(s)}.
92
- ${p}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await k(e)}},A=L;A.description="Generate project files",A.strict=!0,A.hidden=!1,A.flags={help:st.help({char:"h"}),watch:st.boolean({char:"w",description:"Watch for changes to your contracts"})},A.args=[];export{A as Generate};
package/dist/index.d.ts DELETED
@@ -1,64 +0,0 @@
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
- docs?: string;
29
- }
30
- interface ConfigFile extends ConfigFileContents {
31
- contractsDir: string;
32
- contracts: ConfigContract[];
33
- accounts: ClarinetAccounts;
34
- clarinet: string;
35
- }
36
- declare const defaultConfigFile: ConfigFileContents;
37
- declare function configFilePath(rootPath: string): string;
38
- declare function configFileExists(configPath: string): Promise<boolean>;
39
- declare function getConfigFile(rootPath: string): Promise<ConfigFileContents>;
40
- declare function getProjectConfig(rootPath: string): Promise<ConfigFile>;
41
-
42
- declare const jsTypeFromAbiType: (val: ClarityAbiType, isArgument?: boolean) => string;
43
- declare function getArgName(name: string): string;
44
- declare function makePureTypes(abi: ClarityAbi): string;
45
-
46
- declare const generateInterface: ({ provider, contractFile, contractAddress, contractName, }: {
47
- contractFile: string;
48
- provider: NativeClarityBinProvider;
49
- contractAddress: string;
50
- contractName: string;
51
- }) => Promise<ClarityAbi>;
52
- declare const generateInterfaceFile: ({ contractName, abi, }: {
53
- contractName: string;
54
- abi: ClarityAbi;
55
- }) => string;
56
- declare const generateIndexFile: ({ contractFile, contractAddress, contractName, }: {
57
- contractFile: string;
58
- contractAddress: string;
59
- contractName: string;
60
- }) => string;
61
- declare const generateTypesFile: (abi: ClarityAbi, contractName: string) => string;
62
- declare const generateProjectIndexFile: (config: ConfigFile) => string;
63
-
64
- export { ConfigContract, ConfigFile, ConfigFileContents, configFileExists, configFilePath, defaultConfigFile, generateIndexFile, generateInterface, generateInterfaceFile, generateProjectIndexFile, generateTypesFile, getArgName, getConfigFile, getProjectConfig, jsTypeFromAbiType, makePureTypes };
package/dist/index.mjs DELETED
@@ -1,105 +0,0 @@
1
- var lt=Object.defineProperty,pt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var N=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var M=(t,e,r)=>e in t?lt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,y=(t,e)=>{for(var r in e||(e={}))R.call(e,r)&&M(t,r,e[r]);if(N)for(var r of N(e))B.call(e,r)&&M(t,r,e[r]);return t},w=(t,e)=>pt(t,ft(e));var mt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,r)=>(typeof require!="undefined"?require:e)[r]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var j=(t,e)=>{var r={};for(var n in t)R.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&N)for(var n of N(t))e.indexOf(n)<0&&B.call(t,n)&&(r[n]=t[n]);return r};import{fileURLToPath as ut}from"url";import gt from"path";var Ct=()=>ut(import.meta.url),yt=()=>gt.dirname(Ct()),C=yt();import{run as Zr}from"@oclif/command";import{resolve as H,join as Ft,relative as Tt}from"path";import{readFile as vt,access as Pt}from"fs/promises";import{constants as Nt}from"fs";import{parse as J}from"@ltd/j-toml";import{resolve as U}from"path";import{readFile as W}from"fs/promises";import{generateWallet as dt,getStxAddressFromAccount as $t}from"micro-stacks/wallet-sdk";import{array as bt}from"toposort";import{StacksNetworkVersion as xt}from"micro-stacks/crypto";async function wt(t){let e=U(t,"settings","Devnet.toml"),r=await W(e,{encoding:"utf-8"});return J(r,1,`
2
- `,!0,{longer:!0})}async function At(t){let e=U(t,"Clarinet.toml"),r=await W(e,{encoding:"utf-8"});return J(r,1,`
3
- `,!0)}async function z(t,e){let r=await At(t),n=e.deployer.address;return ht(r.contracts).map(a=>({file:r.contracts[a].path.replace(/^contracts\//,""),address:n,name:a}))}function ht(t){let e=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(a=>e.push([o,a]))}),bt(r,e).reverse()}async function K(t){let e=await wt(t),r=await Promise.all(Object.entries(e.accounts).map(async([o,i])=>{let a=await dt(i.mnemonic,"password"),[s]=a.accounts,p=$t(s,xt.testnetP2PKH);return[o,w(y({},i),{address:p})]}));return Object.fromEntries(r)}var q={outputDir:"src/clarigen",clarinet:"."};function jt(t){return H(t,"clarigen.config.json")}async function Et(t){try{return await Pt(t,Nt.R_OK),!0}catch{return!1}}async function It(t){let e=jt(t);if(await Et(e)){let n=await vt(e,{encoding:"utf-8"}),o=JSON.parse(n);return y(y({},q),o)}return q}async function E(t){let e=await It(t),r=H(t,e.clarinet||"."),n=await K(r),o=await z(r,n),i=Tt(process.cwd(),Ft(e.clarinet,"contracts"));return w(y({},e),{contracts:o,contractsDir:i,accounts:n,clarinet:e.clarinet||"."})}import{isClarityAbiBuffer as kt,isClarityAbiList as St,isClarityAbiOptional as Dt,isClarityAbiPrimitive as Vt,isClarityAbiResponse as Q,isClarityAbiStringAscii as Ot,isClarityAbiStringUtf8 as Lt,isClarityAbiTuple as _t}from"micro-stacks/transactions";import{toCamelCase as S}from"@clarigen/core";import{check as Mt}from"reserved-words";var f=(t,e=!1)=>{if(Vt(t)){if(t==="uint128")return e?"number | bigint":"bigint";if(t==="int128")return e?"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(kt(t))return"Uint8Array";if(Q(t)){let r=f(t.response.ok),n=f(t.response.error);return`Response<${r}, ${n}>`}else{if(Dt(t))return`${f(t.optional)} | null`;if(_t(t)){let r=[];return t.tuple.forEach(({name:n,type:o})=>{let i=f(o);r.push(`"${n}": ${i}`)}),`{
4
- ${r.join(`;
5
- `)}
6
- }`}else{if(St(t))return`${f(t.list.type)}[]`;if(Ot(t))return"string";if(Lt(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function D(t){let e=S(t);return`${Mt(e,6)?"_":""}${e}`}var Rt={public:"Public",read_only:"ReadOnly",private:"Private"};function X(t){let e="";return t.functions.forEach((r,n)=>{let o=`${S(r.name)}: `;if(o+=`(${r.args.map(s=>`${D(s.name)}: ${f(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Rt[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!Q(s))throw new Error("Expected response type for public function");let p=f(s.response.ok),l=f(s.response.error);o+=`${p}, ${l}>;`}else o+=`${f(r.outputs.type)}>;`;e+=`${n===0?"":`
7
- `} ${o}`}),t.maps.forEach(r=>{let n=`${S(r.name)}: `,o=f(r.key,!0),i=`key: ${o}`,a=f(r.value);n+=`(${i}) => ContractCalls.Map<${o}, ${a}>;`,e+=`
8
- ${n}`}),e}import{hasStdErr as Bt}from"@clarigen/native-bin";import{toCamelCase as F}from"@clarigen/core";import{dirname as Jt,join as Ut}from"path";var er=async({provider:t,contractFile:e,contractAddress:r,contractName:n})=>{let o=await t.runCommand(["launch",`${r}.${n}`,e,t.dbFilePath,"--output_analysis","--costs","--assets"]);if(Bt(o.stderr))throw new Error(`Error on ${e}:
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[p,l]=s.split(`
13
- Near:
14
- `),g="",u=/start_line: (\d+),/.exec(l);throw u&&(g=u[1]),new Error(`Error on ${e}:
15
- ${p}
16
- ${g?`Near line ${g}`:""}
17
- Raw trace:
18
- ${l}
19
- `)}throw new Error(`Error on ${e}:
20
- ${JSON.stringify(i.error,null,2)}
21
- `)}return i.analysis},Y=({contractName:t,abi:e})=>{let r=F(t,!0),s=e,{clarity_version:n}=s,o=j(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
- `},Z=({contractFile:t,contractAddress:e,contractName:r})=>{let n=F(r,!0),o=F(r),i=`${n}Contract`,a=`${n}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
- import type { ${i} } from './types';
27
- import { ${a} } from './abi';
28
- export type { ${i} } from './types';
29
-
30
- export function ${o}Contract(contractAddress: string, contractName: string) {
31
- return pureProxy<${i}>({
32
- abi: ${a},
33
- contractAddress,
34
- contractName,
35
- });
36
- }
37
-
38
- export const ${o}Info: Contract<${i}> = {
39
- contract: ${o}Contract,
40
- address: '${e}',
41
- contractFile: '${t}',
42
- name: '${r}',
43
- abi: ${a},
44
- };
45
- `},G=(t,e)=>{let r=F(e,!0),n=X(t);return`import { Response, ContractCalls } from '@clarigen/core';
46
-
47
- // prettier-ignore
48
- export interface ${r}Contract {
49
- ${n}
50
- }
51
- `},tt=t=>{let e=["import type { ContractInstances } from '@clarigen/core';"],r=[],n=[],o="";"accounts"in t&&(o=`
52
-
53
- // prettier-ignore
54
- export const accounts = {
55
- ${Object.keys(t.accounts).map(p=>{let l=t.accounts[p];return`"${p}": {
56
- mnemonic: "${l.mnemonic}",
57
- balance: ${l.balance.toString()}n,
58
- address: "${l.address}",
59
- },`}).join(`
60
- `)}
61
- };`),t.contracts.forEach(s=>{let p=s.name,l=F(p),g=`${l}Info`,x=`${F(p,!0)}Contract`,u=Jt(s.file),$=`'./${Ut(u||".",p)}'`,c=`import { ${g} } from ${$};`;e.push(c);let m=`export type { ${x} } from ${$};`;r.push(m);let h=`${l}: ${g},`;n.push(h)});let i=`
62
- export type Contracts = ContractInstances<typeof contracts>;
63
- `;return`${e.join(`
64
- `)}
65
- ${r.join(`
66
- `)}
67
- ${i}
68
- export const contracts = {
69
- ${n.join(`
70
- `)}
71
- };${o}
72
- `};import{Command as xe,flags as st}from"@oclif/command";import{createClarityBin as ge,deployContract as Ce}from"@clarigen/native-bin";import{resolve as b,relative as ye,dirname as de}from"path";import{mkdir as $e}from"fs/promises";import{createContractDocInfo as Wt,generateMarkdown as zt}from"@clarigen/claridocs";import{mkdir as Kt,readFile as qt,writeFile as et}from"fs/promises";import{relative as Ht,resolve as V}from"path";async function rt({contractFile:t,contractName:e,docsPath:r,abi:n,dirName:o}){let i=await qt(t,{encoding:"utf-8"}),a=Wt({contractSrc:i,abi:n}),s=V(process.cwd(),r,o||"."),p=V(s,`${e}.md`),l=zt({contract:a,contractFile:Ht(s,t),contractName:e,abi:n});await Kt(s,{recursive:!0}),await et(p,l)}async function nt(t){if(!t.docs)return;let r=`# Contracts
73
-
74
- ${t.contracts.map(o=>{let i=o.file.replace(".clar",".md");return`- [\`${o.name}\`](${i})`}).join(`
75
- `)}
76
- `,n=V(process.cwd(),t.docs,"README.md");await et(n,r)}import{toCamelCase as v}from"@clarigen/core";import{relative as Qt,resolve as Xt}from"path";import{readFile as Yt}from"fs/promises";import{inspect as O}from"util";function Zt(t){let{abi:e}=t,r=[],$=e,{functions:n,variables:o,maps:i}=$,a=j($,["functions","variables","maps"]);n.forEach(c=>{let m=`${v(c.name)}: `,P=`[${c.args.map(_=>`${D(_.name)}: ${f(_.type,!0)}`).join(", ")}]`;m+=JSON.stringify(c);let ct=f(c.outputs.type);m+=` as TypedAbiFunction<${P}, ${ct}>`,r.push(m)});let s=t.variables.map(c=>{let m=`${v(c.name)}: `,h=f(c.type);return m+=`${O(c,!1,null,!1)} as TypedAbiVariable<${h}>`,m}),l=t.variables.filter(c=>c.access==="constant").map(c=>`"${v(c.name)}": ${te(c.defaultValue)}`),g=i.map(c=>{let m=`${v(c.name)}: `,h=f(c.key),P=f(c.value);return m+=JSON.stringify(c),m+=` as TypedAbiMap<${h}, ${P}>`,m}),x=JSON.stringify(a),u=Qt(process.cwd(),t.contractFile);return`{
77
- ${I("functions",r)}
78
- ${I("variables",s)}
79
- ${I("maps",g)}
80
- ${I("constants",l)}
81
- ${x.slice(1,-1)},
82
- contractName: '${t.contractName}',
83
- contractFile: '${u}',
84
- }`}async function ot(t,e){let r=e.map(a=>{let s=Zt(a);return`${v(a.contractName)}: ${s}`}),n=await ee(),o=Gt(t);return`
85
- ${n}
86
-
87
- export const contracts: Record<string, TypedAbi> = {
88
- ${r.join(`,
89
- `)}
90
- } as const;
91
-
92
- ${o}
93
- `}function Gt(t){let e="";return"accounts"in t&&(e=`export const accounts = {
94
- ${Object.keys(t.accounts).map(n=>{let o=t.accounts[n];return`"${n}": {
95
- mnemonic: "${o.mnemonic}",
96
- balance: ${o.balance.toString()}n,
97
- address: "${o.address}",
98
- },`}).join(`
99
- `)}
100
- } as const;`),e}Uint8Array.prototype[O.custom]=function(){return`Uint8Array.from([${this.join(",")}])`};function te(t){return O(t,!1,null,!1)}function I(t,e){return`"${t}": {
101
- ${e.join(`,
102
- `)}
103
- },`}async function ee(){let t=Xt(C,"../../../core/src/abi-types.ts");return await Yt(t,{encoding:"utf-8"})}import{writeFile as re}from"fs/promises";import{basename as ne}from"path";import{resolveConfig as oe,format as ie}from"prettier";var se={printWidth:80,semi:!0,singleQuote:!0,trailingComma:"es5"};async function ae(){try{let t=await oe(process.cwd());if(t)return t}catch{}return se}async function ce(t,e){try{let r=ne(e),n=await ae();return ie(t,w(y({},n),{filepath:r}))}catch{}return t}async function T(t,e){let r=await ce(e,t);await re(t,r)}import{cvToValue as le}from"@clarigen/core";import{evalRaw as pe}from"@clarigen/native-bin";import{hexToCV as fe}from"micro-stacks/clarity";async function it({abi:t,contractIdentifier:e,provider:r}){let n=t.variables.map(i=>me({variable:i,provider:r,contractIdentifier:e}));return await Promise.all(n)}async function me({contractIdentifier:t,variable:e,provider:r}){let n=ue(e),o=await pe({contractAddress:t,code:n,provider:r}),i=fe(o.output_serialized),a=le(i,!0);return w(y({},e),{defaultValue:a})}function ue(t){let{access:e}=t;return e==="variable"?`(var-get ${t.name})`:t.name}var be=async({contractFile:t,outputFolder:e,provider:r,contractAddress:n,dirName:o,contractName:i,docsPath:a})=>{let s=b(process.cwd(),t),p=`${n}.${i}`,l=await Ce({contractIdentifier:p,contractFilePath:s,provider:r}),g=await it({abi:l,contractIdentifier:p,provider:r}),x=G(l,i),u=Z({contractFile:ye(process.cwd(),s),contractAddress:n,contractName:i}),$=Y({contractName:i,abi:l});typeof a<"u"&&await rt({contractFile:s,contractName:i,abi:l,docsPath:a,dirName:o});let c=b(e,o||".",i);return await $e(c,{recursive:!0}),await T(b(c,"abi.ts"),$),await T(b(c,"index.ts"),u),await T(b(c,"types.ts"),x),{abi:l,contractFile:s,contractName:i,dirName:o,contractAddress:n,variables:g}},k=async t=>{let e=await E(t),{contractsDir:r,outputDir:n,contracts:o}=e,i=b(t,n),a=await ge(),s=[];for(let u of o){let $=b(t,r,u.file),c=de(u.file),m=await be({contractFile:$,outputFolder:i,provider:a,contractAddress:u.address,dirName:c,contractName:u.name,docsPath:e.docs});s.push(m)}let p=tt(e);await nt(e);let l=b(i,"index.ts");await T(l,p);let g=await ot(e,s),x=b(i,"single.ts");await T(x,g)};import{watch as we}from"chokidar";import{basename as Ae}from"path";import{red as he,green as at}from"chalk";var Fe=mt("ora"),L=class extends xe{async run(){let{flags:e}=this.parse(L),r=process.cwd();if(e.watch){let n=Fe("Generating files").start(),{contractsDir:o}=await E(r),i=we([o],{cwd:r});try{await k(r),n.succeed("Finished generating files. Watching for changes.")}catch(a){n.fail(`Error generating files.
104
- ${a.message}`)}i.on("change",async a=>{let s=Ae(a);n.clear(),n.start(`Change detected for ${at(s)}, generating.`);try{await k(r),n.succeed(`Finished generating files for ${at(s)}. Watching for changes.`)}catch(p){let l=p.message;n.fail(`Error after saving ${he(s)}.
105
- ${l}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await k(r)}},A=L;A.description="Generate project files",A.strict=!0,A.hidden=!1,A.flags={help:st.help({char:"h"}),watch:st.boolean({char:"w",description:"Watch for changes to your contracts"})},A.args=[];export{A as Generate,Et as configFileExists,jt as configFilePath,q as defaultConfigFile,Z as generateIndexFile,er as generateInterface,Y as generateInterfaceFile,tt as generateProjectIndexFile,G as generateTypesFile,D as getArgName,It as getConfigFile,E as getProjectConfig,f as jsTypeFromAbiType,X as makePureTypes,Zr as run};