-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2233 lines (1965 loc) · 80.3 KB
/
index.ts
File metadata and controls
2233 lines (1965 loc) · 80.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import * as nodeHttp from 'node:http';
import { createInterface, type Interface as ReadlineInterface } from 'node:readline/promises';
import { spawn, spawnSync } from 'child_process';
import { createRequire } from 'module';
import { fileURLToPath, pathToFileURL } from 'url';
import { Command } from 'commander';
import { generateAppSolidity } from '@tokenhost/generator';
import {
computeSchemaHash,
importLegacyContractsJson,
lintThs,
listThsMigrations,
migrateThsSchema,
validateThsStructural,
type Issue,
type ThsSchema
} from '@tokenhost/schema';
import { createPublicClient, createWalletClient, encodeAbiParameters, http, isAddress, isHex, keccak256, toBytes, type Address, type Hex } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { anvil, sepolia } from 'viem/chains';
const require = createRequire(import.meta.url);
const Ajv2020 = require('ajv/dist/2020') as typeof import('ajv/dist/2020.js').default;
const addFormats = require('ajv-formats') as any;
const solc = require('solc') as any;
function readJsonFile(filePath: string): unknown {
const raw = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(raw);
}
function sha256Digest(data: Buffer | string): string {
const hash = crypto.createHash('sha256').update(data).digest('hex');
return `sha256:${hash}`;
}
function listFilesRecursive(dir: string): string[] {
const out: string[] = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...listFilesRecursive(full));
if (entry.isFile()) out.push(full);
}
return out;
}
function computeDirectoryDigest(dir: string): string {
const files = fs.existsSync(dir) ? listFilesRecursive(dir) : [];
const entries = files
.map((filePath) => {
const rel = path.relative(dir, filePath).replace(/\\\\/g, '/');
const digest = sha256Digest(fs.readFileSync(filePath));
return { path: rel, digest };
})
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
// RFC 8785 canonicalization + SHA-256 (SPEC 11.6.1).
return computeSchemaHash({ version: 1, files: entries });
}
function formatIssues(issues: Issue[]): string {
return issues
.map((i) => `${i.severity.toUpperCase()} ${i.code} ${i.path} - ${i.message}`)
.join('\n');
}
function loadThsSchemaOrThrow(schemaPath: string): ThsSchema {
const input = readJsonFile(schemaPath);
const structural = validateThsStructural(input);
if (!structural.ok) {
throw new Error(formatIssues(structural.issues));
}
const schema = structural.data!;
const lintIssues = lintThs(schema);
const errors = lintIssues.filter((i) => i.severity === 'error');
if (errors.length > 0) {
throw new Error(formatIssues(lintIssues));
}
return schema;
}
function ensureDir(dir: string) {
fs.mkdirSync(dir, { recursive: true });
}
function copyDir(srcDir: string, destDir: string) {
ensureDir(destDir);
for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
const src = path.join(srcDir, entry.name);
const dst = path.join(destDir, entry.name);
if (entry.isDirectory()) {
// Avoid accidentally copying heavy build outputs if a template folder was used as a dev workspace.
if (entry.name === 'node_modules' || entry.name === '.next' || entry.name === 'out') continue;
copyDir(src, dst);
continue;
}
if (entry.isFile()) {
fs.copyFileSync(src, dst);
}
}
}
function addGeneratedUiTestScaffold(uiDir: string, templateDir: string) {
const scaffoldDir = path.join(templateDir, 'test-scaffold');
if (!fs.existsSync(scaffoldDir)) {
throw new Error(`Missing test scaffold template at ${scaffoldDir}`);
}
copyDir(scaffoldDir, uiDir);
const packageJsonPath = path.join(uiDir, 'package.json');
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
const scripts = { ...(pkg.scripts || {}) };
scripts.test = scripts.test || 'pnpm run test:contract && pnpm run test:ui';
scripts['test:contract'] = scripts['test:contract'] || 'node tests/contract/smoke.mjs';
scripts['test:ui'] = scripts['test:ui'] || 'node tests/ui/smoke.mjs';
pkg.scripts = scripts;
fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n');
}
function publishManifestToUiSite(uiSiteDir: string, manifestJson: string) {
ensureDir(uiSiteDir);
ensureDir(path.join(uiSiteDir, '.well-known', 'tokenhost'));
fs.writeFileSync(path.join(uiSiteDir, '.well-known', 'tokenhost', 'manifest.json'), manifestJson);
fs.writeFileSync(path.join(uiSiteDir, 'manifest.json'), manifestJson);
}
function resolveNextExportUiTemplateDir(): string {
const here = path.dirname(fileURLToPath(import.meta.url));
const candidates = [
path.resolve(here, '../../templates/next-export-ui'),
path.resolve(here, '../templates/next-export-ui'),
path.resolve(here, 'templates/next-export-ui')
];
for (const c of candidates) {
if (fs.existsSync(path.join(c, 'package.json'))) return c;
}
const workspace = findUp('pnpm-workspace.yaml', process.cwd());
if (workspace) {
const root = path.dirname(workspace);
const c = path.join(root, 'packages', 'templates', 'next-export-ui');
if (fs.existsSync(path.join(c, 'package.json'))) return c;
}
throw new Error(
`Could not find Next.js export UI template directory (next-export-ui).\nLooked in:\n${candidates
.map((c) => ` - ${c}`)
.join('\n')}`
);
}
function toFileUrl(p: string): string {
return pathToFileURL(path.resolve(p)).toString();
}
function ensureTrailingSlash(url: string): string {
return url.endsWith('/') ? url : `${url}/`;
}
function runCommand(cmd: string, args: string[], opts?: { cwd?: string }) {
const res = spawnSync(cmd, args, {
cwd: opts?.cwd,
stdio: 'inherit'
});
if (res.error && (res.error as any).code === 'ENOENT') {
throw new Error(`${cmd} not found on PATH. Install it and retry.`);
}
if (res.status !== 0) {
throw new Error(`${cmd} ${args.join(' ')} failed with exit code ${res.status ?? 'unknown'}`);
}
}
function runPnpmCommand(args: string[], opts?: { cwd?: string }) {
// Prefer local/global pnpm; fall back to corepack if pnpm isn't installed.
const res = spawnSync('pnpm', args, { cwd: opts?.cwd, stdio: 'inherit' });
if (res.error && (res.error as any).code === 'ENOENT') {
const res2 = spawnSync('corepack', ['pnpm', ...args], { cwd: opts?.cwd, stdio: 'inherit' });
if (res2.error && (res2.error as any).code === 'ENOENT') {
throw new Error(`pnpm not found. Install pnpm or enable corepack, then retry.`);
}
if (res2.status !== 0) {
throw new Error(`corepack pnpm ${args.join(' ')} failed with exit code ${res2.status ?? 'unknown'}`);
}
return;
}
if (res.status !== 0) {
throw new Error(`pnpm ${args.join(' ')} failed with exit code ${res.status ?? 'unknown'}`);
}
}
function renderThsTs(schema: ThsSchema): string {
// Embed the full THS schema in the UI so it can render forms + routes without server-side code.
return (
`/*\n` +
` * GENERATED FILE\n` +
` *\n` +
` * This file is generated by \`th generate\` from the THS schema.\n` +
` */\n\n` +
`export const ths = ${JSON.stringify(schema, null, 2)} as const;\n\n` +
`export type Ths = typeof ths;\n`
);
}
function ensureEd25519PrivateKey(key: crypto.KeyObject): crypto.KeyObject {
const type = (key as any).asymmetricKeyType as string | undefined;
if (type && type !== 'ed25519') {
throw new Error(`Manifest signing key must be Ed25519 (got ${type}).`);
}
return key;
}
function loadManifestSigningKey(): crypto.KeyObject | null {
const keyPath = process.env.TH_MANIFEST_SIGNING_KEY_PATH;
if (keyPath) {
const pem = fs.readFileSync(keyPath, 'utf-8');
return ensureEd25519PrivateKey(crypto.createPrivateKey(pem));
}
const env = process.env.TH_MANIFEST_SIGNING_KEY || process.env.TH_MANIFEST_SIGNING_PRIVATE_KEY;
if (!env) return null;
const raw = env.trim();
if (raw.startsWith('-----BEGIN')) {
return ensureEd25519PrivateKey(crypto.createPrivateKey(raw));
}
// Assume base64-encoded PKCS#8 DER.
const b64 = raw.startsWith('base64:') ? raw.slice('base64:'.length) : raw;
const der = Buffer.from(b64, 'base64');
return ensureEd25519PrivateKey(crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }));
}
function computeKeyIdEd25519(privateKey: crypto.KeyObject): string {
const pub = crypto.createPublicKey(privateKey);
const spki = pub.export({ format: 'der', type: 'spki' }) as Buffer;
return sha256Digest(spki);
}
function signManifest(manifest: any, privateKey: crypto.KeyObject): { alg: string; keyId: string; sig: string } {
// Sign the canonical manifest digest of the manifest with signatures removed.
// Verifiers should recompute this same digest before verifying.
const unsigned = { ...manifest, signatures: [] };
const digest = computeSchemaHash(unsigned);
const signature = crypto.sign(null, Buffer.from(digest, 'utf-8'), privateKey);
return {
alg: 'ed25519',
keyId: computeKeyIdEd25519(privateKey),
sig: signature.toString('base64')
};
}
function findUp(filename: string, startDir: string): string | null {
let dir = path.resolve(startDir);
while (true) {
const candidate = path.join(dir, filename);
if (fs.existsSync(candidate)) return candidate;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
function loadRepoSchema(relPath: string): unknown {
const found = findUp(relPath, process.cwd());
if (!found) {
throw new Error(`Could not find ${relPath} (searched upward from ${process.cwd()})`);
}
return JSON.parse(fs.readFileSync(found, 'utf-8'));
}
function compileSolidity(sourcePath: string, contents: string, contractName: string): { abi: unknown; bytecode: string; deployedBytecode: string } {
const input = {
language: 'Solidity',
sources: {
[sourcePath]: { content: contents }
},
settings: {
optimizer: { enabled: true, runs: 200 },
outputSelection: {
'*': {
'*': ['abi', 'evm.bytecode.object', 'evm.deployedBytecode.object']
}
}
}
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
const errors = (output.errors || []).filter((e: any) => e.severity === 'error');
if (errors.length > 0) {
const msg = errors.map((e: any) => e.formattedMessage || e.message).join('\n');
throw new Error(`Solidity compile failed:\n${msg}`);
}
const compiled = output.contracts?.[sourcePath]?.[contractName];
if (!compiled) {
throw new Error(`Solidity compile output missing ${contractName} in ${sourcePath}`);
}
const abi = compiled.abi;
const bytecode = `0x${compiled.evm.bytecode.object}`;
const deployedBytecode = `0x${compiled.evm.deployedBytecode.object}`;
return { abi, bytecode, deployedBytecode };
}
function titleFromSlug(slug: string): string {
return slug
.split(/[-_]+/g)
.filter(Boolean)
.map((p) => (p.length ? p[0]!.toUpperCase() + p.slice(1) : p))
.join(' ');
}
type KnownChainName = 'anvil' | 'sepolia';
function resolveKnownChain(name: string): { chainName: KnownChainName; chain: any } {
const n = name.toLowerCase();
if (n === 'anvil') return { chainName: 'anvil', chain: anvil };
if (n === 'sepolia') return { chainName: 'sepolia', chain: sepolia };
throw new Error(`Unknown chain "${name}". Supported: anvil, sepolia`);
}
function envKeyForChain(chainName: KnownChainName, suffix: string): string {
return `${chainName.toUpperCase()}_${suffix}`;
}
function resolveRpcUrl(chainName: KnownChainName, chain: any, override?: string): string {
if (override) return override;
const env = process.env[envKeyForChain(chainName, 'RPC_URL')] || process.env.TH_RPC_URL;
if (env) return env;
const fromChain = chain?.rpcUrls?.default?.http?.[0];
if (fromChain) return fromChain;
throw new Error(`No RPC URL configured. Provide --rpc or set ${envKeyForChain(chainName, 'RPC_URL')} / TH_RPC_URL.`);
}
function buildChainConfigArtifact(args: { chainName: KnownChainName; chain: any; rpcUrl: string }): any {
const now = new Date().toISOString();
const isLocal = args.chainName === 'anvil';
const chainConfig: any = {
chainConfigVersion: '1.0.0',
chainId: args.chain.id,
name: String(args.chain?.name ?? args.chainName),
type: 'external-evm',
nativeCurrency: {
name: String(args.chain?.nativeCurrency?.name ?? 'Native'),
symbol: String(args.chain?.nativeCurrency?.symbol ?? 'NATIVE'),
decimals: Number(args.chain?.nativeCurrency?.decimals ?? 18)
},
trust: isLocal ? { posture: 'external', notes: 'Local dev chain' } : { posture: 'external' },
finality: {
model: isLocal ? 'instant' : 'probabilistic',
recommendedConfirmations: isLocal ? 0 : 2,
typicalSeconds: isLocal ? 1 : 12
},
rpc: {
endpoints: [
{
url: args.rpcUrl,
kind: 'public',
priority: 0,
capabilities: {
batching: true,
subscriptions: args.rpcUrl.startsWith('ws') || args.rpcUrl.startsWith('wss')
}
}
]
},
issuer: {
name: 'Token Host (local)',
issuedAt: now
},
signatures: [{ alg: 'none', sig: 'UNSIGNED' }]
};
if (args.chainName === 'sepolia') {
chainConfig.explorers = [
{
name: 'Etherscan',
url: 'https://sepolia.etherscan.io',
apiUrl: 'https://api-sepolia.etherscan.io/api'
}
];
}
return chainConfig;
}
const ANVIL_DEFAULT_PRIVATE_KEY: Hex = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
function normalizePrivateKey(privateKey: string): Hex {
const trimmed = privateKey.trim();
const hex = trimmed.startsWith('0x') ? trimmed : `0x${trimmed}`;
if (!/^0x[0-9a-fA-F]{64}$/.test(hex)) {
throw new Error('Invalid private key. Expected 32-byte hex string (0x + 64 hex chars).');
}
return hex as Hex;
}
function normalizeHexString(value: string, label: string): Hex {
const trimmed = value.trim();
const hex = trimmed.startsWith('0x') ? trimmed : `0x${trimmed}`;
if (!isHex(hex)) throw new Error(`Invalid ${label} hex string.`);
return hex as Hex;
}
function resolvePrivateKey(chainName: KnownChainName, override?: string): Hex {
if (override) return normalizePrivateKey(override);
const chainSpecific = process.env[envKeyForChain(chainName, 'PRIVATE_KEY')];
if (chainSpecific) return normalizePrivateKey(chainSpecific);
// Convenience for local dev. Avoid accidentally using a real PRIVATE_KEY on anvil.
if (chainName === 'anvil') return ANVIL_DEFAULT_PRIVATE_KEY;
const env = process.env.TH_PRIVATE_KEY || process.env.PRIVATE_KEY;
if (env) return normalizePrivateKey(env);
throw new Error(`Missing private key. Provide --private-key or set ${envKeyForChain(chainName, 'PRIVATE_KEY')} / TH_PRIVATE_KEY / PRIVATE_KEY.`);
}
function normalizeAddress(addr: string, label: string): Address {
const trimmed = addr.trim();
if (!isAddress(trimmed)) throw new Error(`Invalid ${label} address: ${addr}`);
return trimmed as Address;
}
function findConstructorInputs(abi: any): any[] {
if (!Array.isArray(abi)) return [];
const ctor = abi.find((x) => x && typeof x === 'object' && x.type === 'constructor');
return Array.isArray(ctor?.inputs) ? ctor.inputs : [];
}
function loadManifestSchema(): any {
return loadRepoSchema('schemas/tokenhost-release-manifest.schema.json');
}
function validateManifest(manifest: any): { ok: boolean; errors: unknown } {
const manifestSchema = loadManifestSchema();
const ajv = new Ajv2020({ allErrors: true, strict: false });
// Add standard JSON Schema format support (uri, date-time, ...).
addFormats(ajv);
const validate = ajv.compile(manifestSchema as any);
const ok = Boolean(validate(manifest));
return { ok, errors: validate.errors };
}
function loadChainConfigSchema(): any {
return loadRepoSchema('schemas/tokenhost-chain-config.schema.json');
}
function validateChainConfig(chainConfig: any): { ok: boolean; errors: unknown } {
const chainSchema = loadChainConfigSchema();
const ajv = new Ajv2020({ allErrors: true, strict: false });
addFormats(ajv);
const validate = ajv.compile(chainSchema as any);
const ok = Boolean(validate(chainConfig));
return { ok, errors: validate.errors };
}
function listSchemaCandidates(rootDir: string): string[] {
const out: string[] = [];
function walk(dir: string) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.next' || entry.name === 'dist' || entry.name === 'out') continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(full);
continue;
}
if (entry.isFile() && entry.name.endsWith('.schema.json')) {
out.push(full);
}
}
}
if (fs.existsSync(rootDir) && fs.statSync(rootDir).isDirectory()) {
walk(rootDir);
}
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
}
async function rpcRequest(rpcUrl: string, method: string, params: any[] = [], timeoutMs = 1000): Promise<any> {
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(rpcUrl, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
signal: controller.signal
});
if (!res.ok) {
throw new Error(`RPC HTTP ${res.status}`);
}
const json = await res.json();
if (json?.error) {
throw new Error(`RPC error: ${JSON.stringify(json.error)}`);
}
return json?.result;
} finally {
clearTimeout(t);
}
}
async function tryGetRpcChainId(rpcUrl: string, timeoutMs = 1000): Promise<number | null> {
try {
const hex = await rpcRequest(rpcUrl, 'eth_chainId', [], timeoutMs);
if (typeof hex !== 'string') return null;
const n = Number.parseInt(hex, 16);
if (!Number.isFinite(n)) return null;
return n;
} catch {
return null;
}
}
function isLocalHttpRpcUrl(rpcUrl: string): { host: string; port: number } | null {
try {
const u = new URL(rpcUrl);
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
const host = u.hostname;
const isLocal = host === '127.0.0.1' || host === 'localhost';
if (!isLocal) return null;
const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;
return { host, port };
} catch {
return null;
}
}
function pipeWithPrefix(stream: NodeJS.ReadableStream, prefix: string, dest: NodeJS.WriteStream) {
let buf = '';
stream.on('data', (chunk) => {
buf += String(chunk);
while (true) {
const idx = buf.indexOf('\n');
if (idx < 0) break;
const line = buf.slice(0, idx + 1);
buf = buf.slice(idx + 1);
dest.write(`${prefix}${line}`);
}
});
stream.on('end', () => {
if (buf) dest.write(`${prefix}${buf}\n`);
});
}
async function ensureAnvilRunning(rpcUrl: string, opts?: { start: boolean; expectedChainId?: number }): Promise<{ child: ReturnType<typeof spawn> | null }> {
const expectedChainId = opts?.expectedChainId ?? 31337;
const start = opts?.start ?? true;
const chainId = await tryGetRpcChainId(rpcUrl, 500);
if (chainId !== null) {
if (chainId !== expectedChainId) {
throw new Error(`RPC at ${rpcUrl} is chainId ${chainId}, expected ${expectedChainId}.`);
}
return { child: null };
}
if (!start) {
throw new Error(`RPC at ${rpcUrl} is not reachable. Start anvil (or pass --no-start-anvil).`);
}
const local = isLocalHttpRpcUrl(rpcUrl);
if (!local) {
throw new Error(`--start-anvil only supports localhost RPC URLs (got ${rpcUrl}).`);
}
const anvilVersion = spawnSync('anvil', ['--version'], { encoding: 'utf-8' });
if (anvilVersion.error && (anvilVersion.error as any).code === 'ENOENT') {
throw new Error('Missing Foundry: `anvil` not found on PATH. Install Foundry from https://book.getfoundry.sh/getting-started/installation');
}
const child = spawn('anvil', ['--host', local.host, '--port', String(local.port), '--chain-id', String(expectedChainId)], {
stdio: ['ignore', 'pipe', 'pipe']
});
if (child.stdout) pipeWithPrefix(child.stdout, '[anvil] ', process.stdout);
if (child.stderr) pipeWithPrefix(child.stderr, '[anvil] ', process.stderr);
const startedAt = Date.now();
const timeoutMs = 10_000;
while (Date.now() - startedAt < timeoutMs) {
const nowChainId = await tryGetRpcChainId(rpcUrl, 500);
if (nowChainId === expectedChainId) return { child };
await new Promise((r) => setTimeout(r, 200));
}
child.kill('SIGTERM');
throw new Error(`Timed out waiting for anvil at ${rpcUrl} to become ready.`);
}
type FaucetConfig = {
enabled: boolean;
rpcUrl: string;
chainId: number;
targetWei: bigint;
};
function startUiSiteServer(args: {
buildDir: string;
host: string;
port: number;
faucet?: FaucetConfig | null;
}): { server: nodeHttp.Server; url: string } {
const resolvedBuildDir = path.resolve(args.buildDir);
const uiSiteDir = path.join(resolvedBuildDir, 'ui-site');
if (!fs.existsSync(uiSiteDir)) {
throw new Error(`Missing ui-site/ in ${resolvedBuildDir}. Re-run \`th build\` without \`--no-ui\`.`);
}
if (!Number.isInteger(args.port) || args.port <= 0 || args.port > 65535) {
throw new Error(`Invalid port: ${args.port}`);
}
const host = String(args.host || '127.0.0.1');
const port = args.port;
const rootAbs = path.resolve(uiSiteDir);
const faucet = args.faucet ?? null;
const faucetPath = '/__tokenhost/faucet';
const faucetTargetEth = faucet?.targetWei ? Number(faucet.targetWei / 10n ** 18n) : 10;
function contentTypeForPath(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case '.html':
return 'text/html; charset=utf-8';
case '.js':
return 'application/javascript; charset=utf-8';
case '.css':
return 'text/css; charset=utf-8';
case '.json':
case '.map':
return 'application/json; charset=utf-8';
case '.svg':
return 'image/svg+xml';
case '.png':
return 'image/png';
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.gif':
return 'image/gif';
case '.webp':
return 'image/webp';
case '.ico':
return 'image/x-icon';
case '.woff2':
return 'font/woff2';
case '.woff':
return 'font/woff';
case '.ttf':
return 'font/ttf';
case '.txt':
return 'text/plain; charset=utf-8';
default:
return 'application/octet-stream';
}
}
function sendText(res: nodeHttp.ServerResponse, status: number, text: string) {
res.statusCode = status;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(text);
}
function sendJson(res: nodeHttp.ServerResponse, status: number, value: unknown) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(value));
}
function toHexQuantity(n: bigint): string {
if (n < 0n) throw new Error('Negative quantity not allowed.');
return `0x${n.toString(16)}`;
}
async function trySetLocalBalance(rpcUrl: string, addr: string, wei: bigint): Promise<{ ok: boolean; method?: string; error?: string }> {
const qty = toHexQuantity(wei);
const methods = ['anvil_setBalance', 'hardhat_setBalance'];
for (const method of methods) {
try {
await rpcRequest(rpcUrl, method, [addr, qty], 2000);
return { ok: true, method };
} catch (e: any) {
const msg = String(e?.message ?? e ?? '');
const unsupported =
/method not found/i.test(msg) ||
/unsupported/i.test(msg) ||
/does not exist/i.test(msg) ||
/-32601/.test(msg);
if (!unsupported) return { ok: false, method, error: msg };
}
}
return { ok: false, error: 'No supported local balance RPC method found (anvil_setBalance, hardhat_setBalance).' };
}
function readBody(req: nodeHttp.IncomingMessage, maxBytes = 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
let raw = '';
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('Request body too large.'));
req.destroy();
return;
}
raw += chunk.toString('utf-8');
});
req.on('end', () => resolve(raw));
req.on('error', reject);
});
}
const server = nodeHttp.createServer((req, res) => {
if (!req.url) return sendText(res, 400, 'Bad Request');
let pathname = '/';
try {
pathname = new URL(req.url, `http://${host}:${port}`).pathname || '/';
} catch {
return sendText(res, 400, 'Bad Request');
}
try {
pathname = decodeURIComponent(pathname);
} catch {
return sendText(res, 400, 'Bad Request');
}
if (pathname === faucetPath) {
(async () => {
const enabled = Boolean(faucet?.enabled && faucet.rpcUrl && faucet.chainId === anvil.id);
if (req.method === 'GET' || req.method === 'HEAD') {
return sendJson(res, 200, {
ok: true,
enabled,
chainId: faucet?.chainId ?? null,
targetEthDefault: faucetTargetEth,
reason: enabled ? null : faucet ? 'disabled' : 'not-configured'
});
}
if (req.method !== 'POST') {
res.setHeader('Allow', 'GET, HEAD, POST');
return sendText(res, 405, 'Method Not Allowed');
}
if (!enabled) {
return sendJson(res, 400, { ok: false, error: 'Faucet is disabled.' });
}
try {
const raw = await readBody(req);
const parsed = raw.trim() ? JSON.parse(raw) : null;
const addr = normalizeAddress(String(parsed?.address ?? ''), 'address');
const rpcChainId = await tryGetRpcChainId(faucet!.rpcUrl, 1000);
if (rpcChainId === null) {
return sendJson(res, 503, { ok: false, error: `RPC not reachable at ${faucet!.rpcUrl}. Start anvil and retry.` });
}
if (rpcChainId !== faucet!.chainId) {
return sendJson(res, 409, {
ok: false,
error: `RPC chainId mismatch. RPC=${rpcChainId} expected=${faucet!.chainId}.`
});
}
const oldHex = (await rpcRequest(faucet!.rpcUrl, 'eth_getBalance', [addr, 'latest'], 2000)) as string;
const oldWei = BigInt(oldHex);
const targetWei = faucet!.targetWei;
let didSet = false;
let setMethod: string | null = null;
if (oldWei < targetWei) {
const setResult = await trySetLocalBalance(faucet!.rpcUrl, addr, targetWei);
if (!setResult.ok) {
return sendJson(res, 400, { ok: false, error: setResult.error ?? 'Failed to set balance.' });
}
didSet = true;
setMethod = setResult.method ?? null;
}
const newHex = (await rpcRequest(faucet!.rpcUrl, 'eth_getBalance', [addr, 'latest'], 2000)) as string;
const newWei = BigInt(newHex);
return sendJson(res, 200, {
ok: true,
address: addr,
chainId: faucet!.chainId,
targetWei: toHexQuantity(targetWei),
oldBalanceWei: toHexQuantity(oldWei),
newBalanceWei: toHexQuantity(newWei),
method: setMethod,
didSet
});
} catch (e: any) {
return sendJson(res, 400, { ok: false, error: String(e?.message ?? e) });
}
})();
return;
}
if (req.method && req.method !== 'GET' && req.method !== 'HEAD') {
res.setHeader('Allow', 'GET, HEAD');
return sendText(res, 405, 'Method Not Allowed');
}
if (!pathname.startsWith('/')) pathname = `/${pathname}`;
const rel = pathname.replace(/^\/+/, '');
const unsafeAbs = path.resolve(rootAbs, rel);
const withinRoot = unsafeAbs === rootAbs || unsafeAbs.startsWith(rootAbs + path.sep);
if (!withinRoot) return sendText(res, 400, 'Bad Request');
// Redirect to trailing-slash routes (Next export uses trailingSlash: true).
if (!pathname.endsWith('/') && fs.existsSync(unsafeAbs) && fs.statSync(unsafeAbs).isDirectory()) {
res.statusCode = 308;
res.setHeader('Location', pathname + '/');
res.setHeader('Cache-Control', 'no-store');
res.end();
return;
}
let filePath = unsafeAbs;
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
filePath = path.join(filePath, 'index.html');
} else if (!fs.existsSync(filePath)) {
// Convenience: allow /foo -> /foo/index.html if present.
const dirIndex = path.join(filePath, 'index.html');
if (fs.existsSync(dirIndex)) {
res.statusCode = 308;
res.setHeader('Location', pathname.endsWith('/') ? pathname : pathname + '/');
res.setHeader('Cache-Control', 'no-store');
res.end();
return;
}
return sendText(res, 404, 'Not Found');
}
try {
const stat = fs.statSync(filePath);
if (!stat.isFile()) return sendText(res, 404, 'Not Found');
res.statusCode = 200;
res.setHeader('Content-Type', contentTypeForPath(filePath));
res.setHeader('Content-Length', String(stat.size));
res.setHeader('Cache-Control', 'no-store');
if (req.method === 'HEAD') {
res.end();
return;
}
fs.createReadStream(filePath).pipe(res);
} catch (e: any) {
return sendText(res, 500, String(e?.message ?? e ?? 'Internal Server Error'));
}
});
server.on('error', (e: any) => {
console.error(String(e?.message ?? e ?? e));
process.exitCode = 1;
});
const url = `http://${host}:${port}/`;
server.listen(port, host, () => {
console.log(`Serving ${uiSiteDir}`);
console.log(url);
const manifestCandidates = [
path.join(uiSiteDir, '.well-known', 'tokenhost', 'manifest.json'),
path.join(uiSiteDir, 'manifest.json'),
path.join(resolvedBuildDir, 'manifest.json')
];
const manifestPath = manifestCandidates.find((p) => fs.existsSync(p)) || null;
if (manifestPath) {
try {
const manifest = readJsonFile(manifestPath) as any;
const deployments = Array.isArray(manifest?.deployments) ? manifest.deployments : [];
const deployment = deployments.find((d: any) => d && d.role === 'primary') ?? deployments[0] ?? null;
const addr = String(deployment?.deploymentEntrypointAddress ?? '');
const chainId = deployment?.chainId ?? null;
console.log(`manifest: ${manifestPath}`);
console.log(`deployment: chainId=${chainId ?? 'unknown'} address=${addr || 'unknown'}`);
const zeroAddress = '0x0000000000000000000000000000000000000000';
if (addr && addr.toLowerCase() === zeroAddress) {
console.log('');
console.log('Not deployed: deploymentEntrypointAddress is 0x0.');
console.log(`Run: th deploy ${resolvedBuildDir} --chain anvil`);
console.log('Then refresh this page.');
}
} catch {
// Ignore manifest parse errors; the UI will surface them at runtime.
}
}
});
return { server, url };
}
function buildFromSchema(
schema: ThsSchema,
outDir: string,
opts: { ui: boolean; quiet?: boolean; schemaPathForHints?: string }
): { outDir: string; uiBundleDir: string | null; uiSiteDir: string | null } {
const resolvedOutDir = path.resolve(outDir);
ensureDir(resolvedOutDir);
// 1) Generate Solidity source
const appSol = generateAppSolidity(schema);
ensureDir(path.join(resolvedOutDir, path.dirname(appSol.path)));
fs.writeFileSync(path.join(resolvedOutDir, appSol.path), appSol.contents);
// 2) Compile (solc-js)
const sourceRelPath = appSol.path.replace(/\\\\/g, '/');
const compiled = compileSolidity(sourceRelPath, appSol.contents, 'App');
const compiledArtifact = {
contractName: 'App',
abi: compiled.abi,
bytecode: compiled.bytecode,
deployedBytecode: compiled.deployedBytecode
};
const compiledJson = JSON.stringify(compiledArtifact, null, 2);
const compiledOutPath = path.join(resolvedOutDir, 'compiled', 'App.json');
ensureDir(path.dirname(compiledOutPath));
fs.writeFileSync(compiledOutPath, compiledJson);
// 3) Write schema copy
fs.writeFileSync(path.join(resolvedOutDir, 'schema.json'), JSON.stringify(schema, null, 2));
// 4) Package build artifacts (SPEC 11)
const sourcesTgzPath = path.join(resolvedOutDir, 'sources.tgz');
const compiledTgzPath = path.join(resolvedOutDir, 'compiled.tgz');
runCommand('tar', ['-czf', sourcesTgzPath, '-C', resolvedOutDir, path.dirname(appSol.path)]);
runCommand('tar', ['-czf', compiledTgzPath, '-C', resolvedOutDir, 'compiled']);
// 5) Build UI bundle (Next.js static export) (SPEC 8 / 11)
const emptyUiBundleDigest = computeSchemaHash({ version: 1, files: [] });
let uiBundleDigest = emptyUiBundleDigest;
let uiBaseUrl = ensureTrailingSlash(process.env.TH_UI_BASE_URL ?? 'http://localhost/');
let uiBundleDir: string | null = null;
let uiSiteDir: string | null = null;
if (opts.ui) {
uiBundleDir = path.join(resolvedOutDir, 'ui-bundle');
uiSiteDir = path.join(resolvedOutDir, 'ui-site');
fs.rmSync(uiBundleDir, { recursive: true, force: true });
ensureDir(uiBundleDir);
const uiWorkDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tokenhost-ui-build-'));
try {
const templateDir = resolveNextExportUiTemplateDir();
copyDir(templateDir, uiWorkDir);
// Inject schema for client-side routing/forms.
const thsTsPath = path.join(uiWorkDir, 'src', 'generated', 'ths.ts');
ensureDir(path.dirname(thsTsPath));
fs.writeFileSync(thsTsPath, renderThsTs(schema));
// Ship ABI alongside the UI so it can operate without additional servers.
const compiledPublicPath = path.join(uiWorkDir, 'public', 'compiled', 'App.json');
ensureDir(path.dirname(compiledPublicPath));
fs.writeFileSync(compiledPublicPath, compiledJson);
// Do not bake a manifest into the UI bundle; it is published separately and signed.
const bakedManifestPath = path.join(uiWorkDir, 'public', '.well-known', 'tokenhost', 'manifest.json');
if (fs.existsSync(bakedManifestPath)) fs.rmSync(bakedManifestPath, { force: true });
runPnpmCommand(['install'], { cwd: uiWorkDir });
runPnpmCommand(['build'], { cwd: uiWorkDir });
const exportedDir = path.join(uiWorkDir, 'out');
if (!fs.existsSync(exportedDir)) {
throw new Error(`UI build did not produce an export directory at ${exportedDir}.`);
}
// Copy the static export output into the build output directory.
copyDir(exportedDir, uiBundleDir);
} finally {
fs.rmSync(uiWorkDir, { recursive: true, force: true });