@typesol/cli 0.31.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 +38 -0
- package/README.md +8 -7
- package/dist/cli.js +50 -5
- package/dist/compiler/analyze.js +14 -5
- package/dist/compiler/emit/base.d.ts +1 -0
- package/dist/compiler/emit/calls.d.ts +2 -0
- package/dist/compiler/emit/calls.js +93 -11
- package/dist/compiler/emit/cpi-core.d.ts +8 -0
- package/dist/compiler/emit/cpi-core.js +15 -0
- package/dist/compiler/emit/cpi.js +10 -4
- package/dist/compiler/emit/create.d.ts +2 -0
- package/dist/compiler/emit/create.js +56 -13
- package/dist/compiler/emit/expressions.js +6 -2
- package/dist/compiler/emit/statements.js +15 -0
- package/dist/compiler/emit/token.js +43 -0
- package/dist/templates.js +13 -36
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +64 -2
- package/dist/workspace.d.ts +16 -1
- package/dist/workspace.js +49 -5
- package/docs/audit.md +1 -1
- package/docs/case-study-escrow.md +3 -3
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-cp-swap.md +51 -21
- package/docs/cli.md +5 -3
- package/docs/errors.md +3 -1
- package/docs/language.md +12 -5
- package/docs/migrate-from-anchor.md +3 -0
- package/docs/test-your-program.md +12 -3
- package/docs/testing.md +1 -1
- package/lib/typesol.d.ts +28 -5
- package/package.json +1 -1
- package/runtime/typesol_rt.h +65 -7
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,44 @@ 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
|
+
|
|
9
47
|
## 0.31.0 — 2026-10-30
|
|
10
48
|
|
|
11
49
|
A second real program checked against its mainnet binary: Raydium CP-Swap's trading core, and the Token-2022 reads an
|
package/README.md
CHANGED
|
@@ -178,7 +178,7 @@ starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-
|
|
|
178
178
|
program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
|
|
179
179
|
checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units), and
|
|
180
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
|
-
(same outcomes, account bytes and events on
|
|
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
|
|
182
182
|
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
183
183
|
|
|
184
184
|
## How it works
|
|
@@ -208,7 +208,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
|
|
|
208
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 |
|
|
209
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 |
|
|
210
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 |
|
|
211
|
-
| **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`) |
|
|
212
212
|
| **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
|
|
213
213
|
| **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard |
|
|
214
214
|
| **Interfaces** | custom discriminators (`@discriminator`), so a TypeSOL program can be a Token-2022 transfer hook, with extra accounts (ExtraAccountMetaList) |
|
|
@@ -220,8 +220,9 @@ The full reference, with every type, check and built-in, is in [docs/language.md
|
|
|
220
220
|
| Command | What it does |
|
|
221
221
|
| --- | --- |
|
|
222
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 |
|
|
223
224
|
| `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
|
|
224
|
-
| `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) |
|
|
225
226
|
| `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
|
|
226
227
|
| `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
|
|
227
228
|
| `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
|
|
@@ -254,16 +255,16 @@ toolchain and records them with every result:
|
|
|
254
255
|
<!-- bench:table -->
|
|
255
256
|
| Instruction | TypeSOL | Pinocchio 0.10 | Native Rust | Anchor 1.0.2 |
|
|
256
257
|
| --- | ---: | ---: | ---: | ---: |
|
|
257
|
-
| counter.initialize | **1,
|
|
258
|
+
| counter.initialize | **1,857** | 3,186 | 4,601 | 6,573 |
|
|
258
259
|
| counter.increment | **110** | 113 | 857 | 2,323 |
|
|
259
|
-
| vault.open | **1,
|
|
260
|
+
| vault.open | **1,874** | 3,185 | 4,613 | 6,627 |
|
|
260
261
|
| vault.deposit | **1,314** | 1,377 | 2,832 | 4,355 |
|
|
261
262
|
| vault.withdraw | **315** | 370 | 1,176 | 3,628 |
|
|
262
263
|
| vault.shut | **161** | 167 | 950 | 2,024 |
|
|
263
|
-
| escrow.make | **3,
|
|
264
|
+
| escrow.make | **3,596** | 6,179 | 9,240 | 13,304 |
|
|
264
265
|
| escrow.take | **4,019** | 4,051 | 8,500 | 14,365 |
|
|
265
266
|
| escrow.refund | **2,696** | 2,769 | 5,695 | 8,449 |
|
|
266
|
-
| binary, counter / vault / escrow | 11.
|
|
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 |
|
|
267
268
|
<!-- /bench:table -->
|
|
268
269
|
|
|
269
270
|
`initialize`, `open` and `make` include the PDA bump search. TypeSOL hashes PDA candidates with the sha256 and
|
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);
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
-
|
|
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(${
|
|
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))
|
|
@@ -419,6 +429,43 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
419
429
|
this.line(`TS_TRY(ts_ata_address(${o.c}, ${m.c}, ${tp.c}, &${t}));`);
|
|
420
430
|
return { c: `(&${t})`, type: PUBKEY };
|
|
421
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
|
+
}
|
|
422
469
|
case "findProgramAddress": {
|
|
423
470
|
// Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
|
|
424
471
|
if (args.length !== 2)
|
|
@@ -592,6 +639,17 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
592
639
|
if (method !== "get")
|
|
593
640
|
this.fail(node, `arrays support get(i), set(i, v) and .length, not ${method}()`);
|
|
594
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
|
+
}
|
|
595
653
|
if (method === "equals") {
|
|
596
654
|
if (args.length !== 1)
|
|
597
655
|
this.fail(node, "equals() takes one argument");
|
|
@@ -622,6 +680,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
622
680
|
return this.systemTransfer(node);
|
|
623
681
|
if (target?.kind.kind === "system" && method === "createAccount")
|
|
624
682
|
return this.createAccount(node, target);
|
|
683
|
+
if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
|
|
684
|
+
return this.allocateOrAssign(node, target, method);
|
|
625
685
|
if (target?.kind.kind === "tokenProgram")
|
|
626
686
|
return this.tokenOp(node, target, method);
|
|
627
687
|
if (target?.kind.kind === "ataProgram")
|
|
@@ -642,7 +702,29 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
642
702
|
this.fail(callee.expression, "fixedArray<T, N>(fill) is only allowed as a local declaration: const xs = fixedArray<u64, 4>(0n)");
|
|
643
703
|
if (ts.isPropertyAccessExpression(callee) && callee.name.text === "slice" && this.isRemaining(callee.expression))
|
|
644
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)");
|
|
645
|
-
this.fail(node,
|
|
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}`;
|
|
646
728
|
}
|
|
647
729
|
vecMethod(node, method, v) {
|
|
648
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
|
|
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 (
|
|
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
|
|
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], ¶ms->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 (
|
|
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
|
}
|
|
@@ -458,8 +458,8 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
458
458
|
this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
|
|
459
459
|
if (this.created.has(target.name))
|
|
460
460
|
this.fail(node, `${target.name} is already created`);
|
|
461
|
-
if (node.arguments.length !== 1)
|
|
462
|
-
this.fail(node, `${call}(payer) takes the payer`);
|
|
461
|
+
if (node.arguments.length !== 1 && node.arguments.length !== 2)
|
|
462
|
+
this.fail(node, `${call}(payer, tokenProgram?) takes the payer and, with several token programs, the one to use`);
|
|
463
463
|
const payer = this.accountParam(node.arguments[0], "the payer");
|
|
464
464
|
if (payer.kind.kind !== "signer" || !payer.kind.mut)
|
|
465
465
|
this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
|
|
@@ -473,11 +473,22 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
473
473
|
};
|
|
474
474
|
const ataProgram = need("ataProgram", "an AssociatedTokenProgram");
|
|
475
475
|
const system = need("system", "a SystemProgram");
|
|
476
|
-
|
|
477
|
-
//
|
|
478
|
-
|
|
479
|
-
if (
|
|
480
|
-
this.
|
|
476
|
+
// The address is derived under the token program: the one passed (Anchor's associated_token::token_program), or the
|
|
477
|
+
// instruction's only one.
|
|
478
|
+
let tokenProgram;
|
|
479
|
+
if (node.arguments[1]) {
|
|
480
|
+
tokenProgram = this.accountParam(node.arguments[1], "the token program");
|
|
481
|
+
if (tokenProgram.kind.kind !== "tokenProgram")
|
|
482
|
+
this.fail(node.arguments[1], "pass a TokenProgram, Token2022Program or TokenInterface parameter");
|
|
483
|
+
if (tokenProgram.optional)
|
|
484
|
+
this.fail(node.arguments[1], `${call}(...) needs "${tokenProgram.name}": it cannot be optional`);
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
|
|
488
|
+
const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
|
|
489
|
+
if (tokenPrograms.length > 1)
|
|
490
|
+
this.fail(node, `${call}(...) needs to know the token program: pass it, ${call}(payer, ${tokenPrograms[0].name}) (found ${tokenPrograms.map((o) => o.name).join(", ")})`);
|
|
491
|
+
}
|
|
481
492
|
const { owner, mint } = target.constraints.ata;
|
|
482
493
|
const a = `a_${target.name}`;
|
|
483
494
|
const create = `TS_TRY(ts_ata_create(params, a_${ataProgram.name}, a_${payer.name}, ${a}, a_${owner}, a_${mint}, a_${system.name}, a_${tokenProgram.name}, false));`;
|
|
@@ -504,17 +515,26 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
504
515
|
return result;
|
|
505
516
|
}
|
|
506
517
|
systemTransfer(node) {
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
518
|
+
const a = node.arguments;
|
|
519
|
+
if (a.length !== 3 && a.length !== 4)
|
|
520
|
+
this.fail(node, "transfer(from, to, lamports, signerSeeds?)");
|
|
521
|
+
const [fromN, toN, amtN] = a;
|
|
510
522
|
const from = this.accountParam(fromN, "transfer's source");
|
|
511
|
-
if (from.kind.kind !== "signer" || !from.kind.mut)
|
|
512
|
-
this.fail(fromN, "the source must be a Mut<Signer>");
|
|
523
|
+
if (a.length === 3 && (from.kind.kind !== "signer" || !from.kind.mut))
|
|
524
|
+
this.fail(fromN, "the source must be a Mut<Signer>, or a Mut<AccountInfo> PDA of this program with signerSeeds");
|
|
525
|
+
if (a.length === 4 && !isWritable(from.kind))
|
|
526
|
+
this.fail(fromN, "the source must be writable (Mut<...>)");
|
|
513
527
|
const to = this.accountParam(toN, "transfer's destination");
|
|
514
528
|
if (!isWritable(to.kind))
|
|
515
529
|
this.fail(toN, "the destination must be writable (Mut<...>)");
|
|
516
530
|
const amt = this.expect(this.expr(amtN, U64), U64, amtN);
|
|
517
|
-
|
|
531
|
+
if (a.length === 3)
|
|
532
|
+
this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
|
|
533
|
+
else {
|
|
534
|
+
// A system-owned PDA of this program (a SOL vault) pays.
|
|
535
|
+
const s = this.signingSeeds(a[3]);
|
|
536
|
+
this.line(`TS_TRY(ts_system_transfer_signed(params, a_${from.name}, a_${to.name}, ${amt.c}, ${s.name}, ${s.count}));`);
|
|
537
|
+
}
|
|
518
538
|
return undefined;
|
|
519
539
|
}
|
|
520
540
|
/** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
|
|
@@ -545,4 +565,27 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
545
565
|
], buf, len, seeds);
|
|
546
566
|
return undefined;
|
|
547
567
|
}
|
|
568
|
+
/** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
|
|
569
|
+
allocateOrAssign(node, system, method) {
|
|
570
|
+
const a = node.arguments;
|
|
571
|
+
if (a.length !== 2 && a.length !== 3)
|
|
572
|
+
this.fail(node, `${method}(account, ${method === "allocate" ? "space" : "owner"}, signerSeeds?)`);
|
|
573
|
+
const acct = this.accountParam(a[0], "the account");
|
|
574
|
+
if (!isWritable(acct.kind))
|
|
575
|
+
this.fail(a[0], `the account must be writable (Mut<Signer> or Mut<AccountInfo>)`);
|
|
576
|
+
if (acct.kind.kind !== "signer" && a.length !== 3)
|
|
577
|
+
this.fail(a[0], "the account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
|
|
578
|
+
const { buf, len, put, finish } = this.byteBuffer("sys", 36, "TS_ERR_INSTRUCTION_DATA", "system instruction");
|
|
579
|
+
const tag = this.tmp("tag");
|
|
580
|
+
this.line(`uint32_t ${tag} = ${method === "allocate" ? 8 : 1}; /* ${method === "allocate" ? "Allocate" : "Assign"} */`);
|
|
581
|
+
put(`&${tag}`, "4", 4);
|
|
582
|
+
if (method === "allocate")
|
|
583
|
+
this.serialize(this.expect(this.expr(a[1], U64), U64, a[1]), a[1], put);
|
|
584
|
+
else
|
|
585
|
+
this.serialize(this.expect(this.expr(a[1], PUBKEY), PUBKEY, a[1]), a[1], put);
|
|
586
|
+
finish(node);
|
|
587
|
+
const seeds = a.length === 3 ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
|
|
588
|
+
this.cpi(`a_${system.name}`, [[`a_${acct.name}`, true, true]], buf, len, seeds);
|
|
589
|
+
return undefined;
|
|
590
|
+
}
|
|
548
591
|
}
|
|
@@ -874,14 +874,18 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
874
874
|
break;
|
|
875
875
|
case K.AsteriskToken:
|
|
876
876
|
// u64: skips the 128-bit __multi3 call when both factors fit in 32 bits (see ts_mul_overflow_u64).
|
|
877
|
-
|
|
877
|
+
// u128: the native 64-bit multiply when both factors fit in 64 bits (see ts_mul_overflow_u128).
|
|
878
|
+
this.line(`if (${type.name === "u64" ? "ts_mul_overflow_u64" : type.name === "u128" ? "ts_mul_overflow_u128" : "__builtin_mul_overflow"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
|
|
878
879
|
break;
|
|
879
880
|
case K.SlashToken:
|
|
880
881
|
case K.PercentToken: {
|
|
881
882
|
this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
|
|
882
883
|
if (INT_INFO[type.name].signed)
|
|
883
884
|
this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
|
|
884
|
-
|
|
885
|
+
if (type.name === "u128")
|
|
886
|
+
this.line(`${t} = ${op === K.SlashToken ? "ts_div_u128" : "ts_rem_u128"}(${left.c}, ${right.c});`);
|
|
887
|
+
else
|
|
888
|
+
this.line(`${t} = ${left.c} ${op === K.SlashToken ? "/" : "%"} ${right.c};`);
|
|
885
889
|
break;
|
|
886
890
|
}
|
|
887
891
|
case K.AmpersandToken:
|