@typesol/cli 0.36.0 → 0.37.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 +27 -0
- package/README.md +5 -1
- package/dist/compiler/analyze.js +20 -1
- package/dist/compiler/emit/calls.js +40 -6
- package/dist/compiler/emit/cpi-core.js +19 -0
- package/dist/compiler/emit/expressions.d.ts +2 -0
- package/dist/compiler/emit/expressions.js +90 -1
- package/dist/compiler/emit/function.js +26 -5
- 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/model.d.ts +1 -1
- package/dist/compiler/model.js +3 -1
- package/docs/case-study-raydium-clmm.md +176 -0
- package/docs/language.md +10 -6
- package/lib/typesol.d.ts +23 -7
- package/package.json +1 -1
- package/runtime/typesol_rt.h +225 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,33 @@ codes, and says so here.
|
|
|
6
6
|
|
|
7
7
|
## Unreleased
|
|
8
8
|
|
|
9
|
+
## 0.37.0 — 2026-10-31
|
|
10
|
+
|
|
11
|
+
Raydium CLMM ported and checked against the mainnet binary, with what it needed: `u256`, big-endian seeds,
|
|
12
|
+
accounts loaded in the body and seed lists picked at run time. Programs that use none of these compile to the same
|
|
13
|
+
binaries as in 0.36.0.
|
|
14
|
+
|
|
15
|
+
- Examples: examples/raydium-clmm, a port of Raydium CLMM's pools, positions and swaps: `create_amm_config`,
|
|
16
|
+
`create_pool`, `open_position_with_token22_nft`, `increase_liquidity_v2`, `decrease_liquidity_v2`, `swap_v2`,
|
|
17
|
+
`collect_protocol_fee` and `collect_fund_fee`, with its math in u256 and u128 and its account layouts byte for byte.
|
|
18
|
+
Swaps work on any pool the original runs (dynamic fees, limit orders filled at a tick, fee modes, rewards, the
|
|
19
|
+
tick array bitmap extension, Token-2022 transfer fees). Checked against the mainnet binary
|
|
20
|
+
(test/programs/raydium_clmm.so) on 166 transactions, including a pool cloned from mainnet: the same outcomes,
|
|
21
|
+
account bytes and events, with 43–83% fewer compute units. See docs/case-study-raydium-clmm.md.
|
|
22
|
+
- New: big-endian integer seeds, Rust's `to_be_bytes()`: `"@start:be"` in `Seeds<…>` and `bigEndian(start)` in a seed
|
|
23
|
+
list. The IDL records the argument, as Anchor's does.
|
|
24
|
+
- New: `loadAccount<T>` / `loadAccountMut<T>` take an `AccountInfo` parameter too (Anchor's `AccountLoader::try_from` on
|
|
25
|
+
an `UncheckedAccount`, for accounts an instruction may create first); a second `loadAccountMut` of one parameter is
|
|
26
|
+
refused (2040), two `Dup<…>` parameters that are one account may each be loaded. A loaded struct is also its account
|
|
27
|
+
(`.key`, `.lamports`) and passes to helpers taking `Account<T>` / `Mut<T>`.
|
|
28
|
+
- New: one of two seed lists picked at run time, `const s = cond ? signer([…]) : signer([…])`.
|
|
29
|
+
- New: `mintTo` and `freezeAccount` take a `Mut<AccountInfo>` token account the instruction created (an associated
|
|
30
|
+
token account made with `ata.create`).
|
|
31
|
+
- New: `u256`, a 256-bit unsigned integer for computation (locals, helpers; never stored, sent or returned), with the
|
|
32
|
+
checked operators, comparisons, casts to and from it, and `mulDiv` / `mulDivCeil` through a 512-bit product. The
|
|
33
|
+
runtime works on 32-bit limbs with 64-bit products and divides with Knuth's algorithm D; a fuzzer checks every
|
|
34
|
+
operator against BigInt.
|
|
35
|
+
|
|
9
36
|
## 0.36.0 — 2026-10-30
|
|
10
37
|
|
|
11
38
|
Verifiable randomness from Switchboard, Anchor's check order for instructions with account groups, and the
|
package/README.md
CHANGED
|
@@ -178,7 +178,10 @@ 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 Raydium CLMM's pools, positions and swaps
|
|
183
|
+
(dynamic fees, limit orders and the tick array bitmap extension included: the same on 166 transactions; 43–83% fewer
|
|
184
|
+
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
185
|
mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
|
|
183
186
|
|
|
184
187
|
## How it works
|
|
@@ -329,6 +332,7 @@ Details are in [docs/testing.md](docs/testing.md).
|
|
|
329
332
|
| [`profiles.ts`](examples/profiles.ts) | nested structs, FixedString, events |
|
|
330
333
|
| [`orderbook/`](examples/orderbook) | a three-file, 28 KiB zero-copy limit order book |
|
|
331
334
|
| [`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 |
|
|
335
|
+
| [`raydium-clmm/`](examples/raydium-clmm) | Raydium CLMM: concentrated-liquidity positions as Token-2022 NFTs, swaps across tick arrays, u256 math, rewards, dynamic fees |
|
|
332
336
|
| [`multisig.ts`](examples/multisig.ts) | coral-xyz/multisig: stored instructions run with `invokeInstruction`, a PDA signing, Anchor's Borsh accounts |
|
|
333
337
|
|
|
334
338
|
## Status
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -470,6 +470,11 @@ export function analyze(entry, files) {
|
|
|
470
470
|
});
|
|
471
471
|
}
|
|
472
472
|
const structs = analyzeStructs(interfaces, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs);
|
|
473
|
+
// u256 is a computation type: nothing stores, sends or returns it (the IDL has no 256-bit integer).
|
|
474
|
+
for (const s of structs.values())
|
|
475
|
+
for (const f of s.fields)
|
|
476
|
+
if (hasU256(f.type))
|
|
477
|
+
reporter.error(s.node ?? interfaces[0].decl, `${s.name}.${f.name}: u256 is for computation; store a u128 (or two u128s)`);
|
|
473
478
|
const checker = program.getTypeChecker();
|
|
474
479
|
// Local `const f = (…) => …` in any function body (and in those local functions): lifted to helpers.
|
|
475
480
|
const locals = [];
|
|
@@ -670,6 +675,11 @@ export function analyze(entry, files) {
|
|
|
670
675
|
reporter.error(fn.node.name ?? fn.node, "a program has at most one @fallback");
|
|
671
676
|
ix.fallback = true;
|
|
672
677
|
}
|
|
678
|
+
for (const a of ix.args)
|
|
679
|
+
if (hasU256(a.type))
|
|
680
|
+
reporter.error(a.node, `${a.name}: u256 is for computation; take a u128 (or two) and convert with u256(…)`);
|
|
681
|
+
if (ix.returns && hasU256(ix.returns))
|
|
682
|
+
reporter.error(fn.node.type ?? fn.node, "u256 is for computation; return a u128 (or a struct of them)");
|
|
673
683
|
instructions.push(ix);
|
|
674
684
|
for (const a of ix.args)
|
|
675
685
|
collectStructs(a.type, structs, dataEnums, argStructs);
|
|
@@ -1487,6 +1497,15 @@ function checkRecursion(sources, decls, checker, reporter) {
|
|
|
1487
1497
|
for (const name of byName.keys())
|
|
1488
1498
|
walk(name, []);
|
|
1489
1499
|
}
|
|
1500
|
+
/** Whether a stored, sent or returned type contains a u256. */
|
|
1501
|
+
function hasU256(t) {
|
|
1502
|
+
if (!t || typeof t !== "object")
|
|
1503
|
+
return false;
|
|
1504
|
+
const x = t;
|
|
1505
|
+
if (x.kind === "int")
|
|
1506
|
+
return x.name === "u256";
|
|
1507
|
+
return ["elem", "inner", "array"].some((k) => hasU256(x[k]));
|
|
1508
|
+
}
|
|
1490
1509
|
/** TypeSOL types an account parameter can have (with the constraint wrappers around them). */
|
|
1491
1510
|
const ACCOUNT_TYPES = new Set([
|
|
1492
1511
|
"Signer",
|
|
@@ -1783,7 +1802,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
|
|
|
1783
1802
|
const c = a.constraints;
|
|
1784
1803
|
const refs = [
|
|
1785
1804
|
...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]),
|
|
1805
|
+
...(c.seeds?.names ?? []).filter((n) => n.startsWith("@")).map((n) => n.slice(1).replace(/:be$/, "").split(".")[0]),
|
|
1787
1806
|
...(c.seeds?.program?.startsWith("@") ? [c.seeds.program.slice(1)] : []),
|
|
1788
1807
|
...(c.seeds?.bump?.startsWith("@") ? [c.seeds.bump.slice(1).split(".")[0]] : []),
|
|
1789
1808
|
...(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)
|
|
@@ -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)) {
|
|
@@ -262,6 +279,8 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
262
279
|
if (v.isNull)
|
|
263
280
|
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
281
|
const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
|
|
282
|
+
if (typed.type.kind === "int" && typed.type.name === "u256")
|
|
283
|
+
this.fail(node, "u256 is for computation: convert to u128 (or smaller) to send it");
|
|
265
284
|
if (typed.type.kind === "pubkey") {
|
|
266
285
|
put(`(${typed.c})`, "32", 32);
|
|
267
286
|
}
|
|
@@ -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)}`);
|
|
@@ -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,28 @@ 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
673
|
idl.push({ kind: "arg", path: snakeCase(n) });
|
|
654
674
|
}
|
|
655
675
|
else {
|
|
676
|
+
notInt();
|
|
656
677
|
if (Buffer.byteLength(n, "utf8") > 32)
|
|
657
678
|
this.reporter.fail(a.node, "a seed can be at most 32 bytes");
|
|
658
679
|
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)";
|
|
@@ -910,6 +910,24 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
910
910
|
this.scopes.at(-1).set(name, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
|
|
911
911
|
continue;
|
|
912
912
|
}
|
|
913
|
+
// One of two seed lists, picked at run time: `const pool = indexed ? signer([…, index, bump]) : signer([…, bump])`.
|
|
914
|
+
// Both lists are built (seeds have no side effects to skip), then one is chosen.
|
|
915
|
+
if (init &&
|
|
916
|
+
ts.isConditionalExpression(init) &&
|
|
917
|
+
[init.whenTrue, init.whenFalse].every((b) => ts.isCallExpression(b) && this.exportName(b.expression) === "signer")) {
|
|
918
|
+
if (mutable)
|
|
919
|
+
this.fail(d, "bind seed lists with const");
|
|
920
|
+
const cond = this.expect(this.expr(init.condition, BOOL), BOOL, init.condition);
|
|
921
|
+
const flag = this.tmp("which");
|
|
922
|
+
this.line(`bool ${flag} = ${cond.c};`);
|
|
923
|
+
const a = this.signerSeedsArg(init.whenTrue);
|
|
924
|
+
const b = this.signerSeedsArg(init.whenFalse);
|
|
925
|
+
this.line(`const SolSignerSeed *${c} = ${flag} ? ${a.name} : ${b.name};`);
|
|
926
|
+
this.line(`int ${c}__n = ${flag} ? ${a.count} : ${b.count};`);
|
|
927
|
+
this.line(`(void)${c}; (void)${c}__n;`);
|
|
928
|
+
this.scopes.at(-1).set(name, { c, type: { kind: "signerSeeds" }, mutable: false });
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
913
931
|
// A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
|
|
914
932
|
if (fn === "signer") {
|
|
915
933
|
if (mutable)
|
|
@@ -936,7 +954,15 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
936
954
|
this.fail(d, "bind loaded accounts with const");
|
|
937
955
|
const t = fn === "loadForeign" ? this.loadForeign(init) : this.loadAccount(init, fn === "loadAccountMut");
|
|
938
956
|
this.line(`${valueC(t.type)}${c} = ${t.c};`);
|
|
939
|
-
|
|
957
|
+
// The account it views, kept to pass the struct on to a helper that takes Account<T> / Mut<T>.
|
|
958
|
+
let loaded;
|
|
959
|
+
if (fn !== "loadForeign" && t.type.kind === "structRef") {
|
|
960
|
+
// The view is `((TSS_T *)(h->data + 8))` over a `TsAccount *h` that stays in scope with it.
|
|
961
|
+
const h = /^\(\(TSS_\w+ \*\)\((\w+)->data \+ 8\)\)$/.exec(t.c)?.[1];
|
|
962
|
+
if (h)
|
|
963
|
+
loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
|
|
964
|
+
}
|
|
965
|
+
this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d, loaded });
|
|
940
966
|
continue;
|
|
941
967
|
}
|
|
942
968
|
// A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
|
|
@@ -7,10 +7,13 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
7
7
|
tokenOp(node, program, method) {
|
|
8
8
|
const a = node.arguments;
|
|
9
9
|
const p = `a_${program.name}`;
|
|
10
|
-
|
|
10
|
+
// `created`: also a Mut<AccountInfo> token account this instruction created (an associated token account).
|
|
11
|
+
const want = (n, kind, mut, what, created = false) => {
|
|
11
12
|
const acct = this.accountParam(n, what);
|
|
13
|
+
if (created && acct.kind.kind === "info" && isWritable(acct.kind))
|
|
14
|
+
return acct;
|
|
12
15
|
if (acct.kind.kind !== kind || (mut && !acct.kind.mut))
|
|
13
|
-
this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}`);
|
|
16
|
+
this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}${created ? ", or a Mut<AccountInfo> token account this instruction created" : ""}`);
|
|
14
17
|
return acct;
|
|
15
18
|
};
|
|
16
19
|
const arity = (fixed) => {
|
|
@@ -46,7 +49,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
46
49
|
const mint = this.accountParam(a[0], "the mint");
|
|
47
50
|
if (!isWritable(mint.kind) || (mint.kind.kind !== "mint" && mint.kind.kind !== "signer" && mint.kind.kind !== "info"))
|
|
48
51
|
this.fail(a[0], "the mint must be a Mut<Mint>, or a Mut<Signer> / Mut<AccountInfo> mint this instruction created");
|
|
49
|
-
const to = want(a[1], "token", true, "the destination");
|
|
52
|
+
const to = want(a[1], "token", true, "the destination", true);
|
|
50
53
|
const auth = this.accountParam(a[2], "the mint authority");
|
|
51
54
|
const amt = amount(a[3]);
|
|
52
55
|
const s = this.signerSeeds(a[4], auth, a[2]);
|
|
@@ -494,7 +497,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
494
497
|
case "mintToChecked": {
|
|
495
498
|
arity(4);
|
|
496
499
|
const mint = want(a[0], "mint", true, "the mint");
|
|
497
|
-
const to = want(a[1], "token", true, "the destination");
|
|
500
|
+
const to = want(a[1], "token", true, "the destination", true);
|
|
498
501
|
const auth = this.accountParam(a[2], "the mint authority");
|
|
499
502
|
const s = this.signerSeeds(a[4], auth, a[2]);
|
|
500
503
|
simple(14, [value(a[3], U64), decimals(mint)], [
|
|
@@ -542,7 +545,7 @@ export class TokenEmitter extends CreateEmitter {
|
|
|
542
545
|
case "freezeAccount":
|
|
543
546
|
case "thawAccount": {
|
|
544
547
|
arity(3);
|
|
545
|
-
const acct = want(a[0], "token", true, "the token account");
|
|
548
|
+
const acct = want(a[0], "token", true, "the token account", true);
|
|
546
549
|
const mint = this.accountParam(a[1], "the mint");
|
|
547
550
|
const auth = this.accountParam(a[2], "the freeze authority");
|
|
548
551
|
simple(method === "freezeAccount" ? 10 : 11, [], [
|
package/dist/compiler/model.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type ts from "typescript";
|
|
2
|
-
export type IntName = "u8" | "u16" | "u32" | "u64" | "u128" | "i8" | "i16" | "i32" | "i64" | "i128";
|
|
2
|
+
export type IntName = "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128";
|
|
3
3
|
export declare const INT_NAMES: readonly IntName[];
|
|
4
4
|
export declare const INT_INFO: Record<IntName, {
|
|
5
5
|
bytes: number;
|
package/dist/compiler/model.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
export const INT_NAMES = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128"];
|
|
1
|
+
export const INT_NAMES = ["u8", "u16", "u32", "u64", "u128", "u256", "i8", "i16", "i32", "i64", "i128"];
|
|
2
2
|
export const INT_INFO = {
|
|
3
3
|
u8: { bytes: 1, signed: false, c: "uint8_t", min: 0n, max: 0xffn },
|
|
4
4
|
u16: { bytes: 2, signed: false, c: "uint16_t", min: 0n, max: 0xffffn },
|
|
5
5
|
u32: { bytes: 4, signed: false, c: "uint32_t", min: 0n, max: 0xffffffffn },
|
|
6
6
|
u64: { bytes: 8, signed: false, c: "uint64_t", min: 0n, max: 2n ** 64n - 1n },
|
|
7
7
|
u128: { bytes: 16, signed: false, c: "unsigned __int128", min: 0n, max: 2n ** 128n - 1n },
|
|
8
|
+
/** A computation type (locals, helpers): no C integer, runtime limbs (TsU256); never stored, sent or returned. */
|
|
9
|
+
u256: { bytes: 32, signed: false, c: "TsU256", min: 0n, max: 2n ** 256n - 1n },
|
|
8
10
|
i8: { bytes: 1, signed: true, c: "int8_t", min: -(2n ** 7n), max: 2n ** 7n - 1n },
|
|
9
11
|
i16: { bytes: 2, signed: true, c: "int16_t", min: -(2n ** 15n), max: 2n ** 15n - 1n },
|
|
10
12
|
i32: { bytes: 4, signed: true, c: "int32_t", min: -(2n ** 31n), max: 2n ** 31n - 1n },
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Case study: Raydium CLMM
|
|
2
|
+
|
|
3
|
+
This page ports the core of a production concentrated-liquidity AMM: [Raydium CLMM](https://github.com/raydium-io/raydium-clmm)
|
|
4
|
+
(`programs/amm` at 6d7a0f8, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
|
|
5
|
+
`CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK`, and its on-chain IDL matches that commit. The port is
|
|
6
|
+
[`examples/raydium-clmm/`](https://github.com/typesol/typesol/blob/main/examples/raydium-clmm). As with
|
|
7
|
+
[Raydium CP-Swap](case-study-raydium-cp-swap.md), it is checked against the binary that runs on mainnet, not a rebuild.
|
|
8
|
+
|
|
9
|
+
## What is ported
|
|
10
|
+
|
|
11
|
+
The port covers 8 of the original's 37 instructions, the ones a pool lives on:
|
|
12
|
+
|
|
13
|
+
- `create_amm_config` and `create_pool`;
|
|
14
|
+
- `open_position_with_token22_nft`, `increase_liquidity_v2` and `decrease_liquidity_v2`;
|
|
15
|
+
- `swap_v2`;
|
|
16
|
+
- `collect_protocol_fee` and `collect_fund_fee`.
|
|
17
|
+
|
|
18
|
+
The files follow the original's modules:
|
|
19
|
+
|
|
20
|
+
| File | From | What |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| `math.ts` | `libraries/` | tick math, sqrt-price math, liquidity and token deltas, the swap step, in u128 and u256 |
|
|
23
|
+
| `state.ts` | `states/` | every account and event, byte for byte |
|
|
24
|
+
| `liquidity.ts` | `states/tick_array.rs`, `pool.rs`, `personal_position.rs`, `instructions/open_position.rs`, … | tick arrays, the tick array bitmap and its extension, rewards, positions' fees and rewards |
|
|
25
|
+
| `swap.ts` | `instructions/swap.rs`, `states/pool_fee.rs`, `states/oracle.rs` | fee splitting, the dynamic fee, limit orders met during a swap, the bitmap searches, the oracle |
|
|
26
|
+
| `raydium_clmm.ts` | `instructions/` | the 8 instructions |
|
|
27
|
+
|
|
28
|
+
The port keeps the original's account layouts:
|
|
29
|
+
|
|
30
|
+
- `PoolState`, `TickArrayState`, `TickArrayBitmapExtension` and `ObservationState` are zero-copy
|
|
31
|
+
`#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
|
|
32
|
+
- `AmmConfig`, `PersonalPositionState` and `ProtocolPositionState` are Borsh accounts with only fixed-size fields, so
|
|
33
|
+
their bytes are the same layout.
|
|
34
|
+
|
|
35
|
+
It also keeps the original's names, argument order and error codes, and emits the same events. The IDL it produces
|
|
36
|
+
matches the on-chain IDL for these instructions: accounts, flags, addresses, PDA seeds, arguments and discriminators.
|
|
37
|
+
|
|
38
|
+
A swap works the same on any pool the original runs, including features whose own instructions are not ported:
|
|
39
|
+
|
|
40
|
+
- the dynamic fee (a pool with a `DynamicFeeInfo`: one tick spacing group at a time, the volatility accumulator, decay);
|
|
41
|
+
- limit orders resting on a tick, filled as the price crosses it;
|
|
42
|
+
- reward streams accruing, and fee modes that take the fee in token 0 only or token 1 only.
|
|
43
|
+
|
|
44
|
+
These are not ported yet:
|
|
45
|
+
|
|
46
|
+
- **The v1 instructions** (`open_position`, `open_position_v2` with a Metaplex NFT, `increase_liquidity`,
|
|
47
|
+
`decrease_liquidity`, `swap`) and `swap_router_base_in`.
|
|
48
|
+
- **`close_position`** and `close_protocol_position`.
|
|
49
|
+
- **The limit order instructions**: `open_limit_order`, `increase_limit_order`, `decrease_limit_order`,
|
|
50
|
+
`settle_limit_order` and `close_limit_order`.
|
|
51
|
+
- **The reward instructions**: `initialize_reward`, `set_reward_params`, `update_reward_infos`,
|
|
52
|
+
`collect_remaining_rewards` and `transfer_reward_owner`.
|
|
53
|
+
- **The other admin instructions**: `update_amm_config`, `update_pool_status`, the operation account and dynamic-fee
|
|
54
|
+
config instructions, `create_customizable_pool` (v1 and v2), the support-mint instructions and
|
|
55
|
+
`collect_excess_lamports`.
|
|
56
|
+
|
|
57
|
+
## What it needed
|
|
58
|
+
|
|
59
|
+
The math needed a 256-bit integer. `u256` is a computation-only type (locals, helpers, never stored or sent). It has
|
|
60
|
+
the checked operators, and `mulDiv` / `mulDivCeil` through a 512-bit product. A fuzzer checks every operator against
|
|
61
|
+
BigInt (`test/verification/fuzz-u256.test.ts`).
|
|
62
|
+
|
|
63
|
+
The positions needed:
|
|
64
|
+
|
|
65
|
+
- **Big-endian seeds.** Tick arrays are at `["tick_array", pool, start_index.to_be_bytes()]`. TypeSOL now has
|
|
66
|
+
`"@start:be"` in `Seeds<…>` and `bigEndian(start)` in seed lists. The IDL records the argument without the byte order,
|
|
67
|
+
as Anchor's does.
|
|
68
|
+
- **Accounts loaded in the body.** A tick array may not exist yet, so the original takes it as an `UncheckedAccount`,
|
|
69
|
+
creates it if needed, then loads it. `loadAccount` / `loadAccountMut` now take an `AccountInfo` parameter. The loaded
|
|
70
|
+
struct is also its account (`.key`, `.lamports`), and it can be passed to helpers that take `Mut<T>`.
|
|
71
|
+
- **One account as two parameters.** A position whose ticks are in one array passes that array twice. `Dup<…>` lets
|
|
72
|
+
both be loaded; a write through one is seen through the other, as in the original.
|
|
73
|
+
- **A seed list picked at run time**, `cond ? signer([…]) : signer([…])`. A pool signs with its seed index if it has one.
|
|
74
|
+
- **`mintTo` and `freezeAccount` on a token account the instruction created**, for the position NFT.
|
|
75
|
+
|
|
76
|
+
Tests for these are in `test/language/loaded-accounts.test.ts`.
|
|
77
|
+
|
|
78
|
+
The swap loop needed nothing new. It is one instruction body:
|
|
79
|
+
|
|
80
|
+
- tick arrays are loaded from the remaining accounts one at a time, as the swap reaches them;
|
|
81
|
+
- the swap state is a struct a helper returns, updated in place;
|
|
82
|
+
- `apply_swap_amounts` is a local closure.
|
|
83
|
+
|
|
84
|
+
## How it was checked
|
|
85
|
+
|
|
86
|
+
[`test/examples/raydium-clmm.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-clmm.test.ts)
|
|
87
|
+
loads the binary dumped from mainnet on 2026-10-30 (sha256 in
|
|
88
|
+
[`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one LiteSVM
|
|
89
|
+
and the port into another. Both use the same program id and the same clock.
|
|
90
|
+
|
|
91
|
+
**Setup.**
|
|
92
|
+
|
|
93
|
+
- Mints and token accounts are made by the same token-program instructions in both.
|
|
94
|
+
- `AmmConfig` accounts are written in both as the original lays them out, because creating one needs Raydium's admin
|
|
95
|
+
key. The mainnet config of the USDC/CC pool is used as cloned.
|
|
96
|
+
- Where a case needs state the ported instructions cannot make, it is written into the pool or a tick array in both
|
|
97
|
+
VMs. This covers fee growth from earlier swaps, a reward stream, a dynamic fee, limit orders on a tick and the pool
|
|
98
|
+
status bits.
|
|
99
|
+
|
|
100
|
+
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
101
|
+
code), the same lamports, owner and data for every account involved, and the same events byte for byte.
|
|
102
|
+
|
|
103
|
+
There are 166 transactions:
|
|
104
|
+
|
|
105
|
+
- **Configs and pools.** SPL Token and Token-2022 transfer-fee pools, the mainnet config, a pre-funded vault, and the
|
|
106
|
+
refusals: mints out of order, a vault that is not the PDA, a price out of range, an open time ahead, the wrong
|
|
107
|
+
token program, an unsupported extension, a config from anyone but the admin.
|
|
108
|
+
- **Positions.**
|
|
109
|
+
- Positions in range, below and above the price, in one tick array or two, and on the lowest array.
|
|
110
|
+
- Liquidity worked out from amount_0 or amount_1, and NFTs with and without metadata.
|
|
111
|
+
- A tick shared by two positions, and a tick array whose address someone pre-funded.
|
|
112
|
+
- A restricted-asset pool, whose position NFT account ends frozen.
|
|
113
|
+
- Adding and removing liquidity down to an empty position: the counts go back to zero and the bitmap bits clear.
|
|
114
|
+
- Fees owed and a reward stream paid out.
|
|
115
|
+
- Arrays past the pool's own bitmap, on both sides, and a missing or wrong extension.
|
|
116
|
+
- The pool status bits.
|
|
117
|
+
- Refusals: slippage, tick order and spacing, wrong arrays, another owner's NFT.
|
|
118
|
+
- **Swaps.**
|
|
119
|
+
- Both directions, by input and by output, across ticks and tick arrays, to a price limit.
|
|
120
|
+
- Fees taken in token 0 only or token 1 only, then protocol and fund fees collected.
|
|
121
|
+
- A dynamic fee across its filter and decay periods; limit orders filled at a tick while a reward stream accrues, and
|
|
122
|
+
orders alone on a tick filled in full (the tick leaves use, its array counts one less).
|
|
123
|
+
- Into the bitmap extension and back, above and below the pool's own bitmap, and Token-2022 transfer-fee mints both
|
|
124
|
+
ways.
|
|
125
|
+
- The USDC/CC pool as cloned from mainnet: its config, vaults, oracle, extension and two tick arrays.
|
|
126
|
+
- Refusals: slippage both ways, a zero amount, a limit on the wrong side, missing or wrong tick arrays, liquidity
|
|
127
|
+
running out, swapped vaults, swaps disabled.
|
|
128
|
+
|
|
129
|
+
## Cost
|
|
130
|
+
|
|
131
|
+
Compute units per transaction, mainnet original against the port, from one run of that test:
|
|
132
|
+
|
|
133
|
+
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
134
|
+
| --- | ---: | ---: | ---: |
|
|
135
|
+
| `create_pool` | 67,818 | 26,935 | −60% |
|
|
136
|
+
| `open_position_with_token22_nft`, in range | 126,375 | 66,015 | −48% |
|
|
137
|
+
| `open_position_with_token22_nft`, Token-2022 transfer fee | 117,706 | 67,592 | −43% |
|
|
138
|
+
| `increase_liquidity_v2` | 39,759 | 15,018 | −62% |
|
|
139
|
+
| `decrease_liquidity_v2` | 40,615 | 17,263 | −57% |
|
|
140
|
+
| `decrease_liquidity_v2`, with a reward paid | 67,766 | 20,683 | −69% |
|
|
141
|
+
| `swap_v2` | 49,023 | 22,504 | −54% |
|
|
142
|
+
| `swap_v2`, across tick arrays | 55,837 | 28,161 | −50% |
|
|
143
|
+
| `swap_v2`, dynamic fee | 58,924 | 30,585 | −48% |
|
|
144
|
+
| `swap_v2`, through limit orders | 74,417 | 36,995 | −50% |
|
|
145
|
+
| `swap_v2`, into the bitmap extension | 78,605 | 44,428 | −43% |
|
|
146
|
+
| `swap_v2`, Token-2022 transfer fee | 47,742 | 23,919 | −50% |
|
|
147
|
+
| `swap_v2`, the mainnet USDC/CC pool | 52,708 | 26,881 | −49% |
|
|
148
|
+
| `collect_protocol_fee` | 13,626 | 2,353 | −83% |
|
|
149
|
+
|
|
150
|
+
Opening a position is mostly the token programs' and the System Program's work: the NFT mint, its metadata, the
|
|
151
|
+
associated token account and the transfers. That work costs the same in both. Pool and position creation also vary
|
|
152
|
+
from run to run with the PDA bump searches of the random keys the test uses, in both programs alike. Refusals cost far
|
|
153
|
+
less; a swap of nothing costs 16,665 against 1,644.
|
|
154
|
+
|
|
155
|
+
On size, the port's binary is 277,784 bytes and the deployed original 1,700,160 bytes. The original also contains the
|
|
156
|
+
29 instructions not ported here, so the ratio overstates the gain for the same feature set.
|
|
157
|
+
|
|
158
|
+
## Where they differ
|
|
159
|
+
|
|
160
|
+
- **Panics.** Where the original panics (an index out of range, an overflow under `overflow-checks`), it fails with
|
|
161
|
+
`ProgramFailedToComplete`; the port fails with a numbered error. For example, a position past the pool's own bitmap
|
|
162
|
+
opened without the extension account: the original reads `remaining_accounts[0]` of none, the port fails with 5104.
|
|
163
|
+
The test checks only that both fail there.
|
|
164
|
+
- **Check order on double faults.** Anchor creates `personal_position` (its `init`) before it checks the token
|
|
165
|
+
accounts after it; the port checks every account first and creates the position at the start of the body. A
|
|
166
|
+
transaction breaking one check gets the same code. One that breaks two at once can be reported differently.
|
|
167
|
+
- **Duplicate tick arrays in a swap.** The original loads every tick array it is given before it starts, so one passed
|
|
168
|
+
twice fails at once. The port loads an array when the swap reaches it. Passed twice but never reached, it does
|
|
169
|
+
not fail.
|
|
170
|
+
- **Two limit-order fills that empty extension arrays in one swap.** Each needs the extension writable. The port loads
|
|
171
|
+
it for each such flip, and a second load in one instruction is refused (2040). Only limit orders can empty an array
|
|
172
|
+
during a swap, and their instructions are not ported.
|
|
173
|
+
- **Logs.** The original's `msg!` lines in these paths (`exact_swap_internal, …`, the dynamic fee's `state.tick:…`,
|
|
174
|
+
`collect reward index: …`) are logged the same. Error messages are TypeSOL's; codes and events are the original's.
|
|
175
|
+
- **Clients and big-endian seeds.** The IDL records tick array seeds as Anchor does, without the byte order, so a client
|
|
176
|
+
that derives them from the IDL alone gets them wrong (with either program). Pass tick arrays explicitly.
|
package/docs/language.md
CHANGED
|
@@ -8,8 +8,8 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| Instruction | an exported function returning `void`, one integer / boolean / `Pubkey`, a `string` (a Borsh String), or a fixed-size struct (sent as return data, at most 1024 bytes; `returns` in the IDL, and the generated client decodes it) |
|
|
10
10
|
| Account data | an exported `interface` with fixed-size fields; interfaces nest (`home: Point`, `trail: FixedArray<Point, 4>`) |
|
|
11
|
-
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits) |
|
|
12
|
-
| Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
|
|
11
|
+
| Integers | `u8` `u16` `u32` `u64` `u128` `i8` `i16` `i32` `i64` `i128` — bigint literals (`1n`), every `+ - * / % **` (and `+=` … `**=`) checked (`**` aborts on a negative exponent, as JS throws); `& \| ^` on equal types, `~` within the width, `<<` / `>>` checked (amount below the width, `<<` may not lose bits). `u256` is for computation (sqrt-price and liquidity math): locals, helper parameters and results, the same checked operators and comparisons, `u256(x)` from any unsigned value and `u128(x)` / `u64(x)` back (4102 when it does not fit); never in account data, arguments, events, return data or CPI data (the IDL has no 256-bit integer), and logged only when it fits in 128 bits |
|
|
12
|
+
| Integer helpers | `mulDiv(a, b, c)` / `mulDivCeil` (u64 through a 128-bit product, u128 through a 256-bit one, u256 through a 512-bit one), `isqrt(x)` (up to u128), `min(a, b)`, `max(a, b)` |
|
|
13
13
|
| Other scalars | `boolean`, `Pubkey` (compare with `===` or `.equals`) |
|
|
14
14
|
| Errors | `export enum MyError { Name = "message" }` + `require(cond, MyError.Name)` → codes 6000+; `require(cond, "message")` makes an error of its own (`RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL); `require(cond, AnchorError.RequireKeysEqViolated)` fails with one of Anchor's own codes (2502 here; any anchor-lang `ErrorCode` can be raised this way). See [errors.md](errors.md) |
|
|
15
15
|
| Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit. A cast is a value: import `u64`, not `type u64` (one import serves as both) |
|
|
@@ -29,7 +29,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
29
29
|
| Fixed-capacity lists | `owners: FixedVec<Pubkey, 8>` — any field, any number of them, in nested structs too: a u32 length and room for N elements (always 4 + N × size bytes), the same `get`, `set`, `push(v)`, `pop()`, `clear()`, `.length` and `for … of`; `push` on a full one fails (5104); `acct.owners = fixedVec([a, b])` writes a whole one (unused slots zeroed), and `acct.owners = owners` copies a `Vec` argument (or another list of the same elements) into it, Anchor's `multisig.owners = owners` (more than N fail with 5104). In account data, returned structs and events; as an argument (`ids: FixedVec<u64, 8>`) it is a Borsh Vec of at most N elements, read like a `Vec` argument (more fail with 102) |
|
|
30
30
|
| Struct arguments | `order: Order`, `ids: FixedArray<u8, 4>`, `orders: Vec<Order>` — fixed layouts, Borsh-identical, validated on entry (bools, enums, option tags, string lengths, enum tags; 102) and read-only. A struct holding a FixedVec that is only ever an argument is read as Anchor sends it (its FixedVec a Borsh Vec, as `@layout borsh`) |
|
|
31
31
|
| Accounts created by hand | `systemProgram.createAccount(…)`, or `allocate(account, space, seeds?)` + `assign(account, owner, seeds?)` for an address someone pre-funded, then `const data = initAccount<T>(account)` (Anchor's `load_init`: owned by this program 3007, writable 3006, large enough 3003, no discriminator yet 3000) gives the struct to fill: for accounts whose address is decided at run time (a PDA or a signing keypair), as Raydium's pools are. `Init<T>` covers the usual case |
|
|
32
|
-
| Remaining accounts | `remainingAccounts()` — `.length`, `.get(i)` → `key`, `owner`, `lamports` (writes check writability), `isSigner`, `isWritable`; `loadAccount<T>` / `loadAccountMut<T>` give checked struct views; pass them to `invoke`, one at a time or spread: `...remainingAccounts()` (each with the flags it was passed with), `...readonly(rest)` / `...writable(rest)` (all with that role), `rest.slice(a, b)` for part of them; a CPI lists at most as many accounts as an instruction takes (5113) |
|
|
32
|
+
| Remaining accounts | `remainingAccounts()` — `.length`, `.get(i)` → `key`, `owner`, `lamports` (writes check writability), `isSigner`, `isWritable`; `loadAccount<T>` / `loadAccountMut<T>` give checked struct views (also of an `AccountInfo` parameter, Anchor's `AccountLoader::try_from` on an `UncheckedAccount`; the view is also its account: `.key`, `.lamports`, and it passes to a helper taking `Account<T>` / `Mut<T>`); pass them to `invoke`, one at a time or spread: `...remainingAccounts()` (each with the flags it was passed with), `...readonly(rest)` / `...writable(rest)` (all with that role), `rest.slice(a, b)` for part of them; a CPI lists at most as many accounts as an instruction takes (5113) |
|
|
33
33
|
| Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
|
|
34
34
|
| Struct references | `const o = side === Side.Bid ? book.bids.get(i) : book.asks.get(i)` — aliases account data like a JS object reference (no copy); replacing the referenced place (`book.bids.set(i, …)`, `pop()`, `clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JS would keep the old object |
|
|
35
35
|
| Other programs' accounts | `const pool = loadForeign<Pool>(account, AMM_PROGRAM)` — owner, `account:Pool` discriminator and size checked (3007 / 3002 / 3003); `readData<u64>(account, offset)` for raw little-endian reads (bounds-checked, 3003) |
|
|
@@ -71,7 +71,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
71
71
|
| `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL |
|
|
72
72
|
| Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it to `pFeesVault`); a group may not be optional or a helper parameter. An instruction with a group checks in Anchor's order: its arguments first (102), then each account in order, a group's constraints right after the group's accounts (as a composite's `try_accounts` does), the other constraints last |
|
|
73
73
|
| `constraint(acct, condition, error?)` | Anchor's `constraint = condition @ error` on `acct`: statements at the very start of the body, run with that account's checks (after its `has_one`, before the next account), so a transaction breaking several checks gets Anchor's code; they read accounts and arguments; the default error is ConstraintRaw (2003) |
|
|
74
|
-
| `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes, `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
|
|
74
|
+
| `HasOne<A, "owner">`, `Seeds<A, ["vault", "@owner"], "bump">`, `CloseTo<A, "owner">` | declarative constraints like Anchor's `has_one`, `seeds`/`bump` and `close`: checked before the body (2001 / 2006), close runs when the instruction succeeds; `"@name"` = account key or argument bytes (`"@name:be"`: an integer's bytes most significant first, Rust's `to_be_bytes()`; the IDL records the argument, as Anchor's does, so clients that derive the address from the IDL get it wrong: pass such accounts explicitly), `"@acct.field"` = a Pubkey, integer or unit enum field of a struct account parameter (also the account's own: `["offer", "@maker", "@offer.id"]`), other strings are literals; recorded as `relations` / `pda` in the IDL. a bump stored in another struct account is named `"@acct.field"` (Anchor `bump = multisig.nonce`); `acct.pdaBump` is the bump (Anchor `ctx.bumps.acct`): the stored field when one is named, else the canonical bump the check found — use it to sign as the PDA |
|
|
75
75
|
| `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
|
|
76
76
|
| `HasOne<TokenAccount, "mint" \| "owner">`, `HasOne<Mint, "mintAuthority" \| "freezeAuthority">` | token constraints (2014 / 2015 / 2016 / 2017) against the parameter with that name; `TokenOf<TokenAccount, "mintParam", "authorityParam", "tokenProgramParam">` / `MintOf<Mint, "authorityParam", "freezeParam", "tokenProgramParam">` name the parameters, as Anchor's `token::mint = …` / `mint::authority = …` / `…::token_program = …` do (`never` leaves one out; the token program one: owned by that token program, 2021 / 2022) |
|
|
77
77
|
| `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
|
|
@@ -110,7 +110,9 @@ account written through `.lamports` or `loadAccountMut` is another account of th
|
|
|
110
110
|
a close destination or `@layout borsh`): a write through either is seen through the other, so read what you need
|
|
111
111
|
before writing. A remaining account
|
|
112
112
|
can be loaded with `loadAccountMut` once per instruction: loading the same one again (`rest.get(i)` and `rest.get(j)`
|
|
113
|
-
with `i == j`) is refused with 2040 too, since the two views would alias.
|
|
113
|
+
with `i == j`) is refused with 2040 too, since the two views would alias. So is a second `loadAccountMut` of one
|
|
114
|
+
`AccountInfo` parameter; two `Dup<…>` parameters that are one account may each be loaded (one array holding both ticks
|
|
115
|
+
of a position, as Raydium CLMM's tick arrays).
|
|
114
116
|
|
|
115
117
|
## Built-ins
|
|
116
118
|
|
|
@@ -163,7 +165,9 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
|
|
|
163
165
|
- `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
|
|
164
166
|
lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
|
|
165
167
|
- A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
|
|
166
|
-
wherever signerSeeds go.
|
|
168
|
+
wherever signerSeeds go. One of two lists picked at run time: `const pool = indexed ? signer([…, index, bump]) :
|
|
169
|
+
signer([…, bump])`.
|
|
170
|
+
- `bigEndian(x)` in a seed list: an integer's bytes most significant first (`["tick_array", pool.key, bigEndian(start)]`).
|
|
167
171
|
- After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
|
|
168
172
|
A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans, Pubkeys,
|
|
169
173
|
unit enums and arrays is read as its bytes (bools and enums checked); a struct with Options, strings or Vecs is
|
package/lib/typesol.d.ts
CHANGED
|
@@ -19,6 +19,12 @@ export type u16 = bigint;
|
|
|
19
19
|
export type u32 = bigint;
|
|
20
20
|
export type u64 = bigint;
|
|
21
21
|
export type u128 = bigint;
|
|
22
|
+
/**
|
|
23
|
+
* 256-bit unsigned integers for computation (sqrt-price and liquidity math): locals, helper parameters and results,
|
|
24
|
+
* `u256(x)` and back with `u128(x)` / `u64(x)` (checked). Not in account data, arguments, events or return data
|
|
25
|
+
* (the IDL has no 256-bit integer).
|
|
26
|
+
*/
|
|
27
|
+
export type u256 = bigint;
|
|
22
28
|
export type i8 = bigint;
|
|
23
29
|
export type i16 = bigint;
|
|
24
30
|
export type i32 = bigint;
|
|
@@ -168,12 +174,14 @@ export interface RemainingSlice extends Iterable<CpiAccount> {
|
|
|
168
174
|
export declare function remainingAccounts(): RemainingAccounts;
|
|
169
175
|
|
|
170
176
|
/**
|
|
171
|
-
* Read a struct of this program from a remaining account
|
|
177
|
+
* Read a struct of this program from a remaining account or an `AccountInfo` parameter (Anchor's
|
|
178
|
+
* `AccountLoader::try_from` on an `UncheckedAccount`): owner, discriminator and size are checked.
|
|
172
179
|
* `loadAccountMut` also requires it to be writable, not aliased by another writable account, and not already loaded
|
|
173
|
-
* with `loadAccountMut` in this instruction (2040).
|
|
180
|
+
* with `loadAccountMut` in this instruction (2040). The result is also the account (`.key`, `.lamports`), and passes
|
|
181
|
+
* to a helper that takes `Account<T>` / `Mut<T>`.
|
|
174
182
|
*/
|
|
175
|
-
export declare function loadAccount<T>(account: RemainingAccount):
|
|
176
|
-
export declare function loadAccountMut<T>(account: RemainingAccount): T
|
|
183
|
+
export declare function loadAccount<T>(account: RemainingAccount | AccountInfo): Account<T>;
|
|
184
|
+
export declare function loadAccountMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
|
|
177
185
|
|
|
178
186
|
/** 32 bytes of hash output (sha256 / keccak256, Merkle roots). Compare with `===`. */
|
|
179
187
|
export interface Hash {
|
|
@@ -535,6 +543,11 @@ export interface TokenMetadataProgram extends AccountMeta {
|
|
|
535
543
|
/** The Metaplex master edition address of a mint (PDA ["metadata", program, mint, "edition"]). */
|
|
536
544
|
export declare function masterEditionAddress(mint: Pubkey): Pubkey;
|
|
537
545
|
/** The canonical program address of `seeds` under `program` (Rust `Pubkey::find_program_address(seeds, program).0`). */
|
|
546
|
+
/**
|
|
547
|
+
* An integer seed with its bytes most significant first (Rust's `x.to_be_bytes()`), inside a seeds list:
|
|
548
|
+
* `["tick_array", pool.key, bigEndian(startIndex)]`. In `Seeds<…>` write `"@startIndex:be"`.
|
|
549
|
+
*/
|
|
550
|
+
export declare function bigEndian(value: bigint): Seed;
|
|
538
551
|
export declare function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey;
|
|
539
552
|
/** The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. */
|
|
540
553
|
export declare function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8;
|
|
@@ -1631,7 +1644,8 @@ interface TokenOps {
|
|
|
1631
1644
|
transfer(from: TokenAccount, to: TokenAccount, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1632
1645
|
transferChecked(from: TokenAccount, mint: Mint, to: TokenAccount, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1633
1646
|
/** `mint`: a Mut<Mint>, or a mint this instruction created and initialized (Mut<Signer> / Mut<AccountInfo>). */
|
|
1634
|
-
|
|
1647
|
+
/** `to`: a Mut<TokenAccount>, or a Mut<AccountInfo> token account this instruction created (e.g. with `ata.create`). */
|
|
1648
|
+
mintTo(mint: Mint | AccountMeta, to: TokenAccount | AccountInfo, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1635
1649
|
burn(from: TokenAccount, mint: Mint, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1636
1650
|
/** Close a token account (empty), or under Token-2022 a mint with no supply left (its MintCloseAuthority signs). */
|
|
1637
1651
|
closeAccount(account: TokenAccount | Mint, destination: AccountMeta, authority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
@@ -1644,7 +1658,8 @@ interface TokenOps {
|
|
|
1644
1658
|
burnChecked(from: TokenAccount, mint: Mint, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1645
1659
|
/** Change or remove (null) an authority of a mint or token account: `AuthorityType.MintTokens`, …. */
|
|
1646
1660
|
setAuthority(target: AccountMeta, currentAuthority: AccountMeta, authorityType: u8, newAuthority: Pubkey | null, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1647
|
-
|
|
1661
|
+
/** `account`: a Mut<TokenAccount>, or (freezeAccount) a Mut<AccountInfo> token account this instruction created. */
|
|
1662
|
+
freezeAccount(account: TokenAccount | AccountInfo, mint: AccountMeta, freezeAuthority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1648
1663
|
thawAccount(account: TokenAccount, mint: AccountMeta, freezeAuthority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1649
1664
|
/** Update a wrapped-SOL account's amount after lamports were sent to it. */
|
|
1650
1665
|
syncNative(account: TokenAccount): void;
|
|
@@ -2009,12 +2024,13 @@ export declare function u32(value: bigint): u32;
|
|
|
2009
2024
|
export declare function u64(value: bigint): u64;
|
|
2010
2025
|
export declare function i64(value: bigint): i64;
|
|
2011
2026
|
export declare function u128(value: bigint): u128;
|
|
2027
|
+
export declare function u256(value: bigint): u256;
|
|
2012
2028
|
export declare function i8(value: bigint): i8;
|
|
2013
2029
|
export declare function i16(value: bigint): i16;
|
|
2014
2030
|
export declare function i32(value: bigint): i32;
|
|
2015
2031
|
export declare function i128(value: bigint): i128;
|
|
2016
2032
|
|
|
2017
|
-
/** floor(a * b / c) with a double-width intermediate (all u64, or all
|
|
2033
|
+
/** floor(a * b / c) with a double-width intermediate (all u64, all u128, or all u256); aborts if c is 0 or the result does not fit. */
|
|
2018
2034
|
export declare function mulDiv(a: u64, b: u64, c: u64): u64;
|
|
2019
2035
|
/** ceil(a * b / c), like mulDiv. */
|
|
2020
2036
|
export declare function mulDivCeil(a: u64, b: u64, c: u64): u64;
|
package/package.json
CHANGED
package/runtime/typesol_rt.h
CHANGED
|
@@ -186,6 +186,219 @@ static inline __attribute__((always_inline)) unsigned __int128 ts_rem_u128(unsig
|
|
|
186
186
|
return a % b;
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
/*
|
|
190
|
+
* u256: a computation type (locals, helper parameters and results; never stored), for math such as concentrated
|
|
191
|
+
* liquidity's sqrt-price formulas. Four little-endian 64-bit limbs. Additions, subtractions and comparisons work on
|
|
192
|
+
* the 64-bit limbs; multiplication and division on 32-bit limbs with 64-bit products (SBF has no 128-bit instructions,
|
|
193
|
+
* and the __int128 library routines cost hundreds of CU each). Division is Knuth's algorithm D, as Hacker's Delight
|
|
194
|
+
* writes it (divmnu), also used for mulDiv's 512-bit intermediate.
|
|
195
|
+
*/
|
|
196
|
+
typedef struct {
|
|
197
|
+
uint64_t w[4];
|
|
198
|
+
} TsU256;
|
|
199
|
+
|
|
200
|
+
static inline TsU256 ts_u256_lit(uint64_t a, uint64_t b, uint64_t c, uint64_t d) {
|
|
201
|
+
TsU256 r = {{a, b, c, d}};
|
|
202
|
+
return r;
|
|
203
|
+
}
|
|
204
|
+
static inline TsU256 ts_u256_from_u128(unsigned __int128 v) { return ts_u256_lit((uint64_t)v, (uint64_t)(v >> 64), 0, 0); }
|
|
205
|
+
static inline bool ts_u256_is_zero(TsU256 a) { return (a.w[0] | a.w[1] | a.w[2] | a.w[3]) == 0; }
|
|
206
|
+
static inline int ts_u256_cmp(TsU256 a, TsU256 b) {
|
|
207
|
+
for (int i = 3; i >= 0; i--)
|
|
208
|
+
if (a.w[i] != b.w[i]) return a.w[i] < b.w[i] ? -1 : 1;
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
/* Whether the value fits in `bits` (64 or 128) bits. */
|
|
212
|
+
static inline bool ts_u256_fits(TsU256 a, int bits) { return bits >= 128 ? (a.w[2] | a.w[3]) == 0 : (a.w[1] | a.w[2] | a.w[3]) == 0; }
|
|
213
|
+
static inline unsigned __int128 ts_u256_lo128(TsU256 a) { return ((unsigned __int128)a.w[1] << 64) | a.w[0]; }
|
|
214
|
+
|
|
215
|
+
static inline bool ts_u256_add(TsU256 a, TsU256 b, TsU256 *out) {
|
|
216
|
+
uint64_t carry = 0;
|
|
217
|
+
for (int i = 0; i < 4; i++) {
|
|
218
|
+
uint64_t s = a.w[i] + b.w[i];
|
|
219
|
+
uint64_t c1 = s < a.w[i];
|
|
220
|
+
uint64_t s2 = s + carry;
|
|
221
|
+
carry = c1 | (s2 < s);
|
|
222
|
+
out->w[i] = s2;
|
|
223
|
+
}
|
|
224
|
+
return carry != 0;
|
|
225
|
+
}
|
|
226
|
+
static inline bool ts_u256_sub(TsU256 a, TsU256 b, TsU256 *out) {
|
|
227
|
+
uint64_t borrow = 0;
|
|
228
|
+
for (int i = 0; i < 4; i++) {
|
|
229
|
+
uint64_t d = a.w[i] - b.w[i];
|
|
230
|
+
uint64_t b1 = a.w[i] < b.w[i];
|
|
231
|
+
uint64_t d2 = d - borrow;
|
|
232
|
+
borrow = b1 | (d < borrow);
|
|
233
|
+
out->w[i] = d2;
|
|
234
|
+
}
|
|
235
|
+
return borrow != 0;
|
|
236
|
+
}
|
|
237
|
+
static inline TsU256 ts_u256_bit(TsU256 a, TsU256 b, int op) {
|
|
238
|
+
TsU256 r;
|
|
239
|
+
for (int i = 0; i < 4; i++) r.w[i] = op == 0 ? a.w[i] & b.w[i] : op == 1 ? a.w[i] | b.w[i] : a.w[i] ^ b.w[i];
|
|
240
|
+
return r;
|
|
241
|
+
}
|
|
242
|
+
static inline TsU256 ts_u256_shl(TsU256 a, uint64_t s) {
|
|
243
|
+
TsU256 r = {{0, 0, 0, 0}};
|
|
244
|
+
int limbs = (int)(s / 64), bits = (int)(s % 64);
|
|
245
|
+
for (int i = 3; i >= limbs; i--) {
|
|
246
|
+
r.w[i] = a.w[i - limbs] << bits;
|
|
247
|
+
if (bits && i - limbs - 1 >= 0) r.w[i] |= a.w[i - limbs - 1] >> (64 - bits);
|
|
248
|
+
}
|
|
249
|
+
return r;
|
|
250
|
+
}
|
|
251
|
+
static inline TsU256 ts_u256_shr(TsU256 a, uint64_t s) {
|
|
252
|
+
TsU256 r = {{0, 0, 0, 0}};
|
|
253
|
+
int limbs = (int)(s / 64), bits = (int)(s % 64);
|
|
254
|
+
for (int i = 0; i + limbs < 4; i++) {
|
|
255
|
+
r.w[i] = a.w[i + limbs] >> bits;
|
|
256
|
+
if (bits && i + limbs + 1 < 4) r.w[i] |= a.w[i + limbs + 1] << (64 - bits);
|
|
257
|
+
}
|
|
258
|
+
return r;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
static inline void ts_u256_to32(TsU256 a, uint32_t *x) {
|
|
262
|
+
for (int i = 0; i < 4; i++) {
|
|
263
|
+
x[2 * i] = (uint32_t)a.w[i];
|
|
264
|
+
x[2 * i + 1] = (uint32_t)(a.w[i] >> 32);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
static inline TsU256 ts_u256_from32(const uint32_t *x) {
|
|
268
|
+
TsU256 r;
|
|
269
|
+
for (int i = 0; i < 4; i++) r.w[i] = (uint64_t)x[2 * i] | ((uint64_t)x[2 * i + 1] << 32);
|
|
270
|
+
return r;
|
|
271
|
+
}
|
|
272
|
+
/* r[0 .. n+m) = a[0 .. n) * b[0 .. m), 32-bit limbs. */
|
|
273
|
+
static __attribute__((noinline)) void ts_mul32(const uint32_t *a, int n, const uint32_t *b, int m, uint32_t *r) {
|
|
274
|
+
for (int i = 0; i < n + m; i++) r[i] = 0;
|
|
275
|
+
for (int j = 0; j < m; j++) {
|
|
276
|
+
uint64_t k = 0;
|
|
277
|
+
for (int i = 0; i < n; i++) {
|
|
278
|
+
uint64_t t = (uint64_t)a[i] * b[j] + r[i + j] + k;
|
|
279
|
+
r[i + j] = (uint32_t)t;
|
|
280
|
+
k = t >> 32;
|
|
281
|
+
}
|
|
282
|
+
r[j + n] = (uint32_t)k;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/*
|
|
286
|
+
* Knuth's algorithm D (Hacker's Delight, divmnu): q[0 .. m-n] = u / v and r[0 .. n) = u % v for an m-limb u and an
|
|
287
|
+
* n-limb v whose top limb is not zero, m >= n, 32-bit limbs, m <= 16.
|
|
288
|
+
*/
|
|
289
|
+
static __attribute__((noinline)) void ts_divmnu(uint32_t *q, uint32_t *r, const uint32_t *u, const uint32_t *v, int m, int n) {
|
|
290
|
+
const uint64_t b = 4294967296ULL;
|
|
291
|
+
if (n == 1) {
|
|
292
|
+
uint64_t k = 0;
|
|
293
|
+
for (int j = m - 1; j >= 0; j--) {
|
|
294
|
+
uint64_t cur = (k << 32) | u[j];
|
|
295
|
+
q[j] = (uint32_t)(cur / v[0]);
|
|
296
|
+
k = cur - (uint64_t)q[j] * v[0];
|
|
297
|
+
}
|
|
298
|
+
r[0] = (uint32_t)k;
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
uint32_t vn[8], un[17];
|
|
302
|
+
int s = __builtin_clz(v[n - 1]);
|
|
303
|
+
for (int i = n - 1; i > 0; i--) vn[i] = (v[i] << s) | (s ? v[i - 1] >> (32 - s) : 0);
|
|
304
|
+
vn[0] = v[0] << s;
|
|
305
|
+
un[m] = s ? u[m - 1] >> (32 - s) : 0;
|
|
306
|
+
for (int i = m - 1; i > 0; i--) un[i] = (u[i] << s) | (s ? u[i - 1] >> (32 - s) : 0);
|
|
307
|
+
un[0] = u[0] << s;
|
|
308
|
+
for (int j = m - n; j >= 0; j--) {
|
|
309
|
+
uint64_t num = ((uint64_t)un[j + n] << 32) | un[j + n - 1];
|
|
310
|
+
uint64_t qhat = num / vn[n - 1];
|
|
311
|
+
uint64_t rhat = num - qhat * vn[n - 1];
|
|
312
|
+
while (qhat >= b || qhat * vn[n - 2] > ((rhat << 32) | un[j + n - 2])) {
|
|
313
|
+
qhat--;
|
|
314
|
+
rhat += vn[n - 1];
|
|
315
|
+
if (rhat >= b) break;
|
|
316
|
+
}
|
|
317
|
+
int64_t t;
|
|
318
|
+
int64_t k = 0;
|
|
319
|
+
for (int i = 0; i < n; i++) {
|
|
320
|
+
uint64_t p = qhat * vn[i];
|
|
321
|
+
t = (int64_t)un[i + j] - k - (int64_t)(p & 0xFFFFFFFFULL);
|
|
322
|
+
un[i + j] = (uint32_t)t;
|
|
323
|
+
k = (int64_t)(p >> 32) - (t >> 32);
|
|
324
|
+
}
|
|
325
|
+
t = (int64_t)un[j + n] - k;
|
|
326
|
+
un[j + n] = (uint32_t)t;
|
|
327
|
+
q[j] = (uint32_t)qhat;
|
|
328
|
+
if (t < 0) {
|
|
329
|
+
q[j]--;
|
|
330
|
+
uint64_t c = 0;
|
|
331
|
+
for (int i = 0; i < n; i++) {
|
|
332
|
+
uint64_t sum = (uint64_t)un[i + j] + vn[i] + c;
|
|
333
|
+
un[i + j] = (uint32_t)sum;
|
|
334
|
+
c = sum >> 32;
|
|
335
|
+
}
|
|
336
|
+
un[j + n] += (uint32_t)c;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
for (int i = 0; i < n; i++) r[i] = (un[i] >> s) | (s ? un[i + 1] << (32 - s) : 0);
|
|
340
|
+
}
|
|
341
|
+
static inline int ts_len32(const uint32_t *x, int n) {
|
|
342
|
+
while (n > 0 && x[n - 1] == 0) n--;
|
|
343
|
+
return n;
|
|
344
|
+
}
|
|
345
|
+
/* u / v (div) or u % v (!div), for an m-limb u (up to 16 limbs) and a 256-bit v, not zero. */
|
|
346
|
+
static __attribute__((noinline)) void ts_divmod32(const uint32_t *u, int mmax, TsU256 v, uint32_t *q, TsU256 *rem) {
|
|
347
|
+
uint32_t vv[8], r[8] = {0};
|
|
348
|
+
ts_u256_to32(v, vv);
|
|
349
|
+
int n = ts_len32(vv, 8), m = ts_len32(u, mmax);
|
|
350
|
+
for (int i = 0; i < mmax; i++) q[i] = 0;
|
|
351
|
+
if (m < n) {
|
|
352
|
+
for (int i = 0; i < 8 && i < mmax; i++) r[i] = u[i];
|
|
353
|
+
} else {
|
|
354
|
+
ts_divmnu(q, r, u, vv, m, n);
|
|
355
|
+
}
|
|
356
|
+
if (rem) *rem = ts_u256_from32(r);
|
|
357
|
+
}
|
|
358
|
+
static inline bool ts_u256_mul(TsU256 a, TsU256 b, TsU256 *out) {
|
|
359
|
+
if (ts_u256_fits(a, 128) && ts_u256_fits(b, 128) && ((a.w[1] | b.w[1]) == 0)) {
|
|
360
|
+
*out = ts_u256_from_u128((unsigned __int128)a.w[0] * b.w[0]);
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
uint32_t x[8], y[8], r[16];
|
|
364
|
+
ts_u256_to32(a, x);
|
|
365
|
+
ts_u256_to32(b, y);
|
|
366
|
+
ts_mul32(x, 8, y, 8, r);
|
|
367
|
+
*out = ts_u256_from32(r);
|
|
368
|
+
for (int i = 8; i < 16; i++)
|
|
369
|
+
if (r[i]) return true;
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
372
|
+
static inline TsU256 ts_u256_divmod(TsU256 a, TsU256 b, bool div) {
|
|
373
|
+
if (ts_u256_fits(a, 128) && ts_u256_fits(b, 128)) {
|
|
374
|
+
unsigned __int128 x = ts_u256_lo128(a), y = ts_u256_lo128(b);
|
|
375
|
+
return ts_u256_from_u128(div ? ts_div_u128(x, y) : ts_rem_u128(x, y));
|
|
376
|
+
}
|
|
377
|
+
uint32_t u[8], q[8];
|
|
378
|
+
TsU256 rem;
|
|
379
|
+
ts_u256_to32(a, u);
|
|
380
|
+
ts_divmod32(u, 8, b, q, &rem);
|
|
381
|
+
return div ? ts_u256_from32(q) : rem;
|
|
382
|
+
}
|
|
383
|
+
/* floor or ceil(a * b / c) with a 512-bit product; false when c is zero or the result needs more than 256 bits. */
|
|
384
|
+
static __attribute__((noinline)) bool ts_u256_muldiv(TsU256 a, TsU256 b, TsU256 c, bool ceil, TsU256 *out) {
|
|
385
|
+
if (ts_u256_is_zero(c)) return false;
|
|
386
|
+
uint32_t x[8], y[8], p[16], q[16];
|
|
387
|
+
ts_u256_to32(a, x);
|
|
388
|
+
ts_u256_to32(b, y);
|
|
389
|
+
ts_mul32(x, 8, y, 8, p);
|
|
390
|
+
TsU256 rem;
|
|
391
|
+
ts_divmod32(p, 16, c, q, &rem);
|
|
392
|
+
for (int i = 8; i < 16; i++)
|
|
393
|
+
if (q[i]) return false;
|
|
394
|
+
*out = ts_u256_from32(q);
|
|
395
|
+
if (ceil && !ts_u256_is_zero(rem)) {
|
|
396
|
+
TsU256 one = {{1, 0, 0, 0}};
|
|
397
|
+
if (ts_u256_add(*out, one, out)) return false;
|
|
398
|
+
}
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
|
|
189
402
|
/* ---- Well-known program ids --------------------------------------------- */
|
|
190
403
|
static const SolPubkey TS_SYSTEM_PROGRAM_ID = {{0}};
|
|
191
404
|
/* TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA */
|
|
@@ -531,6 +744,18 @@ static inline uint64_t ts_claim_mut(TsParams *params, const TsAccount *a) {
|
|
|
531
744
|
return SUCCESS;
|
|
532
745
|
}
|
|
533
746
|
|
|
747
|
+
/* loadAccountMut of the account parameter at index `at`: its aliasing was checked on entry, a second load is refused. */
|
|
748
|
+
static inline uint64_t ts_claim_mut_at(TsParams *params, uint64_t at) {
|
|
749
|
+
#if TS_MAX_ACCOUNTS > 64
|
|
750
|
+
if (params->loaded_mut[at >> 6] >> (at & 63) & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
|
|
751
|
+
params->loaded_mut[at >> 6] |= (uint64_t)1 << (at & 63);
|
|
752
|
+
#else
|
|
753
|
+
if (params->loaded_mut >> at & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
|
|
754
|
+
params->loaded_mut |= (uint64_t)1 << at;
|
|
755
|
+
#endif
|
|
756
|
+
return SUCCESS;
|
|
757
|
+
}
|
|
758
|
+
|
|
534
759
|
static inline uint64_t ts_check_address(const TsAccount *a, const SolPubkey *expected) {
|
|
535
760
|
if (!ts_key_eq(&a->key, expected)) TS_FAIL(TS_ERR_WRONG_PROGRAM, "TypeSOL: unexpected program address");
|
|
536
761
|
return SUCCESS;
|