@typesol/cli 0.33.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
  }
@@ -94,11 +94,16 @@ function idlType(t, borshOption = false) {
94
94
  * composite accounts), a field of another group as `<group>_<field>` (how clients flatten groups), else the name.
95
95
  */
96
96
  function relativePath(path, from) {
97
- const at = path.indexOf("__");
98
- if (at < 0)
97
+ if (!path.includes("__"))
99
98
  return path;
100
- const group = path.slice(0, at);
101
- return group === from ? path.slice(at + 2) : `${group}_${path.slice(at + 2)}`;
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("__", "_");
102
107
  }
103
108
  function relativeSeeds(seeds, from) {
104
109
  if (!Array.isArray(seeds))
@@ -121,6 +126,12 @@ function accountEntry(ix, name, k, programAddress) {
121
126
  entry.address = "Sysvar1nstructions1111111111111111111111111";
122
127
  if (k.kind === "ataProgram")
123
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";
124
135
  if (k.kind === "metadataProgram")
125
136
  entry.address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s";
126
137
  if (k.kind === "coreProgram")
@@ -160,18 +171,20 @@ function accountEntry(ix, name, k, programAddress) {
160
171
  /** The instruction's account entries, an account group's fields nested under it: `{ name: "pool", accounts: [...] }`. */
161
172
  function nestGroups(ix, entry) {
162
173
  const out = [];
163
- let open;
174
+ // The groups open at the current account, outermost first: their paths and entry lists.
175
+ let open = [];
164
176
  for (const a of ix.accounts) {
165
- if (!a.group) {
166
- open = undefined;
167
- out.push(entry(a));
168
- continue;
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);
169
186
  }
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));
187
+ (open.length ? open[open.length - 1].accounts : out).push(entry(a));
175
188
  }
176
189
  return out;
177
190
  }
