@typesol/cli 0.43.0 → 0.44.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 (64) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/NOTICE +71 -0
  3. package/README.md +25 -11
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +4 -0
  9. package/dist/compiler/emit/alias.d.ts +1 -1
  10. package/dist/compiler/emit/alias.js +10 -4
  11. package/dist/compiler/emit/base.d.ts +3 -1
  12. package/dist/compiler/emit/base.js +20 -3
  13. package/dist/compiler/emit/borsh.js +11 -5
  14. package/dist/compiler/emit/calls.d.ts +13 -0
  15. package/dist/compiler/emit/calls.js +91 -8
  16. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  17. package/dist/compiler/emit/cpi-core.js +35 -7
  18. package/dist/compiler/emit/create.js +3 -0
  19. package/dist/compiler/emit/expressions.js +6 -1
  20. package/dist/compiler/emit/function.js +10 -0
  21. package/dist/compiler/emit/shared.d.ts +17 -0
  22. package/dist/compiler/emit/shared.js +36 -3
  23. package/dist/compiler/emit/statements.js +17 -4
  24. package/dist/compiler/emit/storage.d.ts +2 -0
  25. package/dist/compiler/emit/storage.js +16 -8
  26. package/dist/compiler/index.d.ts +15 -1
  27. package/dist/compiler/index.js +40 -3
  28. package/dist/compiler/toolchain.d.ts +41 -1
  29. package/dist/compiler/toolchain.js +102 -3
  30. package/dist/testing-stake.d.ts +2 -1
  31. package/dist/testing-stake.js +2 -1
  32. package/dist/testing.js +6 -4
  33. package/dist/tools/clientgen.d.ts +15 -0
  34. package/dist/tools/clientgen.js +173 -7
  35. package/dist/tools/cpigen.d.ts +0 -15
  36. package/dist/tools/cpigen.js +19 -8
  37. package/dist/tools/doctor.d.ts +17 -2
  38. package/dist/tools/doctor.js +64 -4
  39. package/dist/tools/portgen.js +43 -18
  40. package/dist/workspace.d.ts +20 -0
  41. package/dist/workspace.js +173 -6
  42. package/docs/ai.md +10 -5
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +63 -17
  45. package/docs/case-study-escrow.md +1 -1
  46. package/docs/case-study-phoenix.md +10 -10
  47. package/docs/case-study-raydium-amm.md +3 -3
  48. package/docs/case-study-spl-stake-pool.md +5 -5
  49. package/docs/cli.md +17 -8
  50. package/docs/client.md +11 -3
  51. package/docs/errors.md +1 -1
  52. package/docs/language.md +10 -5
  53. package/docs/mainnet.md +21 -10
  54. package/docs/migrate-from-anchor.md +2 -1
  55. package/docs/runtime.md +11 -1
  56. package/docs/security-model.md +38 -6
  57. package/docs/stability.md +21 -2
  58. package/docs/testing.md +25 -0
  59. package/docs/troubleshooting.md +12 -0
  60. package/llms-full.txt +168 -52
  61. package/llms.txt +1 -1
  62. package/package.json +3 -1
  63. package/runtime/typesol_rt.h +22 -13
  64. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -17,8 +17,48 @@ export declare function findToolchain(sbpf?: Sbpf): Toolchain;
17
17
  /** The SBF stack frame of one function. */
18
18
  export declare const STACK_FRAME = 4096;
19
19
  export declare function buildSharedObject(cFile: string, outSo: string, sbpf?: Sbpf, tc?: Toolchain): void;
20
- /** The clang version string, for build manifests. */
20
+ /**
21
+ * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
22
+ * execution, differential and fuzz test runs on binaries this clang built. The C TypeSOL emits is only checked
23
+ * against this backend; another clang can compile it differently (how struct arguments are passed, for one), so
24
+ * binaries from another toolchain are outside what the tests cover. Changing it is a release note.
25
+ */
26
+ export declare const TESTED_TOOLCHAIN: {
27
+ readonly agave: "3.1.10";
28
+ readonly platformTools: "v1.52";
29
+ readonly clang: "clang version 20.1.7-rust-dev (https://github.com/anza-xyz/llvm-project.git 78496716176191b2dfb728e5e38501812e7467db)";
30
+ };
31
+ /** The commands that install the tested toolchain (the Agave CLI, then its platform-tools). */
32
+ export declare const INSTALL_TESTED_TOOLCHAIN: readonly ["sh -c \"$(curl -sSfL https://release.anza.xyz/v3.1.10/install)\"", "cargo-build-sbf --install-only --force-tools-install --tools-version v1.52"];
33
+ /** The clang version string (the first line of `clang --version`), for build manifests. */
21
34
  export declare function toolchainVersion(tc?: Toolchain): string;
35
+ /**
36
+ * The platform-tools version of an SDK, or undefined when it cannot be told for sure. cargo-build-sbf records the
37
+ * installed version as an empty `dependencies/platform-tools-<version>.md` next to `dependencies/platform-tools`,
38
+ * which links into `~/.cache/solana/<version>/platform-tools`; both have to agree when both are there.
39
+ */
40
+ export declare function platformToolsVersion(tc?: Pick<Toolchain, "sdk">): string | undefined;
41
+ /** A clang version line made short enough for a message: `clang 20.1.7-rust-dev (anza-xyz/llvm-project 78496716)`. */
42
+ export declare function shortClang(version: string): string;
43
+ export interface ToolchainInfo {
44
+ clang: string;
45
+ platformTools?: string;
46
+ /** The clang is the one the release is tested with. */
47
+ tested: boolean;
48
+ }
49
+ /** The active toolchain's versions, and whether it is the tested one (the clang is what compiles, so it decides). */
50
+ export declare function toolchainInfo(tc?: Toolchain): ToolchainInfo;
51
+ /** What to say about a toolchain that is not the tested one; undefined for the tested one. */
52
+ export declare function untestedToolchainMessage(info: ToolchainInfo): string | undefined;
53
+ /** `--toolchain-strict`: refuse an untested toolchain for the rest of the process, as TYPESOL_TOOLCHAIN=strict does. */
54
+ export declare function setToolchainStrict(on?: boolean): void;
55
+ /** Whether an untested toolchain is an error: `--toolchain-strict` or TYPESOL_TOOLCHAIN=strict ("warn", the default). */
56
+ export declare function toolchainStrict(): boolean;
57
+ /**
58
+ * Before a build: an untested toolchain gets one warning per process on stderr (a workspace or a test run builds many
59
+ * programs), or an error in strict mode. `info` is the active toolchain's, unless given.
60
+ */
61
+ export declare function checkToolchain(info?: ToolchainInfo, warn?: (message: string) => void): ToolchainInfo;
22
62
  /** One variable slot of a function's stack frame as clang laid it out: its size and the C variables sharing it. */
23
63
  export interface FrameSlot {
24
64
  size: number;
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
- import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
2
+ import { existsSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -116,9 +116,108 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
116
116
  ]);
117
117
  rmSync(obj, { force: true }); // the object file is only an intermediate
118
118
  }
