@typesol/cli 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -458,8 +458,8 @@ export class CreateEmitter extends CpiCoreEmitter {
458
458
  this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
459
459
  if (this.created.has(target.name))
460
460
  this.fail(node, `${target.name} is already created`);
461
- if (node.arguments.length !== 1)
462
- this.fail(node, `${call}(payer) takes the payer`);
461
+ if (node.arguments.length !== 1 && node.arguments.length !== 2)
462
+ this.fail(node, `${call}(payer, tokenProgram?) takes the payer and, with several token programs, the one to use`);
463
463
  const payer = this.accountParam(node.arguments[0], "the payer");
464
464
  if (payer.kind.kind !== "signer" || !payer.kind.mut)
465
465
  this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
@@ -473,11 +473,22 @@ export class CreateEmitter extends CpiCoreEmitter {
473
473
  };
474
474
  const ataProgram = need("ataProgram", "an AssociatedTokenProgram");
475
475
  const system = need("system", "a SystemProgram");
476
- const tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
477
- // The address is derived under the token program: with two, which one the mint uses is not known here.
478
- const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
479
- if (tokenPrograms.length > 1)
480
- this.fail(node, `${call}(...) needs exactly one token program parameter (found ${tokenPrograms.map((o) => o.name).join(", ")}); use TokenInterface`);
476
+ // The address is derived under the token program: the one passed (Anchor's associated_token::token_program), or the
477
+ // instruction's only one.
478
+ let tokenProgram;
479
+ if (node.arguments[1]) {
480
+ tokenProgram = this.accountParam(node.arguments[1], "the token program");
481
+ if (tokenProgram.kind.kind !== "tokenProgram")
482
+ this.fail(node.arguments[1], "pass a TokenProgram, Token2022Program or TokenInterface parameter");
483
+ if (tokenProgram.optional)
484
+ this.fail(node.arguments[1], `${call}(...) needs "${tokenProgram.name}": it cannot be optional`);
485
+ }
486
+ else {
487
+ tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
488
+ const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
489
+ if (tokenPrograms.length > 1)
490
+ this.fail(node, `${call}(...) needs to know the token program: pass it, ${call}(payer, ${tokenPrograms[0].name}) (found ${tokenPrograms.map((o) => o.name).join(", ")})`);
491
+ }
481
492
  const { owner, mint } = target.constraints.ata;
482
493
  const a = `a_${target.name}`;
483
494
  const create = `TS_TRY(ts_ata_create(params, a_${ataProgram.name}, a_${payer.name}, ${a}, a_${owner}, a_${mint}, a_${system.name}, a_${tokenProgram.name}, false));`;
@@ -504,17 +515,26 @@ export class CreateEmitter extends CpiCoreEmitter {
504
515
  return result;
505
516
  }
506
517
  systemTransfer(node) {
507
- if (node.arguments.length !== 3)
508
- this.fail(node, "transfer(from, to, lamports) takes three arguments");
509
- const [fromN, toN, amtN] = node.arguments;
518
+ const a = node.arguments;
519
+ if (a.length !== 3 && a.length !== 4)
520
+ this.fail(node, "transfer(from, to, lamports, signerSeeds?)");
521
+ const [fromN, toN, amtN] = a;
510
522
  const from = this.accountParam(fromN, "transfer's source");
511
- if (from.kind.kind !== "signer" || !from.kind.mut)
512
- this.fail(fromN, "the source must be a Mut<Signer>");
523
+ if (a.length === 3 && (from.kind.kind !== "signer" || !from.kind.mut))
524
+ this.fail(fromN, "the source must be a Mut<Signer>, or a Mut<AccountInfo> PDA of this program with signerSeeds");
525
+ if (a.length === 4 && !isWritable(from.kind))
526
+ this.fail(fromN, "the source must be writable (Mut<...>)");
513
527
  const to = this.accountParam(toN, "transfer's destination");
514
528
  if (!isWritable(to.kind))
515
529
  this.fail(toN, "the destination must be writable (Mut<...>)");
516
530
  const amt = this.expect(this.expr(amtN, U64), U64, amtN);
517
- this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
531
+ if (a.length === 3)
532
+ this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
533
+ else {
534
+ // A system-owned PDA of this program (a SOL vault) pays.
535
+ const s = this.signingSeeds(a[3]);
536
+ this.line(`TS_TRY(ts_system_transfer_signed(params, a_${from.name}, a_${to.name}, ${amt.c}, ${s.name}, ${s.count}));`);
537
+ }
518
538
  return undefined;
519
539
  }
520
540
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
@@ -545,4 +565,27 @@ export class CreateEmitter extends CpiCoreEmitter {
545
565
  ], buf, len, seeds);
