@typesol/cli 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,58 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.32.0 — 2026-10-30
10
+
11
+ Anchor parity and usability: Raydium CP-Swap's pool creation and what creating accounts by hand needs, several PDAs
12
+ signing one CPI, PDA-signed SOL transfers, the checked token instructions, faster u128 arithmetic and Clock reads,
13
+ clearer errors, and tooling for fresh clones, multi-program projects and token tests.
14
+
15
+ - New: `systemProgram.allocate(account, space, seeds?)` / `assign(account, owner, seeds?)`, `programId()`,
16
+ `findProgramAddressBump(seeds, program)`, `initAccount<T>(account)` (Anchor's `load_init` on an account the body
17
+ created: 3007 / 3006 / 3003 / 3000), `Pubkey.compare(other)` (Rust's byte order), and `ata.create(payer,
18
+ tokenProgram)` / `createIfNeeded(payer, tokenProgram)` to pick among several token programs.
19
+ - Changed: an `Init` create on an address already in use now fails as Anchor's `init` does, with the System Program's
20
+ AccountAlreadyInUse (custom 0) instead of TypeSOL's 3000; a payer that is the account being created fails with 4101
21
+ (TryingToInitPayerAsProgramAccount). Programs creating accounts use 9–13 fewer compute units; binaries move by ±1%.
22
+ - Faster: u128 multiplication, division and remainder take the native 64-bit instructions when the values fit in 64
23
+ bits (most amounts and rates) instead of the 128-bit library routines; results are unchanged (the arithmetic fuzzer
24
+ now samples such values a third of the time).
25
+ - Faster: an instruction reads the Clock sysvar once, on its first `now()` / `currentSlot()` / `currentEpoch()`, and
26
+ reuses it (the Clock does not change within a transaction). With both, Raydium CP-Swap's swap drops from 7,478 to
27
+ 5,734 compute units.
28
+ - Changed: examples/raydium-cp-swap ports `initialize` too (10 of 24 instructions; 70 transactions against mainnet).
29
+ - New: several PDAs can sign one CPI: `invoke` / `invokeInstruction` take a list of seed lists (`[["vault", key, b1],
30
+ ["fees", b2]]`, at most 16). A seed list can be named once and reused: `const vault = signer([...])`.
31
+ - New: `systemProgram.transfer(from, to, lamports, signerSeeds)` pays out of a system-owned PDA of the program (a SOL
32
+ vault).
33
+ - New: `tokenProgram.mintToChecked`, `burnChecked` and `approveChecked`, which take the decimals from the mint.
34
+ - Better errors: `throw`, `try`/`catch`, optional and default parameters, `...rest` parameters and optional fields now
35
+ say what to write instead; "unsupported call" names the callee and, for common JavaScript calls (`console.log`,
36
+ `Math.min`, `BigInt`, …), the TypeSOL form.
37
+ - Tooling: a project without its program keypair (a fresh clone, CI) builds and tests at the address `typesol.json`
38
+ records; only `deploy` needs the keypair. New projects run `typesol build` before `npm test` and `npm run
39
+ typecheck`, which import the client it writes.
40
+ - Tooling: `typesol new <program>` adds a program and its test to a project; `typesol check` with no argument checks
41
+ every program of the project (or those named).
42
+ - Testing: `t.mint`, `t.tokenAccount` and `t.tokenBalance` write and read SPL Token / Token-2022 accounts in the VM,
43
+ `t.warp` moves the Clock, `t.errorName(code)` names an error, and a failed `t.ok` names the error. The escrow
44
+ template uses them (and no longer needs `@solana-program/token`).
45
+ - Docs: the docs in the npm package link to tests and examples on GitHub.
46
+
47
+ ## 0.31.0 — 2026-10-30
48
+
49
+ A second real program checked against its mainnet binary: Raydium CP-Swap's trading core, and the Token-2022 reads an
50
+ AMM needs. Programs that do not use the new reads compile to the same binaries as in 0.30.0.
51
+
52
+ - New: Token-2022 fee and extension reads: `transferFeeInverse(mint, amountReceived)` (spl-token-2022's
53
+ `calculate_inverse_epoch_fee`: what to send so the recipient gets that much), `transferFeeBasisPoints(mint)` and
54
+ `transferFeeMaximum(mint)` (this epoch's), and `extensionsWithin(account, [types…])` (accept only mints whose
55
+ extensions you handle).
56
+ - New: examples/raydium-cp-swap, Raydium CP-Swap's trading core (swaps both ways, deposit, withdraw, fee collection,
57
+ config and status admin; 9 of its 24 instructions), checked against the program deployed on mainnet on 59
58
+ transactions (creator fees, the price oracle's wrap and Token-2022 transfer fees included): same outcomes, account
59
+ bytes and events, 51–79% fewer compute units. docs/case-study-raydium-cp-swap.md.
60
+
9
61
  ## 0.30.0 — 2026-10-30
10
62
 
11
63
  Editor errors that follow you through a program, faster. The compiler's output is the same as 0.29.0 for every
package/README.md CHANGED
@@ -176,7 +176,9 @@ program's address.
176
176
  Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, `typesol port`
177
177
  starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one complete Anchor
178
178
  program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
179
- checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
179
+ checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
180
+ [docs/case-study-raydium-cp-swap.md](docs/case-study-raydium-cp-swap.md) does the same for Raydium CP-Swap's swaps and liquidity
181
+ (pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
180
182
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
181
183
 
182
184
  ## How it works
@@ -206,7 +208,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
206
208
  | **Constraints** | `HasOne`, `Seeds` (also from account fields and under another program; `pdaBump` like `ctx.bumps`), `CloseTo`, `Ata`, `Address`, `Owner`, `Executable`. They are checked before the body runs and recorded in the IDL |
207
209
  | **Data** | `u8`…`u128`, `i8`…`i128`, `boolean`, `Pubkey`, `Hash`, nested structs, `FixedArray`, `FixedString`, `Option`, unit enums, data enums (discriminated unions), `Vec` that resizes its account, `FixedVec` lists anywhere, and Anchor's own byte layout (`@layout borsh`) to take over existing Anchor accounts and to pass, return and emit structs with String / Vec / Option fields as Anchor does |
208
210
  | **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics), list callbacks (`some`, `find`, `reduce`, …) across multiple files |
209
- | **CPIs** | System, SPL Token, Token-2022 (including extension reads and metadata), ATA, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing, return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
211
+ | **CPIs** | System, SPL Token, Token-2022 (including extension reads and metadata), ATA, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
210
212
  | **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
211
213
  | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard |
212
214
  | **Interfaces** | custom discriminators (`@discriminator`), so a TypeSOL program can be a Token-2022 transfer hook, with extra accounts (ExtraAccountMetaList) |
@@ -218,8 +220,9 @@ The full reference, with every type, check and built-in, is in [docs/language.md
218
220
  | Command | What it does |
219
221
  | --- | --- |
220
222
  | `typesol init` | scaffold a project with a program, a LiteSVM test and TypeScript configs |
223
+ | `typesol new <program>` | add another program and its test to a project |
221
224
  | `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