119
- /** The clang version string, for build manifests. */
119
+ /**
120
+ * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
121
+ * execution, differential and fuzz test runs on binaries this clang built. The C TypeSOL emits is only checked
122
+ * against this backend; another clang can compile it differently (how struct arguments are passed, for one), so
123
+ * binaries from another toolchain are outside what the tests cover. Changing it is a release note.
124
+ */
125
+ export const TESTED_TOOLCHAIN = {
126
+ agave: "3.1.10",
127
+ platformTools: "v1.52",
128
+ clang: "clang version 20.1.7-rust-dev (https://github.com/anza-xyz/llvm-project.git 78496716176191b2dfb728e5e38501812e7467db)",
129
+ };
130
+ /** The commands that install the tested toolchain (the Agave CLI, then its platform-tools). */
131
+ export const INSTALL_TESTED_TOOLCHAIN = [
132
+ `sh -c "$(curl -sSfL https://release.anza.xyz/v${TESTED_TOOLCHAIN.agave}/install)"`,
133
+ `cargo-build-sbf --install-only --force-tools-install --tools-version ${TESTED_TOOLCHAIN.platformTools}`,
134
+ ];
135
+ // One `clang --version` per clang a process uses: up-to-date checks and manifests ask for it on every build.
136
+ const clangVersions = new Map();
137
+ /** The clang version string (the first line of `clang --version`), for build manifests. */
120
138
  export function toolchainVersion(tc = findToolchain()) {
121
- return execFileSync(tc.clang, ["--version"], { encoding: "utf8" }).split("\n")[0].trim();
139
+ let v = clangVersions.get(tc.clang);
140
+ if (v === undefined) {
141
+ v = execFileSync(tc.clang, ["--version"], { encoding: "utf8" }).split("\n")[0].trim();
142
+ clangVersions.set(tc.clang, v);
143
+ }
144
+ return v;
145
+ }
146
+ /**
147
+ * The platform-tools version of an SDK, or undefined when it cannot be told for sure. cargo-build-sbf records the
148
+ * installed version as an empty `dependencies/platform-tools-<version>.md` next to `dependencies/platform-tools`,
149
+ * which links into `~/.cache/solana/<version>/platform-tools`; both have to agree when both are there.
150
+ */
151
+ export function platformToolsVersion(tc = findToolchain()) {
152
+ const deps = path.join(tc.sdk, "dependencies");
153
+ let markers;
154
+ try {
155
+ markers = readdirSync(deps).flatMap((f) => /^platform-tools-(v\d+\.\d+(?:\.\d+)?)\.md$/.exec(f)?.[1] ?? []);
156
+ }
157
+ catch {
158
+ return undefined;
159
+ }
160
+ let linked;
161
+ try {
162
+ linked = /[/\\](v\d+\.\d+(?:\.\d+)?)[/\\]platform-tools$/.exec(realpathSync(path.join(deps, "platform-tools")))?.[1];
163
+ }
164
+ catch {
165
+ /* no platform-tools directory */
166
+ }
167
+ if (linked)
168
+ return markers.length === 0 || markers.includes(linked) ? linked : undefined;
169
+ return markers.length === 1 ? markers[0] : undefined;
170
+ }
171
+ /** A clang version line made short enough for a message: `clang 20.1.7-rust-dev (anza-xyz/llvm-project 78496716)`. */
172
+ export function shortClang(version) {
173
+ return version
174
+ .replace(/^clang version /, "clang ")
175
+ .replace(/\(https:\/\/github\.com\/([^\s)]+?)(?:\.git)? ([0-9a-f]{8})[0-9a-f]*\)/, "($1 $2)")
176
+ .trim();
177
+ }
178
+ /** The active toolchain's versions, and whether it is the tested one (the clang is what compiles, so it decides). */
179
+ export function toolchainInfo(tc = findToolchain()) {
180
+ const clang = toolchainVersion(tc);
181
+ return { clang, platformTools: platformToolsVersion(tc), tested: clang === TESTED_TOOLCHAIN.clang };
182
+ }
183
+ /** What to say about a toolchain that is not the tested one; undefined for the tested one. */
184
+ export function untestedToolchainMessage(info) {
185
+ if (info.tested)
186
+ return undefined;
187
+ const t = TESTED_TOOLCHAIN;
188
+ return (`this build uses ${shortClang(info.clang)}${info.platformTools ? ` (platform-tools ${info.platformTools})` : ""}; ` +
189
+ `TypeSOL is tested with ${shortClang(t.clang)} (platform-tools ${t.platformTools}, Agave ${t.agave}). ` +
190
+ `Binaries from an untested toolchain are not covered by the project's tests. ` +
191
+ `Install the tested one: ${INSTALL_TESTED_TOOLCHAIN[1]}`);
192
+ }
193
+ let strictFlag = false;
194
+ let warned = false;
195
+ /** `--toolchain-strict`: refuse an untested toolchain for the rest of the process, as TYPESOL_TOOLCHAIN=strict does. */
196
+ export function setToolchainStrict(on = true) {
197
+ strictFlag = on;
198
+ }
199
+ /** Whether an untested toolchain is an error: `--toolchain-strict` or TYPESOL_TOOLCHAIN=strict ("warn", the default). */
200
+ export function toolchainStrict() {
201
+ const env = process.env.TYPESOL_TOOLCHAIN;
202
+ if (env && env !== "strict" && env !== "warn")
203
+ throw new Error(`TYPESOL_TOOLCHAIN=${env}: expected "strict" or "warn"`);
204
+ return strictFlag || env === "strict";
205
+ }
206
+ /**
207
+ * Before a build: an untested toolchain gets one warning per process on stderr (a workspace or a test run builds many
208
+ * programs), or an error in strict mode. `info` is the active toolchain's, unless given.
209
+ */
210
+ export function checkToolchain(info = toolchainInfo(), warn = (m) => console.error(`warning: ${m}`)) {
211
+ const message = untestedToolchainMessage(info);
212
+ if (!message)
213
+ return info;
214
+ if (toolchainStrict())
215
+ throw new Error(`${message.replace(/^this build uses/, "refusing to build with")} (an untested toolchain is an error with --toolchain-strict or TYPESOL_TOOLCHAIN=strict)`);
216
+ if (!warned) {
217
+ warned = true;
218
+ warn(message);
219
+ }
220
+ return info;
122
221
  }
123
222
  const STACK_OVER = /stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/;
124
223
  /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
@@ -77,7 +77,8 @@ export interface StakeActivationOptions {
77
77
  }
78
78
  /**
79
79
  * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
80
- * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
80
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0,
81
+ * https://github.com/solana-program/stake, Copyright Anza Maintainers; licence recorded in NOTICE), BigInt math with
81
82
  * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
82
83
  * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
83
84
  */
@@ -130,7 +130,8 @@ function allowanceFloat(epoch, account, clusterPortion, clusterEffective, rateEp
130
130
  }
131
131
  /**
132
132
  * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
133
- * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
133
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0,
134
+ * https://github.com/solana-program/stake, Copyright Anza Maintainers; licence recorded in NOTICE), BigInt math with
134
135
  * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
135
136
  * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
136
137
  */
package/dist/testing.js CHANGED
@@ -25,7 +25,7 @@ import { fileURLToPath } from "node:url";
25
25
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
26
  import { loadClonedAccounts } from "./tools/clone.js";
27
27
  import { svmConnection } from "./tools/svmrpc.js";
28
- import { buildWorkspace, findWorkspace } from "./workspace.js";
28
+ import { buildForTest, findWorkspace } from "./workspace.js";
29
29
  export { svmConnection };
30
30
  export * from "./testing-stake.js";
31
31
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
@@ -64,13 +64,15 @@ export async function testProgram(program, from) {
64
64
  throw new Error(`no typesol.json at or above ${start}`);
65
65
  if (!ws.programs[program])
66
66
  throw new Error(`typesol.json has no program "${program}" (it has ${Object.keys(ws.programs).join(", ")})`);
67
- const [built] = buildWorkspace(ws, [program]);
67
+ // Every test file calls this, often in parallel workers: an up-to-date build is reused, and concurrent builds of the
68
+ // same program wait for each other instead of writing over each other's files.
69
+ const built = buildForTest(ws, program);
68
70
  const svm = new LiteSVM();
69
71
  const programId = built.address;
70
- svm.addProgramFromFile(programId, built.result.soPath);
72
+ svm.addProgramFromFile(programId, built.soPath);
71
73
  // Accounts and programs `typesol clone` copied from a cluster (tests/accounts), in place before the first test.
72
74
  loadClonedAccounts(svm, ws.accounts);
73
- return programHarness(svm, programId, built.result.idl);
75
+ return programHarness(svm, programId, built.idl);
74
76
  }
