@typesol/cli 0.36.0 → 0.38.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 +53 -0
- package/README.md +8 -1
- package/dist/compiler/analyze.d.ts +6 -0
- package/dist/compiler/analyze.js +47 -8
- package/dist/compiler/emit/calls.js +40 -6
- package/dist/compiler/emit/cpi-core.js +24 -2
- package/dist/compiler/emit/expressions.d.ts +2 -0
- package/dist/compiler/emit/expressions.js +90 -1
- package/dist/compiler/emit/function.js +31 -7
- package/dist/compiler/emit/program.js +1 -1
- package/dist/compiler/emit/shared.d.ts +6 -0
- package/dist/compiler/emit/shared.js +4 -0
- package/dist/compiler/emit/statements.js +27 -1
- package/dist/compiler/emit/token.js +8 -5
- package/dist/compiler/idl.d.ts +1 -1
- package/dist/compiler/idl.js +7 -3
- package/dist/compiler/model.d.ts +1 -1
- package/dist/compiler/model.js +3 -1
- package/docs/case-study-jito-mev.md +167 -0
- package/docs/case-study-raydium-clmm.md +215 -0
- package/docs/errors.md +3 -0
- package/docs/language.md +10 -6
- package/docs/migrate-from-anchor.md +1 -1
- package/lib/typesol.d.ts +25 -7
- package/package.json +1 -1
- package/runtime/typesol_rt.h +225 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,59 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.38.0 — 2026-11-01
|
|
10
|
+
|
|
11
|
+
Raydium CLMM ported in full, and Jito's three MEV programs ported, each checked against its mainnet binary. The
|
|
12
|
+
compiler gained what the Jito programs needed: stored bumps in nested struct fields, Anchor's names for arguments
|
|
13
|
+
that share an account's name, and error members without messages. Programs that use none of these compile to the
|
|
14
|
+
same binaries as in 0.37.0.
|
|
15
|
+
|
|
16
|
+
- Examples: examples/raydium-clmm now ports all 37 of Raydium CLMM's instructions. Added: the customizable pools,
|
|
17
|
+
the v1 and v2 positions with Metaplex NFTs, `close_position`, `swap` and the multi-hop `swap_router_base_in`, the
|
|
18
|
+
five limit order instructions, the reward instructions, and the admin instructions (configs, operators, dynamic fee
|
|
19
|
+
configs, support mints, pool status, `collect_excess_lamports`). The differential test runs the admin instructions
|
|
20
|
+
too, with Raydium's admin key swapped for a test key in both programs: 300 transactions, the same outcomes, account
|
|
21
|
+
bytes and events, 33–84% fewer compute units.
|
|
22
|
+
- Examples: examples/jito-mev, ports of Jito's three MEV programs (tip payment, tip distribution, priority fee
|
|
23
|
+
distribution; all 24 instructions), checked against the mainnet binaries (test/programs/jito_*.so) on 150
|
|
24
|
+
transactions: the same outcomes, account bytes, events and log lines, with 58–95% fewer compute units. The tip
|
|
25
|
+
payment port follows the binary on mainnet, which is the program of Jito's #143 (no `claim_tips`). See
|
|
26
|
+
docs/case-study-jito-mev.md.
|
|
27
|
+
- New: a `Seeds<…>` bump stored in a struct field of another account, `"@config.bumps.vault"` (Anchor's
|
|
28
|
+
`bump = config.bumps.vault`).
|
|
29
|
+
- New: an error enum member with an empty message, `X = ""`, has no `msg` in the IDL (an Anchor variant without
|
|
30
|
+
`#[msg]`).
|
|
31
|
+
- IDL: an instruction argument named like one of its accounts plus a trailing underscore (`authority_` next to an
|
|
32
|
+
`authority` account) keeps the account's name in the IDL, as Anchor names such an argument.
|
|
33
|
+
- Typings: `Hash.compare(other)`, the byte order of two hashes (-1, 0 or 1), which the compiler already supported.
|
|
34
|
+
|
|
35
|
+
## 0.37.0 — 2026-10-31
|
|
36
|
+
|
|
37
|
+
Raydium CLMM ported and checked against the mainnet binary, with what it needed: `u256`, big-endian seeds,
|
|
38
|
+
accounts loaded in the body and seed lists picked at run time. Programs that use none of these compile to the same
|
|
39
|
+
binaries as in 0.36.0.
|
|
40
|
+
|
|
41
|
+
- Examples: examples/raydium-clmm, a port of Raydium CLMM's pools, positions and swaps: `create_amm_config`,
|
|
42
|
+
`create_pool`, `open_position_with_token22_nft`, `increase_liquidity_v2`, `decrease_liquidity_v2`, `swap_v2`,
|
|
43
|
+
`collect_protocol_fee` and `collect_fund_fee`, with its math in u256 and u128 and its account layouts byte for byte.
|
|
44
|
+
Swaps work on any pool the original runs (dynamic fees, limit orders filled at a tick, fee modes, rewards, the
|
|
45
|
+
tick array bitmap extension, Token-2022 transfer fees). Checked against the mainnet binary
|
|
46
|
+
(test/programs/raydium_clmm.so) on 166 transactions, including a pool cloned from mainnet: the same outcomes,
|
|
47
|
+
account bytes and events, with 43–83% fewer compute units. See docs/case-study-raydium-clmm.md.
|
|
48
|
+
- New: big-endian integer seeds, Rust's `to_be_bytes()`: `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in a seed
|
|
49
|
+
list. The IDL records the argument, as Anchor's does.
|
|
50
|
+
- New: `loadAccount<T>` / `loadAccountMut<T>` take an `AccountInfo` parameter too (Anchor's `AccountLoader::try_from` on
|
|
51
|
+
an `UncheckedAccount`, for accounts an instruction may create first); a second `loadAccountMut` of one parameter is
|
|
52
|
+
refused (2040), two `Dup<…>` parameters that are one account may each be loaded. A loaded struct is also its account
|
|
53
|
+
(`.key`, `.lamports`) and passes to helpers taking `Account<T>` / `Mut<T>`.
|
|
54
|
+
- New: one of two seed lists picked at run time, `const s = cond ? signer([…]) : signer([…])`.
|
|
55
|
+
- New: `mintTo` and `freezeAccount` take a `Mut<AccountInfo>` token account the instruction created (an associated
|
|
56
|
+
token account made with `ata.create`).
|
|
57
|
+
- New: `u256`, a 256-bit unsigned integer for computation (locals, helpers; never stored, sent or returned), with the
|
|
58
|
+
checked operators, comparisons, casts to and from it, and `mulDiv` / `mulDivCeil` through a 512-bit product. The
|
|
59
|
+
runtime works on 32-bit limbs with 64-bit products and divides with Knuth's algorithm D; a fuzzer checks every
|
|
60
|
+
operator against BigInt.
|
|
61
|
+
|
|
9
62
|
## 0.36.0 — 2026-10-30
|
|
10
63
|
|
|
11
64
|
Verifiable randomness from Switchboard, Anchor's check order for instructions with account groups, and the
|
package/README.md
CHANGED
|
@@ -178,7 +178,12 @@ 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
|
-
(pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units)
|
|
181
|
+
(pool creation included: same outcomes, account bytes and events on 70 transactions; 45–79% fewer compute units), and
|
|
182
|
+
[docs/case-study-raydium-clmm.md](docs/case-study-raydium-clmm.md) for all 37 instructions of Raydium CLMM
|
|
183
|
+
(pools, positions, swaps and routes, limit orders, rewards, admin: the same on 300 transactions; 33–84% fewer
|
|
184
|
+
compute units), and [docs/case-study-jito-mev.md](docs/case-study-jito-mev.md) for Jito's three MEV programs (tip
|
|
185
|
+
payment, tip distribution with Merkle claims, priority fee distribution: the same on 150 transactions; 58–95% fewer
|
|
186
|
+
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
187
|
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
183
188
|
|
|
184
189
|
## How it works
|
|
@@ -329,6 +334,8 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
329
334
|
| [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
|
|
330
335
|
| [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
|
|
331
336
|
| [`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 |
|
|
337
|
+
| [`raydium-clmm/`](examples/raydium-clmm) | Raydium CLMM in full: concentrated-liquidity positions as NFTs, swaps and multi-hop routes across tick arrays, limit orders, rewards, dynamic fees, u256 math |
|
|
338
|
+
| [`jito-mev/`](examples/jito-mev) | Jito's tip payment, tip distribution and priority fee distribution: tips paid out per leader, Merkle-proof claims, epochs and expiry |
|
|
332
339
|
| [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
333
340
|
|
|
334
341
|
## Status
|
|
@@ -46,6 +46,12 @@ export interface TypeScope {
|
|
|
46
46
|
}>;
|
|
47
47
|
}
|
|
48
48
|
export declare function snakeCase(name: string): string;
|
|
49
|
+
/**
|
|
50
|
+
* An argument's IDL name. Anchor keeps arguments and accounts apart, so an instruction may take an account and an
|
|
51
|
+
* argument of one name (`authority`); TypeScript cannot, so the argument is written with a trailing underscore
|
|
52
|
+
* (`authority_`) and recorded without it.
|
|
53
|
+
*/
|
|
54
|
+
export declare function argIdlName(name: string, accountNames: readonly string[]): string;
|
|
49
55
|
export declare function discriminator(preimage: string): number[];
|
|
50
56
|
/** Source text by absolute path: an editor's unsaved buffers, read instead of the files on disk. */
|
|
51
57
|
export type SourceOverrides = ReadonlyMap<string, string>;
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -141,6 +141,17 @@ export function snakeCase(name) {
|
|
|
141
141
|
.replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
|
|
142
142
|
.toLowerCase();
|
|
143
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* An argument's IDL name. Anchor keeps arguments and accounts apart, so an instruction may take an account and an
|
|
146
|
+
* argument of one name (`authority`); TypeScript cannot, so the argument is written with a trailing underscore
|
|
147
|
+
* (`authority_`) and recorded without it.
|
|
148
|
+
*/
|
|
149
|
+
export function argIdlName(name, accountNames) {
|
|
150
|
+
const base = snakeCase(name);
|
|
151
|
+
if (base.length > 1 && base.endsWith("_") && !base.endsWith("__") && accountNames.some((a) => snakeCase(a) === base.slice(0, -1)))
|
|
152
|
+
return base.slice(0, -1);
|
|
153
|
+
return base;
|
|
154
|
+
}
|
|
144
155
|
/**
|
|
145
156
|
* An account struct's discriminator: Anchor's sha256("account:<Name>")[..8], or the one a `/** @discriminator … *\/` tag
|
|
146
157
|
* gives (a sha256 preimage such as `account:Counter`, or 0x and 8 bytes), e.g. for an old version of a struct kept under
|
|
@@ -470,6 +481,11 @@ export function analyze(entry, files) {
|
|
|
470
481
|
});
|
|
471
482
|
}
|
|
472
483
|
const structs = analyzeStructs(interfaces, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs);
|
|
484
|
+
// u256 is a computation type: nothing stores, sends or returns it (the IDL has no 256-bit integer).
|
|
485
|
+
for (const s of structs.values())
|
|
486
|
+
for (const f of s.fields)
|
|
487
|
+
if (hasU256(f.type))
|
|
488
|
+
reporter.error(s.node ?? interfaces[0].decl, `${s.name}.${f.name}: u256 is for computation; store a u128 (or two u128s)`);
|
|
473
489
|
const checker = program.getTypeChecker();
|
|
474
490
|
// Local `const f = (…) => …` in any function body (and in those local functions): lifted to helpers.
|
|
475
491
|
const locals = [];
|
|
@@ -670,6 +686,11 @@ export function analyze(entry, files) {
|
|
|
670
686
|
reporter.error(fn.node.name ?? fn.node, "a program has at most one @fallback");
|
|
671
687
|
ix.fallback = true;
|
|
672
688
|
}
|
|
689
|
+
for (const a of ix.args)
|
|
690
|
+
if (hasU256(a.type))
|
|
691
|
+
reporter.error(a.node, `${a.name}: u256 is for computation; take a u128 (or two) and convert with u256(…)`);
|
|
692
|
+
if (ix.returns && hasU256(ix.returns))
|
|
693
|
+
reporter.error(fn.node.type ?? fn.node, "u256 is for computation; return a u128 (or a struct of them)");
|
|
673
694
|
instructions.push(ix);
|
|
674
695
|
for (const a of ix.args)
|
|
675
696
|
collectStructs(a.type, structs, dataEnums, argStructs);
|
|
@@ -1487,6 +1508,15 @@ function checkRecursion(sources, decls, checker, reporter) {
|
|
|
1487
1508
|
for (const name of byName.keys())
|
|
1488
1509
|
walk(name, []);
|
|
1489
1510
|
}
|
|
1511
|
+
/** Whether a stored, sent or returned type contains a u256. */
|
|
1512
|
+
function hasU256(t) {
|
|
1513
|
+
if (!t || typeof t !== "object")
|
|
1514
|
+
return false;
|
|
1515
|
+
const x = t;
|
|
1516
|
+
if (x.kind === "int")
|
|
1517
|
+
return x.name === "u256";
|
|
1518
|
+
return ["elem", "inner", "array"].some((k) => hasU256(x[k]));
|
|
1519
|
+
}
|
|
1490
1520
|
/** TypeSOL types an account parameter can have (with the constraint wrappers around them). */
|
|
1491
1521
|
const ACCOUNT_TYPES = new Set([
|
|
1492
1522
|
"Signer",
|
|
@@ -1742,15 +1772,24 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
|
|
|
1742
1772
|
reporter.fail(a.node, `HasOne<…, "${f}">: ${struct.name} needs a Pubkey field "${f}"`);
|
|
1743
1773
|
}
|
|
1744
1774
|
if (c.seeds?.bump?.startsWith("@")) {
|
|
1745
|
-
// "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`)
|
|
1746
|
-
|
|
1775
|
+
// "@acct.field": the bump stored in another struct account (Anchor `bump = multisig.nonce`), or in a struct
|
|
1776
|
+
// field of it ("@config.bumps.vault", Anchor `bump = config.bumps.vault`).
|
|
1777
|
+
const [owner, ...path] = c.seeds.bump.slice(1).split(".");
|
|
1747
1778
|
const o = accounts.find((x) => x.name === owner);
|
|
1748
|
-
|
|
1749
|
-
if (!os || !
|
|
1779
|
+
let os = o?.kind.kind === "account" ? o.kind.struct : undefined;
|
|
1780
|
+
if (!os || !path.length)
|
|
1750
1781
|
reporter.fail(a.node, `Seeds bump: "${c.seeds.bump}" must name a u8 field of a struct account parameter ("@config.bump")`);
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1782
|
+
for (let i = 0; i < path.length; i++) {
|
|
1783
|
+
const bf = os.fields.find((x) => x.name === path[i]);
|
|
1784
|
+
if (i < path.length - 1) {
|
|
1785
|
+
const inner = bf?.type.kind === "struct" ? structs.get(bf.type.name) : undefined;
|
|
1786
|
+
if (!inner)
|
|
1787
|
+
reporter.fail(a.node, `Seeds bump: ${os.name}.${path[i]} must be a struct field`);
|
|
1788
|
+
os = inner;
|
|
1789
|
+
}
|
|
1790
|
+
else if (!bf || bf.type.kind !== "int" || bf.type.name !== "u8")
|
|
1791
|
+
reporter.fail(a.node, `Seeds bump: ${os.name} needs a u8 field "${path[i]}"`);
|
|
1792
|
+
}
|
|
1754
1793
|
}
|
|
1755
1794
|
else if (c.seeds?.bump) {
|
|
1756
1795
|
if (!struct)
|
|
@@ -1783,7 +1822,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
|
|
|
1783
1822
|
const c = a.constraints;
|
|
1784
1823
|
const refs = [
|
|
1785
1824
|
...c.hasOne.map((e) => (e.includes("=") ? e.split("=").at(-1) : (c.hasOneParams?.get(e) ?? e))),
|
|
1786
|
-
...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).split(".")[0]),
|
|
1825
|
+
...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).replace(/:be$/, "").split(".")[0]),
|
|
1787
1826
|
...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
|
|
1788
1827
|
...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
|
|
1789
1828
|
...(c.closeTo ? [c.closeTo] : []),
|
|
@@ -165,7 +165,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
165
165
|
// a * b / c with a double-width intermediate (128-bit for u64, 256-bit for u128), rounding down or up;
|
|
166
166
|
// aborts if the result does not fit. All three are u64, or all u128 (literals take the others' type).
|
|
167
167
|
if (args.length !== 3)
|
|
168
|
-
this.fail(node, `${builtin}(a, b, c) takes three u64 or
|
|
168
|
+
this.fail(node, `${builtin}(a, b, c) takes three u64, u128 or u256 values`);
|
|
169
169
|
const vals = [];
|
|
170
170
|
for (const a of args) {
|
|
171
171
|
const mark = this.lines.length;
|
|
@@ -175,6 +175,16 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
175
175
|
vals.push(v);
|
|
176
176
|
}
|
|
177
177
|
const typed = vals.find((v) => v.literal === undefined);
|
|
178
|
+
if (typed?.type.kind === "int" && typed.type.name === "u256") {
|
|
179
|
+
// u256: a 512-bit product in the runtime.
|
|
180
|
+
const ty = typed.type;
|
|
181
|
+
const [x, y, z] = vals.map((v, i) => this.expect(v.literal !== undefined ? this.literal(v.literal, ty, args[i]) : v, ty, args[i]));
|
|
182
|
+
const t = this.tmp("md");
|
|
183
|
+
this.line(`TsU256 ${t};`);
|
|
184
|
+
this.line(`if (ts_u256_is_zero(${z.c})) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
|
|
185
|
+
this.line(`if (!ts_u256_muldiv(${x.c}, ${y.c}, ${z.c}, ${builtin === "mulDivCeil"}, &${t})) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow");`);
|
|
186
|
+
return { c: t, type: ty };
|
|
187
|
+
}
|
|
178
188
|
const wide = typed?.type.kind === "int" && typed.type.name === "u128";
|
|
179
189
|
const ty = wide ? { kind: "int", name: "u128" } : U64;
|
|
180
190
|
const [x, y, z] = vals.map((v, i) => this.expect(v.literal !== undefined ? this.literal(v.literal, ty, args[i]) : v, ty, args[i]));
|
|
@@ -529,6 +539,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
529
539
|
return { c: "", type: { kind: "remaining" } };
|
|
530
540
|
case "readData":
|
|
531
541
|
return this.readData(node);
|
|
542
|
+
case "bigEndian":
|
|
543
|
+
this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
|
|
532
544
|
case "loadAccount":
|
|
533
545
|
case "loadAccountMut":
|
|
534
546
|
case "loadForeign":
|
|
@@ -1239,10 +1251,22 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1239
1251
|
if (s.layout === "borsh")
|
|
1240
1252
|
this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
|
|
1241
1253
|
if (node.arguments.length !== 1)
|
|
1242
|
-
this.fail(node, "loadAccount<T>(account) takes one remaining account");
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1254
|
+
this.fail(node, "loadAccount<T>(account) takes one remaining account or AccountInfo parameter");
|
|
1255
|
+
let h = this.handle(node.arguments[0]);
|
|
1256
|
+
// An AccountInfo parameter (Anchor: AccountLoader::try_from on an UncheckedAccount). The entry checks already
|
|
1257
|
+
// refuse it aliasing another writable parameter (unless Dup<…>), so only a second load of it is refused here.
|
|
1258
|
+
let param;
|
|
1259
|
+
if (!h) {
|
|
1260
|
+
const acct = this.accountParam(node.arguments[0], "the account");
|
|
1261
|
+
if (acct.kind.kind !== "info")
|
|
1262
|
+
this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
|
|
1263
|
+
if (mut && !isWritable(acct.kind))
|
|
1264
|
+
this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadAccountMut`);
|
|
1265
|
+
if (!this.ix)
|
|
1266
|
+
this.fail(node, `load ${acct.name} in the instruction and pass the struct to this helper as ${mut ? "Mut" : "Account"}<${s.name}>`);
|
|
1267
|
+
h = `a_${acct.name}`;
|
|
1268
|
+
param = this.ix.accounts.indexOf(acct);
|
|
1269
|
+
}
|
|
1246
1270
|
if (this.model.events.has(s.name) && s.fields.some((f) => f.type.kind === "option" || f.type.kind === "dataEnum"))
|
|
1247
1271
|
this.fail(node, `${s.name} is emitted as an event and has Option or enum fields; declare a separate event struct`);
|
|
1248
1272
|
this.model.accountStructs.add(s.name);
|
|
@@ -1252,7 +1276,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1252
1276
|
this.line(l);
|
|
1253
1277
|
if (mut) {
|
|
1254
1278
|
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
1255
|
-
this.line(`TS_TRY(ts_claim_mut(params, ${h}));`);
|
|
1279
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
|
|
1256
1280
|
}
|
|
1257
1281
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: mut } };
|
|
1258
1282
|
}
|
|
@@ -1477,6 +1501,16 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1477
1501
|
/** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
|
|
1478
1502
|
helperArg(h, p, n) {
|
|
1479
1503
|
if (p.account) {
|
|
1504
|
+
// A struct of this program loaded with loadAccount / loadAccountMut: its account, as Account<T> / Mut<T>.
|
|
1505
|
+
const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
|
|
1506
|
+
if (l?.loaded) {
|
|
1507
|
+
const want = p.account;
|
|
1508
|
+
if (want.kind !== "account" || want.struct.name !== l.loaded.struct || want.struct.layout === "borsh" || want.struct.vec)
|
|
1509
|
+
this.fail(n, `${h.name}() takes ${p.name} as another kind of account; ${n.text} is a loaded ${l.loaded.struct}`);
|
|
1510
|
+
if (want.mut && !l.loaded.mut)
|
|
1511
|
+
this.fail(n, `${h.name}() takes ${p.name} as Mut<${l.loaded.struct}>: load it with loadAccountMut`);
|
|
1512
|
+
return l.loaded.handle;
|
|
1513
|
+
}
|
|
1480
1514
|
const acct = this.accountParam(n, `${h.name}()'s ${p.name}`);
|
|
1481
1515
|
const why = accountMismatch(acct.kind, p.account);
|
|
1482
1516
|
if (why)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { snakeCase } from "../analyze.js";
|
|
2
|
+
import { argIdlName, snakeCase } from "../analyze.js";
|
|
3
3
|
import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
|
|
4
4
|
import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
|
|
5
5
|
import { CallEmitter } from "./calls.js";
|
|
@@ -38,6 +38,20 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
38
38
|
parts.push(`{(const uint8_t *)${cString(el.text)}, ${len}}`);
|
|
39
39
|
continue;
|
|
40
40
|
}
|
|
41
|
+
// bigEndian(x): the integer's bytes most significant first (Rust's `x.to_be_bytes()`).
|
|
42
|
+
if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian") {
|
|
43
|
+
if (el.arguments.length !== 1)
|
|
44
|
+
this.fail(el, "bigEndian(value) takes one integer");
|
|
45
|
+
const v = this.expr(el.arguments[0]);
|
|
46
|
+
if (v.type.kind !== "int" || v.literal !== undefined)
|
|
47
|
+
this.fail(el, "bigEndian(value) takes a typed integer (an argument, a field or a local), not a literal");
|
|
48
|
+
const info = INT_INFO[v.type.name];
|
|
49
|
+
const t = this.tmp("seed");
|
|
50
|
+
this.line(`uint8_t ${t}[${info.bytes}];`);
|
|
51
|
+
this.line(`{ ${info.c} ${t}_v = ${v.c}; for (int ${t}_i = 0; ${t}_i < ${info.bytes}; ${t}_i++) ${t}[${t}_i] = ((const uint8_t *)&${t}_v)[${info.bytes - 1} - ${t}_i]; }`);
|
|
52
|
+
parts.push(`{${t}, ${info.bytes}}`);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
41
55
|
// Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
|
|
42
56
|
const v = this.expr(el);
|
|
43
57
|
if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
|
|
@@ -86,6 +100,9 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
86
100
|
return { name, count: parts.length, idl };
|
|
87
101
|
}
|
|
88
102
|
describeSeed(el) {
|
|
103
|
+
// Anchor's IDL records `x.to_be_bytes()` as the argument (or field) itself, without the byte order.
|
|
104
|
+
if (ts.isCallExpression(el) && this.exportName(el.expression) === "bigEndian" && el.arguments.length === 1)
|
|
105
|
+
return this.describeSeed(el.arguments[0]);
|
|
89
106
|
if (ts.isStringLiteral(el))
|
|
90
107
|
return { kind: "const", value: [...Buffer.from(el.text, "utf8")] };
|
|
91
108
|
if (ts.isBigIntLiteral(el)) {
|
|
@@ -98,7 +115,10 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
98
115
|
}
|
|
99
116
|
// Only the argument itself, not a local that shadows its name.
|
|
100
117
|
if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
|
|
101
|
-
return {
|
|
118
|
+
return {
|
|
119
|
+
kind: "arg",
|
|
120
|
+
path: argIdlName(el.text, this.ix.accounts.map((o) => o.name)),
|
|
121
|
+
};
|
|
102
122
|
if (ts.isIdentifier(el) && !this.lookup(el.text)) {
|
|
103
123
|
const k = this.model.constants.get(el.text);
|
|
104
124
|
if (k && typeof k.value === "string")
|
|
@@ -262,6 +282,8 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
262
282
|
if (v.isNull)
|
|
263
283
|
this.fail(node, "a bare null has no type here; pass an Option value (e.g. a local declared `const x: u64 | null = null`)");
|
|
264
284
|
const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
|
|
285
|
+
if (typed.type.kind === "int" && typed.type.name === "u256")
|
|
286
|
+
this.fail(node, "u256 is for computation: convert to u128 (or smaller) to send it");
|
|
265
287
|
if (typed.type.kind === "pubkey") {
|
|
266
288
|
put(`(${typed.c})`, "32", 32);
|
|
267
289
|
}
|
|
@@ -69,6 +69,8 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
|
|
|
69
69
|
protected binary(node: ts.BinaryExpression, hint?: ValueType): Value;
|
|
70
70
|
/** Checked integer arithmetic into a fresh temporary. */
|
|
71
71
|
protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
|
|
72
|
+
/** u256 arithmetic through the runtime's limb routines (checked like the other integers). */
|
|
73
|
+
private arith256;
|
|
72
74
|
protected cast(arg: ts.Expression, to: ScalarType & {
|
|
73
75
|
kind: "int";
|
|
74
76
|
}): Value;
|
|
@@ -234,6 +234,8 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
234
234
|
const typed = v.literal !== undefined ? this.literal(v.literal, hint?.kind === "int" ? hint : U64, node) : v;
|
|
235
235
|
if (typed.type.kind !== "int")
|
|
236
236
|
this.fail(node, "~ needs an integer");
|
|
237
|
+
if (typed.type.name === "u256")
|
|
238
|
+
return { c: `ts_u256_bit(${typed.c}, ts_u256_lit(~0ULL, ~0ULL, ~0ULL, ~0ULL), 2)`, type: typed.type };
|
|
237
239
|
return { c: `((${INT_INFO[typed.type.name].c})~${typed.c})`, type: typed.type };
|
|
238
240
|
}
|
|
239
241
|
this.fail(node, "this operator is not supported");
|
|
@@ -322,6 +324,23 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
322
324
|
}
|
|
323
325
|
this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and isWritable, not ${field}`);
|
|
324
326
|
}
|
|
327
|
+
// A struct loaded with loadAccount / loadAccountMut is also its account: key, lamports, dataLen, isSigner, isWritable.
|
|
328
|
+
if (ts.isIdentifier(node.expression)) {
|
|
329
|
+
const l = this.lookup(node.expression.text);
|
|
330
|
+
// A field of the struct by that name comes first (as before loaded structs were accounts too).
|
|
331
|
+
const own = l?.loaded && this.model.structs.get(l.loaded.struct)?.fields.some((f) => f.name === field);
|
|
332
|
+
const acct = own ? undefined : l?.loaded?.handle;
|
|
333
|
+
if (acct && field === "key")
|
|
334
|
+
return { c: `&${acct}->key`, type: PUBKEY };
|
|
335
|
+
if (acct && field === "lamports")
|
|
336
|
+
return { c: `${acct}->lamports`, type: U64 };
|
|
337
|
+
if (acct && field === "dataLen")
|
|
338
|
+
return { c: `${acct}->data_len`, type: U64 };
|
|
339
|
+
if (acct && field === "isSigner")
|
|
340
|
+
return { c: `${acct}->is_signer`, type: BOOL };
|
|
341
|
+
if (acct && field === "isWritable")
|
|
342
|
+
return { c: `${acct}->is_writable`, type: BOOL };
|
|
343
|
+
}
|
|
325
344
|
if (this.accountAt(node))
|
|
326
345
|
this.fail(node, `"${node.getText()}" is an account; use ${node.getText()}.key for its address`);
|
|
327
346
|
if (this.isGroupValue(node))
|
|
@@ -595,6 +614,9 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
595
614
|
/** C statement writing the decimal text of an integer into the TS_Str `out`. */
|
|
596
615
|
textOfInt(name, c, out) {
|
|
597
616
|
const info = INT_INFO[name];
|
|
617
|
+
// u256 prints as text when it fits in 128 bits (logs of larger values are refused at run time: 5100).
|
|
618
|
+
if (name === "u256")
|
|
619
|
+
return `if (!ts_u256_fits(${c}, 128)) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: u256 too large to print"); TS_TRY(ts_str_u128(ts_u256_lo128(${c}), false, &${out}));`;
|
|
598
620
|
if (info.bytes === 16)
|
|
599
621
|
return info.signed ? `TS_TRY(ts_str_i128(${c}, &${out}));` : `TS_TRY(ts_str_u128(${c}, false, &${out}));`;
|
|
600
622
|
return info.signed ? `TS_TRY(ts_str_i64((int64_t)(${c}), &${out}));` : `TS_TRY(ts_str_u64((uint64_t)(${c}), false, &${out}));`;
|
|
@@ -877,11 +899,15 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
877
899
|
? `ts_key_eq(${left.c}, ${right.c})`
|
|
878
900
|
: left.type.kind === "string"
|
|
879
901
|
? `ts_str_eq(${left.c}, ${right.c})`
|
|
880
|
-
:
|
|
902
|
+
: left.type.kind === "int" && left.type.name === "u256"
|
|
903
|
+
? `(ts_u256_cmp(${left.c}, ${right.c}) == 0)`
|
|
904
|
+
: `(${left.c} == ${right.c})`;
|
|
881
905
|
return { c: neg ? `(!${c})` : c, type: BOOL };
|
|
882
906
|
}
|
|
883
907
|
if (left.type.kind !== "int")
|
|
884
908
|
this.fail(node, `${node.operatorToken.getText()} needs integer operands`);
|
|
909
|
+
if (isCmp && left.type.name === "u256")
|
|
910
|
+
return { c: `(ts_u256_cmp(${left.c}, ${right.c}) ${node.operatorToken.getText()} 0)`, type: BOOL };
|
|
885
911
|
if (isCmp)
|
|
886
912
|
return { c: `(${left.c} ${node.operatorToken.getText()} ${right.c})`, type: BOOL };
|
|
887
913
|
return this.arith(op, left, right, node);
|
|
@@ -896,6 +922,8 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
896
922
|
const K = ts.SyntaxKind;
|
|
897
923
|
this.line(`${ct} ${t};`);
|
|
898
924
|
const overflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
|
|
925
|
+
if (type.name === "u256")
|
|
926
|
+
return this.arith256(op, left, right, node, t, overflow);
|
|
899
927
|
switch (op) {
|
|
900
928
|
case K.PlusToken:
|
|
901
929
|
// u64 through the runtime helpers: one compare instead of a materialized carry flag on SBF.
|
|
@@ -949,6 +977,48 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
949
977
|
}
|
|
950
978
|
return { c: t, type };
|
|
951
979
|
}
|
|
980
|
+
/** u256 arithmetic through the runtime's limb routines (checked like the other integers). */
|
|
981
|
+
arith256(op, left, right, node, t, overflow) {
|
|
982
|
+
const K = ts.SyntaxKind;
|
|
983
|
+
const type = left.type;
|
|
984
|
+
switch (op) {
|
|
985
|
+
case K.PlusToken:
|
|
986
|
+
case K.MinusToken:
|
|
987
|
+
case K.AsteriskToken:
|
|
988
|
+
this.line(`if (ts_u256_${op === K.PlusToken ? "add" : op === K.MinusToken ? "sub" : "mul"}(${left.c}, ${right.c}, &${t})) ${overflow};`);
|
|
989
|
+
break;
|
|
990
|
+
case K.SlashToken:
|
|
991
|
+
case K.PercentToken:
|
|
992
|
+
this.line(`if (ts_u256_is_zero(${right.c})) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
|
|
993
|
+
this.line(`${t} = ts_u256_divmod(${left.c}, ${right.c}, ${op === K.SlashToken});`);
|
|
994
|
+
break;
|
|
995
|
+
case K.AmpersandToken:
|
|
996
|
+
case K.BarToken:
|
|
997
|
+
case K.CaretToken:
|
|
998
|
+
this.line(`${t} = ts_u256_bit(${left.c}, ${right.c}, ${op === K.AmpersandToken ? 0 : op === K.BarToken ? 1 : 2});`);
|
|
999
|
+
break;
|
|
1000
|
+
case K.LessThanLessThanToken:
|
|
1001
|
+
case K.GreaterThanGreaterThanToken: {
|
|
1002
|
+
if (right.type.kind !== "int")
|
|
1003
|
+
this.fail(node, "shift amounts must be integers");
|
|
1004
|
+
if (right.type.name === "u256")
|
|
1005
|
+
this.fail(node, "shift by a u64 (or smaller) amount");
|
|
1006
|
+
const sh = this.tmp("sh");
|
|
1007
|
+
this.line(`if (${INT_INFO[right.type.name].signed ? `${right.c} < 0 || ` : ""}${right.c} >= 256) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range");`);
|
|
1008
|
+
this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
|
|
1009
|
+
if (op === K.GreaterThanGreaterThanToken)
|
|
1010
|
+
this.line(`${t} = ts_u256_shr(${left.c}, ${sh});`);
|
|
1011
|
+
else {
|
|
1012
|
+
this.line(`${t} = ts_u256_shl(${left.c}, ${sh});`);
|
|
1013
|
+
this.line(`if (ts_u256_cmp(ts_u256_shr(${t}, ${sh}), ${left.c}) != 0) ${overflow};`);
|
|
1014
|
+
}
|
|
1015
|
+
break;
|
|
1016
|
+
}
|
|
1017
|
+
default:
|
|
1018
|
+
this.fail(node, "unsupported arithmetic operator");
|
|
1019
|
+
}
|
|
1020
|
+
return { c: t, type };
|
|
1021
|
+
}
|
|
952
1022
|
cast(arg, to) {
|
|
953
1023
|
const v = this.expr(arg);
|
|
954
1024
|
if (v.literal !== undefined)
|
|
@@ -959,6 +1029,25 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
959
1029
|
return v;
|
|
960
1030
|
const from = INT_INFO[v.type.name];
|
|
961
1031
|
const target = INT_INFO[to.name];
|
|
1032
|
+
if (to.name === "u256") {
|
|
1033
|
+
// Widen: any unsigned value, or a signed one that is not negative.
|
|
1034
|
+
if (from.signed)
|
|
1035
|
+
this.line(`if (${v.c} < 0) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in u256");`);
|
|
1036
|
+
const t = this.tmp();
|
|
1037
|
+
this.line(`TsU256 ${t} = ts_u256_from_u128((unsigned __int128)${v.c});`);
|
|
1038
|
+
return { c: t, type: to };
|
|
1039
|
+
}
|
|
1040
|
+
if (v.type.name === "u256") {
|
|
1041
|
+
// Narrow: the value must fit the target (checked on the limbs, then on the low 128 bits).
|
|
1042
|
+
const t = this.tmp();
|
|
1043
|
+
const lo = this.tmp("lo");
|
|
1044
|
+
this.line(`if (!ts_u256_fits(${v.c}, 128)) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in ${to.name}");`);
|
|
1045
|
+
this.line(`unsigned __int128 ${lo} = ts_u256_lo128(${v.c});`);
|
|
1046
|
+
if (target.max < 2n ** 128n - 1n)
|
|
1047
|
+
this.line(`if (${lo} > ${intLiteral(target.max, "u128")}) TS_FAIL(TS_ERR_CAST, "TypeSOL: value does not fit in ${to.name}");`);
|
|
1048
|
+
this.line(`${target.c} ${t} = (${target.c})${lo};`);
|
|
1049
|
+
return { c: t, type: to };
|
|
1050
|
+
}
|
|
962
1051
|
const conds = [];
|
|
963
1052
|
if (from.min < target.min)
|
|
964
1053
|
conds.push(`${v.c} < ${intLiteral(target.min, v.type.name)}`);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { snakeCase } from "../analyze.js";
|
|
2
|
+
import { snakeCase, argIdlName } from "../analyze.js";
|
|
3
3
|
import { decodeAddress } from "../../keys.js";
|
|
4
4
|
import { INT_INFO, isScalar, isWritable, scalarSize, typeName, } from "../model.js";
|
|
5
5
|
import { borshIdentical, borshMinSize } from "./borsh.js";
|
|
@@ -607,10 +607,21 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
607
607
|
const c = a.constraints;
|
|
608
608
|
const parts = [];
|
|
609
609
|
const idl = [];
|
|
610
|
-
for (const
|
|
610
|
+
for (const named of c.seeds.names) {
|
|
611
611
|
// "@name" refers to an account parameter (its key) or an argument (its bytes); anything else is a literal.
|
|
612
|
+
// "@name:be" takes an integer's bytes most significant first (Rust's `to_be_bytes()`).
|
|
613
|
+
const be = named.startsWith("@") && named.endsWith(":be");
|
|
614
|
+
const raw = be ? named.slice(0, -3) : named;
|
|
612
615
|
const ref = raw.startsWith("@") ? raw.slice(1) : undefined;
|
|
613
616
|
const n = ref ?? raw;
|
|
617
|
+
const intSeed = (place, size) => {
|
|
618
|
+
if (!be)
|
|
619
|
+
return `{(const uint8_t *)&${place}, ${size}}`;
|
|
620
|
+
const t = `sbe_${a.name}_${parts.length}`;
|
|
621
|
+
out.push(` uint8_t ${t}[${size}]; for (int i = 0; i < ${size}; i++) ${t}[i] = ((const uint8_t *)&${place})[${size - 1} - i];`);
|
|
622
|
+
return `{${t}, ${size}}`;
|
|
623
|
+
};
|
|
624
|
+
const notInt = () => be && this.reporter.fail(a.node, `Seeds: "${named}": only integers have a byte order`);
|
|
614
625
|
// "@acct.field": a field of a struct account parameter (its data was checked in the head), Anchor's
|
|
615
626
|
// `seeds = [pool.amm.as_ref()]`. The account may be this one (`seeds = [offer.id.to_le_bytes()]`).
|
|
616
627
|
if (ref?.includes(".")) {
|
|
@@ -623,9 +634,13 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
623
634
|
if (!f)
|
|
624
635
|
this.reporter.fail(a.node, `Seeds: ${st.name} has no field "${field}"`);
|
|
625
636
|
const t = f.type;
|
|
626
|
-
if (t.kind === "
|
|
637
|
+
if (t.kind === "int")
|
|
638
|
+
parts.push(intSeed(`d_${owner}->${field}`, scalarSize(t)));
|
|
639
|
+
else if (notInt())
|
|
640
|
+
return out;
|
|
641
|
+
else if (t.kind === "pubkey")
|
|
627
642
|
parts.push(`{(const uint8_t *)&d_${owner}->${field}, 32}`);
|
|
628
|
-
else if (t.kind === "
|
|
643
|
+
else if (t.kind === "enum")
|
|
629
644
|
parts.push(`{(const uint8_t *)&d_${owner}->${field}, ${scalarSize(t)}}`);
|
|
630
645
|
else
|
|
631
646
|
this.reporter.fail(a.node, `Seeds: field "${ref}" of type ${typeName(t)} cannot be a seed (use a Pubkey, an integer or a unit enum)`);
|
|
@@ -637,22 +652,31 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
637
652
|
if (ref && !acct && !arg)
|
|
638
653
|
this.reporter.fail(a.node, `Seeds: "@${ref}" is neither an account parameter nor an argument`);
|
|
639
654
|
if (acct) {
|
|
655
|
+
notInt();
|
|
640
656
|
parts.push(`{(const uint8_t *)&a_${n}->key, 32}`);
|
|
641
657
|
idl.push({ kind: "account", path: snakeCase(n) });
|
|
642
658
|
}
|
|
643
659
|
else if (arg) {
|
|
644
660
|
const t = arg.type;
|
|
645
|
-
if (t.kind === "
|
|
661
|
+
if (t.kind === "int")
|
|
662
|
+
parts.push(intSeed(`arg_${n}`, scalarSize(t)));
|
|
663
|
+
else if (notInt())
|
|
664
|
+
return out;
|
|
665
|
+
else if (t.kind === "string")
|
|
646
666
|
parts.push(`{arg_${n}.ptr, arg_${n}.len}`);
|
|
647
667
|
else if (t.kind === "pubkey")
|
|
648
668
|
parts.push(`{(const uint8_t *)&arg_${n}, 32}`);
|
|
649
|
-
else if (t.kind === "
|
|
669
|
+
else if (t.kind === "enum")
|
|
650
670
|
parts.push(`{(const uint8_t *)&arg_${n}, ${scalarSize(t)}}`);
|
|
651
671
|
else
|
|
652
672
|
this.reporter.fail(a.node, `Seeds: argument "${n}" of type ${typeName(t)} cannot be a seed`);
|
|
653
|
-
idl.push({
|
|
673
|
+
idl.push({
|
|
674
|
+
kind: "arg",
|
|
675
|
+
path: argIdlName(n, ix.accounts.map((o) => o.name)),
|
|
676
|
+
});
|
|
654
677
|
}
|
|
655
678
|
else {
|
|
679
|
+
notInt();
|
|
656
680
|
if (Buffer.byteLength(n, "utf8") > 32)
|
|
657
681
|
this.reporter.fail(a.node, "a seed can be at most 32 bytes");
|
|
658
682
|
parts.push(`{(const uint8_t *)${cString(n)}, ${Buffer.byteLength(n, "utf8")}}`);
|
|
@@ -158,7 +158,7 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
158
158
|
// Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
|
|
159
159
|
if (limit > 32)
|
|
160
160
|
out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
|
|
161
|
-
if ([...helperBodies, ...ixBodies].some((b) =>
|
|
161
|
+
if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?\(/.test(b)))
|
|
162
162
|
out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
|
|
163
163
|
const fallback = model.instructions.find((ix) => ix.fallback);
|
|
164
164
|
const dispatched = model.instructions.filter((ix) => !ix.fallback);
|
|
@@ -83,6 +83,12 @@ export interface Local {
|
|
|
83
83
|
decl?: ts.VariableDeclaration | ts.ParameterDeclaration;
|
|
84
84
|
/** A local closure (`const f = (…) => …` reading the enclosing function's variables), expanded where it is called. */
|
|
85
85
|
closure?: Closure;
|
|
86
|
+
/** `const t = loadAccount<T>(acct)` / `loadAccountMut`: the account it views (a `TsAccount *`), to pass to helpers. */
|
|
87
|
+
loaded?: {
|
|
88
|
+
handle: string;
|
|
89
|
+
struct: string;
|
|
90
|
+
mut: boolean;
|
|
91
|
+
};
|
|
86
92
|
}
|
|
87
93
|
/** A closure and the scopes it was declared in (its free names resolve there, wherever it is called). */
|
|
88
94
|
export interface Closure {
|
|
@@ -29,6 +29,10 @@ export const isStable = (c) => /^\w+$/.test(c) || /^\(&\w+\)$/.test(c) || /^&\w+
|
|
|
29
29
|
/** A C string literal of the UTF-8 bytes. Octal escapes (at most three digits) cannot swallow following characters. */
|
|
30
30
|
export const cString = (s) => `"${[...Buffer.from(s, "utf8")].map((b) => (b >= 0x20 && b < 0x7f && b !== 0x22 && b !== 0x5c && b !== 0x3f ? String.fromCharCode(b) : `\\${b.toString(8).padStart(3, "0")}`)).join("")}"`;
|
|
31
31
|
export function intLiteral(value, name) {
|
|
32
|
+
if (name === "u256") {
|
|
33
|
+
const w = [0n, 1n, 2n, 3n].map((i) => (value >> (64n * i)) & (2n ** 64n - 1n));
|
|
34
|
+
return `ts_u256_lit(${w.map((x) => `${x}ULL`).join(", ")})`;
|
|
35
|
+
}
|
|
32
36
|
if (name === "i64") {
|
|
33
37
|
if (value === INT_INFO.i64.min)
|
|
34
38
|
return "(-9223372036854775807LL - 1)";
|