@typesol/cli 0.32.0 → 0.34.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.
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { isWritable } from "../model.js";
2
3
  import { U64, U8, BOOL, PUBKEY, STRING, cBytes, optC } from "./shared.js";
3
4
  import { CreateEmitter } from "./create.js";
@@ -140,7 +141,74 @@ export class TokenEmitter extends CreateEmitter {
140
141
  return anyAcct(a[0], "the mint", true);
141
142
  };
142
143
  const none = { name: "NULL", count: 0 };
144
+ // The Token Group interface (spl-token-group-interface), which Token-2022 implements: 8-byte discriminators.
145
+ const grouped = (disc, fields, metas, seeds) => {
146
+ const { buf, len, put, finish } = this.byteBuffer("grp", 96, "TS_ERR_INSTRUCTION_DATA", "token group instruction");
147
+ const d = this.tmp("disc");
148
+ this.line(`static const uint8_t ${d}[8] = {${disc.join(", ")}};`);
149
+ put(d, "8", 8);
150
+ for (const f of fields)
151
+ f(put);
152
+ finish(node);
153
+ this.cpi(p, metas.map(([acc, w, sg]) => [`a_${acc.name}`, w, sg]), buf, len, seeds);
154
+ };
143
155
  switch (method) {
156
+ case "initializeTokenGroup": {
157
+ token2022Only();
158
+ if (a.length !== 5 && a.length !== 6)
159
+ this.fail(node, "initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize, signerSeeds?)");
160
+ const group = anyAcct(a[0], "the group", true);
161
+ const mint = anyAcct(a[1], "the mint", false);
162
+ const auth = this.accountParam(a[2], "the mint authority");
163
+ grouped([121, 113, 108, 39, 54, 51, 0, 4], [nonZeroKey(a[3]), value(a[4], U64)], [
164
+ [group, true, false],
165
+ [mint, false, false],
166
+ [auth, false, true],
167
+ ], this.signerSeeds(a[5], auth, a[2]));
168
+ return undefined;
169
+ }
170
+ case "initializeGroupMember": {
171
+ token2022Only();
172
+ if (a.length !== 5 && a.length !== 6)
173
+ this.fail(node, "initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority, signerSeeds?)");
174
+ const member = anyAcct(a[0], "the member", true);
175
+ const memberMint = anyAcct(a[1], "the member mint", false);
176
+ const mintAuth = this.accountParam(a[2], "the member mint's authority");
177
+ const group = anyAcct(a[3], "the group", true);
178
+ const groupAuth = this.accountParam(a[4], "the group's update authority");
179
+ grouped([152, 32, 222, 176, 223, 237, 116, 134], [], [
180
+ [member, true, false],
181
+ [memberMint, false, false],
182
+ [mintAuth, false, true],
183
+ [group, true, false],
184
+ [groupAuth, false, true],
185
+ ], a[5] ? this.signingSeeds(a[5]) : none);
186
+ return undefined;
187
+ }
188
+ case "updateGroupMaxSize": {
189
+ token2022Only();
190
+ if (a.length !== 3 && a.length !== 4)
191
+ this.fail(node, "updateGroupMaxSize(group, updateAuthority, maxSize, signerSeeds?)");
192
+ const group = anyAcct(a[0], "the group", true);
193
+ const auth = this.accountParam(a[1], "the update authority");
194
+ grouped([108, 37, 171, 143, 248, 30, 18, 110], [value(a[2], U64)], [
195
+ [group, true, false],
196
+ [auth, false, true],
197
+ ], this.signerSeeds(a[3], auth, a[1]));
198
+ return undefined;
199
+ }
200
+ case "updateGroupAuthority": {
201
+ token2022Only();
202
+ if (a.length !== 3 && a.length !== 4)
203
+ this.fail(node, "updateGroupAuthority(group, updateAuthority, next | null, signerSeeds?)");
204
+ const group = anyAcct(a[0], "the group", true);
205
+ const auth = this.accountParam(a[1], "the update authority");
206
+ grouped([161, 105, 88, 1, 237, 221, 216, 203], [nonZeroKey(a[2])], [
207
+ [group, true, false],
208
+ [auth, false, true],
209
+ ], this.signerSeeds(a[3], auth, a[1]));
210
+ return undefined;
211
+ }
144
212
  case "initializeTransferFeeConfig": {
145
213
  const mint = mintOnly(5, "initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)");
146
214
  this.model.options.set("pubkey", PUBKEY);
@@ -533,4 +601,125 @@ export class TokenEmitter extends CreateEmitter {
533
601
  this.line(`TS_TRY(ts_ata_create(params, a_${program.name}, a_${payer.name}, a_${ata.name}, a_${owner.name}, a_${mint.name}, a_${sys.name}, a_${tp.name}, ${method === "createIdempotent"}));`);
534
602
  return undefined;
535
603
  }
604
+ /** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
605
+ memoOp(node, program, method) {
606
+ if (method !== "memo")
607
+ this.fail(node.expression, "the Memo program has memo(text, signers?, signerSeeds?)");
608
+ const a = node.arguments;
609
+ if (a.length < 1 || a.length > 3)
610
+ this.fail(node, "memo(text, signers?, signerSeeds?)");
611
+ const text = this.expect(this.expr(a[0], STRING), STRING, a[0]);
612
+ const list = a[1];
613
+ if (list && !ts.isArrayLiteralExpression(list))
614
+ this.fail(list, "the signers are a list of accounts: [authority, …]");
615
+ const signers = list ? list.elements.map((e) => this.accountParam(e, "a memo signer")) : [];
616
+ const t = this.tmp("memo");
617
+ this.line(`TS_Str ${t} = ${text.c};`);
618
+ const seeds = a[2] ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
619
+ if (!signers.length)
620
+ this.line(`TS_TRY(ts_cpi(params, a_${program.name}, (uint8_t *)${t}.ptr, ${t}.len, NULL, 0, ${seeds.name}, ${seeds.count}));`);
621
+ else
622
+ this.cpi(`a_${program.name}`, signers.map((s) => [`a_${s.name}`, false, true]), `(uint8_t *)${t}.ptr`, `${t}.len`, seeds);
623
+ return undefined;
624
+ }
625
+ /**
626
+ * The Stake program (bincode: a u32 instruction tag): initialize, authorize, delegate, deactivate and withdraw, with
627
+ * the sysvar and config accounts it reads passed in, as anchor-spl's stake module does. Each authority signs (a PDA of
628
+ * this program with `signerSeeds`).
629
+ */
630
+ stakeOp(node, program, method) {
631
+ const a = node.arguments;
632
+ const acct = (i, what, mut = false) => {
633
+ const x = this.accountParam(a[i], what);
634
+ if (mut && !isWritable(x.kind))
635
+ this.fail(a[i], `${what} must be writable (Mut<...>)`);
636
+ return x;
637
+ };
638
+ const send = (tag, fields, metas, seeds) => {
639
+ const { buf, len, put, finish } = this.byteBuffer("stk", 116, "TS_ERR_INSTRUCTION_DATA", "stake instruction");
640
+ const t = this.tmp("tag");
641
+ this.line(`uint32_t ${t} = ${tag};`);
642
+ put(`&${t}`, "4", 4);
643
+ for (const f of fields)
644
+ f(put);
645
+ finish(node);
646
+ this.cpi(`a_${program.name}`, metas.map(([x, w, sg]) => [`a_${x.name}`, w, sg]), buf, len, seeds);
647
+ };
648
+ const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
649
+ const zeros = (n) => (put) => {
650
+ const z = this.tmp("z");
651
+ this.line(`uint8_t ${z}[${n}] = {0};`);
652
+ put(z, String(n), n);
653
+ };
654
+ const arity = (n, usage) => {
655
+ if (a.length !== n && a.length !== n + 1)
656
+ this.fail(node, usage);
657
+ };
658
+ switch (method) {
659
+ case "initialize": {
660
+ // Authorized { staker, withdrawer }, Lockup { unix_timestamp, epoch, custodian }: no lockup.
661
+ if (a.length !== 4)
662
+ this.fail(node, "initialize(stake, rentSysvar, staker, withdrawer)");
663
+ send(0, [value(a[2], PUBKEY), value(a[3], PUBKEY), zeros(48)], [
664
+ [acct(0, "the stake account", true), true, false],
665
+ [acct(1, "the Rent sysvar"), false, false],
666
+ ], {
667
+ name: "NULL",
668
+ count: 0,
669
+ });
670
+ return undefined;
671
+ }
672
+ case "authorize": {
673
+ arity(5, 'authorize(stake, clockSysvar, authority, newAuthority, "staker" | "withdrawer", signerSeeds?)');
674
+ const kind = a[4];
675
+ const i = ts.isStringLiteral(kind) ? ["staker", "withdrawer"].indexOf(kind.text) : -1;
676
+ if (i < 0)
677
+ this.fail(kind, 'the authority to change is "staker" or "withdrawer"');
678
+ const auth = acct(2, "the authority");
679
+ const k = this.tmp("which");
680
+ send(1, [value(a[3], PUBKEY), (put) => (this.line(`uint32_t ${k} = ${i};`), put(`&${k}`, "4", 4))], [
681
+ [acct(0, "the stake account", true), true, false],
682
+ [acct(1, "the Clock sysvar"), false, false],
683
+ [auth, false, true],
684
+ ], this.signerSeeds(a[5], auth, a[2]));
685
+ return undefined;
686
+ }
687
+ case "delegate": {
688
+ arity(6, "delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker, signerSeeds?)");
689
+ const staker = acct(5, "the staker");
690
+ send(2, [], [
691
+ [acct(0, "the stake account", true), true, false],
692
+ [acct(1, "the vote account"), false, false],
693
+ [acct(2, "the Clock sysvar"), false, false],
694
+ [acct(3, "the StakeHistory sysvar"), false, false],
695
+ [acct(4, "the stake config account"), false, false],
696
+ [staker, false, true],
697
+ ], this.signerSeeds(a[6], staker, a[5]));
698
+ return undefined;
699
+ }
700
+ case "deactivate": {
701
+ arity(3, "deactivate(stake, clockSysvar, staker, signerSeeds?)");
702
+ const staker = acct(2, "the staker");
703
+ send(5, [], [
704
+ [acct(0, "the stake account", true), true, false],
705
+ [acct(1, "the Clock sysvar"), false, false],
706
+ [staker, false, true],
707
+ ], this.signerSeeds(a[3], staker, a[2]));
708
+ return undefined;
709
+ }
710
+ case "withdraw": {
711
+ arity(6, "withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, signerSeeds?)");
712
+ const withdrawer = acct(4, "the withdrawer");
713
+ send(4, [value(a[5], U64)], [
714
+ [acct(0, "the stake account", true), true, false],
715
+ [acct(1, "the destination", true), true, false],
716
+ [acct(2, "the Clock sysvar"), false, false],
717
+ [acct(3, "the StakeHistory sysvar"), false, false],
718
+ [withdrawer, false, true],
719
+ ], this.signerSeeds(a[6], withdrawer, a[4]));
720
+ return undefined;
721
+ }
722
+ }
723
+ this.fail(node.expression, `the Stake program supports initialize, authorize, delegate, deactivate and withdraw, not ${method}`);
724
+ }
536
725
  }
@@ -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,31 @@ 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
+ if (!path.includes("__"))
98
+ return path;
99
+ if (from &&
100
+ path.startsWith(`${from}__`) &&
101
+ !path
102
+ .slice(from.length + 2)
103
+ .split(".")[0]
104
+ .includes("__"))
105
+ return path.slice(from.length + 2);
106
+ return path.replaceAll("__", "_");
107
+ }
108
+ function relativeSeeds(seeds, from) {
109
+ if (!Array.isArray(seeds))
110
+ return seeds;
111
+ return seeds.map((sd) => (sd.kind === "account" && sd.path ? { ...sd, path: relativePath(sd.path, from) } : sd));
112
+ }
89
113
  function accountEntry(ix, name, k, programAddress) {
90
114
  const param = ix.accounts.find((a) => a.name === name);
91
- const entry = { name: snakeCase(name), ...(param ? paramDocs(param.node) : {}) };
115
+ const group = param?.group ? snakeCase(param.group.param) : undefined;
116
+ const entry = { name: snakeCase(param?.group ? param.group.field : name), ...(param ? paramDocs(param.node) : {}) };
92
117
  if (isWritable(k))
93
118
  entry.writable = true;
94
119
  if (param?.optional)
@@ -101,6 +126,12 @@ function accountEntry(ix, name, k, programAddress) {
101
126
  entry.address = "Sysvar1nstructions1111111111111111111111111";
102
127
  if (k.kind === "ataProgram")
103
128
  entry.address = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
129
+ if (k.kind === "memoProgram")
130
+ entry.address = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
131
+ if (k.kind === "stakeProgram")
132
+ entry.address = "Stake11111111111111111111111111111111111111";
133
+ if (k.kind === "slotHashes")
134
+ entry.address = "SysvarS1otHashes111111111111111111111111111";
104
135
  if (k.kind === "metadataProgram")
105
136
  entry.address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s";
106
137
  if (k.kind === "coreProgram")
@@ -115,13 +146,16 @@ function accountEntry(ix, name, k, programAddress) {
115
146
  entry.address = k.address.base58;
116
147
  // Anchor's direction: the account named by a has_one lists the accounts that hold it (Anchor clients then read
117
148
  // `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);
149
+ const holds = (a) => a.constraints.hasOne.some((f) => !f.includes("=") && (a.constraints.hasOneParams?.get(f) ?? f) === name);
150
+ const relations = ix.accounts.filter((a) => a.kind.kind === "account" && holds(a)).map((a) => relativePath(snakeCase(a.name), group));
119
151
  if (relations.length)
120
- entry.relations = relations.map(snakeCase);
152
+ entry.relations = relations;
121
153
  const seeds = ix.pdas.get(name);
122
154
  const program = ix.pdaPrograms.get(name);
123
- if (seeds)
124
- entry.pda = program ? { seeds, program } : { seeds };
155
+ if (seeds) {
156
+ const own = relativeSeeds(seeds, group);
157
+ entry.pda = program ? { seeds: own, program: relativeSeeds([program], group)[0] } : { seeds: own };
158
+ }
125
159
  const address = ix.accounts.find((a) => a.name === name)?.constraints.address;
126
160
  if (address)
127
161
  entry.address = address.base58;
@@ -134,6 +168,26 @@ function accountEntry(ix, name, k, programAddress) {
134
168
  entry.pda = { seeds: [{ kind: "const", value: [...programId] }], program: { kind: "const", value: BPF_UPGRADEABLE_LOADER } };
135
169
  return entry;
136
170
  }
171
+ /** The instruction's account entries, an account group's fields nested under it: `{ name: "pool", accounts: [...] }`. */
172
+ function nestGroups(ix, entry) {
173
+ const out = [];
174
+ // The groups open at the current account, outermost first: their paths and entry lists.
175
+ let open = [];
176
+ for (const a of ix.accounts) {
177
+ const path = a.group?.path ?? [];
178
+ let keep = 0;
179
+ while (keep < open.length && keep < path.length && open[keep].path.join("__") === path.slice(0, keep + 1).join("__"))
180
+ keep++;
181
+ open = open.slice(0, keep);
182
+ for (let i = keep; i < path.length; i++) {
183
+ const g = { path: path.slice(0, i + 1), accounts: [] };
184
+ (i === 0 ? out : open[i - 1].accounts).push({ name: snakeCase(path[i]), accounts: g.accounts });
185
+ open.push(g);
186
+ }
187
+ (open.length ? open[open.length - 1].accounts : out).push(entry(a));
188
+ }
189
+ return out;
190
+ }
137
191
  /** Anchor IDL (spec 0.1.0) so existing Anchor / Codama clients can talk to TypeSOL programs. */
138
192
  export function buildIdl(model, address, version = "0.1.0") {
139
193
  const structs = [...model.structs.values()];
@@ -141,11 +195,13 @@ export function buildIdl(model, address, version = "0.1.0") {
141
195
  const idl = {
142
196
  address,
143
197
  metadata: { name: model.name, version, spec: "0.1.0", description: "Built with TypeSOL" },
144
- instructions: model.instructions.map((ix) => ({
198
+ instructions: model.instructions
199
+ .filter((ix) => !ix.fallback)
200
+ .map((ix) => ({
145
201
  name: ix.name,
146
202
  ...docsOf(ix.node),
147
203
  discriminator: ix.discriminator,
148
- accounts: ix.accounts.map((a) => accountEntry(ix, a.name, a.kind, address)),
204
+ accounts: nestGroups(ix, (a) => accountEntry(ix, a.name, a.kind, address)),
149
205
  args: ix.args.map((a) => ({ name: snakeCase(a.name), ...paramDocs(a.node), type: idlType(a.type, true) })),
150
206
  ...(ix.returns ? { returns: idlType(ix.returns) } : {}),
151
207
  })),
@@ -242,6 +242,18 @@ export type ParamKind = {
242
242
  kind: "programData";
243
243
  } | {
244
244
  kind: "ataProgram";
245
+ }
246
+ /** The SPL Memo program (v2). */
247
+ | {
248
+ kind: "memoProgram";
249
+ }
250
+ /** The native Stake program. */
251
+ | {
252
+ kind: "stakeProgram";
253
+ }
254
+ /** The SlotHashes sysvar account (too large for the sysvar syscalls, so read as an account). */
255
+ | {
256
+ kind: "slotHashes";
245
257
  } | {
246
258
  kind: "metadataProgram";
247
259
  } | {
@@ -293,6 +305,17 @@ export interface Constraints {
293
305
  owner: string;
294
306
  mint: string;
295
307
  };
308
+ /**
309
+ * Your errors for these checks (Anchor's `@ ErrorCode.X`), by check: "mut", "signer", "owner", "address" or
310
+ * "hasOne:<field>"; the enum and member named in the type, looked up among the program's error enums.
311
+ */
312
+ errors?: Map<string, {
313
+ enumName: string;
314
+ member: string;
315
+ node: ts.Node;
316
+ }>;
317
+ /** HasOne fields checked against another parameter than the one of the same name (a field of the same group). */
318
+ hasOneParams?: Map<string, string>;
296
319
  }
297
320
  export interface AccountParam {
298
321
  name: string;
@@ -300,8 +323,19 @@ export interface AccountParam {
300
323
  kind: ParamKind;
301
324
  /** `A | null` / `Optional<A>`: the client passes this program's id instead of an account to leave it out. */
302
325
  optional?: boolean;
303
- node: ts.ParameterDeclaration;
326
+ /** The parameter, or the field of an account group. */
327
+ node: ts.ParameterDeclaration | ts.PropertySignature;
304
328
  constraints: Constraints;
329
+ /**
330
+ * A field of an account group: `path` the group parameter and the fields of groups inside it down to this one,
331
+ * `param` their names joined with "__", the field, and the group's interface. `name` is `<param>__<field>`.
332
+ */
333
+ group?: {
334
+ param: string;
335
+ field: string;
336
+ type: string;
337
+ path: string[];
338
+ };
305
339
  /** Created in the body as a new keypair account (`create(payer, null, …)`), so it signs: the IDL says so. */
306
340
  signsInit?: boolean;
307
341
  }
@@ -323,6 +357,8 @@ export type IdlSeed = {
323
357
  path: string;
324
358
  };
325
359
  export interface Instruction {
360
+ /** `@fallback`: run when no instruction's discriminator matches; not in the IDL. */
361
+ fallback?: boolean;
326
362
  name: string;
327
363
  discriminator: number[];
328
364
  accounts: AccountParam[];
package/dist/testing.d.ts CHANGED
@@ -19,8 +19,11 @@
19
19
  import anchor, { type Idl } from "@anchor-lang/core";
20
20
  import { type Address, type Instruction, type KeyPairSigner } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm";
22
+ import { loadClonedAccounts } from "./tools/clone.js";
22
23
  import { type SvmConnection, svmConnection } from "./tools/svmrpc.js";
23
24
  export { type SvmConnection, svmConnection };
25
+ /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
26
+ export { loadClonedAccounts };
24
27
  declare const BorshCoder: typeof anchor.BorshCoder;
25
28
  type BorshCoder = InstanceType<typeof BorshCoder>;
26
29
  export type Result = TransactionMetadata | FailedTransactionMetadata;
package/dist/testing.js CHANGED
@@ -23,11 +23,33 @@ import { createHash } from "node:crypto";
23
23
  import path from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
25
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
+ import { loadClonedAccounts } from "./tools/clone.js";
26
27
  import { svmConnection } from "./tools/svmrpc.js";
27
28
  import { buildWorkspace, findWorkspace } from "./workspace.js";
28
29
  export { svmConnection };
30
+ /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
31
+ export { loadClonedAccounts };
29
32
  // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
30
33
  const { BN, BorshCoder } = anchor;
34
+ /**
35
+ * An instruction's accounts with groups flattened as the generated client does: `pool.vault` becomes `pool_vault`
36
+ * (`poolVault` in `t.ix`), and a seed naming a field of the same group names its flattened account.
37
+ */
38
+ function flattenAccounts(items, prefix = "") {
39
+ const out = [];
40
+ for (const it of items) {
41
+ if (it.accounts) {
42
+ const group = `${prefix}${it.name}_`;
43
+ const fields = new Set(it.accounts.filter((f) => !f.accounts).map((f) => f.name));
44
+ const local = (sd) => (sd.kind === "account" && fields.has(sd.path.split(".")[0]) ? { ...sd, path: `${group}${sd.path}` } : sd);
45
+ for (const f of flattenAccounts(it.accounts, group))
46
+ out.push(f.pda ? { ...f, pda: { seeds: f.pda.seeds.map(local), ...(f.pda.program ? { program: local(f.pda.program) } : {}) } } : f);
47
+ continue;
48
+ }
49
+ out.push({ ...it, name: `${prefix}${it.name}` });
50
+ }
51
+ return out;
52
+ }
31
53
  const BIG = new Set(["u64", "i64", "u128", "i128"]);
32
54
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
33
55
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
@@ -45,12 +67,15 @@ export async function testProgram(program, from) {
45
67
  const svm = new LiteSVM();
46
68
  const programId = built.address;
47
69
  svm.addProgramFromFile(programId, built.result.soPath);
70
+ // Accounts and programs `typesol clone` copied from a cluster (tests/accounts), in place before the first test.
71
+ loadClonedAccounts(svm, ws.accounts);
48
72
  return programHarness(svm, programId, built.result.idl);
49
73
  }
50
74
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
51
75
  export function programHarness(svm, programId, idl) {
52
76
  const coder = new BorshCoder(idl);
53
- const pidl = idl;
77
+ const source = idl;
78
+ const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
54
79
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
55
80
  const enc = getAddressEncoder();
56
81
  /** A plain value → what the Anchor coder expects for `type`. */
@@ -0,0 +1,40 @@
1
+ export interface ClonedAccount {
2
+ address: string;
3
+ lamports: string;
4
+ owner: string;
5
+ executable: boolean;
6
+ data: string;
7
+ }
8
+ interface RpcAccount {
9
+ lamports: bigint | number;
10
+ owner: string;
11
+ executable: boolean;
12
+ data: [string, string];
13
+ }
14
+ /** What the clone needs of an RPC: kit's `getMultipleAccounts(…, { encoding: "base64" })`. */
15
+ export interface CloneRpc {
16
+ getMultipleAccounts(addresses: never[], config: {
17
+ encoding: "base64";
18
+ }): {
19
+ send(): Promise<{
20
+ value: (RpcAccount | null)[];
21
+ }>;
22
+ };
23
+ }
24
+ /** Fetch `addresses` and write them to `dir`. Returns what was written, one line per account. */
25
+ export declare function cloneAccounts(rpc: CloneRpc, addresses: string[], dir: string): Promise<string[]>;
26
+ /** What loading needs of a LiteSVM. */
27
+ export interface CloneSvm {
28
+ setAccount(account: {
29
+ address: never;
30
+ lamports: never;
31
+ programAddress: never;
32
+ executable: boolean;
33
+ data: Uint8Array;
34
+ space: bigint;
35
+ }): unknown;
36
+ addProgramFromFile(programId: never, path: string): unknown;
37
+ }
38
+ /** Load every account and program `cloneAccounts` wrote to `dir` into `svm`. Returns how many. */
39
+ export declare function loadClonedAccounts(svm: CloneSvm, dir: string): number;
40
+ export {};
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Copies of cluster accounts for tests (Anchor's `[test.validator.clone]`): `typesol clone` fetches them once and
3
+ * writes them under `tests/accounts/`, and `testProgram` loads that directory into its LiteSVM.
4
+ *
5
+ * - an account: `<address>.json` with its lamports, owner, executable flag and data (base64);
6
+ * - a program: `<address>.so`, its ELF (from the ProgramData account for the upgradeable loader), loaded with
7
+ * `addProgramFromFile`.
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
10
+ import path from "node:path";
11
+ const UPGRADEABLE_LOADER = "BPFLoaderUpgradeab1e11111111111111111111111";
12
+ const LOADERS = new Set(["BPFLoader2111111111111111111111111111111111", "BPFLoader1111111111111111111111111111111111"]);
13
+ /** ProgramData: u32 tag, u64 slot, Option<Pubkey> authority (1 + 32), then the ELF. */
14
+ const PROGRAM_DATA_HEADER = 45;
15
+ async function fetchAll(rpc, addresses) {
16
+ const out = [];
17
+ for (let i = 0; i < addresses.length; i += 100) {
18
+ const { value } = await rpc.getMultipleAccounts(addresses.slice(i, i + 100), { encoding: "base64" }).send();
19
+ out.push(...value);
20
+ }
21
+ return out;
22
+ }
23
+ /** Fetch `addresses` and write them to `dir`. Returns what was written, one line per account. */
24
+ export async function cloneAccounts(rpc, addresses, dir) {
25
+ mkdirSync(dir, { recursive: true });
26
+ const accounts = await fetchAll(rpc, addresses);
27
+ const missing = addresses.filter((_, i) => !accounts[i]);
28
+ if (missing.length)
29
+ throw new Error(`not found on the cluster: ${missing.join(", ")}`);
30
+ const written = [];
31
+ // Upgradeable programs: the ELF is in their ProgramData account (named in the program account's data).
32
+ const programData = new Map();
33
+ accounts.forEach((a, i) => {
34
+ if (a.executable && a.owner === UPGRADEABLE_LOADER) {
35
+ const raw = Buffer.from(a.data[0], "base64");
36
+ if (raw.length < 36 || raw.readUInt32LE(0) !== 2)
37
+ throw new Error(`${addresses[i]}: not an upgradeable program account`);
38
+ programData.set(addresses[i], base58(raw.subarray(4, 36)));
39
+ }
40
+ });
41
+ const datas = await fetchAll(rpc, [...programData.values()]);
42
+ const elfOf = new Map([...programData.keys()].map((p, i) => [p, datas[i]]));
43
+ accounts.forEach((a, i) => {
44
+ const address = addresses[i];
45
+ if (a.executable && (a.owner === UPGRADEABLE_LOADER || LOADERS.has(a.owner))) {
46
+ const pd = elfOf.get(address);
47
+ if (a.owner === UPGRADEABLE_LOADER && !pd)
48
+ throw new Error(`${address}: its ProgramData account is gone (the program was closed)`);
49
+ const elf = pd ? Buffer.from(pd.data[0], "base64").subarray(PROGRAM_DATA_HEADER) : Buffer.from(a.data[0], "base64");
50
+ writeFileSync(path.join(dir, `${address}.so`), elf);
51
+ written.push(`${address}.so program, ${elf.length} bytes`);
52
+ return;
53
+ }
54
+ const entry = { address, lamports: String(a.lamports), owner: a.owner, executable: a.executable, data: a.data[0] };
55
+ writeFileSync(path.join(dir, `${address}.json`), JSON.stringify(entry, null, 2) + "\n");
56
+ written.push(`${address}.json ${Buffer.from(a.data[0], "base64").length} bytes, owner ${a.owner}`);
57
+ });
58
+ return written;
59
+ }
60
+ /** Load every account and program `cloneAccounts` wrote to `dir` into `svm`. Returns how many. */
61
+ export function loadClonedAccounts(svm, dir) {
62
+ if (!existsSync(dir))
63
+ return 0;
64
+ let n = 0;
65
+ for (const f of readdirSync(dir).sort()) {
66
+ const file = path.join(dir, f);
67
+ if (f.endsWith(".so")) {
68
+ svm.addProgramFromFile(f.slice(0, -3), file);
69
+ n++;
70
+ }
71
+ else if (f.endsWith(".json")) {
72
+ const a = JSON.parse(readFileSync(file, "utf8"));
73
+ const data = new Uint8Array(Buffer.from(a.data, "base64"));
74
+ svm.setAccount({
75
+ address: a.address,
76
+ lamports: BigInt(a.lamports),
77
+ programAddress: a.owner,
78
+ executable: a.executable,
79
+ data,
80
+ space: BigInt(data.length),
81
+ });
82
+ n++;
83
+ }
84
+ }
85
+ return n;
86
+ }
87
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
88
+ function base58(bytes) {
89
+ let n = 0n;
90
+ for (const b of bytes)
91
+ n = (n << 8n) | BigInt(b);
92
+ let out = "";
93
+ while (n > 0n) {
94
+ out = ALPHABET[Number(n % 58n)] + out;
95
+ n /= 58n;
96
+ }
97
+ for (const b of bytes) {
98
+ if (b !== 0)
99
+ break;
100
+ out = "1" + out;
101
+ }
102
+ return out;
103
+ }
@@ -12,6 +12,10 @@ export interface Workspace {
12
12
  programs: Record<string, ProgramEntry>;
13
13
  out: string;
14
14
  sbpf: Sbpf;
15
+ /** Cluster accounts `typesol clone` copies for the tests (Anchor's `[test.validator.clone]`). */
16
+ clone: string[];
17
+ /** Where cloned accounts are kept and testProgram loads them from (default tests/accounts). */
18
+ accounts: string;
15
19
  }
16
20
  export declare function findWorkspace(dir: string): Workspace | undefined;
17
21
  export interface ProgramPaths {
package/dist/workspace.js CHANGED
@@ -48,7 +48,19 @@ function readWorkspace(file) {
48
48
  throw new Error(`${file}: program "${name}" needs a snake_case name and { "path": "…", "address"?: "…" } (or just the path)`);
49
49
  programs[name] = e;
50
50
  }
51
- return { root: path.dirname(file), file, programs, out: raw.out ?? "target", sbpf: raw.sbpf ?? "v0" };
51
+ if (raw.clone !== undefined && (!Array.isArray(raw.clone) || raw.clone.some((a) => typeof a !== "string")))
52
+ throw new Error(`${file}: "clone" must be a list of base58 addresses`);
53
+ if (raw.accounts !== undefined && typeof raw.accounts !== "string")
54
+ throw new Error(`${file}: "accounts" must be a directory path`);
55
+ return {
56
+ root: path.dirname(file),
57
+ file,
58
+ programs,
59
+ out: raw.out ?? "target",
60
+ sbpf: raw.sbpf ?? "v0",
61
+ clone: raw.clone ?? [],
62
+ accounts: path.resolve(path.dirname(file), raw.accounts ?? "tests/accounts"),
63
+ };
52
64
  }
53
65
  export function programPaths(ws, name) {
54
66
  const entry = ws.programs[name];
package/docs/cli.md CHANGED
@@ -12,6 +12,7 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
12
12
  | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
13
13
  | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
14
14
  | `typesol check [<program>… \| <file.ts>] [--json] [--stdin]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk). |
15
+ | `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
15
16
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
16
17
  | `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
17
18
  | `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
@@ -33,7 +34,8 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
33
34
  }
34
35
  ```
35
36
 
36
- `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
37
+ `"clone": ["<address>", …]` lists the cluster accounts `typesol clone` copies for the tests, and `"accounts"` where
38
+ they are kept (default `tests/accounts`). `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
37
39
  safe and out of git: it is each program's address and its first upgrade authority must not lose it. A clone without
38
40
  it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
39
41