75
77
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
76
78
  export function programHarness(svm, programId, idl) {
@@ -95,6 +95,21 @@ export declare class ClientIdlError extends Error {
95
95
  * the constraints raise their Anchor codes), then TypeSOL's own runtime errors (runtime/typesol_rt.h).
96
96
  */
97
97
  export declare const TYPESOL_ERRORS: Record<number, string>;
98
+ /** Text safe to print on a terminal (notes, errors): C0 and C1 control characters and bidi overrides escaped. */
99
+ export declare const printable: (s: string) => string;
100
+ /** Text that can sit inside a block or line comment: printable ASCII (no line breaks), no comment terminator. */
101
+ export declare const commentText: (s: string) => string;
102
+ /** Whether `idl` is in the format Anchor wrote before 0.30: `isMut` / `isSigner` accounts, or a name and version at the top and no discriminators. */
103
+ export declare function isLegacyAnchorIdl(idl: unknown): boolean;
104
+ /**
105
+ * Throws ClientIdlError unless `idl` is an Anchor 0.30+ / 1.x or TypeSOL IDL whose values are safe to paste into generated
106
+ * source: identifiers that are identifiers, base58 addresses, byte lists. `typesol client`, `typesol cpi` and `typesol port`
107
+ * all check an IDL this way first. `instructions: "required"` also refuses an IDL without any (nothing to generate).
108
+ */
109
+ export declare function checkIdl(idl: unknown, opts?: {
110
+ address?: string;
111
+ instructions?: "required";
112
+ }): asserts idl is ClientIdl;
98
113
  export declare function generateClient(idl: ClientIdl, opts?: {
99
114
  address?: string;
100
115
  }): ClientGenResult;
@@ -78,7 +78,7 @@ export const TYPESOL_ERRORS = {
78
78
  5114: "NoReturnData",
79
79
  5115: "AccountMissing",
80
80
  };
81
- const INTS = { u8: 8, u16: 16, u32: 32, u64: 64, u128: 128, i8: 8, i16: 16, i32: 32, i64: 64, i128: 128 };
81
+ const INTS = { u8: 8, u16: 16, u32: 32, u64: 64, u128: 128, u256: 256, i8: 8, i16: 16, i32: 32, i64: 64, i128: 128, i256: 256 };
82
82
  const FLOATS = { f32: 32, f64: 64 };
83
83
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
84
84
  /** A seed path: `arg`, `arg.field…`, or `opt.unwrap_or(N)` (Anchor's text for an Option argument with a default). */
@@ -105,6 +105,8 @@ const TAKEN = [
105
105
  "fixedString",
106
106
  "fixedOption",
107
107
  "unitEnum",
108
+ "lazyCodec",
109
+ "wideInt",
108
110
  // exports
109
111
  "PROGRAM_ADDRESS",
110
112
  "ERRORS",
@@ -117,6 +119,9 @@ const TAKEN = [
117
119
  "AccountRole",
118
120
  "Address",
119
121
  "Codec",
122
+ "Option",
123
+ "OptionOrNullable",
124
+ "getOptionCodec",
120
125
  "FetchAccountConfig",
121
126
  "GetAccountInfoApi",
122
127
  "Instruction",
@@ -128,6 +133,7 @@ const TAKEN = [
128
133
  "addCodecSizePrefix",
129
134
  "address",
130
135
  "createCodec",
136
+ "isFixedSize",
131
137
  "fetchEncodedAccount",
132
138
  "fixCodecSize",
133
139
  "getAddressCodec",
@@ -205,6 +211,8 @@ const KIT_TYPES = [
205
211
  "ReadonlyUint8Array",
206
212
  "Rpc",
207
213
  "TransactionSigner",
214
+ "Option",
215
+ "OptionOrNullable",
208
216
  ];
209
217
  const KIT_VALUES = [
210
218
  "AccountRole",
@@ -227,6 +235,7 @@ const KIT_VALUES = [
227
235
  "addCodecSizePrefix",
228
236
  "address",
229
237
  "createCodec",
238
+ "isFixedSize",
230
239
  "fetchEncodedAccount",
231
240
  "fixCodecSize",
232
241
  "getAddressCodec",
@@ -245,6 +254,7 @@ const KIT_VALUES = [
245
254
  "getI64Codec",
246
255
  "getI8Codec",
247
256
  "getNullableCodec",
257
+ "getOptionCodec",
248
258
  "getProgramDerivedAddress",
249
259
  "getStructCodec",
250
260
  "getTupleCodec",
@@ -289,16 +299,49 @@ const pascal = (s) => {
289
299
  };
290
300
  const prop = (s) => (NAME.test(s) && !JS_RESERVED.has(s) ? s : JSON.stringify(s));
291
301
  /** Text safe to print on a terminal (notes, errors): C0 and C1 control characters and bidi overrides escaped. */
292
- const printable = (s) => s.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
293
- /** Text that can sit inside a block comment: printable ASCII, no comment terminator. */
294
- const commentText = (s) => s.replace(/[^\x20-\x7e]/g, " ").replace(/\*\//g, "* /");
302
+ export const printable = (s) => s.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
303
+ /** Text that can sit inside a block or line comment: printable ASCII (no line breaks), no comment terminator. */
304
+ export const commentText = (s) => s.replace(/[^\x20-\x7e]/g, " ").replace(/\*\//g, "* /");
295
305
  const doc = (lines, indent = "") => Array.isArray(lines) && lines.length && lines.every((l) => typeof l === "string")
296
306
  ? `${indent}/** ${lines.map(commentText).join(`\n${indent} * `)} */\n`
297
307
  : "";
298
308
  const bytes = (b) => `new Uint8Array([${b.join(", ")}])`;
299
309
  const definedName = (t) => typeof t === "object" && t !== null && t.defined ? (typeof t.defined === "string" ? t.defined : t.defined.name) : undefined;
310
+ /** An `option` type (Anchor's Option; not a COption, whose fixed layout differs). */
311
+ const nestedOption = (t) => typeof t === "object" && t !== null && t.option !== undefined;
300
312
  const isField = (f) => typeof f === "object" && f !== null && "name" in f && "type" in f;
301
313
  const sortCodeUnits = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
314
+ /** What to do with an IDL written before Anchor 0.30's format (the generators read only 0.30+ / 1.x and TypeSOL IDLs). */
315
+ const LEGACY_IDL = "this is a pre-0.30 Anchor IDL (accounts marked isMut / isSigner, no discriminators): convert it first with `anchor idl convert <idl.json>` (Anchor 0.30+), then pass the converted file";
316
+ /** Whether `idl` is in the format Anchor wrote before 0.30: `isMut` / `isSigner` accounts, or a name and version at the top and no discriminators. */
317
+ export function isLegacyAnchorIdl(idl) {
318
+ if (typeof idl !== "object" || idl === null)
319
+ return false;
320
+ const o = idl;
321
+ const ixs = Array.isArray(o.instructions) ? o.instructions : [];
322
+ const obj = (x) => typeof x === "object" && x !== null;
323
+ const flagged = (items) => Array.isArray(items) && items.some((a) => obj(a) && ("isMut" in a || "isSigner" in a || flagged(a.accounts)));
324
+ if (ixs.some((ix) => obj(ix) && flagged(ix.accounts)))
325
+ return true;
326
+ return typeof o.name === "string" && typeof o.version === "string" && ixs.length > 0 && ixs.every((ix) => obj(ix) && ix.discriminator === undefined);
327
+ }
328
+ /**
329
+ * Throws ClientIdlError unless `idl` is an Anchor 0.30+ / 1.x or TypeSOL IDL whose values are safe to paste into generated
330
+ * source: identifiers that are identifiers, base58 addresses, byte lists. `typesol client`, `typesol cpi` and `typesol port`
331
+ * all check an IDL this way first. `instructions: "required"` also refuses an IDL without any (nothing to generate).
332
+ */
333
+ export function checkIdl(idl, opts = {}) {
334
+ if (typeof idl !== "object" || idl === null || Array.isArray(idl))
335
+ throw new ClientIdlError("not an Anchor IDL: expected a JSON object");
336
+ if (isLegacyAnchorIdl(idl))
337
+ throw new ClientIdlError(LEGACY_IDL);
338
+ const ixs = idl.instructions;
339
+ if (!Array.isArray(ixs))
340
+ throw new ClientIdlError("not an Anchor IDL: it has no `instructions` list");
341
+ if (opts.instructions === "required" && !ixs.length)
342
+ throw new ClientIdlError("the IDL has no instructions: nothing to generate");
343
+ validate(idl, opts.address ?? idl.address);
344
+ }
302
345
  /** Throws ClientIdlError unless every value that reaches the generated source is well-formed. */
303
346
  function validate(idl, programAddress) {
304
347
  const fail = (what) => {
@@ -371,6 +414,8 @@ function validate(idl, programAddress) {
371
414
  if (!Array.isArray(idl.instructions))
372
415
  fail("no instructions list");
373
416
  for (const ix of idl.instructions) {
417
+ if (typeof ix !== "object" || ix === null)
418
+ fail("an instruction is not an object");
374
419
  name(ix.name, "instruction");
375
420
  if (ix.discriminator === undefined)
376
421
  fail(`instruction ${ix.name} has no discriminator: this looks like a pre-0.30 Anchor IDL (convert it with \`anchor idl convert\`)`);
@@ -379,6 +424,8 @@ function validate(idl, programAddress) {
379
424
  if (!Array.isArray(items))
380
425
  fail(`${where}: accounts must be a list`);
381
426
  for (const a of items) {
427
+ if (typeof a !== "object" || a === null)
428
+ fail(`${where}: an account is not an object`);
382
429
  name(a.name, where);
383
430
  if (a.accounts) {
384
431
  walk(a.accounts, `${where}.${a.name}`);
@@ -410,7 +457,11 @@ function validate(idl, programAddress) {
410
457
  if (ix.returns !== undefined)
411
458
  type(ix.returns, `instruction ${ix.name} return`);
412
459
  }
460
+ if (idl.types !== undefined && !Array.isArray(idl.types))
461
+ fail("types must be a list");
413
462
  for (const t of idl.types ?? []) {
463
+ if (typeof t !== "object" || t === null)
464
+ fail("a type definition is not an object");
414
465
  name(t.name, "type");
415
466
  if (typeof t.type !== "object" || t.type === null)
416
467
  fail(`type ${t.name} has no definition`);
@@ -428,7 +479,11 @@ function validate(idl, programAddress) {
428
479
  fail(`type ${t.name}: repr align ${JSON.stringify(align)} is not a power of two`);
429
480
  }
430
481
  fields(t.type.fields, `type ${t.name}`);
482
+ if (t.type.variants !== undefined && !Array.isArray(t.type.variants))
483
+ fail(`type ${t.name}: variants must be a list`);
431
484
  for (const v of t.type.variants ?? []) {
485
+ if (typeof v !== "object" || v === null)
486
+ fail(`type ${t.name}: a variant is not an object`);
432
487
  name(v.name, `type ${t.name} variant`);
433
488
  fields(v.fields, `type ${t.name}.${v.name}`);
434
489
  }
@@ -438,12 +493,21 @@ function validate(idl, programAddress) {
438
493
  for (const [list, what] of [
439
494
  [idl.accounts, "account"],
440
495
  [idl.events, "event"],
441
- ])
496
+ ]) {
497
+ if (list !== undefined && !Array.isArray(list))
498
+ fail(`${what}s must be a list`);
442
499
  for (const a of list ?? []) {
500
+ if (typeof a !== "object" || a === null)
501
+ fail(`an ${what} entry is not an object`);
443
502
  name(a.name, what);
444
503
  byteList(a.discriminator, `${what} ${a.name}`);
445
504
  }
505
+ }
506
+ if (idl.errors !== undefined && !Array.isArray(idl.errors))
507
+ fail("errors must be a list");
446
508
  for (const e of idl.errors ?? []) {
509
+ if (typeof e !== "object" || e === null)
510
+ fail("an error entry is not an object");
447
511
  if (!Number.isInteger(e.code) || e.code < 0 || e.code > 0xffffffff)
448
512
  fail(`error code ${JSON.stringify(e.code)} is not a u32`);
449
513
  name(e.name, "error");
@@ -597,8 +661,8 @@ export function generateClient(idl, opts = {}) {
597
661
  }
598
662
  }
599
663
  function generate(idl, opts) {
664
+ checkIdl(idl, { address: opts.address });
600
665
  const programAddress = opts.address ?? idl.address;
601
- validate(idl, programAddress);
602
666
  idl = monomorphize(idl);
603
667
  if (!programAddress)
604
668
  throw new ClientIdlError("the IDL has no program address; pass one");
@@ -705,8 +769,12 @@ function generate(idl, opts) {
705
769
  return Number.isInteger(Number(t.array[1])) ? issue(t.array[0]) : "array lengths must be numbers (generic lengths are not supported)";
706
770
  if (t.vec !== undefined)
707
771
  return issue(t.vec);
708
- if (t.option !== undefined)
772
+ if (t.option !== undefined) {
773
+ // Option<Option<T>> is held as `Option<T> | null` (kit's Option inside), so Some(None) is expressible; one level more is not.
774
+ if (nestedOption(t.option) && nestedOption(t.option.option))
775
+ return "Option<Option<Option<…>>> is not supported";
709
776
  return issue(t.option);
777
+ }
710
778
  if (t.coption !== undefined)
711
779
  return issue(t.coption);
712
780
  const n = definedName(t);
@@ -757,6 +825,9 @@ function generate(idl, opts) {
757
825
  const tsName = (n) => tsNames.get(n);
758
826
  const isU8 = (t) => t === "u8";
759
827
  function tsType(t, dir) {
828
+ // Option<Option<T>>: null is None, kit's none() is Some(None), some(x) (or x) is Some(Some(x)).
829
+ if (typeof t === "object" && t.option !== undefined && nestedOption(t.option))
830
+ return `${dir === "in" ? "OptionOrNullable" : "Option"}<${tsType(t.option.option, dir)}> | null`;
760
831
  if (typeof t === "string") {
761
832
  if (t in INTS)
762
833
  return INTS[t] >= 64 ? (dir === "in" ? "number | bigint" : "bigint") : "number";
@@ -795,8 +866,56 @@ function generate(idl, opts) {
795
866
  let needsFixedVec = false;
796
867
  let needsUnitEnum = false;
797
868
  let needsCStruct = false;
869
+ let needsLazy = false;
870
+ let needsWideInt = false;
871
+ // Types that hold themselves (`Shape { Rec { kids: Vec<Shape> } }`): their codecs refer to each other lazily, or
872
+ // building one would build itself again without end.
873
+ const recursive = new Set();
874
+ {
875
+ const refs = (t, out) => {
876
+ if (t === undefined || t === null || typeof t === "string")
877
+ return;
878
+ if (t.array)
879
+ return refs(t.array[0], out);
880
+ for (const inner of [t.vec, t.option, t.coption])
881
+ if (inner !== undefined)
882
+ return refs(inner, out);
883
+ const n = definedName(t);
884
+ if (n !== undefined)
885
+ out.push(n);
886
+ };
887
+ const edges = new Map();
888
+ for (const d of defs.values()) {
889
+ const out = [];
890
+ for (const f of d.type.fields ?? [])
891
+ refs(isField(f) ? f.type : f, out);
892
+ for (const v of d.type.variants ?? [])
893
+ for (const f of v.fields ?? [])
894
+ refs(isField(f) ? f.type : f, out);
895
+ refs(d.type.alias, out);
896
+ edges.set(d.name, out);
897
+ }
898
+ for (const start of edges.keys()) {
899
+ const seen = new Set();
900
+ const stack = [...edges.get(start)];
901
+ while (stack.length) {
902
+ const n = stack.pop();
903
+ if (n === start) {
904
+ recursive.add(start);
905
+ break;
906
+ }
907
+ if (seen.has(n))
908
+ continue;
909
+ seen.add(n);
910
+ stack.push(...(edges.get(n) ?? []));
911
+ }
912
+ }
913
+ }
798
914
  function codec(t) {
799
915
  if (typeof t === "string") {
916
+ // kit has no 256-bit codecs: 32 bytes, little-endian, as Borsh (and Anchor) write them.
917
+ if (INTS[t] === 256)
918
+ return ((needsWideInt = true), `wideInt(${t === "i256"})`);
800
919
  if (t in INTS || t in FLOATS) {
801
920
  const fn = `get${t.toUpperCase()}Codec`;
802
921
  use(fn);
@@ -821,6 +940,8 @@ function generate(idl, opts) {
821
940
  return (use("addCodecSizePrefix", "getBytesCodec", "getU32Codec"), "addCodecSizePrefix(getBytesCodec(), getU32Codec())");
822
941
  return (use("getArrayCodec"), `getArrayCodec(${codec(t.vec)})`);
823
942
  }
943
+ if (t.option !== undefined && nestedOption(t.option))
944
+ return (use("getNullableCodec", "getOptionCodec"), `getNullableCodec(getOptionCodec(${codec(t.option.option)}))`);
824
945
  if (t.option !== undefined)
825
946
  return (use("getNullableCodec"), `getNullableCodec(${codec(t.option)})`);
826
947
  if (t.coption !== undefined) {
@@ -850,6 +971,8 @@ function generate(idl, opts) {
850
971
  }
851
972
  if (s?.kind === "fenum")
852
973
  return (use("fixCodecSize"), `fixCodecSize(get${tsName(s.base)}Codec(), ${s.size})`);
974
+ if (recursive.has(n))
975
+ return ((needsLazy = true), `lazyCodec(() => get${tsName(n)}Codec())`);
853
976
  return `get${tsName(n)}Codec()`;
854
977
  }
855
978
  /** Byte size of a fixed-size IDL type (undefined when it varies). Memoized by type name, so shared types are sized once. */
@@ -1672,6 +1795,49 @@ function generate(idl, opts) {
1672
1795
  ` });`,
1673
1796
  ],
1674
1797
  });
1798
+ if (needsWideInt)
1799
+ helperDefs.push({
1800
+ name: "wideInt",
1801
+ lines: [
1802
+ `/** A u256 (or, signed, an i256): 32 bytes, little-endian, two's complement. */`,
1803
+ `const wideInt = (signed: boolean): Codec<number | bigint, bigint> =>`,
1804
+ ` createCodec<number | bigint, bigint>({`,
1805
+ ` fixedSize: 32,`,
1806
+ ` write: (value, bytes, offset) => {`,
1807
+ ` let v = BigInt(value);`,
1808
+ ` const [min, max] = signed ? [-(1n << 255n), (1n << 255n) - 1n] : [0n, (1n << 256n) - 1n];`,
1809
+ ` if (v < min || v > max) throw new RangeError(String(value) + " does not fit in " + (signed ? "i256" : "u256"));`,
1810
+ ` if (v < 0n) v += 1n << 256n;`,
1811
+ ` for (let i = 0; i < 32; i++, v >>= 8n) bytes[offset + i] = Number(v & 0xffn);`,
1812
+ ` return offset + 32;`,
1813
+ ` },`,
1814
+ ` read: (bytes, offset) => {`,
1815
+ ` let v = 0n;`,
1816
+ ` for (let i = 31; i >= 0; i--) v = (v << 8n) | BigInt(bytes[offset + i] ?? 0);`,
1817
+ ` return [signed && v >> 255n ? v - (1n << 256n) : v, offset + 32];`,
1818
+ ` },`,
1819
+ ` });`,
1820
+ ],
1821
+ });
1822
+ if (needsLazy)
1823
+ helperDefs.push({
1824
+ name: "lazyCodec",
1825
+ lines: [
1826
+ `/** A codec made on first use: a type that holds itself (through a Vec or an Option) refers to its own codec. */`,
1827
+ `const lazyCodec = <From, To extends From>(make: () => Codec<From, To>): Codec<From, To> => {`,
1828
+ ` let inner: Codec<From, To> | undefined;`,
1829
+ ` const get = () => (inner ??= make());`,
1830
+ ` return createCodec<From, To>({`,
1831
+ ` getSizeFromValue: (value) => {`,
1832
+ ` const c = get();`,
1833
+ ` return isFixedSize(c) ? c.fixedSize : c.getSizeFromValue(value);`,
1834
+ ` },`,
1835
+ ` write: (value, bytes, offset) => get().write(value, bytes, offset),`,
1836
+ ` read: (bytes, offset) => get().read(bytes, offset),`,
1837
+ ` });`,
1838
+ `};`,
1839
+ ],
1840
+ });
1675
1841
  if (needsUnitEnum)
1676
1842
  helperDefs.push({
1677
1843
  name: "unitEnum",
@@ -1,18 +1,3 @@
1
- /**
2
- * `typesol cpi <idl.json>`: TypeSOL helper functions that call another program's instructions,
3
- * generated from its Anchor IDL (spec 0.1.0, as written by Anchor 0.30+ and by TypeSOL itself).
4
- *
5
- * Each instruction becomes
6
- *
7
- * export function vaultDeposit(program: Program<"…">, vault: Mut<AccountMeta>, owner: AccountMeta,
8
- * amount: u64, seeds: SignerSeeds): void {
9
- * invoke(program, [writable(vault), readonlySigner(owner)], [hex("f223c689…"), amount], seeds);
10
- * }
11
- *
12
- * Call it with `signer([...])` for a PDA of the calling program that must sign, or `signer([])`.
13
- * Argument types without a Borsh-identical TypeSOL type (strings or Options inside structs, data-carrying
14
- * enums, nested Vecs, generics) are reported and the instruction is left out.
15
- */
16
1
  type IdlType = string | {
17
2
  vec?: IdlType;
18
3
  option?: IdlType;