@typesol/cli 0.31.0 → 0.33.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -9
  3. package/dist/cli.js +50 -5
  4. package/dist/compiler/analyze.js +187 -42
  5. package/dist/compiler/emit/alias.js +5 -1
  6. package/dist/compiler/emit/base.d.ts +5 -0
  7. package/dist/compiler/emit/base.js +24 -6
  8. package/dist/compiler/emit/calls.d.ts +5 -1
  9. package/dist/compiler/emit/calls.js +109 -15
  10. package/dist/compiler/emit/cpi-core.d.ts +8 -0
  11. package/dist/compiler/emit/cpi-core.js +17 -2
  12. package/dist/compiler/emit/cpi.js +10 -4
  13. package/dist/compiler/emit/create.d.ts +2 -0
  14. package/dist/compiler/emit/create.js +56 -13
  15. package/dist/compiler/emit/expressions.js +16 -6
  16. package/dist/compiler/emit/function.d.ts +3 -1
  17. package/dist/compiler/emit/function.js +21 -12
  18. package/dist/compiler/emit/statements.js +53 -3
  19. package/dist/compiler/emit/storage.js +8 -8
  20. package/dist/compiler/emit/token.js +43 -0
  21. package/dist/compiler/idl.js +47 -6
  22. package/dist/compiler/model.d.ts +19 -1
  23. package/dist/templates.js +13 -36
  24. package/dist/testing.d.ts +30 -0
  25. package/dist/testing.js +85 -3
  26. package/dist/workspace.d.ts +16 -1
  27. package/dist/workspace.js +49 -5
  28. package/docs/audit.md +1 -1
  29. package/docs/case-study-escrow.md +3 -3
  30. package/docs/case-study-multisig.md +3 -3
  31. package/docs/case-study-raydium-cp-swap.md +51 -21
  32. package/docs/cli.md +5 -3
  33. package/docs/errors.md +3 -1
  34. package/docs/language.md +17 -5
  35. package/docs/migrate-from-anchor.md +6 -0
  36. package/docs/test-your-program.md +12 -3
  37. package/docs/testing.md +1 -1
  38. package/lib/typesol.d.ts +51 -15
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -7
@@ -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) {
@@ -543,8 +547,9 @@ export class StatementEmitter extends CpiEmitter {
543
547
  params.set(name, { c: "", type: BOOL, mutable: false, closure: this.closureOf(arg) });
544
548
  return;
545
549
  }
546
- if (p.type && ts.isIdentifier(arg) && !this.lookup(arg.text) && this.accounts.has(arg.text) && !resolveValueType(p.type, calleeScope)) {
547
- aliases.set(name, this.accounts.get(arg.text));
550
+ const passed = ts.isIdentifier(arg) && this.lookup(arg.text) ? undefined : this.accountAt(arg);
551
+ if (p.type && passed && !resolveValueType(p.type, calleeScope)) {
552
+ aliases.set(name, passed);
548
553
  return;
549
554
  }
550
555
  const c2 = `l_${name}_${this.temp++}`;
@@ -883,7 +888,7 @@ export class StatementEmitter extends CpiEmitter {
883
888
  if (this.scopes.at(-1).has(name))
884
889
  this.fail(d.name, `"${name}" is already declared`);
885
890
  // Account lookups go by name, so a local must not hide a parameter (it would read the parameter instead).
886
- if (this.accounts.has(name) || this.args.has(name))
891
+ if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
887
892
  this.fail(d.name, `"${name}" shadows the parameter "${name}"; use another name`);
888
893
  const c = `l_${name}_${this.temp++}`;
889
894
  const init = d.initializer;
@@ -897,6 +902,17 @@ export class StatementEmitter extends CpiEmitter {
897
902
  continue;
898
903
  }
899
904
  const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
905
+ // A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
906
+ if (fn === "signer") {
907
+ if (mutable)
908
+ this.fail(d, "bind seed lists with const");
909
+ const s = this.signerSeedsArg(init);
910
+ this.line(`const SolSignerSeed *${c} = ${s.name};`);
911
+ this.line(`int ${c}__n = ${s.count};`);
912
+ this.line(`(void)${c}; (void)${c}__n;`);
913
+ this.scopes.at(-1).set(name, { c, type: { kind: "signerSeeds" }, mutable: false });
914
+ continue;
915
+ }
900
916
  if (fn === "fixedArray") {
901
917
  const t = this.localArray(init, c);
902
918
  this.scopes.at(-1).set(name, { c, type: t, mutable });
@@ -915,6 +931,40 @@ export class StatementEmitter extends CpiEmitter {
915
931
  this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d });
916
932
  continue;
917
933
  }
934
+ // A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
935
+ if (fn === "returnData" && this.returnedStruct(init)) {
936
+ if (mutable)
937
+ this.fail(d, "bind return data with const (its fields can still be updated)");
938
+ const S = this.returnedStruct(init);
939
+ const call = init;
940
+ if (call.arguments.length !== 1)
941
+ this.fail(call, "returnData<T>(program) takes the program that returned it");
942
+ const program = this.accountParam(call.arguments[0], "returnData's program");
943
+ const bad = `TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid ${S.name} return data")`;
944
+ if (S.layout === "borsh") {
945
+ // Borsh of any size: unpacked into the fixed-layout struct, every byte used.
946
+ const raw = `${c}__raw`;
947
+ this.line(`uint8_t *${raw};`);
948
+ this.line(`uint64_t ${raw}_len = 0, ${raw}_used = 0;`);
949
+ this.line(`TS_TRY(ts_return_data_any(a_${program.name}, &${raw}, &${raw}_len));`);
950
+ this.line(`TSS_${S.name} *${c};`);
951
+ this.line(`TS_TRY(ts_alloc(sizeof(TSS_${S.name}), (uint8_t **)&${c}));`);
952
+ this.line(`if (ts_unpack_${S.name}(${raw}, ${raw}_len, ${c}, &${raw}_used) != SUCCESS || ${raw}_used != ${raw}_len) ${bad};`);
953
+ for (const f of S.fields)
954
+ if (f.type.kind === "fstring")
955
+ this.line(`if (!ts_utf8_valid(${c}->${f.name}.bytes, ${c}->${f.name}.len)) ${bad};`);
956
+ }
957
+ else {
958
+ // A fixed layout whose bytes are its Borsh form: copied in, then bools and enums checked.
959
+ this.line(`TSS_${S.name} ${c}__v;`);
960
+ this.line(`TS_TRY(ts_return_data_exact(a_${program.name}, &${c}__v, sizeof(TSS_${S.name})));`);
961
+ for (const l of this.validation(`${c}__v`, { kind: "struct", name: S.name }, "", bad))
962
+ this.line(l.trim());
963
+ this.line(`TSS_${S.name} *${c} = &${c}__v;`);
964
+ }
965
+ this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
966
+ continue;
967
+ }
918
968
  // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
919
969
  const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
920
970
  if (structType) {
@@ -184,8 +184,8 @@ export class StorageEmitter extends AliasEmitter {
184
184
  if (ts.isPropertyAccessExpression(node)) {
185
185
  const field = node.name.text;
186
186
  // Migrate<From, To>: acct.from (the old data, read-only, until migrate()) and acct.to (after it).
187
- if (ts.isIdentifier(node.expression)) {
188
- const m = this.accounts.get(node.expression.text);
187
+ if (this.accountAt(node.expression)) {
188
+ const m = this.accountAt(node.expression);
189
189
  if (m?.kind.kind === "migrate") {
190
190
  const migrated = this.created.has(m.name);
191
191
  if (field === "from") {
@@ -202,8 +202,8 @@ export class StorageEmitter extends AliasEmitter {
202
202
  }
203
203
  }
204
204
  // acct.field on a struct account
205
- if (ts.isIdentifier(node.expression)) {
206
- const a = this.accounts.get(node.expression.text);
205
+ if (this.accountAt(node.expression)) {
206
+ const a = this.accountAt(node.expression);
207
207
  if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
208
208
  const f = a.kind.struct.fields.find((x) => x.name === field);
209
209
  if (!f)
@@ -445,9 +445,9 @@ export class StorageEmitter extends AliasEmitter {
445
445
  */
446
446
  /** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
447
447
  wholeAccount(node) {
448
- if (!ts.isIdentifier(node) || this.lookup(node.text))
448
+ if (ts.isIdentifier(node) && this.lookup(node.text))
449
449
  return undefined;
450
- const a = this.accounts.get(node.text);
450
+ const a = this.accountAt(node);
451
451
  if (!a || !(a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "initIfNeeded") || a.kind.struct.size === undefined || a.kind.struct.vec)
452
452
  return undefined;
453
453
  this.assertUsable(a, node);
@@ -680,8 +680,8 @@ export class StorageEmitter extends AliasEmitter {
680
680
  return { type: l.type, read: `(&${l.c})`, write: (c) => `${l.c} = *(${c})` };
681
681
  return { type: l.type, read: l.c, write: (c) => `${l.c} = ${c}` };
682
682
  }
683
- if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.name.text === "lamports") {
684
- const a = this.accounts.get(node.expression.text);
683
+ if (ts.isPropertyAccessExpression(node) && node.name.text === "lamports" && this.accountAt(node.expression)) {
684
+ const a = this.accountAt(node.expression);
685
685
  if (a) {
686
686
  this.assertUsable(a, node);
687
687
  if (!isWritable(a.kind))
@@ -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");
@@ -22,6 +22,9 @@ function docsOf(node) {
22
22
  }
23
23
  /** `@param name text` of a function parameter. */
24
24
  function paramDocs(param) {
25
+ // A group's field: its own doc comment.
26
+ if (ts.isPropertySignature(param))
27
+ return docsOf(param);
25
28
  const text = ts
26
29
  .getJSDocParameterTags(param)
27
30
  .map((t) => (typeof t.comment === "string" ? t.comment : (ts.getTextOfJSDocComment(t.comment) ?? "")))
@@ -86,9 +89,26 @@ function idlType(t, borshOption = false) {
86
89
  throw new Error(`no IDL type for ${t.kind}`);
87
90
  }
88
91
  }
92
+ /**
93
+ * An account path as the IDL writes it from where it is used: a field of the same group by its own name (Anchor's
94
+ * composite accounts), a field of another group as `<group>_<field>` (how clients flatten groups), else the name.
95
+ */
96
+ function relativePath(path, from) {
97
+ const at = path.indexOf("__");
98
+ if (at < 0)
99
+ return path;
100
+ const group = path.slice(0, at);
101
+ return group === from ? path.slice(at + 2) : `${group}_${path.slice(at + 2)}`;
102
+ }
103
+ function relativeSeeds(seeds, from) {
104
+ if (!Array.isArray(seeds))
105
+ return seeds;
106
+ return seeds.map((sd) => (sd.kind === "account" && sd.path ? { ...sd, path: relativePath(sd.path, from) } : sd));
107
+ }
89
108
  function accountEntry(ix, name, k, programAddress) {
90
109
  const param = ix.accounts.find((a) => a.name === name);
91
- const entry = { name: snakeCase(name), ...(param ? paramDocs(param.node) : {}) };
110
+ const group = param?.group ? snakeCase(param.group.param) : undefined;
111
+ const entry = { name: snakeCase(param?.group ? param.group.field : name), ...(param ? paramDocs(param.node) : {}) };
92
112
  if (isWritable(k))
93
113
  entry.writable = true;
94
114
  if (param?.optional)
@@ -115,13 +135,16 @@ function accountEntry(ix, name, k, programAddress) {
115
135
  entry.address = k.address.base58;
116
136
  // Anchor's direction: the account named by a has_one lists the accounts that hold it (Anchor clients then read
117
137
  // `holder.data[name]` to fill it in). Only struct accounts' HasOne are has_one relations in Anchor's sense.
118
- const relations = ix.accounts.filter((a) => a.kind.kind === "account" && a.constraints.hasOne.includes(name)).map((a) => a.name);
138
+ const holds = (a) => a.constraints.hasOne.some((f) => !f.includes("=") && (a.constraints.hasOneParams?.get(f) ?? f) === name);
139
+ const relations = ix.accounts.filter((a) => a.kind.kind === "account" && holds(a)).map((a) => relativePath(snakeCase(a.name), group));
119
140
  if (relations.length)
120
- entry.relations = relations.map(snakeCase);
141
+ entry.relations = relations;
121
142
  const seeds = ix.pdas.get(name);
122
143
  const program = ix.pdaPrograms.get(name);
123
- if (seeds)
124
- entry.pda = program ? { seeds, program } : { seeds };
144
+ if (seeds) {
145
+ const own = relativeSeeds(seeds, group);
146
+ entry.pda = program ? { seeds: own, program: relativeSeeds([program], group)[0] } : { seeds: own };
147
+ }
125
148
  const address = ix.accounts.find((a) => a.name === name)?.constraints.address;
126
149
  if (address)
127
150
  entry.address = address.base58;
@@ -134,6 +157,24 @@ function accountEntry(ix, name, k, programAddress) {
134
157
  entry.pda = { seeds: [{ kind: "const", value: [...programId] }], program: { kind: "const", value: BPF_UPGRADEABLE_LOADER } };
135
158
  return entry;
136
159
  }
160
+ /** The instruction's account entries, an account group's fields nested under it: `{ name: "pool", accounts: [...] }`. */
161
+ function nestGroups(ix, entry) {
162
+ const out = [];
163
+ let open;
164
+ for (const a of ix.accounts) {
165
+ if (!a.group) {
166
+ open = undefined;
167
+ out.push(entry(a));
168
+ continue;
169
+ }
170
+ if (open?.param !== a.group.param) {
171
+ open = { param: a.group.param, accounts: [] };
172
+ out.push({ name: snakeCase(a.group.param), accounts: open.accounts });
173
+ }
174
+ open.accounts.push(entry(a));
175
+ }
176
+ return out;
177
+ }
137
178
  /** Anchor IDL (spec 0.1.0) so existing Anchor / Codama clients can talk to TypeSOL programs. */
138
179
  export function buildIdl(model, address, version = "0.1.0") {
139
180
  const structs = [...model.structs.values()];
@@ -145,7 +186,7 @@ export function buildIdl(model, address, version = "0.1.0") {
145
186
  name: ix.name,
146
187
  ...docsOf(ix.node),
147
188
  discriminator: ix.discriminator,
148
- accounts: ix.accounts.map((a) => accountEntry(ix, a.name, a.kind, address)),
189
+ accounts: nestGroups(ix, (a) => accountEntry(ix, a.name, a.kind, address)),
149
190
  args: ix.args.map((a) => ({ name: snakeCase(a.name), ...paramDocs(a.node), type: idlType(a.type, true) })),
150
191
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
151
192
  })),
@@ -293,6 +293,17 @@ export interface Constraints {
293
293
  owner: string;
294
294
  mint: string;
295
295
  };
296
+ /**
297
+ * Your errors for these checks (Anchor's `@ ErrorCode.X`), by check: "mut", "signer", "owner", "address" or
298
+ * "hasOne:<field>"; the enum and member named in the type, looked up among the program's error enums.
299
+ */
300
+ errors?: Map<string, {
301
+ enumName: string;
302
+ member: string;
303
+ node: ts.Node;
304
+ }>;
305
+ /** HasOne fields checked against another parameter than the one of the same name (a field of the same group). */
306
+ hasOneParams?: Map<string, string>;
296
307
  }
297
308
  export interface AccountParam {
298
309
  name: string;
@@ -300,8 +311,15 @@ export interface AccountParam {
300
311
  kind: ParamKind;
301
312
  /** `A | null` / `Optional<A>`: the client passes this program's id instead of an account to leave it out. */
302
313
  optional?: boolean;
303
- node: ts.ParameterDeclaration;
314
+ /** The parameter, or the field of an account group. */
315
+ node: ts.ParameterDeclaration | ts.PropertySignature;
304
316
  constraints: Constraints;
317
+ /** A field of an account group: the group parameter, the field, and the group's interface. `name` is `<param>__<field>`. */
318
+ group?: {
319
+ param: string;
320
+ field: string;
321
+ type: string;
322
+ };
305
323
  /** Created in the body as a new keypair account (`create(payer, null, …)`), so it signs: the IDL says so. */
306
324
  signsInit?: boolean;
307
325
  }
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,15 +22,36 @@ 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 };
28
29
  // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
29
30
  const { BN, BorshCoder } = anchor;
31
+ /**
32
+ * An instruction's accounts with groups flattened as the generated client does: `pool.vault` becomes `pool_vault`
33
+ * (`poolVault` in `t.ix`), and a seed naming a field of the same group names its flattened account.
34
+ */
35
+ function flattenAccounts(items, prefix = "") {
36
+ const out = [];
37
+ for (const it of items) {
38
+ if (it.accounts) {
39
+ const group = `${prefix}${it.name}_`;
40
+ const fields = new Set(it.accounts.filter((f) => !f.accounts).map((f) => f.name));
41
+ const local = (sd) => (sd.kind === "account" && fields.has(sd.path.split(".")[0]) ? { ...sd, path: `${group}${sd.path}` } : sd);
42
+ for (const f of flattenAccounts(it.accounts, group))
43
+ out.push(f.pda ? { ...f, pda: { seeds: f.pda.seeds.map(local), ...(f.pda.program ? { program: local(f.pda.program) } : {}) } } : f);
44
+ continue;
45
+ }
46
+ out.push({ ...it, name: `${prefix}${it.name}` });
47
+ }
48
+ return out;
49
+ }
30
50
  const BIG = new Set(["u64", "i64", "u128", "i128"]);
31
51
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
32
52
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
33
53
  const isSigner = (v) => typeof v === "object" && v !== null && "address" in v && "signTransactions" in v;
54
+ const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
34
55
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
35
56
  export async function testProgram(program, from) {
36
57
  const start = typeof from === "string" && !from.startsWith("file:") ? from : path.dirname(fileURLToPath(from));
@@ -48,7 +69,8 @@ export async function testProgram(program, from) {
48
69
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
49
70
  export function programHarness(svm, programId, idl) {
50
71
  const coder = new BorshCoder(idl);
51
- const pidl = idl;
72
+ const source = idl;
73
+ const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
52
74
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
53
75
  const enc = getAddressEncoder();
54
76
  /** A plain value → what the Anchor coder expects for `type`. */
@@ -289,8 +311,11 @@ export function programHarness(svm, programId, idl) {
289
311
  return res;
290
312
  },
291
313
  ok(res) {
292
- if (res instanceof FailedTransactionMetadata)
293
- throw new Error(`transaction failed: ${String(res.err())}\n${res.meta().logs().join("\n")}`);
314
+ if (res instanceof FailedTransactionMetadata) {
315
+ const m = /Custom\D*(\d+)/.exec(String(res.err()));
316
+ const name = m ? harness.errorName(Number(m[1])) : undefined;
317
+ throw new Error(`transaction failed: ${String(res.err())}${name ? ` (${name})` : ""}\n${res.meta().logs().join("\n")}`);
318
+ }
294
319
  return res;
295
320
  },
296
321
  errorCode(res) {
@@ -301,6 +326,63 @@ export function programHarness(svm, programId, idl) {
301
326
  throw new Error(`not a custom program error: ${String(res.err())}\n${res.meta().logs().join("\n")}`);
302
327
  return Number(m[1]);
303
328
  },
329
+ errorName(code) {
330
+ return pidl.errors?.find((e) => e.code === code)?.name ?? TYPESOL_ERRORS[code];
331
+ },
332
+ async mint({ authority, decimals = 6, supply = 0n, freezeAuthority, tokenProgram = TOKEN_PROGRAM, address }) {
333
+ const at = address ?? (await generateKeyPairSigner()).address;
334
+ const data = new Uint8Array(82);
335
+ const view = new DataView(data.buffer);
336
+ view.setUint32(0, 1, true);
337
+ data.set(enc.encode(authority), 4);
338
+ view.setBigUint64(36, supply, true);
339
+ data[44] = decimals;
340
+ data[45] = 1;
341
+ if (freezeAuthority) {
342
+ view.setUint32(46, 1, true);
343
+ data.set(enc.encode(freezeAuthority), 50);
344
+ }
345
+ svm.setAccount({
346
+ address: at,
347
+ data,
348
+ executable: false,
349
+ lamports: lamports(svm.minimumBalanceForRentExemption(82n)),
350
+ programAddress: tokenProgram,
351
+ space: 82n,
352
+ });
353
+ return at;
354
+ },
355
+ async tokenAccount({ mint, owner, amount = 0n, tokenProgram = TOKEN_PROGRAM, address }) {
356
+ const at = address ?? (await generateKeyPairSigner()).address;
357
+ const data = new Uint8Array(165);
358
+ data.set(enc.encode(mint), 0);
359
+ data.set(enc.encode(owner), 32);
360
+ new DataView(data.buffer).setBigUint64(64, amount, true);
361
+ data[108] = 1; // AccountState::Initialized
362
+ svm.setAccount({
363
+ address: at,
364
+ data,
365
+ executable: false,
366
+ lamports: lamports(svm.minimumBalanceForRentExemption(165n)),
367
+ programAddress: tokenProgram,
368
+ space: 165n,
369
+ });
370
+ return at;
371
+ },
372
+ tokenBalance(address) {
373
+ const a = svm.getAccount(address);
374
+ return a.exists && a.data.length >= 72 ? new DataView(a.data.buffer, a.data.byteOffset).getBigUint64(64, true) : null;
375
+ },
376
+ warp({ unixTimestamp, slot, seconds }) {
377
+ const clock = svm.getClock();
378
+ if (slot !== undefined)
379
+ clock.slot = slot;
380
+ if (unixTimestamp !== undefined)
381
+ clock.unixTimestamp = unixTimestamp;
382
+ if (seconds !== undefined)
383
+ clock.unixTimestamp += seconds;
384
+ svm.setClock(clock);
385
+ },
304
386
  async account(type, address) {
305
387
  const a = svm.getAccount(address);
306
388
  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
+ };