222
- | `typesol check` | typecheck and subset-check without compiling |
225
+ | `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file) |
223
226
  | `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
224
227
  | `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
225
228
  | `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
@@ -252,16 +255,16 @@ toolchain and records them with every result:
252
255
  <!-- bench:table -->
253
256
  | Instruction | TypeSOL | Pinocchio 0.10 | Native Rust | Anchor 1.0.2 |
254
257
  | --- | ---: | ---: | ---: | ---: |
255
- | counter.initialize | **1,866** | 3,186 | 4,601 | 6,573 |
258
+ | counter.initialize | **1,857** | 3,186 | 4,601 | 6,573 |
256
259
  | counter.increment | **110** | 113 | 857 | 2,323 |
257
- | vault.open | **1,885** | 3,185 | 4,613 | 6,627 |
260
+ | vault.open | **1,874** | 3,185 | 4,613 | 6,627 |
258
261
  | vault.deposit | **1,314** | 1,377 | 2,832 | 4,355 |
259
262
  | vault.withdraw | **315** | 370 | 1,176 | 3,628 |
260
263
  | vault.shut | **161** | 167 | 950 | 2,024 |
261
- | escrow.make | **3,605** | 6,179 | 9,240 | 13,304 |
264
+ | escrow.make | **3,596** | 6,179 | 9,240 | 13,304 |
262
265
  | escrow.take | **4,019** | 4,051 | 8,500 | 14,365 |
263
266
  | escrow.refund | **2,696** | 2,769 | 5,695 | 8,449 |
264
- | binary, counter / vault / escrow | 11.0 / 14.1 / 21.3 KB | 19.6 / 22.9 / 29.4 KB | 27.9 / 35.0 / 46.5 KB | 145.2 / 158.9 / 190.7 KB |
267
+ | binary, counter / vault / escrow | 11.1 / 14.1 / 21.4 KB | 19.6 / 22.9 / 29.4 KB | 27.9 / 35.0 / 46.5 KB | 145.2 / 158.9 / 190.7 KB |
265
268
  <!-- /bench:table -->
266
269
 