546
566
  return undefined;
547
567
  }
568
+ /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
569
+ allocateOrAssign(node, system, method) {
570
+ const a = node.arguments;
571
+ if (a.length !== 2 && a.length !== 3)
572
+ this.fail(node, `${method}(account, ${method === "allocate" ? "space" : "owner"}, signerSeeds?)`);
573
+ const acct = this.accountParam(a[0], "the account");
574
+ if (!isWritable(acct.kind))
575
+ this.fail(a[0], `the account must be writable (Mut<Signer> or Mut<AccountInfo>)`);
576
+ if (acct.kind.kind !== "signer" && a.length !== 3)
577
+ this.fail(a[0], "the account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
578
+ const { buf, len, put, finish } = this.byteBuffer("sys", 36, "TS_ERR_INSTRUCTION_DATA", "system instruction");
579
+ const tag = this.tmp("tag");
580
+ this.line(`uint32_t ${tag} = ${method === "allocate" ? 8 : 1}; /* ${method === "allocate" ? "Allocate" : "Assign"} */`);
581
+ put(`&${tag}`, "4", 4);
582
+ if (method === "allocate")
583
+ this.serialize(this.expect(this.expr(a[1], U64), U64, a[1]), a[1], put);
584
+ else
585
+ this.serialize(this.expect(this.expr(a[1], PUBKEY), PUBKEY, a[1]), a[1], put);
586
+ finish(node);
587
+ const seeds = a.length === 3 ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
588
+ this.cpi(`a_${system.name}`, [[`a_${acct.name}`, true, true]], buf, len, seeds);
589
+ return undefined;
590
+ }
548
591
  }
@@ -874,14 +874,18 @@ export class ExpressionEmitter extends StorageEmitter {
874
874
  break;
875
875
  case K.AsteriskToken:
876
876
  // u64: skips the 128-bit __multi3 call when both factors fit in 32 bits (see ts_mul_overflow_u64).
877
- this.line(`if (${type.name === "u64" ? "ts_mul_overflow_u64" : "__builtin_mul_overflow"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
877
+ // u128: the native 64-bit multiply when both factors fit in 64 bits (see ts_mul_overflow_u128).
878
+ this.line(`if (${type.name === "u64" ? "ts_mul_overflow_u64" : type.name === "u128" ? "ts_mul_overflow_u128" : "__builtin_mul_overflow"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
878
879
  break;
879
880
  case K.SlashToken:
880
881
  case K.PercentToken: {
881
882
  this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
882
883
  if (INT_INFO[type.name].signed)
883
884
  this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
884
- this.line(`${t} = ${left.c} ${op === K.SlashToken ? "/" : "%"} ${right.c};`);
885
+ if (type.name === "u128")
886
+ this.line(`${t} = ${op === K.SlashToken ? "ts_div_u128" : "ts_rem_u128"}(${left.c}, ${right.c});`);
887
+ else
888
+ this.line(`${t} = ${left.c} ${op === K.SlashToken ? "/" : "%"} ${right.c};`);
885
889
  break;
886
890
  }
887
891
  case K.AmpersandToken:
@@ -69,6 +69,10 @@ export class StatementEmitter extends CpiEmitter {
69
69
  return this.doLoop(stmt);
70
70
  if (ts.isForInStatement(stmt))
71
71
  this.fail(stmt, "for … in is not supported: use for (init; cond; step), for (const x of list), while or do … while");
72
+ if (ts.isThrowStatement(stmt))
73
+ this.fail(stmt, 'throw is not supported: fail the instruction with require(false, ErrorCode.X) or require(cond, "message")');
74
+ if (ts.isTryStatement(stmt))
75
+ this.fail(stmt, "try/catch is not supported: a failed check or CPI aborts the whole instruction, so check first with require(…)");
72
76
  this.fail(stmt, `${ts.SyntaxKind[stmt.kind]} is not supported in TypeSOL`);
73
77
  }
74
78
  returnStatement(stmt) {
@@ -897,6 +901,17 @@ export class StatementEmitter extends CpiEmitter {
897
901
  continue;
898
902
  }
899
903
  const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
904
+ // A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
905
+ if (fn === "signer") {
906
+ if (mutable)
907
+ this.fail(d, "bind seed lists with const");
908
+ const s = this.signerSeedsArg(init);
909
+ this.line(`const SolSignerSeed *${c} = ${s.name};`);
910
+ this.line(`int ${c}__n = ${s.count};`);
911
+ this.line(`(void)${c}; (void)${c}__n;`);
912
+ this.scopes.at(-1).set(name, { c, type: { kind: "signerSeeds" }, mutable: false });
913
+ continue;
914
+ }
900
915
  if (fn === "fixedArray") {
901
916
  const t = this.localArray(init, c);
902
917
  this.scopes.at(-1).set(name, { c, type: t, mutable });
@@ -114,6 +114,7 @@ export class TokenEmitter extends CreateEmitter {
114
114
  const optKey = { kind: "option", inner: PUBKEY };
115
115
  const U16 = { kind: "int", name: "u16" };
116
116
  const I16 = { kind: "int", name: "i16" };
117
+ const decimals = (mint) => (put) => put(`&a_${mint.name}->data[44]`, "1", 1);
117
118
  const byte = (k) => (put) => {
118
119
  const t = this.tmp("b");
119
120
  this.line(`uint8_t ${t} = ${k};`);
@@ -406,6 +407,48 @@ export class TokenEmitter extends CreateEmitter {
406
407
  ], s);
407
408
  return undefined;
408
409
  }
410
+ // The checked forms take the decimals from the mint, as transferChecked does.
411
+ case "approveChecked": {
412
+ arity(5);
413
+ const src = want(a[0], "token", true, "the source");
414
+ const mint = want(a[1], "mint", false, "the mint");
415
+ const delegate = this.accountParam(a[2], "the delegate");
416
+ const owner = this.accountParam(a[3], "the owner");
417
+ const s = this.signerSeeds(a[5], owner, a[3]);
418
+ simple(13, [value(a[4], U64), decimals(mint)], [
419
+ [src, true, false],
420
+ [mint, false, false],
421
+ [delegate, false, false],
422
+ [owner, false, true],
423
+ ], s);
424
+ return undefined;
425
+ }
426
+ case "mintToChecked": {
427
+ arity(4);
428
+ const mint = want(a[0], "mint", true, "the mint");
429
+ const to = want(a[1], "token", true, "the destination");
430
+ const auth = this.accountParam(a[2], "the mint authority");
431
+ const s = this.signerSeeds(a[4], auth, a[2]);
432
+ simple(14, [value(a[3], U64), decimals(mint)], [
433
+ [mint, true, false],
434
+ [to, true, false],
435
+ [auth, false, true],
436
+ ], s);
437
+ return undefined;
438
+ }
439
+ case "burnChecked": {
440
+ arity(4);
441
+ const from = want(a[0], "token", true, "the burned account");
442
+ const mint = want(a[1], "mint", true, "the mint");
443
+ const auth = this.accountParam(a[2], "the authority");
444
+ const s = this.signerSeeds(a[4], auth, a[2]);
445
+ simple(15, [value(a[3], U64), decimals(mint)], [
446
+ [from, true, false],
447
+ [mint, true, false],
448
+ [auth, false, true],
449
+ ], s);
450
+ return undefined;
451
+ }
409
452
  case "revoke": {
410
453
  arity(2);
411
454
  const src = want(a[0], "token", true, "the source");
package/dist/templates.js CHANGED
@@ -256,46 +256,24 @@ export function refund(
256
256
  }
257
257
  `,
258
258
  test: (name) => testFile(name, {
259
- imports: `import { AccountState, getMintEncoder, getMintSize, getTokenDecoder, getTokenEncoder, getTokenSize } from "@solana-program/token";\nimport { type Address, type KeyPairSigner, generateKeyPairSigner, lamports } from "@solana/kit";\n`,
259
+ imports: `import { type Address, type KeyPairSigner } from "@solana/kit";\n`,
260
260
  body: `
261
- const TOKEN = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address;
262
- /** A mint, written straight into the VM (a real client sends System CreateAccount + InitializeMint2). */
263
- const mint = async (authority: Address) => {
264
- const address = (await generateKeyPairSigner()).address;
265
- const data = getMintEncoder().encode({ mintAuthority: authority, supply: 0n, decimals: 6, isInitialized: true, freezeAuthority: null });
266
- t.svm.setAccount({ address, data: new Uint8Array(data), executable: false, lamports: lamports(1_461_600n), programAddress: TOKEN, space: BigInt(getMintSize()) });
267
- return address;
268
- };
269
- /** A token account of owner for mint holding amount, written straight into the VM. */
270
- const tokenAccount = async (owner: Address, mintAddress: Address, amount: bigint) => {
271
- const address = (await generateKeyPairSigner()).address;
272
- const data = getTokenEncoder().encode({
273
- mint: mintAddress,
274
- owner,
275
- amount,
276
- delegate: null,
277
- state: AccountState.Initialized,
278
- isNative: null,
279
- delegatedAmount: 0n,
280
- closeAuthority: null,
281
- });
282
- t.svm.setAccount({ address, data: new Uint8Array(data), executable: false, lamports: lamports(2_039_280n), programAddress: TOKEN, space: BigInt(getTokenSize()) });
283
- return address;
284
- };
285
- const balance = (address: Address) => {
286
- const account = t.svm.getAccount(address);
287
- return account.exists ? getTokenDecoder().decode(account.data).amount : null;
288
- };
261
+ // Mints and token accounts are written straight into the VM (a real client sends System CreateAccount and
262
+ // InitializeMint2 / InitializeAccount3).
263
+ const mint = (authority: KeyPairSigner) => t.mint({ authority: authority.address, decimals: 6 });
264
+ const tokenAccount = (owner: KeyPairSigner | Address, mintAddress: Address, amount: bigint) =>
265
+ t.tokenAccount({ owner: typeof owner === "string" ? owner : owner.address, mint: mintAddress, amount });
266
+ const balance = (address: Address) => t.tokenBalance(address);
289
267
 
290
268
  it("escrows mint A for mint B; the taker swaps, the maker can refund", async () => {
291
269
  const maker = await t.wallet();
292
270
  const taker = await t.wallet();
293
- const mintA = await mint(maker.address);
294
- const mintB = await mint(taker.address);
295
- const makerTokenA = await tokenAccount(maker.address, mintA, 1_000n);
296
- const makerTokenB = await tokenAccount(maker.address, mintB, 0n);
297
- const takerTokenA = await tokenAccount(taker.address, mintA, 0n);
298
- const takerTokenB = await tokenAccount(taker.address, mintB, 500n);
271
+ const mintA = await mint(maker);
272
+ const mintB = await mint(taker);
273
+ const makerTokenA = await tokenAccount(maker, mintA, 1_000n);
274
+ const makerTokenB = await tokenAccount(maker, mintB, 0n);
275
+ const takerTokenA = await tokenAccount(taker, mintA, 0n);
276
+ const takerTokenB = await tokenAccount(taker, mintB, 500n);
299
277
 
300
278
  const open = async (seed: bigint) => {
301
279
  const offer = await t.pda("offer", maker, seed);
@@ -319,6 +297,5 @@ export function refund(
319
297
  });
320
298
  `,
321
299
  }),
322
- devDependencies: { "@solana-program/token": "~0.18.0" },
323
300
  },
324
301
  };
package/dist/testing.d.ts CHANGED
@@ -62,6 +62,36 @@ export interface TestProgram {
62
62
  balance(address: Address): bigint;
63
63
  /** A kit RPC and subscriptions pair over this LiteSVM, for the generated client (`svmConnection`). */
64
64
  connection: SvmConnection;
65
+ /** The name of an error code: the program's own (6000+), TypeSOL's or Anchor's; undefined for others. */
66
+ errorName(code: number): string | undefined;
67
+ /**
68
+ * A mint written straight into the VM (as System CreateAccount + InitializeMint2 would leave it). SPL Token unless
69
+ * `tokenProgram` is Token-2022; no extensions.
70
+ */
71
+ mint(opts: {
72
+ authority: Address;
73
+ decimals?: number;
74
+ supply?: bigint;
75
+ freezeAuthority?: Address;
76
+ tokenProgram?: Address;
77
+ address?: Address;
78
+ }): Promise<Address>;
79
+ /** A token account of `owner` for `mint` holding `amount`, written straight into the VM (at `address`, e.g. an ATA). */
80
+ tokenAccount(opts: {
81
+ mint: Address;
82
+ owner: Address;
83
+ amount?: bigint;
84
+ tokenProgram?: Address;
85
+ address?: Address;
86
+ }): Promise<Address>;
87
+ /** The amount a token account holds, or null when it does not exist. */
88
+ tokenBalance(address: Address): bigint | null;
89
+ /** Move the Clock: to a unix timestamp and/or a slot, or forward by `seconds`. */
90
+ warp(to: {
91
+ unixTimestamp?: bigint;
92
+ slot?: bigint;
93
+ seconds?: bigint;
94
+ }): void;
65
95
  }
66
96
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
67
97
  export declare function testProgram(program: string, from: string | URL): Promise<TestProgram>;
package/dist/testing.js CHANGED
@@ -22,6 +22,7 @@ import { FailedTransactionMetadata, LiteSVM } from "litesvm";
22
22
  import { createHash } from "node:crypto";
23
23
  import path from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
+ import { TYPESOL_ERRORS } from "./tools/clientgen.js";
25
26
  import { svmConnection } from "./tools/svmrpc.js";
26
27
  import { buildWorkspace, findWorkspace } from "./workspace.js";
27
28
  export { svmConnection };
@@ -31,6 +32,7 @@ const BIG = new Set(["u64", "i64", "u128", "i128"]);
31
32
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
32
33
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
33
34
  const isSigner = (v) => typeof v === "object" && v !== null && "address" in v && "signTransactions" in v;
35
+ const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
34
36
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
35
37
  export async function testProgram(program, from) {
36
38
  const start = typeof from === "string" && !from.startsWith("file:") ? from : path.dirname(fileURLToPath(from));
@@ -289,8 +291,11 @@ export function programHarness(svm, programId, idl) {
289
291
  return res;
290
292
  },
291
293
  ok(res) {
292
- if (res instanceof FailedTransactionMetadata)
293
- throw new Error(`transaction failed: ${String(res.err())}\n${res.meta().logs().join("\n")}`);
294
+ if (res instanceof FailedTransactionMetadata) {
295
+ const m = /Custom\D*(\d+)/.exec(String(res.err()));
296
+ const name = m ? harness.errorName(Number(m[1])) : undefined;
297
+ throw new Error(`transaction failed: ${String(res.err())}${name ? ` (${name})` : ""}\n${res.meta().logs().join("\n")}`);
298
+ }
294
299
  return res;
295
300
  },
296
301
  errorCode(res) {
@@ -301,6 +306,63 @@ export function programHarness(svm, programId, idl) {
301
306
  throw new Error(`not a custom program error: ${String(res.err())}\n${res.meta().logs().join("\n")}`);
302
307
  return Number(m[1]);
303
308
  },
309
+ errorName(code) {
310
+ return pidl.errors?.find((e) => e.code === code)?.name ?? TYPESOL_ERRORS[code];
311
+ },
312
+ async mint({ authority, decimals = 6, supply = 0n, freezeAuthority, tokenProgram = TOKEN_PROGRAM, address }) {
313
+ const at = address ?? (await generateKeyPairSigner()).address;
314
+ const data = new Uint8Array(82);
315
+ const view = new DataView(data.buffer);
316
+ view.setUint32(0, 1, true);
317
+ data.set(enc.encode(authority), 4);
318
+ view.setBigUint64(36, supply, true);
319
+ data[44] = decimals;
320
+ data[45] = 1;
321
+ if (freezeAuthority) {
322
+ view.setUint32(46, 1, true);
323
+ data.set(enc.encode(freezeAuthority), 50);
324
+ }
325
+ svm.setAccount({
326
+ address: at,
327
+ data,
328
+ executable: false,
329
+ lamports: lamports(svm.minimumBalanceForRentExemption(82n)),
330
+ programAddress: tokenProgram,
331
+ space: 82n,
332
+ });
333
+ return at;
334
+ },
335
+ async tokenAccount({ mint, owner, amount = 0n, tokenProgram = TOKEN_PROGRAM, address }) {
336
+ const at = address ?? (await generateKeyPairSigner()).address;
337
+ const data = new Uint8Array(165);
338
+ data.set(enc.encode(mint), 0);
339
+ data.set(enc.encode(owner), 32);
340
+ new DataView(data.buffer).setBigUint64(64, amount, true);
341
+ data[108] = 1; // AccountState::Initialized
342
+ svm.setAccount({
343
+ address: at,
344
+ data,
345
+ executable: false,
346
+ lamports: lamports(svm.minimumBalanceForRentExemption(165n)),
347
+ programAddress: tokenProgram,
348
+ space: 165n,
349
+ });
350
+ return at;
351
+ },
352
+ tokenBalance(address) {
353
+ const a = svm.getAccount(address);
354
+ return a.exists && a.data.length >= 72 ? new DataView(a.data.buffer, a.data.byteOffset).getBigUint64(64, true) : null;
355
+ },
356
+ warp({ unixTimestamp, slot, seconds }) {
357
+ const clock = svm.getClock();
358
+ if (slot !== undefined)
359
+ clock.slot = slot;
360
+ if (unixTimestamp !== undefined)
361
+ clock.unixTimestamp = unixTimestamp;
362
+ if (seconds !== undefined)
363
+ clock.unixTimestamp += seconds;
364
+ svm.setClock(clock);
365
+ },
304
366
  async account(type, address) {
305
367
  const a = svm.getAccount(address);
306
368
  if (!a.exists)
@@ -26,19 +26,26 @@ export declare function programForEntry(ws: Workspace, file: string): string | u
26
26
  /**
27
27
  * The program's keypair (created on first use) checked against the address recorded in typesol.json, which is
28
28
  * recorded on first build. A mismatch means the keypair was lost or replaced: deploying would create a new program.
29
+ * Building and testing only need the address: without the keypair (a fresh clone, CI) they use the recorded one,
30
+ * and only deploying (`needKeypair`) refuses.
29
31
  */
30
- export declare function programAddress(ws: Workspace, name: string): {
32
+ export declare function programAddress(ws: Workspace, name: string, opts?: {
33
+ needKeypair?: boolean;
34
+ }): {
31
35
  address: string;
32
36
  created: boolean;
37
+ keyless?: boolean;
33
38
  };
34
39
  /** Build every program (or the ones named). */
35
40
  export declare function buildWorkspace(ws: Workspace, names?: string[], opts?: {
36
41
  sbpf?: Sbpf;
37
42
  profile?: boolean;
43
+ needKeypair?: boolean;
38
44
  }): {
39
45
  paths: ProgramPaths;
40
46
  address: string;
41
47
  created: boolean;
48
+ keyless?: boolean;
42
49
  result: BuildResult;
43
50
  clientPath: string;
44
51
  }[];
@@ -50,3 +57,11 @@ export declare function deployArgs(soPath: string, keypair: string, opts: {
50
57
  }): string[];
51
58
  /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
52
59
  export declare function scaffold(dir: string, name: string, template?: TemplateName): string[];
60
+ /**
61
+ * Add a program to an existing project: programs/<name>.ts and tests/<name>.test.ts from a template, and its entry in
62
+ * typesol.json. Returns the files written and the template's extra devDependencies the package.json lacks.
63
+ */
64
+ export declare function addProgram(ws: Workspace, name: string, template?: TemplateName): {
65
+ files: string[];
66
+ missing: string[];
67
+ };
package/dist/workspace.js CHANGED
@@ -65,10 +65,14 @@ export function programForEntry(ws, file) {
65
65
  /**
66
66
  * The program's keypair (created on first use) checked against the address recorded in typesol.json, which is
67
67
  * recorded on first build. A mismatch means the keypair was lost or replaced: deploying would create a new program.
68
+ * Building and testing only need the address: without the keypair (a fresh clone, CI) they use the recorded one,
69
+ * and only deploying (`needKeypair`) refuses.
68
70
  */
69
- export function programAddress(ws, name) {
71
+ export function programAddress(ws, name, opts = {}) {
70
72
  const paths = programPaths(ws, name);
71
73
  const recorded = ws.programs[name].address;
74
+ if (recorded && !existsSync(paths.keypair) && !opts.needKeypair)
75
+ return { address: recorded, created: false, keyless: true };
72
76
  if (recorded && !existsSync(paths.keypair))
73
77
  throw new Error(`${name}: ${path.relative(ws.root, paths.keypair)} is missing, but ${CONFIG} records ${recorded}. Restore the keypair (it is the program's address); removing "address" from ${CONFIG} would give the program a new address.`);
74
78
  mkdirSync(path.dirname(paths.keypair), { recursive: true });
@@ -87,11 +91,11 @@ export function programAddress(ws, name) {
87
91
  export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {}) {
88
92
  return names.map((name) => {
89
93
  const paths = programPaths(ws, name);
90
- const { address, created } = programAddress(ws, name);
94
+ const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
91
95
  const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
92
96
  // The TypeScript client (docs/client.md) is written with the build, from the same IDL.
93
97
  const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
94
- return { paths, address, created, result, clientPath };
98
+ return { paths, address, created, keyless, result, clientPath };
95
99
  });
96
100
  }
97
101
  /** The `solana program deploy` arguments for one built program (deploying again upgrades it). */
@@ -132,7 +136,15 @@ export function scaffold(dir, name, template = "counter") {
132
136
  name,
133
137
  private: true,
134
138
  type: "module",
135
- scripts: { build: "typesol build", test: "vitest run", typecheck: "tsc -p tsconfig.json", deploy: "typesol deploy" },
139
+ scripts: {
140
+ build: "typesol build",
141
+ // The tests and the typecheck import the client the build writes: build first.
142
+ pretest: "typesol build --quiet",
143
+ test: "vitest run",
144
+ pretypecheck: "typesol build --quiet",
145
+ typecheck: "tsc -p tsconfig.json",
146
+ deploy: "typesol deploy",
147
+ },
136
148
  engines: { node: ">=22.12" },
137
149
  devDependencies: {
138
150
  // Published as @typesol/cli, installed under the name programs import ("typesol", "typesol/workspace").
@@ -149,7 +161,7 @@ export function scaffold(dir, name, template = "counter") {
149
161
  // VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
150
162
  ".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
151
163
  // target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
152
- ".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# A fresh clone cannot build or deploy a program whose address is recorded in typesol.json without its keypair.\ntarget/\n",
164
+ ".gitignore": "node_modules/\n# target/deploy/*-keypair.json are the programs' addresses (and upgrade keys): never commit them, but BACK THEM UP.\n# Without it, a fresh clone still builds and tests at the address recorded in typesol.json, but cannot deploy.\ntarget/\n",
153
165
  "tsconfig.json": JSON.stringify({
154
166
  compilerOptions: {
155
167
  target: "ES2022",
@@ -172,3 +184,35 @@ export function scaffold(dir, name, template = "counter") {
172
184
  }
173
185
  return Object.keys(files);
174
186
  }
187
+ /**
188
+ * Add a program to an existing project: programs/<name>.ts and tests/<name>.test.ts from a template, and its entry in
189
+ * typesol.json. Returns the files written and the template's extra devDependencies the package.json lacks.
190
+ */
191
+ export function addProgram(ws, name, template = "counter") {
192
+ if (!/^[a-z][a-z0-9_]*$/.test(name))
193
+ throw new Error(`program name "${name}" must be snake_case`);
194
+ if (ws.programs[name])
195
+ throw new Error(`${CONFIG} already has a program "${name}"`);
196
+ const t = TEMPLATES[template];
197
+ const files = { [`programs/${name}.ts`]: t.program, [`tests/${name}.test.ts`]: t.test(name) };
198
+ const existing = Object.keys(files).filter((f) => existsSync(path.join(ws.root, f)));
199
+ if (existing.length)
200
+ throw new Error(`refusing to overwrite: ${existing.join(", ")}`);
201
+ for (const [file, text] of Object.entries(files)) {
202
+ mkdirSync(path.dirname(path.join(ws.root, file)), { recursive: true });
203
+ writeFileSync(path.join(ws.root, file), text);
204
+ }
205
+ const raw = JSON.parse(readFileSync(ws.file, "utf8"));
206
+ raw.programs[name] = { path: `programs/${name}.ts` };
207
+ writeFileSync(ws.file, JSON.stringify(raw, null, 2) + "\n");
208
+ ws.programs[name] = { path: `programs/${name}.ts` };
209
+ const pkgFile = path.join(ws.root, "package.json");
210
+ const pkg = existsSync(pkgFile)
211
+ ? JSON.parse(readFileSync(pkgFile, "utf8"))
212
+ : {};
213
+ const have = { ...pkg.dependencies, ...pkg.devDependencies };
214
+ const missing = Object.entries(t.devDependencies ?? {})
215
+ .filter(([dep]) => !(dep in have))
216
+ .map(([dep, v]) => `${dep}@${v}`);
217
+ return { files: [...Object.keys(files), CONFIG], missing };
218
+ }
package/docs/audit.md CHANGED
@@ -67,7 +67,7 @@ Internal reviews, by the maintainers, in October 2026. Their findings and fixes
67
67
  sequences against state models with value conservation; account layout with two growable Vecs and aliasing through
68
68
  remaining accounts. Each run prints its seed (`FUZZ_SEED`), `pnpm fuzz` runs them wide.
69
69
  - **Ported programs**: all 46 programs of solana-developers/program-examples, run through their original tests' flows
70
- and failure paths ([test/ports/README.md](../test/ports/README.md)).
70
+ and failure paths ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)).
71
71
  - **Four-way comparison**: [typesol/benchmarks](https://github.com/typesol/benchmarks) runs 17 of those programs in
72
72
  TypeSOL, Anchor, native Rust and Pinocchio, requires the same outcome, and records how each refuses the hostile calls
73
73
  and with which error.
@@ -4,7 +4,7 @@ This page follows one complete Anchor program into TypeSOL: the token escrow fro
4
4
  [solana-developers/program-examples](https://github.com/solana-developers/program-examples/tree/de090195e4de698e150572c4f886c333323a64a5/tokens/escrow/anchor)
5
5
  (`tokens/escrow`, commit `de09019`). It shows the original and the port side by side, what changed, how the two were
6
6
  checked against each other, where they still differ, and what the port costs to run. The port is
7
- [`test/ports/tokens/escrow.ts`](../test/ports/tokens/escrow.ts); [Migrate from Anchor](migrate-from-anchor.md) is the
7
+ [`test/ports/tokens/escrow.ts`](https://github.com/typesol/typesol/blob/main/test/ports/tokens/escrow.ts); [Migrate from Anchor](migrate-from-anchor.md) is the
8
8
  general reference.
9
9
 
10
10
  ## The program
@@ -160,13 +160,13 @@ tokenProgram.closeAccount(vault, maker, offer, ["offer", maker.key, offer.id, of
160
160
  | `ErrorCode::CustomError` (unused upstream) | `enum ErrorCode`, the same code 6000 |
161
161
 
162
162
  Nothing in the program needed a construct TypeSOL lacks, and every account constraint has its TypeSOL form; the port
163
- is marked PORTED in [the ports table](../test/ports/README.md).
163
+ is marked PORTED in [the ports table](https://github.com/typesol/typesol/blob/main/test/ports/README.md).
164
164
 
165
165
  ## Same inputs, same results
166
166
 
167
167
  Two independent checks run the original and the port against each other.
168
168
 
169
- - **The port's own test** ([`test/porting/ports-tokens.test.ts`](../test/porting/ports-tokens.test.ts)) runs the upstream flow with SPL
169
+ - **The port's own test** ([`test/porting/ports-tokens.test.ts`](https://github.com/typesol/typesol/blob/main/test/porting/ports-tokens.test.ts)) runs the upstream flow with SPL
170
170
  Token mints and again with Token-2022 mints: make, take (creating the taker's and the maker's missing token accounts),
171
171
  make again, a refund attempt by someone other than the maker, and the refund. It checks balances, the decoded offer
172
172
  and that offer and vault are closed.
@@ -3,8 +3,8 @@
3
3
  This page ports a program that holds real authority on mainnet:
4
4
  [coral-xyz/multisig](https://github.com/coral-xyz/multisig) (`programs/multisig/src/lib.rs`, Anchor 0.25, Apache-2.0),
5
5
  deployed at `msigUdDBsR4zSUYqYEDrc1LcgtmuSDDM7KxpRUXNC6U`. The port is
6
- [`examples/multisig.ts`](../examples/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
- binary that runs on mainnet: [`test/examples/multisig.test.ts`](../test/examples/multisig.test.ts) runs both under the
6
+ [`examples/multisig.ts`](https://github.com/typesol/typesol/blob/main/examples/multisig.ts). Instead of a twin built for the occasion, it is checked against the
7
+ binary that runs on mainnet: [`test/examples/multisig.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/multisig.test.ts) runs both under the
8
8
  same program id and compares every outcome and every account byte. See
9
9
  [case-study-escrow.md](case-study-escrow.md) for a token program and [Migrate from Anchor](migrate-from-anchor.md) for
10
10
  the general reference.
@@ -99,7 +99,7 @@ existing clients and existing accounts work with the port unchanged.
99
99
  ## How it was checked
100
100
 
101
101
  `test/programs/coral_multisig.so` is the program dumped from mainnet on 2026-10-29 (sha256 in
102
- [`test/programs/SOURCES.md`](../test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
102
+ [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)). The test loads it into one LiteSVM and the port into
103
103
  another, both at `msigUdDB…`, then sends each transaction to both. After each one it requires the same outcome (success,
104
104
  or the same error down to the code) and the same lamports, owner and data bytes for every account involved.
105
105