@@ -182,7 +195,9 @@ export function buildIdl(model, address, version = "0.1.0") {
182
195
  const idl = {
183
196
  address,
184
197
  metadata: { name: model.name, version, spec: "0.1.0", description: "Built with TypeSOL" },
185
- instructions: model.instructions.map((ix) => ({
198
+ instructions: model.instructions
199
+ .filter((ix) => !ix.fallback)
200
+ .map((ix) => ({
186
201
  name: ix.name,
187
202
  ...docsOf(ix.node),
188
203
  discriminator: ix.discriminator,
@@ -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
  } | {
@@ -314,11 +326,15 @@ export interface AccountParam {
314
326
  /** The parameter, or the field of an account group. */
315
327
  node: ts.ParameterDeclaration | ts.PropertySignature;
316
328
  constraints: Constraints;
317
- /** A field of an account group: the group parameter, the field, and the group's interface. `name` is `<param>__<field>`. */
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
+ */
318
333
  group?: {
319
334
  param: string;
320
335
  field: string;
321
336
  type: string;
337
+ path: string[];
322
338
  };
323
339
  /** Created in the body as a new keypair account (`create(payer, null, …)`), so it signs: the IDL says so. */
324
340
  signsInit?: boolean;
@@ -341,6 +357,8 @@ export type IdlSeed = {
341
357
  path: string;
342
358
  };
343
359
  export interface Instruction {
360
+ /** `@fallback`: run when no instruction's discriminator matches; not in the IDL. */
361
+ fallback?: boolean;
344
362
  name: string;
345
363
  discriminator: number[];
346
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,9 +23,12 @@ 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;
31
34
  /**
@@ -64,6 +67,8 @@ export async function testProgram(program, from) {
64
67
  const svm = new LiteSVM();
65
68
  const programId = built.address;
66
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);
67
72
  return programHarness(svm, programId, built.result.idl);
68
73
  }
69
74
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
@@ -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
 
package/docs/language.md CHANGED
@@ -50,7 +50,7 @@ The full reference. For a tour, start with the [README](../README.md).
50
50
  | Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
51
51
  | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
52
52
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
53
- | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent) |
53
+ | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness) |
54
54
  | Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account) |
55
55
  | Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferFeeInverse(mint, amountReceived)` (the fee when the recipient is to get that much: spl-token-2022's `calculate_inverse_epoch_fee`), `transferFeeBasisPoints(mint)` / `transferFeeMaximum(mint)` (this epoch's; 0 without the extension), `extensionsWithin(account, [1n, 18n, …])` (every extension is one of those types), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
56
56
  | Events through CPI | `emitCpi<Paid>({ … }, eventAuthority, self)` with `eventAuthority: EventAuthority, self: SelfProgram` parameters — Anchor `emit_cpi!`: the event rides in a self-CPI (inner instruction), not in logs; the program accepts Anchor's event instruction (2002 / 2006 otherwise) |
@@ -67,7 +67,8 @@ The full reference. For a tour, start with the [README](../README.md).
67
67
  | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
68
68
  | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size) |
69
69
  | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
70
- | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`); a group may not be optional, nest another group, or be a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
70
+ | `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL |
71
+ | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it to `pFeesVault`); a group may not be optional or a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
71
72
  | `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
72
73
  | `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes, `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
73
74
  | `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
@@ -90,7 +91,9 @@ The full reference. For a tour, start with the [README](../README.md).
90
91
  | `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
91
92
  | `TokenInterface` | either token program |
92
93
  | `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
93
- | `TokenMetadataProgram` | Metaplex `createV3(...)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection: mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be `verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection); `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply \| null)`; `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar)` (Verify with CollectionV1); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
94
+ | `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
95
+ | `TokenMetadataProgram` | Metaplex `createV3(...)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection: mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be `verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection); `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply \| null)`; `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar)` (Verify with CollectionV1); `updateMetadataAccountsV2(metadata, updateAuthority, data \| null, newUpdateAuthority \| null, primarySaleHappened \| null, isMutable \| null)` (`data` replaces the whole DataV2: `{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`; each null leaves that part); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
96
+ | `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer)` (no lockup), `authorize(stake, clockSysvar, authority, newAuthority, "staker" \| "withdrawer")`, `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`, `deactivate(stake, clockSysvar, staker)`, `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports)`; the sysvar and config accounts are parameters, as in anchor-spl's stake module; authorities sign (PDAs with signerSeeds) |
94
97
  | `InstructionsSysvar`, `PythPriceUpdate`, `SwitchboardFeed` | exact address / owner program + discriminator |
95
98
  | `InstructionsSysvar` (introspection) | `ixs.length`, `ixs.currentIndex()` (the top-level instruction being executed), `ixs.get(i)` → a `TransactionInstruction`: `programId`, `accountsLength`, `dataLength`, `accountKey(j)` / `accountIsSigner(j)` / `accountIsWritable(j)`, `readU8/U16/U32/U64/readPubkey(offset)` (little-endian), `is(program, "name")` (that program's instruction by its default Anchor discriminator, sha256("global:<name>"); an instruction with its own `@discriminator` is matched with `programId` and `readU64(0)` instead). Every read is bounds-checked (5104). It is the transaction author's data: require things of the transaction with it (a repay instruction after a flash loan), never treat it as proof |
96
99
  | `Program<"Address…">` | exact program address + executable |
@@ -119,7 +122,7 @@ with `i == j`) is refused with 2040 too, since the two views would alias.
119
122
  `burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
120
123
  come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
121
124
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
122
- `initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`. Each takes optional signerSeeds
125
+ `initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`; and the Token Group interface: `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)` (a collection mint with a GroupPointer to itself; fund the rent for the group, which Token-2022 adds to the account), `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`, `updateGroupMaxSize(group, authority, maxSize)`, `updateGroupAuthority(group, authority, next | null)`. Each takes optional signerSeeds
123
126
  - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
124
127
  - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
125
128
  stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick