@typesol/cli 0.39.0 → 0.40.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 +46 -0
- package/README.md +22 -19
- package/dist/cli.js +37 -3
- package/dist/compiler/analyze.js +10 -5
- package/dist/compiler/emit/base.d.ts +2 -1
- package/dist/compiler/emit/calls.d.ts +5 -0
- package/dist/compiler/emit/calls.js +165 -4
- package/dist/compiler/emit/expressions.d.ts +6 -0
- package/dist/compiler/emit/expressions.js +95 -2
- package/dist/compiler/emit/program.js +12 -0
- package/dist/compiler/emit/shared.d.ts +10 -0
- package/dist/compiler/emit/statements.d.ts +20 -1
- package/dist/compiler/emit/statements.js +177 -7
- package/dist/compiler/hints.d.ts +5 -0
- package/dist/compiler/hints.js +88 -0
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +6 -1
- package/docs/case-study-marginfi.md +2 -2
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/language.md +27 -7
- package/docs/testing.md +6 -5
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +73 -2
- package/package.json +1 -1
- package/runtime/typesol_rt.h +47 -0
- package/ts-plugin/index.js +24 -1
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Case study: Raydium AMM v4
|
|
2
|
+
|
|
3
|
+
This page ports [Raydium AMM v4](https://github.com/raydium-io/raydium-amm), Raydium's original constant-product AMM,
|
|
4
|
+
from `program/src` at d26944b (Apache-2.0). The port is checked against the binary that runs on mainnet as
|
|
5
|
+
`675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8` (deployed in slot 445763204, dumped in slot 466115597), not a rebuild.
|
|
6
|
+
|
|
7
|
+
Unlike the other ports here, AMM v4 is a native program: no Anchor. Its entrypoint reads a tag byte and the arguments
|
|
8
|
+
after it, takes its accounts by position (a swap accepts 17 or 18 of them, the v2 swaps 8), keeps its accounts as
|
|
9
|
+
`#[repr(C, packed)]` structs with no discriminator, and fails with built-in program errors and panics as often as with
|
|
10
|
+
its own errors. The port keeps all of that.
|
|
11
|
+
|
|
12
|
+
| File | Holds |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| [`raydium_amm.ts`](../showcase/mainnet/raydium-amm/raydium_amm.ts) | the entrypoint (one `@fallback` over `instructionData()` and `remainingAccounts()`), every instruction, the token and system CPIs, the P&L calculation |
|
|
15
|
+
| [`state.ts`](../showcase/mainnet/raydium-amm/state.ts) | AmmInfo (752 bytes), TargetOrders, AmmConfig, Fees, the ray_log records, the 61 errors (codes 0–60) |
|
|
16
|
+
| [`math.ts`](../showcase/mainnet/raydium-amm/math.ts) | decimal normalization, the constant-product amounts, the exchange rates, with the original's panics at their places |
|
|
17
|
+
|
|
18
|
+
## What is ported
|
|
19
|
+
|
|
20
|
+
All of it. The live instructions: Initialize2 (tag 1, both its 19- and 21-account forms), Deposit (3, 11 or 14–15
|
|
21
|
+
accounts, the optional minimum), Withdraw (4, 11 or 20–23 accounts, the optional minimums), SetParams (6: status, state,
|
|
22
|
+
fees, open time), WithdrawPnl (7), SwapBaseIn / SwapBaseOut (9 / 11, 17 or 18 accounts), CreateConfigAccount (14),
|
|
23
|
+
UpdateConfigAccount (15), SwapBaseInV2 / SwapBaseOutV2 (16 / 17, 8 accounts) and WithdrawExcessLamports (18). The
|
|
24
|
+
retired ones (0, 2, 5, 8, 10, 12, 13) panic with `not implemented` at the original's source location, as it does.
|
|
25
|
+
The order book (OpenBook) was removed upstream in July 2026; its accounts are still accepted where the original
|
|
26
|
+
accepts them, and ignored.
|
|
27
|
+
|
|
28
|
+
## What it needed
|
|
29
|
+
|
|
30
|
+
TypeSOL gained what a native program needs (docs/language.md, "Porting a native program"):
|
|
31
|
+
|
|
32
|
+
- `loadRaw<T>` / `loadRawMut<T>`: accounts with no discriminator, read from byte 0. The port makes the original's own
|
|
33
|
+
checks first (owner, an exact size, its error codes), then loads.
|
|
34
|
+
- `instructionData().readU64(offset)` and the other little-endian readers, for the hand-packed arguments (optional
|
|
35
|
+
ones are present when enough bytes follow).
|
|
36
|
+
- Errors from code 0 (returned as Solana's CUSTOM_ZERO, as `ProgramError::Custom(0)` is), `ProgramError.X` for the
|
|
37
|
+
built-in errors (`NotEnoughAccountKeys`, `InvalidInstructionData`, `InsufficientFunds`), `panic(message, location)`
|
|
38
|
+
and `PANIC_ON_OVERFLOW` for `unwrap()` and checked arithmetic, `ERROR_LOG_PREFIX` / `PROGRAM_ERROR_LOG_PREFIX` for the
|
|
39
|
+
entrypoint's "AMM error: …" / "Program error: …" lines.
|
|
40
|
+
- `logBase64` for the ray_log records (bincode of a packed struct, base64), `createProgramAddress` for the authority
|
|
41
|
+
derived from the stored nonce, and `isqrt` of a u256 (the P&L uses U256).
|
|
42
|
+
|
|
43
|
+
## How it is checked
|
|
44
|
+
|
|
45
|
+
`showcase/test/raydium-amm.test.ts` runs the mainnet binary and the port in two LiteSVMs under the same program id
|
|
46
|
+
and clock. Raydium's three fixed keys (its admin, the pool fee destination and the lamports collector) are swapped for
|
|
47
|
+
test keys in both, in the original where its code loads them (lddw immediates) and in the port's source, so the admin
|
|
48
|
+
instructions run too. Every transaction must give the same outcome, the same bytes in every account it touches and
|
|
49
|
+
the same log lines: the ray_log records, the original's messages ("initialize2: …", "withdrawpnl …", mismatch lines),
|
|
50
|
+
the entrypoint's error lines and, for panics, the message and the source location the runtime reports.
|
|
51
|
+
|
|
52
|
+
Covered: pool creation in both forms (open now and later), swaps in both directions, base in and base out, in all three
|
|
53
|
+
account forms; refusals (slippage, more than held, zero, the whole pool out, wrong account counts, short data, a vault
|
|
54
|
+
as the user's account, a wrong token program); deposits on either side with and without the minimum, withdrawals with
|
|
55
|
+
and without minimums, amounts past u64; status, state, fees and open time changes and their refusals; the P&L taken by
|
|
56
|
+
the P&L owner after the pool grew; config creation and updates; the retired tags; excess lamports; and a random mix of
|
|
57
|
+
swaps, deposits and withdrawals (`FUZZ_SEED`, `FUZZ_STEPS`). 484 transactions in all at 400 fuzz steps.
|
|
58
|
+
|
|
59
|
+
## Differences
|
|
60
|
+
|
|
61
|
+
None found in outcomes, account bytes or log lines. Two things are outside what the test compares:
|
|
62
|
+
|
|
63
|
+
- **Compute-unit lines** ("consumed N of M compute units") differ, by design (see below).
|
|
64
|
+
- **Overflow panics the inputs cannot reach.** The original's `checked_*().unwrap()` sites that user input can reach
|
|
65
|
+
(a base-out swap for the whole side or more, an exchange rate past u64, a zero total) panic in the port with the
|
|
66
|
+
original's message and location. Arithmetic that cannot overflow for any input (u64 by u64 products in u128, for
|
|
67
|
+
instance) still panics there under `PANIC_ON_OVERFLOW`, but with an empty location.
|
|
68
|
+
|
|
69
|
+
## Cost
|
|
70
|
+
|
|
71
|
+
| | original | TypeSOL | |
|
|
72
|
+
| --- | ---: | ---: | ---: |
|
|
73
|
+
| swap base in (v2) | 15,222 | 6,597 | 43% |
|
|
74
|
+
| swap base out (v2) | 15,894 | 6,800 | 43% |
|
|
75
|
+
| swap base in (17 accounts) | 16,317 | 6,875 | 42% |
|
|
76
|
+
| deposit | 44,406 | 16,544 | 37% |
|
|
77
|
+
| withdraw | 45,278 | 16,045 | 35% |
|
|
78
|
+
| initialize2 | 107,403 | 62,158 | 58% |
|
|
79
|
+
|
|
80
|
+
The binary is 147,536 bytes against the original's 308,616.
|
package/docs/language.md
CHANGED
|
@@ -49,9 +49,9 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
49
49
|
| Multiple files | `import { Side, min } from "./math"` — structs, enums, constants and helpers can live in other files; only the entry file's exported functions are instructions; names are program-wide, so imports from TypeSOL files cannot be renamed; error codes number imported files first |
|
|
50
50
|
| Loops | `for (let i = 0n; i < n; i++)`, `while`, `do … while`, `for (const x of list)` over a `Vec` or `FixedArray` (each `x` is what `list.get(i)` gives: a value, or a reference into account data for structs; the length is read again every step, as in JS), `break`, `continue` — bounded by the compute budget. Remaining accounts are iterated by index |
|
|
51
51
|
| Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds`, remaining accounts (`RemainingAccount`, or the list: `RemainingAccounts`) and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
|
|
52
|
-
| Arrow functions and closures | `const fee = (x: u64): u64 => x / 100n` (or `const f = function (…) {…}`) at the top level or inside a function. One that reads or writes the enclosing function's variables (a closure: `let total = 0n; const add = (v: u64): void => { total += v; }`) is expanded where it is called: its names mean what they meant where it was declared, struct parameters are references, `return` leaves the closure; it cannot call itself. One that captures nothing becomes a helper. Parameter types may be left out on closures (taken from the arguments). Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called (`const add5 = adder(5n)`, or `adder(5n)(x)`) |
|
|
52
|
+
| Arrow functions and closures | `const fee = (x: u64): u64 => x / 100n` (or `const f = function (…) {…}`) at the top level or inside a function. One that reads or writes the enclosing function's variables (a closure: `let total = 0n; const add = (v: u64): void => { total += v; }`) is expanded where it is called: its names mean what they meant where it was declared, struct parameters are references, `return` leaves the closure; it cannot call itself. One that captures nothing becomes a helper. Parameter types may be left out on closures (taken from the arguments). Functions are values where they can be expanded: `const h = g` names the same function, and a function that returns one (`function adder(n: u64): (x: u64) => u64 { return (x) => x + n; }`) makes a closure where it is called (`const add5 = adder(5n)`, or `adder(5n)(x)`). A function can be chosen at run time between named ones, `const g = k === 1n ? dbl : inc` (the condition is read once, there; a call runs only the chosen one), and a list of named functions can be run in turn, `for (const f of [dbl, inc]) total += f(x)` (unrolled; `continue` and `break` work) |
|
|
53
53
|
| Functions as arguments | a helper may take a function parameter (`function applyTwice(f: (x: u64) => u64, v: u64): u64`): it is compiled once per named function passed (a helper or a local function that captures nothing). An arrow written at the call works too (`applyTwice((x) => x * 3n, v)`: its types come from the parameter) when it reads none of the function's variables. Given a closure (one that reads them), the helper is expanded where it is called instead, like a closure, so it runs where the closure can (its type parameters bound from the call, its accounts the caller's) |
|
|
54
|
-
| List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements), `findIndex` (i64, -1 when absent), `reduce(fn, initial)`, `includes(value)`, `indexOf(value)` (i64), `map` and `filter`. The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference) and may read and write the function's variables. A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop that stores nothing; callbacks after a filter get the index among the elements it let through. Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from; from a `Vec`, give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104). `map` gives integers, booleans, Pubkeys or enums; stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>` annotation it gives structs (`(o) => ({ qty: o.qty })`) or text |
|
|
54
|
+
| List callbacks | on a `Vec`, `FixedArray`, `FixedVec` or `Vec` argument: `forEach`, `some`, `every`, `find` (an Option of the element; scalar elements; on struct elements read a field with `xs.find(f)!.qty`, which aborts with 5108 when nothing matched, or `xs.find(f)?.qty`, an Option), `findIndex` (i64, -1 when absent), `reduce(fn, initial)`, `includes(value)`, `indexOf(value)` (i64), `map` and `filter`. The arrow written at the call is expanded into a loop (elements as `list.get(i)` gives them, structs by reference) and may read and write the function's variables. A `map` / `filter` chain used right away (`xs.filter(f).map(g).reduce(h, 0n)`, `.length`, `for … of`) is one loop that stores nothing; callbacks after a filter get the index among the elements it let through. Stored (`const ys = xs.filter(f)`), it is a FixedVec on the stack as big as the list it starts from; from a `Vec`, give the size: `const ys: FixedVec<u64, 16> = …` (at most 2 KiB; one element more aborts with 5104). `map` gives integers, booleans, Pubkeys or enums; stored with a `FixedVec<Struct, N>` or `FixedVec<FixedString<N>, M>` annotation it gives structs (`(o) => ({ qty: o.qty })`) or text, and inside a chain it gives structs when the callback names its struct, `xs.map((o): Scored => ({ … })).filter(…).reduce(…)` (one struct per element, nothing stored) |
|
|
55
55
|
| Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
|
|
56
56
|
| Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
|
|
57
57
|
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
@@ -212,13 +212,33 @@ When an instruction calls `x.create(payer, seeds)` or `requirePda(x, seeds, bump
|
|
|
212
212
|
an integer literal, an argument, `acct.key` or a scalar field of an account, the IDL entry for `x` gets Anchor `pda.seeds`
|
|
213
213
|
(`const` / `arg` / `account`), so Anchor and Codama clients derive the address themselves.
|
|
214
214
|
|
|
215
|
+
## Porting a native program
|
|
216
|
+
|
|
217
|
+
A program written without Anchor (Raydium AMM v4, SPL programs) reads a tag byte and its arguments itself and takes its
|
|
218
|
+
accounts by position. TypeSOL ports one as it is (see `showcase/mainnet/raydium-amm` and `test/fixtures/native.ts`):
|
|
219
|
+
|
|
220
|
+
- One `/** @fallback */` entry: `const data = instructionData()` gives the bytes, with `data.readU8/U16/U32/U64/U128/
|
|
221
|
+
readPubkey(offset)` (little-endian, bounds-checked: 5104); `remainingAccounts()` gives the accounts by position.
|
|
222
|
+
- Accounts without a discriminator: `loadRaw<T>(acct)` / `loadRawMut<T>(acct)` view one as a fixed-layout struct from
|
|
223
|
+
byte 0 (this program's, 3007; at least the struct's size, 3003; `loadRawMut`: writable, loaded once). Make the
|
|
224
|
+
original's own checks (an exact size, its error codes) before the load. Structs are packed, as `#[repr(C, packed)]`.
|
|
225
|
+
- Errors as the original returns them: an error enum may start at code 0 (`/** @code 0 */`, Rust's
|
|
226
|
+
`ProgramError::Custom(0)`, returned as Solana's CUSTOM_ZERO); `require(c, ProgramError.InvalidInstructionData)` for a
|
|
227
|
+
built-in error; `panic(message, "program/src/lib.rs:12:5")` for a Rust panic (ProgramFailedToComplete, the runtime
|
|
228
|
+
reporting that location); `const PANIC_ON_OVERFLOW = true` makes arithmetic overflow and division by zero panic as
|
|
229
|
+
`checked_*().unwrap()` does instead of failing with 5100 / 5101.
|
|
230
|
+
- Log lines as the original writes them: `const ERROR_LOG_PREFIX = "AMM error: "` and `const PROGRAM_ERROR_LOG_PREFIX =
|
|
231
|
+
"Program error: "` replace the compiler's failure line with the entrypoint's (`msg!("AMM error: {}", e)`);
|
|
232
|
+
`logBase64("ray_log: ", record)` logs a struct's bytes in base64 (a native `bincode` log record);
|
|
233
|
+
`createProgramAddress(seeds, program)` is `Pubkey::create_program_address` (null for no address).
|
|
234
|
+
|
|
215
235
|
## Not supported yet
|
|
216
236
|
|
|
217
|
-
A struct holding a FixedVec that is both an argument and account data (
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
a
|
|
221
|
-
(by design).
|
|
237
|
+
A struct holding a FixedVec that is both an argument and account data (its bytes differ there, and the IDL describes a
|
|
238
|
+
type one way: declare one for each), growing an account by more than 10 KiB in one instruction (Solana's limit: realloc
|
|
239
|
+
again in the next instruction), `?.` and `!` on anything but optional accounts, Options and a `find` on struct elements,
|
|
240
|
+
functions stored in a struct, chosen from a list by index or returned from an instruction, a fused `map` to strings
|
|
241
|
+
(store it, annotated), floating point (by design).
|
|
222
242
|
They are rejected at compile time rather than half-supported.
|
|
223
243
|
|
|
224
244
|
`Init.create` handles a PDA address someone pre-funded: it tops up rent, then allocates and assigns instead of
|
package/docs/testing.md
CHANGED
|
@@ -21,16 +21,17 @@ Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio
|
|
|
21
21
|
|
|
22
22
|
## Reproducing a release
|
|
23
23
|
|
|
24
|
-
From
|
|
25
|
-
`scripts/release-manifest.ts` from the
|
|
24
|
+
From 0.39.0 on, each release's GitHub Release carries its manifest, `typesol-<version>-manifest.json`, attached by
|
|
25
|
+
hand after the npm publish (written by `scripts/release-manifest.ts` from the tag's sources; the scripts need Node 22.18
|
|
26
|
+
or later):
|
|
26
27
|
|
|
27
28
|
- the compiler and toolchain versions (clang, platform-tools, Node, TypeScript, the runtime header's sha256);
|
|
28
29
|
- the sha256 of the SBF binary, IDL and C that every program under `examples/` and `showcase/program-examples/` builds to;
|
|
29
30
|
- the sha256 of the reference binaries the differential tests run against (`test/programs/`);
|
|
30
31
|
- a hash of the test corpus.
|
|
31
32
|
|
|
32
|
-
It also carries the previous release's sources built by the previous package and by this one,
|
|
33
|
-
|
|
33
|
+
It also carries `binary-diff.txt`: the previous release's sources built by the previous package and by this one,
|
|
34
|
+
compared program by program. That is the check behind a changelog line such as "programs that use none of these compile to the
|
|
34
35
|
same binaries". To redo it, or to compare other versions:
|
|
35
36
|
|
|
36
37
|
```sh
|
|
@@ -42,6 +43,6 @@ node scripts/release-manifest.ts --compiler /tmp/b/node_modules/@typesol/cli --s
|
|
|
42
43
|
node scripts/release-manifest.ts --diff a.json b.json
|
|
43
44
|
```
|
|
44
45
|
|
|
45
|
-
For 0.37.0 → 0.38.0 (run by hand before
|
|
46
|
+
For 0.37.0 → 0.38.0 (run by hand before release manifests existed): all 67 programs of the 0.37.0 sources build to
|
|
46
47
|
the same binary and IDL with both packages.
|
|
47
48
|
|
package/docs/troubleshooting.md
CHANGED
|
@@ -17,6 +17,12 @@ printed commands yourself.
|
|
|
17
17
|
Restore it from your backup. Without it you cannot upgrade the deployed program; removing `"address"` from
|
|
18
18
|
`typesol.json` gives the program a new address.
|
|
19
19
|
|
|
20
|
+
**A build error you don't recognize** — the compiler adds a `hint:` line under TypeScript's message where TypeScript's
|
|
21
|
+
own advice points the wrong way for a program. The usual ones: integers are `bigint` (`1n`, `u64` parameters, not
|
|
22
|
+
`number`); `require`, `log`, `min`, `max` and `fixedArray` are imported from `"typesol"`; arrays are read with `.get(i)`
|
|
23
|
+
and written with `.set(i, v)`; an account you change is a `Mut<T>` parameter; there is no `async`, `try`, `throw` or
|
|
24
|
+
`class`. The full list of what the subset covers is in [language.md](language.md).
|
|
25
|
+
|
|
20
26
|
**A transaction fails with a custom error** — see [errors.md](errors.md). Failures raised by the
|
|
21
27
|
compiler's checks log their TypeScript location, e.g. `TypeSOL: arithmetic overflow (vault.ts:42)`.
|
|
22
28
|
|
package/lib/typesol.d.ts
CHANGED
|
@@ -184,6 +184,14 @@ export declare function remainingAccounts(): RemainingAccounts;
|
|
|
184
184
|
*/
|
|
185
185
|
export declare function loadAccount<T>(account: RemainingAccount | AccountInfo): Account<T>;
|
|
186
186
|
export declare function loadAccountMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
|
|
187
|
+
/**
|
|
188
|
+
* A native (non-Anchor) program's own account as a fixed-layout struct, as a `#[repr(C)]` type's `load_checked` /
|
|
189
|
+
* `load_mut_checked` reads it: owned by this program (3007) and at least as large as the struct (3003). There is no
|
|
190
|
+
* discriminator: the fields start at byte 0. `loadRawMut` also requires the account to be writable and not loaded
|
|
191
|
+
* mutably twice in the instruction (2040). Bind it with const: `const amm = loadRawMut<AmmInfo>(ammInfo)`.
|
|
192
|
+
*/
|
|
193
|
+
export declare function loadRaw<T>(account: RemainingAccount | AccountInfo): Account<T>;
|
|
194
|
+
export declare function loadRawMut<T>(account: RemainingAccount | AccountInfo): Mut<T>;
|
|
187
195
|
|
|
188
196
|
/** 32 bytes of hash output (sha256 / keccak256, Merkle roots). Compare with `===`. */
|
|
189
197
|
export interface Hash {
|
|
@@ -553,6 +561,17 @@ export declare function masterEditionAddress(mint: Pubkey): Pubkey;
|
|
|
553
561
|
*/
|
|
554
562
|
export declare function bigEndian(value: bigint): Seed;
|
|
555
563
|
export declare function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey;
|
|
564
|
+
/**
|
|
565
|
+
* `Pubkey::create_program_address(seeds, program)`: the address of these seeds with the bump given as the last seed,
|
|
566
|
+
* or null when they give no program address (a point on the curve, or too many / too long seeds).
|
|
567
|
+
*/
|
|
568
|
+
export declare function createProgramAddress(seeds: Seed[], program: Pubkey): Pubkey | null;
|
|
569
|
+
/**
|
|
570
|
+
* Log `prefix` followed by the base64 (standard, padded) of a struct value's bytes, as a native program's
|
|
571
|
+
* `msg!("ray_log: {}", base64(bincode(log)))` does. The struct holds integers, Pubkeys and fixed arrays of them only,
|
|
572
|
+
* so its bytes are its serialized form.
|
|
573
|
+
*/
|
|
574
|
+
export declare function logBase64(prefix: string, value: object): void;
|
|
556
575
|
/** The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. */
|
|
557
576
|
export declare function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8;
|
|
558
577
|
/** This program's address (`crate::ID`). */
|
|
@@ -1993,7 +2012,48 @@ export declare enum AnchorError {
|
|
|
1993
2012
|
* as computed at run time (`require(r.err === 0n, r.err)`, a helper returning its error as a value, as Rust's `?` passes
|
|
1994
2013
|
* one on); a zero code fails with 5100.
|
|
1995
2014
|
*/
|
|
1996
|
-
export declare function require(condition: boolean, error: string | AnchorError | u32): asserts condition;
|
|
2015
|
+
export declare function require(condition: boolean, error: string | AnchorError | ProgramError | u32): asserts condition;
|
|
2016
|
+
|
|
2017
|
+
/**
|
|
2018
|
+
* Solana's built-in program errors (`solana_program::program_error::ProgramError`, no custom code): a native program's
|
|
2019
|
+
* `Err(ProgramError::InvalidInstructionData)`. `require(condition, ProgramError.InvalidInstructionData)` fails the same
|
|
2020
|
+
* way (the runtime reports the built-in error, not a custom one). Not listed in the IDL's errors.
|
|
2021
|
+
*/
|
|
2022
|
+
export declare enum ProgramError {
|
|
2023
|
+
InvalidArgument = 2,
|
|
2024
|
+
InvalidInstructionData = 3,
|
|
2025
|
+
InvalidAccountData = 4,
|
|
2026
|
+
AccountDataTooSmall = 5,
|
|
2027
|
+
InsufficientFunds = 6,
|
|
2028
|
+
IncorrectProgramId = 7,
|
|
2029
|
+
MissingRequiredSignature = 8,
|
|
2030
|
+
AccountAlreadyInitialized = 9,
|
|
2031
|
+
UninitializedAccount = 10,
|
|
2032
|
+
NotEnoughAccountKeys = 11,
|
|
2033
|
+
AccountBorrowFailed = 12,
|
|
2034
|
+
MaxSeedLengthExceeded = 13,
|
|
2035
|
+
InvalidSeeds = 14,
|
|
2036
|
+
BorshIoError = 15,
|
|
2037
|
+
AccountNotRentExempt = 16,
|
|
2038
|
+
UnsupportedSysvar = 17,
|
|
2039
|
+
IllegalOwner = 18,
|
|
2040
|
+
MaxAccountsDataAllocationsExceeded = 19,
|
|
2041
|
+
InvalidRealloc = 20,
|
|
2042
|
+
MaxInstructionTraceLengthExceeded = 21,
|
|
2043
|
+
BuiltinProgramsMustConsumeComputeUnits = 22,
|
|
2044
|
+
InvalidAccountOwner = 23,
|
|
2045
|
+
ArithmeticOverflow = 24,
|
|
2046
|
+
Immutable = 25,
|
|
2047
|
+
IncorrectAuthority = 26,
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Stop the program as a Rust `panic!` / `unwrap()` on `None` / `unreachable!()` does: the message is logged and the
|
|
2052
|
+
* instruction fails with ProgramFailedToComplete (no error code). For porting native programs whose failures panic:
|
|
2053
|
+
* `location` ("program/src/instruction.rs:482:17") is the place the runtime reports, as the original's panic gives it;
|
|
2054
|
+
* by default this source line.
|
|
2055
|
+
*/
|
|
2056
|
+
export declare function panic(message?: string, location?: string): never;
|
|
1997
2057
|
/**
|
|
1998
2058
|
* Anchor's `constraint = condition @ error` on `account`. Written at the start of an instruction's body (before any
|
|
1999
2059
|
* other statement), it runs with that account's checks, after its has_one and before its owner check, so a transaction
|
|
@@ -2007,7 +2067,18 @@ export declare function constraint(account: AccountMeta | RemainingAccount | nul
|
|
|
2007
2067
|
* `data.get(i)`, or pass it on to `invokeInstruction`. A `/** @fallback *\/` instruction (Anchor's fallback: no
|
|
2008
2068
|
* parameters, run when no instruction matches) reads its input this way, and its accounts with remainingAccounts().
|
|
2009
2069
|
*/
|
|
2010
|
-
export declare function instructionData():
|
|
2070
|
+
export declare function instructionData(): InstructionBytes;
|
|
2071
|
+
|
|
2072
|
+
/** The instruction data, read in place: its bytes, and little-endian values at a byte offset. */
|
|
2073
|
+
export interface InstructionBytes extends IndexedList<u8> {
|
|
2074
|
+
/** The little-endian value at `offset`; reading past the end fails the instruction (5104). */
|
|
2075
|
+
readU8(offset: u64): u8;
|
|
2076
|
+
readU16(offset: u64): u16;
|
|
2077
|
+
readU32(offset: u64): u32;
|
|
2078
|
+
readU64(offset: u64): u64;
|
|
2079
|
+
readU128(offset: u64): u128;
|
|
2080
|
+
readPubkey(offset: u64): Pubkey;
|
|
2081
|
+
}
|
|
2011
2082
|
|
|
2012
2083
|
/** Write a string, integer or pubkey to the program log. */
|
|
2013
2084
|
export declare function log(value: string | bigint | Pubkey | Hash): void;
|
package/package.json
CHANGED
package/runtime/typesol_rt.h
CHANGED
|
@@ -71,6 +71,15 @@
|
|
|
71
71
|
/* Every failure logs through this one sol_log_ call: each syscall call site costs a 16-byte relocation in the binary. */
|
|
72
72
|
static __attribute__((noinline)) uint64_t ts_fail(uint64_t code, const char *msg, uint64_t len) {
|
|
73
73
|
sol_log_(msg, len);
|
|
74
|
+
#ifdef TS_PANIC_ON_OVERFLOW
|
|
75
|
+
/* PANIC_ON_OVERFLOW: arithmetic fails as a Rust `checked_*().unwrap()` does, with a panic (ProgramFailedToComplete). */
|
|
76
|
+
if (code == TS_ERR_OVERFLOW || code == TS_ERR_DIV_ZERO) sol_panic_("", 0, 0, 0);
|
|
77
|
+
#endif
|
|
78
|
+
#ifdef TS_CUSTOM_ZERO
|
|
79
|
+
/* An error with code 0 (a native program's first error) is returned as solana_program returns
|
|
80
|
+
* ProgramError::Custom(0): the built-in CUSTOM_ZERO, since 0 itself means success. */
|
|
81
|
+
if (code == 0) return (uint64_t)1 << 32;
|
|
82
|
+
#endif
|
|
74
83
|
return code;
|
|
75
84
|
}
|
|
76
85
|
#define TS_FAIL(code, msg) return ts_fail((code), (msg), sol_strlen(msg))
|
|
@@ -664,6 +673,28 @@ static inline uint64_t ts_create_pda_address(const SolSignerSeed *seeds, int n,
|
|
|
664
673
|
return SUCCESS;
|
|
665
674
|
}
|
|
666
675
|
|
|
676
|
+
/* msg!("{prefix}{base64(bytes)}") with standard padding, as Raydium's ray_log writes it (at most 300 bytes in). */
|
|
677
|
+
static __attribute__((noinline, unused)) void ts_log_base64(const char *prefix, uint64_t plen, const uint8_t *data, uint64_t len) {
|
|
678
|
+
static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
679
|
+
char out[64 + 4 * ((300 + 2) / 3)];
|
|
680
|
+
if (plen > 64 || len > 300) return;
|
|
681
|
+
uint64_t o = 0;
|
|
682
|
+
for (uint64_t i = 0; i < plen; i++) out[o++] = prefix[i];
|
|
683
|
+
uint64_t i = 0;
|
|
684
|
+
for (; i + 3 <= len; i += 3) {
|
|
685
|
+
uint32_t v = ((uint32_t)data[i] << 16) | ((uint32_t)data[i + 1] << 8) | data[i + 2];
|
|
686
|
+
out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = tbl[(v >> 6) & 63]; out[o++] = tbl[v & 63];
|
|
687
|
+
}
|
|
688
|
+
if (len - i == 1) {
|
|
689
|
+
uint32_t v = (uint32_t)data[i] << 16;
|
|
690
|
+
out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = '='; out[o++] = '=';
|
|
691
|
+
} else if (len - i == 2) {
|
|
692
|
+
uint32_t v = ((uint32_t)data[i] << 16) | ((uint32_t)data[i + 1] << 8);
|
|
693
|
+
out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = tbl[(v >> 6) & 63]; out[o++] = '=';
|
|
694
|
+
}
|
|
695
|
+
sol_log_(out, o);
|
|
696
|
+
}
|
|
697
|
+
|
|
667
698
|
/* sol_try_find_program_address: the canonical (highest) bump. */
|
|
668
699
|
static inline uint64_t ts_find_pda(const SolSignerSeed *seeds, int n, const SolPubkey *program, SolPubkey *out, uint8_t *bump_out) {
|
|
669
700
|
if (!ts_pda_seeds_ok(seeds, n, TS_MAX_PDA_SEEDS - 1)) return 1; /* not SUCCESS: the PDA syscalls fail the same inputs */
|
|
@@ -2025,6 +2056,22 @@ static inline unsigned __int128 ts_isqrt_u128(unsigned __int128 x) {
|
|
|
2025
2056
|
}
|
|
2026
2057
|
}
|
|
2027
2058
|
|
|
2059
|
+
/* floor(sqrt(x)) of a u256 (the `uint` crate's U256::integer_sqrt): Newton's method from a power of two above it. */
|
|
2060
|
+
static inline TsU256 ts_isqrt_u256(TsU256 x) {
|
|
2061
|
+
int top = 3;
|
|
2062
|
+
while (top > 0 && x.w[top] == 0) top--;
|
|
2063
|
+
if (top == 0 && x.w[0] < 2) return x;
|
|
2064
|
+
int bits = 64 * top + (64 - __builtin_clzll(x.w[top]));
|
|
2065
|
+
TsU256 r = ts_u256_shl(ts_u256_lit(1, 0, 0, 0), (uint64_t)((bits + 1) / 2));
|
|
2066
|
+
while (1) {
|
|
2067
|
+
TsU256 q = ts_u256_divmod(x, r, true), s;
|
|
2068
|
+
ts_u256_add(r, q, &s); /* r + x / r stays below 2^256: r <= 2^128 and x / r < 2^256 / r */
|
|
2069
|
+
TsU256 n = ts_u256_shr(s, 1);
|
|
2070
|
+
if (ts_u256_cmp(n, r) >= 0) return r;
|
|
2071
|
+
r = n;
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2028
2075
|
/* Decimal text of a 128-bit integer on the heap. */
|
|
2029
2076
|
static inline uint64_t ts_str_u128(unsigned __int128 v, bool negative, TS_Str *out) {
|
|
2030
2077
|
char tmp[40];
|
package/ts-plugin/index.js
CHANGED
|
@@ -99,10 +99,33 @@ function init({ typescript: ts }) {
|
|
|
99
99
|
return found;
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* TypeScript's errors in a TypeSOL project's files, each with the hint the CLI prints under it (TypeScript's own
|
|
104
|
+
* advice, such as installing @types/node, points the wrong way in a program). Needs the in-process compiler.
|
|
105
|
+
*/
|
|
106
|
+
function withHints(fileName, diagnostics) {
|
|
107
|
+
if (!compiler || !compiler.typescriptHint || !entriesNear(path.dirname(path.resolve(fileName))).size) return diagnostics;
|
|
108
|
+
return diagnostics.map((d) => {
|
|
109
|
+
if (d.category !== ts.DiagnosticCategory.Error) return d;
|
|
110
|
+
let hint;
|
|
111
|
+
try {
|
|
112
|
+
hint = compiler.typescriptHint(d);
|
|
113
|
+
} catch {
|
|
114
|
+
return d;
|
|
115
|
+
}
|
|
116
|
+
if (!hint) return d;
|
|
117
|
+
const text = `hint: ${hint}`;
|
|
118
|
+
const messageText =
|
|
119
|
+
typeof d.messageText === "string"
|
|
120
|
+
? `${d.messageText}\n${text}`
|
|
121
|
+
: { ...d.messageText, next: [...(d.messageText.next || []), { messageText: text, category: d.category, code: d.code, next: undefined }] };
|
|
122
|
+
return { ...d, messageText };
|
|
123
|
+
});
|
|
124
|
+
}
|
|
102
125
|
const proxy = Object.create(null);
|
|
103
126
|
for (const k of Object.keys(ls)) proxy[k] = (...args) => ls[k](...args);
|
|
104
127
|
proxy.getSemanticDiagnostics = (fileName) => {
|
|
105
|
-
const prior = ls.getSemanticDiagnostics(fileName);
|
|
128
|
+
const prior = withHints(fileName, ls.getSemanticDiagnostics(fileName));
|
|
106
129
|
if (prior.some((d) => d.category === ts.DiagnosticCategory.Error)) return prior; // TypeScript's errors first
|
|
107
130
|
const target = path.resolve(fileName);
|
|
108
131
|
const entries = entriesNear(path.dirname(target));
|