267
270
  `initialize`, `open` and `make` include the PDA bump search. TypeSOL hashes PDA candidates with the sha256 and
@@ -324,6 +327,7 @@ Details are in [docs/testing.md](docs/testing.md).
324
327
  | [`relay.ts`](examples/relay.ts), [`caller.ts`](examples/caller.ts) | generic `invoke`, PDA-signed transfers, return data |
325
328
  | [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
326
329
  | [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
330
+ | [`raydium-cp-swap/`](examples/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
327
331
  | [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
328
332
 
329
333
  ## Status
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import { buildIdl } from "./compiler/idl.js";
13
13
  import { decodeAddress, loadOrCreateKeypair, readKeypair } from "./keys.js";
14
14
  import { formatProfile, profileLogs } from "./tools/profile.js";
15
15
  import { TEMPLATE_NAMES } from "./templates.js";
16
- import { buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold } from "./workspace.js";
16
+ import { addProgram, buildWorkspace, CONFIG, deployArgs, findWorkspace, programAddress, programForEntry, programPaths, scaffold, } from "./workspace.js";
17
17
  import { clusterUrl, deployPreflight, doctorChecks, formatChecks, INSTALL_AGAVE, solanaConfig as readSolanaConfig, toolchainCheck } from "./tools/doctor.js";
18
18
  const ASSETS = fileURLToPath(new URL("../assets/", import.meta.url));
19
19
  /** A usage problem: printed with the command's help, exit code 2. */
@@ -40,6 +40,29 @@ function banner() {
40
40
  }
41
41
  const SBPF = `--sbpf v0|v1|v2 SBPF version (default v0, or "sbpf" in ${CONFIG}); v1/v2 need clusters that enabled them`;
42
42
  const COMMANDS = {
43
+ new: {
44
+ usage: "typesol new <program> [--template counter|vault|escrow]",
45
+ help: [
46
+ "Add a program to this project: programs/<program>.ts, tests/<program>.test.ts and its entry in typesol.json.",
47
+ "Refuses to overwrite files. <program> must be snake_case. Templates as for `typesol init`.",
48
+ ].join("\n "),
49
+ options: { template: { type: "string" } },
50
+ run(v, args) {
51
+ const name = one(args, "<program>");
52
+ if (!/^[a-z][a-z0-9_]*$/.test(name))
53
+ throw new UsageError(`"${name}" must be snake_case (a-z, 0-9, _; starting with a letter)`);
54
+ const template = v.template ?? "counter";
55
+ if (!TEMPLATE_NAMES.includes(template))
56
+ throw new UsageError(`--template "${template}" is not one of ${TEMPLATE_NAMES.join(", ")}`);
57
+ const ws = needWorkspace("new");
58
+ const { files, missing } = addProgram(ws, name, template);
59
+ for (const f of files)
60
+ log(` ${f === CONFIG ? "updated" : "created"} ${path.relative(process.cwd(), path.join(ws.root, f)) || f}`);
61
+ if (missing.length)
62
+ log(`\n The ${template} test also needs: npm install -D ${missing.join(" ")}`);
63
+ return 0;
64
+ },
65
+ },
43
66
  init: {
44
67
  usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
45
68
  help: [
@@ -103,7 +126,7 @@ const COMMANDS = {
103
126
  if (!v.quiet && process.stdout.isTTY)
104
127
  log(banner());
105
128
  for (const b of buildWorkspace(ws, inProject ? [inProject] : names(ws, args), { sbpf, profile }))
106
- log(` ${b.paths.name.padEnd(12)} ${b.address}${b.created ? " (new keypair)" : ""} ${path.relative(process.cwd(), b.result.soPath)}`);
129
+ log(` ${b.paths.name.padEnd(12)} ${b.address}${b.created ? " (new keypair)" : b.keyless ? " (no keypair here: deploying needs it)" : ""} ${path.relative(process.cwd(), b.result.soPath)}`);
107
130
  return 0;
108
131
  }
109
132
  if (!file)
@@ -131,15 +154,37 @@ const COMMANDS = {
131
154
  },
132
155
  },
133
156
  check: {
134
- usage: "typesol check <program.ts> [--json] [--stdin | --files]",
157
+ usage: "typesol check [<program.ts> | <program>…] [--json] [--stdin | --files]",
135
158
  help: [
136
- "Typecheck and validate the TypeSOL subset without building.",
159
+ "Typecheck and validate the TypeSOL subset without building. In a project, no argument checks every program.",
137
160
  "--json print { ok, diagnostics: [{ file, line, column, message }] } (exit 1 when there are diagnostics)",
138
161
  "--stdin read <program.ts>'s text from stdin instead of the file (an editor's unsaved buffer); its imports are read from disk",
139
162
  '--files read { "files": { "<absolute path>": "<text>", … } } from stdin: those files\' texts instead of the disk (unsaved buffers)',
140
163
  ].join("\n "),
141
164
  options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
142
165
  run(v, args) {
166
+ // In a project: the named programs, or all of them.
167
+ const ws = !v.stdin && !v.files && !args.some((a) => a.endsWith(".ts")) ? findWorkspace(process.cwd()) : undefined;
168
+ if (ws) {
169
+ const diagnostics = [];
170
+ for (const name of names(ws, args)) {
171
+ try {
172
+ const { model } = generate(programPaths(ws, name).entry);
173
+ if (!v.json)
174
+ log(`ok ${name}: ${model.instructions.length} instruction(s), ${model.accountStructs.size} account type(s), ${model.events.size} event(s)`);
175
+ }
176
+ catch (e) {
177
+ if (!(e instanceof CompileError))
178
+ throw e;
179
+ diagnostics.push(...e.diagnostics);
180
+ if (!v.json)
181
+ console.error(`${name}:\n${e.message}`);
182
+ }
183
+ }
184
+ if (v.json)
185
+ log(JSON.stringify({ ok: !diagnostics.length, diagnostics }));
186
+ return diagnostics.length ? 1 : 0;
187
+ }
143
188
  const file = path.resolve(one(args, "<program.ts>"));
144
189
  let files;
145
190
  if (v.stdin)
@@ -203,7 +248,7 @@ const COMMANDS = {
203
248
  options: { url: { type: "string" }, keypair: { type: "string" }, config: { type: "string" }, "dry-run": { type: "boolean" }, sbpf: { type: "string" } },
204
249
  async run(v, args) {
205
250
  const ws = needWorkspace("deploy");
206
- const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v) });
251
+ const built = buildWorkspace(ws, names(ws, args), { sbpf: sbpfOf(v), needKeypair: true });
207
252
  if (!v["dry-run"]) {
208
253
  // Before any transaction: the RPC answers and the payer can afford it, with what to do if not.
209
254
  const cfg = solanaConfig(v.config);
@@ -25,6 +25,17 @@ const C_RESERVED = new Set([
25
25
  ..."auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while bool true false asm typeof".split(" "),
26
26
  ..."NULL SUCCESS HEAP_LENGTH HEAP_START_ADDRESS MAX_PERMITTED_DATA_INCREASE MAX_RETURN_DATA MAX_SEED_LENGTH_EXCEEDED INVALID_SEEDS SIZE_PUBKEY memcpy memset strlen static_assert offsetof sol_log_64".split(" "),
27
27
  ]);
28
+ /** A parameter is a plain name with an explicit type; say what to write instead of the rest. */
29
+ function paramShape(p, reporter) {
30
+ if (p.questionToken)
31
+ reporter.fail(p, `optional parameters are not supported; use ${p.name.getText()}: Option<T> and pass null for none`);
32
+ if (p.initializer)
33
+ reporter.fail(p, "default values are not supported; the client passes every argument");
34
+ if (p.dotDotDotToken)
35
+ reporter.fail(p, "...rest parameters are not supported; take a Vec<T> argument, or remainingAccounts() for accounts");
36
+ if (!ts.isIdentifier(p.name) || !p.type)
37
+ reporter.fail(p, "parameters need a plain name and an explicit type");
38
+ }
28
39
  /** Why a name cannot be used as a C member, or undefined when it can. */
29
40
  export function cNameProblem(name) {
30
41
  if (name.includes("__") || name.startsWith("_"))
@@ -997,7 +1008,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
997
1008
  if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
998
1009
  reporter.fail(m, "structs may only contain plain fields");
999
1010
  if (m.questionToken)
1000
- reporter.fail(m, "optional fields are not supported");
1011
+ reporter.fail(m, `optional fields are not supported; use ${m.name.getText()}: Option<T> (null for none)`);
1001
1012
  const name = m.name.text;
1002
1013
  if (RESERVED_FIELDS.has(name))
1003
1014
  reporter.fail(m.name, `"${name}" is reserved; pick another field name`);
@@ -1374,8 +1385,7 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1374
1385
  const params = fn.parameters
1375
1386
  .filter((_, i) => !skip.has(i))
1376
1387
  .map((p) => {
1377
- if (!ts.isIdentifier(p.name) || !p.type || p.initializer || p.questionToken || p.dotDotDotToken)
1378
- reporter.fail(p, "parameters need a plain name and an explicit type");
1388
+ paramShape(p, reporter);
1379
1389
  // `p_<name>__n` carries a SignerSeeds count: "__" in a name could collide with it.
1380
1390
  if (p.name.text.includes("__") || p.name.text.includes("$"))
1381
1391
  reporter.error(p.name, `"${p.name.text}": "__" and "$" are reserved in names`);
@@ -1487,8 +1497,7 @@ function analyzeInstruction(fn, reporter, scope, structs) {
1487
1497
  let minArgsSize = 0;
1488
1498
  for (const p of fn.parameters) {
1489
1499
  reporter.guard(() => {
1490
- if (!ts.isIdentifier(p.name) || !p.type || p.initializer || p.questionToken || p.dotDotDotToken)
1491
- reporter.fail(p, "parameters need a plain name and an explicit type");
1500
+ paramShape(p, reporter);
1492
1501
  const value = resolveValueType(p.type, scope, true) ?? resolveArgAggregate(p.type, scope, structs);
1493
1502
  if (value) {
1494
1503
  args.push({ name: p.name.text, type: value, node: p });
@@ -125,6 +125,7 @@ export declare abstract class EmitterBase {
125
125
  protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
126
126
  protected abstract systemTransfer(node: ts.CallExpression): undefined;
127
127
  protected abstract createAccount(node: ts.CallExpression, system: AccountParam): undefined;
128
+ protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
128
129
  protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
129
130
  protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
130
131
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
@@ -4,6 +4,8 @@ import { type Value, type Ref, type Closure } from "./shared.js";
4
4
  import { ExpressionEmitter } from "./expressions.js";
5
5
  export declare abstract class CallEmitter extends ExpressionEmitter {
6
6
  protected call(node: ts.CallExpression, topLevel: boolean): Value | undefined;
7
+ /** "unsupported call" naming the callee, with the TypeSOL form of common JavaScript calls. */
8
+ private unsupportedCall;
7
9
  protected vecMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
8
10
  /** sha256(...) / keccak256(...) over strings, Pubkeys, Hashes, integers (LE) and booleans. */
9
11
  protected hashCall(node: ts.CallExpression, fn: "sha256" | "keccak256"): Value;
@@ -107,22 +107,32 @@ export class CallEmitter extends ExpressionEmitter {
107
107
  return { c: t, type: U64 };
108
108
  }
109
109
  case "currentSlot":
110
- case "currentEpoch": {
110
+ case "currentEpoch":
111
+ case "now": {
111
112
  if (args.length !== 0)
112
113
  this.fail(node, `${builtin}() takes no arguments`);
114
+ // Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp }
115
+ const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : 4;
113
116
  const t = this.tmp();
117
+ if (this.ix) {
118
+ // The Clock does not change within a transaction: an instruction reads it once, on first use.
119
+ if (!this.hoisted.some((l) => l.includes("ts_clk_ok")))
120
+ this.hoisted.push(` uint64_t ts_clk[5]; bool ts_clk_ok = false;`);
121
+ this.line(`if (!ts_clk_ok) { TS_TRY(ts_read_clock(ts_clk)); ts_clk_ok = true; }`);
122
+ if (builtin === "now")
123
+ return { c: `((int64_t)ts_clk[4])`, type: I64 };
124
+ this.line(`uint64_t ${t} = ts_clk[${field}];`);
125
+ return { c: t, type: U64 };
126
+ }
127
+ if (builtin === "now") {
128
+ this.line(`int64_t ${t};`);
129
+ this.line(`TS_TRY(ts_now(&${t}));`);
130
+ return { c: t, type: I64 };
131
+ }
114
132
  this.line(`uint64_t ${t};`);
115
- this.line(`TS_TRY(ts_clock_u64(${builtin === "currentSlot" ? 0 : 2}, &${t}));`);
133
+ this.line(`TS_TRY(ts_clock_u64(${field}, &${t}));`);
116
134
  return { c: t, type: U64 };
117
135
  }
118
- case "now": {
119
- if (args.length !== 0)
120
- this.fail(node, "now() takes no arguments");
121
- const t = this.tmp();
122
- this.line(`int64_t ${t};`);
123
- this.line(`TS_TRY(ts_now(&${t}));`);
124
- return { c: t, type: I64 };
125
- }
126
136
  case "pubkey": {
127
137
  const lit = args[0];
128
138
  if (args.length !== 1 || !ts.isStringLiteral(lit))
@@ -241,6 +251,38 @@ export class CallEmitter extends ExpressionEmitter {
241
251
  this.line(`TS_TRY(ts_t22_transfer_fee(${m}, ${amt.c}, &${t}));`);
242
252
  return { c: t, type: U64 };
243
253
  }
254
+ case "transferFeeInverse": {
255
+ if (args.length !== 2)
256
+ this.fail(node, "transferFeeInverse(mint, amountReceived) takes the mint and the amount the recipient is to get");
257
+ const m = this.anyAccount(args[0], "the mint");
258
+ this.line(`TS_TRY(ts_t22_layout(${m}, 1));`);
259
+ const amt = this.expect(this.expr(args[1], U64), U64, args[1]);
260
+ const t = this.tmp("fee");
261
+ this.line(`uint64_t ${t};`);
262
+ this.line(`TS_TRY(ts_t22_transfer_fee_inverse(${m}, ${amt.c}, &${t}));`);
263
+ return { c: t, type: U64 };
264
+ }
265
+ case "transferFeeBasisPoints":
266
+ case "transferFeeMaximum": {
267
+ if (args.length !== 1)
268
+ this.fail(node, `${builtin}(mint) takes the mint`);
269
+ const m = this.anyAccount(args[0], "the mint");
270
+ this.line(`TS_TRY(ts_t22_layout(${m}, 1));`);
271
+ const t = this.tmp("tf");
272
+ this.line(`uint64_t ${t}b, ${t}m;`);
273
+ this.line(`TS_TRY(ts_t22_epoch_fee(${m}, &${t}b, &${t}m));`);
274
+ return builtin === "transferFeeBasisPoints" ? { c: `((uint16_t)${t}b)`, type: { kind: "int", name: "u16" } } : { c: `${t}m`, type: U64 };
275
+ }
276
+ case "extensionsWithin": {
277
+ if (args.length !== 2 || !ts.isArrayLiteralExpression(args[1]))
278
+ this.fail(node, "extensionsWithin(account, [types…]) takes a Token-2022 mint or account and a list of u16 extension types");
279
+ const m = this.anyAccount(args[0], "the account");
280
+ this.line(`TS_TRY(ts_t22_layout(${m}, 0));`);
281
+ const types = args[1].elements.map((e) => this.expect(this.expr(e, { kind: "int", name: "u16" }), { kind: "int", name: "u16" }, e).c);
282
+ const t = this.tmp("ext");
283
+ this.line(`const uint16_t ${t}[${Math.max(types.length, 1)}] = {${types.join(", ")}};`);
284
+ return { c: `ts_t22_extensions_within(${m}, ${t}, ${types.length})`, type: BOOL };
285
+ }
244
286
  case "isTransferring": {
245
287
  // TransferHookAccount (15) on a Token-2022 token account: set only while Token-2022 runs a transfer of it.
246
288
  if (args.length !== 1)
@@ -387,6 +429,43 @@ export class CallEmitter extends ExpressionEmitter {
387
429
  this.line(`TS_TRY(ts_ata_address(${o.c}, ${m.c}, ${tp.c}, &${t}));`);
388
430
  return { c: `(&${t})`, type: PUBKEY };
389
431
  }
432
+ case "programId":
433
+ if (args.length !== 0)
434
+ this.fail(node, "programId() takes no arguments");
435
+ return { c: `params->program_id`, type: PUBKEY };
436
+ case "findProgramAddressBump": {
437
+ // Pubkey::find_program_address(seeds, program).1: the bump of the canonical PDA.
438
+ if (args.length !== 2)
439
+ this.fail(node, "findProgramAddressBump(seeds, program) takes the seeds and the program's address");
440
+ const seeds = this.seeds(args[0], 0);
441
+ const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
442
+ const t = this.tmp("pda");
443
+ const b = this.tmp("bump");
444
+ this.line(`SolPubkey ${t}; uint8_t ${b};`);
445
+ this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
446
+ return { c: `((uint64_t)${b})`, type: { kind: "int", name: "u8" } };
447
+ }
448
+ case "initAccount": {
449
+ // Anchor's AccountLoader::load_init on an account created in the body (system createAccount / allocate +
450
+ // assign): owned by this program (3007), writable (3006), large enough (3003), discriminator still zero
451
+ // (3000); then the discriminator is written and the struct is a mutable view of the data.
452
+ const targ = node.typeArguments?.[0];
453
+ const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
454
+ if (!s || s.size === undefined || s.vec || s.layout === "borsh")
455
+ this.fail(node, "initAccount<T>(account) takes a fixed-layout account struct of this program (no growable Vec, not @layout borsh)");
456
+ if (args.length !== 1)
457
+ this.fail(node, "initAccount<T>(account) takes one account");
458
+ let h = this.handle(args[0]);
459
+ if (!h) {
460
+ const acct = this.accountParam(args[0], "the account");
461
+ if (acct.kind.kind !== "info")
462
+ this.fail(args[0], "initAccount<T>(account) takes a Mut<AccountInfo> parameter or a remaining account");
463
+ h = `a_${acct.name}`;
464
+ }
465
+ this.model.accountStructs.add(s.name);
466
+ this.line(`TS_TRY(ts_init_account(${h}, params->program_id, TS_DISC_${s.name}, sizeof(TSS_${s.name})));`);
467
+ return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: true } };
468
+ }
390
469
  case "findProgramAddress": {
391
470
  // Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
392
471
  if (args.length !== 2)
@@ -560,6 +639,17 @@ export class CallEmitter extends ExpressionEmitter {
560
639
  if (method !== "get")
561
640
  this.fail(node, `arrays support get(i), set(i, v) and .length, not ${method}()`);
562
641
  }
642
+ if (method === "compare") {
643
+ // Pubkey.compare: Rust's Ord on [u8; 32] (lexicographic bytes), as -1, 0 or 1.
644
+ if (args.length !== 1)
645
+ this.fail(node, "compare() takes one argument");
646
+ const left = this.expr(callee.expression);
647
+ if (left.type.kind !== "pubkey")
648
+ this.fail(callee.expression, "compare() orders Pubkeys or Hashes");
649
+ const mark = this.lines.length;
650
+ const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
651
+ return { c: `ts_key_cmp(${this.settle(left, mark).c}, ${right.c})`, type: { kind: "int", name: "i64" } };
652
+ }
563
653
  if (method === "equals") {
564
654
  if (args.length !== 1)
565
655
  this.fail(node, "equals() takes one argument");
@@ -590,6 +680,8 @@ export class CallEmitter extends ExpressionEmitter {
590
680
  return this.systemTransfer(node);
591
681
  if (target?.kind.kind === "system" && method === "createAccount")
592
682
  return this.createAccount(node, target);
683
+ if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
684
+ return this.allocateOrAssign(node, target, method);
593
685
  if (target?.kind.kind === "tokenProgram")
594
686
  return this.tokenOp(node, target, method);
595
687
  if (target?.kind.kind === "ataProgram")
@@ -610,7 +702,29 @@ export class CallEmitter extends ExpressionEmitter {
610
702
  this.fail(callee.expression, "fixedArray<T, N>(fill) is only allowed as a local declaration: const xs = fixedArray<u64, 4>(0n)");
611
703
  if (ts.isPropertyAccessExpression(callee) && callee.name.text === "slice" && this.isRemaining(callee.expression))
612
704
  this.fail(node, "rest.slice(a, b) is only for spreading into a CPI's accounts: invoke(p, [..., ...readonly(rest.slice(a, b))], data)");
613
- this.fail(node, "unsupported call");
705
+ this.fail(node, this.unsupportedCall(callee));
706
+ }
707
+ /** "unsupported call" naming the callee, with the TypeSOL form of common JavaScript calls. */
708
+ unsupportedCall(callee) {
709
+ const text = callee.getText();
710
+ const hints = {
711
+ "console.log": "log(…)",
712
+ "Math.min": "min(a, b)",
713
+ "Math.max": "max(a, b)",
714
+ "Date.now": "now() (the Clock's unix timestamp)",
715
+ "JSON.stringify": "log(…) with the values",
716
+ Number: "u64(x) or another integer cast",
717
+ BigInt: "u64(x) or another integer cast",
718
+ String: "a FixedString<N> field, or log(…)",
719
+ };
720
+ const hint = hints[text];
721
+ if (hint)
722
+ return `unsupported call: ${text}; use ${hint}`;
723
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
724
+ if (this.accounts.get(callee.expression.text))
725
+ return `unsupported call: the account ${callee.expression.text} has no method ${callee.name.text}`;
726
+ }
727
+ return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
614
728
  }
615
729
  vecMethod(node, method, v) {
616
730
  const args = node.arguments;
@@ -36,6 +36,14 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
36
36
  name: string;
37
37
  count: number | string;
38
38
  };
39
+ /**
40
+ * Several PDAs signing one CPI: `[["vault", owner.key, vaultBump], ["fees", feeBump]]` (or SignerSeeds parameters
41
+ * in the list). Undefined for a single seed list, which keeps the one-signer code.
42
+ */
43
+ protected signerSets(node: ts.Expression): {
44
+ ptr: string;
45
+ count: number;
46
+ } | undefined;
39
47
  /** Object literal properties by name, refusing others. */
40
48
  protected literalProps(o: ts.ObjectLiteralExpression, allowed: string[], what: string): Map<string, ts.Expression>;
41
49
  /** `acct.key` of an account parameter, as an expression to serialize. */
@@ -166,6 +166,21 @@ export class CpiCoreEmitter extends CallEmitter {
166
166
  }
167
167
  return this.seeds(node, 0);
168
168
  }
169
+ /**
170
+ * Several PDAs signing one CPI: `[["vault", owner.key, vaultBump], ["fees", feeBump]]` (or SignerSeeds parameters
171
+ * in the list). Undefined for a single seed list, which keeps the one-signer code.
172
+ */
173
+ signerSets(node) {
174
+ const isSet = (e) => ts.isArrayLiteralExpression(e) || (ts.isIdentifier(e) && this.lookup(e.text)?.type.kind === "signerSeeds");
175
+ if (!ts.isArrayLiteralExpression(node) || node.elements.length === 0 || !node.elements.every(isSet))
176
+ return undefined;
177
+ if (node.elements.length > 16)
178
+ this.fail(node, "at most 16 PDAs can sign one CPI");
179
+ const sets = node.elements.map((e) => this.signingSeeds(e));
180
+ const arr = this.tmp("signers");
181
+ this.line(`SolSignerSeeds ${arr}[${sets.length}] = {${sets.map((s) => `{${s.name}, ${s.count}}`).join(", ")}};`);
182
+ return { ptr: arr, count: sets.length };
183
+ }
169
184
  /** Object literal properties by name, refusing others. */
170
185
  literalProps(o, allowed, what) {
171
186
  const props = new Map();
@@ -133,7 +133,8 @@ export class CpiEmitter extends MetaplexEmitter {
133
133
  this.serialize(this.expr(el), el, put);
134
134
  }
135
135
  finish(a[2]);
136
- const seeds = hasSeeds ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
136
+ const multi = hasSeeds ? this.signerSets(a[3]) : undefined;
137
+ const seeds = hasSeeds && !multi ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
137
138
  const metasName = this.tmp("metas");
138
139
  let count = String(metas.length);
139
140
  if (parts.some((p) => p.kind === "spread")) {
@@ -167,7 +168,9 @@ export class CpiEmitter extends MetaplexEmitter {
167
168
  this.line(`SolAccountMeta ${metasName}[${Math.max(metas.length, 1)}] = {${metas.join(", ")}};`);
168
169
  const ixName = this.tmp("cpi");
169
170
  this.line(`SolInstruction ${ixName} = {${programKey}, ${metasName}, ${count}, ${buf}, ${len}};`);
170
- if (hasSeeds) {
171
+ if (multi)
172
+ this.line(`TS_TRY(ts_invoke(params, &${ixName}, ${multi.ptr}, ${multi.count}));`);
173
+ else if (hasSeeds) {
171
174
  const signer = this.tmp("signer");
172
175
  this.line(`SolSignerSeeds ${signer} = {${seeds.name}, ${seeds.count}};`);
173
176
  // No seeds (e.g. signer([]) passed to a helper) means no PDA signature at all.
@@ -213,7 +216,8 @@ export class CpiEmitter extends MetaplexEmitter {
213
216
  if (data.elem.kind !== "int" || data.elem.name !== "u8")
214
217
  this.fail(a[2], "the data is a list of u8");
215
218
  const range = this.remainingRange(a[3]) ?? this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b)");
216
- const seeds = a.length === 5 ? this.signingSeeds(a[4]) : undefined;
219
+ const multi = a.length === 5 ? this.signerSets(a[4]) : undefined;
220
+ const seeds = a.length === 5 && !multi ? this.signingSeeds(a[4]) : undefined;
217
221
  const n = this.tmp("dn");
218
222
  const m = this.tmp("dmetas");
219
223
  const i = this.tmp("di");
@@ -232,7 +236,9 @@ export class CpiEmitter extends MetaplexEmitter {
232
236
  this.line(`for (uint64_t ${i}b = ${base} + ${range.from}; ${i}b < ${base} + ${range.to}; ${i}b++) ts_info(params->ka[${i}b], &params->infos[${k}++]);`);
233
237
  const ixName = this.tmp("cpi");
234
238
  this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
235
- if (seeds) {
239
+ if (multi)
240
+ this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, ${multi.ptr}, ${multi.count}));`);
241
+ else if (seeds) {
236
242
  const signer = this.tmp("signer");
237
243
  this.line(`SolSignerSeeds ${signer} = {${seeds.name}, ${seeds.count}};`);
238
244
  this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, &${signer}, ${typeof seeds.count === "number" ? (seeds.count > 0 ? 1 : 0) : `${seeds.count} > 0 ? 1 : 0`}));`);
@@ -36,4 +36,6 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
36
36
  protected systemTransfer(node: ts.CallExpression): undefined;
37
37
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
38
38
  protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
39
+ /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
40
+ protected allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
39
41
  }