@typesol/cli 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +11 -7
- package/dist/cli.js +50 -5
- package/dist/compiler/analyze.js +14 -5
- package/dist/compiler/emit/base.d.ts +1 -0
- package/dist/compiler/emit/calls.d.ts +2 -0
- package/dist/compiler/emit/calls.js +125 -11
- package/dist/compiler/emit/cpi-core.d.ts +8 -0
- package/dist/compiler/emit/cpi-core.js +15 -0
- package/dist/compiler/emit/cpi.js +10 -4
- package/dist/compiler/emit/create.d.ts +2 -0
- package/dist/compiler/emit/create.js +56 -13
- package/dist/compiler/emit/expressions.js +6 -2
- package/dist/compiler/emit/statements.js +15 -0
- package/dist/compiler/emit/token.js +43 -0
- package/dist/templates.js +13 -36
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +64 -2
- package/dist/workspace.d.ts +16 -1
- package/dist/workspace.js +49 -5
- package/docs/audit.md +1 -1
- package/docs/case-study-escrow.md +3 -3
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-cp-swap.md +152 -0
- package/docs/cli.md +5 -3
- package/docs/errors.md +3 -1
- package/docs/language.md +13 -6
- package/docs/migrate-from-anchor.md +3 -0
- package/docs/test-your-program.md +12 -3
- package/docs/testing.md +1 -1
- package/lib/typesol.d.ts +43 -5
- package/package.json +1 -1
- package/runtime/typesol_rt.h +121 -7
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Case study: Raydium CP-Swap
|
|
2
|
+
|
|
3
|
+
This page ports the trading core of a production AMM: [Raydium CP-Swap](https://github.com/raydium-io/raydium-cp-swap)
|
|
4
|
+
(`programs/cp-swap`, Anchor 1.0.2, Apache-2.0). It is deployed on mainnet at
|
|
5
|
+
`CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`. The port is [`examples/raydium-cp-swap/`](https://github.com/typesol/typesol/blob/main/examples/raydium-cp-swap)
|
|
6
|
+
(`state.ts`, `curve.ts`, `raydium_cp_swap.ts`). As with [coral-xyz/multisig](case-study-multisig.md), it is checked
|
|
7
|
+
against the binary that runs on mainnet, not a rebuild.
|
|
8
|
+
|
|
9
|
+
## What is ported
|
|
10
|
+
|
|
11
|
+
The port covers 10 of the original's 24 instructions:
|
|
12
|
+
|
|
13
|
+
- `initialize`, which creates a pool with its first liquidity;
|
|
14
|
+
- the four trading instructions: `swap_base_input`, `swap_base_output`, `deposit` and `withdraw`;
|
|
15
|
+
- `collect_protocol_fee` and `collect_fund_fee`;
|
|
16
|
+
- the admin instructions `create_amm_config`, `update_amm_config` and `update_pool_status`.
|
|
17
|
+
|
|
18
|
+
The port keeps the original's account layouts:
|
|
19
|
+
|
|
20
|
+
- `AmmConfig` is a Borsh account of fixed size.
|
|
21
|
+
- `PoolState` and `ObservationState` are zero-copy `#[repr(C, packed)]` structs, which is TypeSOL's fixed layout.
|
|
22
|
+
|
|
23
|
+
It also keeps the original's names, argument order and error codes, and emits the same events (`SwapEvent`,
|
|
24
|
+
`LpChangeEvent`). Existing pools, clients and indexers work with it unchanged.
|
|
25
|
+
|
|
26
|
+
These are not ported yet:
|
|
27
|
+
|
|
28
|
+
- **`initialize_with_permission`.** It is `initialize` for a creator the admin authorized, with the creator fee on.
|
|
29
|
+
- **The creator-fee instructions**: `collect_creator_fee`, `collect_creator_fee_permissionless`,
|
|
30
|
+
`create_creator_fee_share` and `close_creator_fee_share`.
|
|
31
|
+
- **The permission instructions**: `create_permission_pda` and `close_permission_pda`.
|
|
32
|
+
- **The support-mint instructions**: `create_support_mint_associated` and `close_support_mint_associated`.
|
|
33
|
+
- **`collect_excess_lamports`.**
|
|
34
|
+
|
|
35
|
+
The pool logic these depend on is in the port (fee booking, the creator-fee split in the swap math, tested below with
|
|
36
|
+
the creator fee on), so a pool the original created and configured is traded the same way.
|
|
37
|
+
|
|
38
|
+
## What it needed
|
|
39
|
+
|
|
40
|
+
Creating the pool by hand, as the original does, needed a few general features (`test/language/manual-init.test.ts`):
|
|
41
|
+
|
|
42
|
+
- `systemProgram.allocate` and `assign`, for an address someone pre-funded;
|
|
43
|
+
- `programId()` and `findProgramAddressBump(seeds, program)`, to sign as the pool PDA;
|
|
44
|
+
- `initAccount<T>(account)`, Anchor's `load_init`: a program account the body created becomes a struct to fill;
|
|
45
|
+
- `Pubkey.compare`, for the original's `token_0_mint < token_1_mint`;
|
|
46
|
+
- `ata.create(payer, tokenProgram)`, an associated token account under one of several token programs.
|
|
47
|
+
|
|
48
|
+
`Init` accounts also now fail on an address already in use as Anchor's do. TypeSOL used to check first and fail with
|
|
49
|
+
3000; now the System Program refuses the address (`AccountAlreadyInUse`, custom 0). It also checks that the payer is
|
|
50
|
+
not the account being created (4101).
|
|
51
|
+
|
|
52
|
+
Four Token-2022 reads were added to the compiler for this port (`test/integrations/t22ext.test.ts`):
|
|
53
|
+
|
|
54
|
+
- `transferFeeInverse(mint, amountReceived)`: spl-token-2022's `calculate_inverse_epoch_fee`, used for deposits and
|
|
55
|
+
exact-output swaps.
|
|
56
|
+
- `transferFeeBasisPoints(mint)` and `transferFeeMaximum(mint)`: the fee in force this epoch.
|
|
57
|
+
- `extensionsWithin(account, [types])`: the original's list of mint extensions a pool accepts.
|
|
58
|
+
|
|
59
|
+
The rest uses features TypeSOL already had:
|
|
60
|
+
|
|
61
|
+
- `constraint(…)`, for Anchor's `address = pool_state.load()?.amm_config` and `constraint = …` in Anchor's order;
|
|
62
|
+
- u128 arithmetic for the constant-product curve and the price oracle;
|
|
63
|
+
- token CPIs signed by the pool authority PDA;
|
|
64
|
+
- events.
|
|
65
|
+
|
|
66
|
+
## How it was checked
|
|
67
|
+
|
|
68
|
+
[`test/examples/raydium-cp-swap.test.ts`](https://github.com/typesol/typesol/blob/main/test/examples/raydium-cp-swap.test.ts) loads the binary dumped from
|
|
69
|
+
mainnet on 2026-10-30 (slot 452376460; sha256 in [`test/programs/SOURCES.md`](https://github.com/typesol/typesol/blob/main/test/programs/SOURCES.md)) into one
|
|
70
|
+
LiteSVM and the port into another. Both use the same program id and the same clock.
|
|
71
|
+
|
|
72
|
+
**Setup.**
|
|
73
|
+
|
|
74
|
+
- Mints and token accounts are made by the same SPL Token / Token-2022 instructions in both.
|
|
75
|
+
- The program's own accounts (an `AmmConfig`, a pool's `PoolState` and its `ObservationState`) are written in both as
|
|
76
|
+
the original lays them out, because creating a config needs Raydium's admin key.
|
|
77
|
+
|
|
78
|
+
**Comparison.** For each transaction, the test requires the same outcome (success, or the same error down to the
|
|
79
|
+
code), the same lamports, owner and data for every account involved, and the same events byte for byte.
|
|
80
|
+
|
|
81
|
+
There are 70 transactions:
|
|
82
|
+
|
|
83
|
+
- **Pool creation.** These cases are covered:
|
|
84
|
+
- a pool at its PDA, at a signing keypair, and at a pre-funded address;
|
|
85
|
+
- a pool with the creation fee, paid in wrapped SOL;
|
|
86
|
+
- a pool of Token-2022 fee mints;
|
|
87
|
+
- creating the same pool twice;
|
|
88
|
+
- an address that did not sign (2501);
|
|
89
|
+
- mints in the wrong order (2003);
|
|
90
|
+
- an unsupported extension (6007);
|
|
91
|
+
- a disabled config (6000);
|
|
92
|
+
- too little liquidity (6009).
|
|
93
|
+
- **Swaps.** Both directions, by input and by output; the observation ring advancing as the clock moves; slippage
|
|
94
|
+
(6005); zero amounts.
|
|
95
|
+
- **Liquidity.** Deposit, a partial withdrawal, slippage both ways, withdrawing more LP than held, zero.
|
|
96
|
+
- **Fees.** Protocol and fund fees collected by their owners after trading, and refused for anyone else (6001).
|
|
97
|
+
- **Creator fees.** Pools with the creator fee on at 0.05%, taken from the input token, only token_0, or only
|
|
98
|
+
token_1: swaps both ways, by input and by output, booking the fee on the right side.
|
|
99
|
+
- **The price oracle.** A new point, a second swap within 15 seconds (added to the current point), and a ring at its
|
|
100
|
+
last slot whose cumulative price is 10 below `u128::MAX`: the next point wraps to slot 0 and the sum wraps around.
|
|
101
|
+
- **Token-2022.** A pool of two transfer-fee mints (1.5% and 0.37%): swaps both ways and by output, deposit and
|
|
102
|
+
withdrawal, through the inverse-fee path; and a pool of Token-2022 mints without a fee.
|
|
103
|
+
- **Refusals.**
|
|
104
|
+
- Another config (2012), another pool's vault (2003), another observation account (2012) or mint (2012).
|
|
105
|
+
- The same vault twice, a wrong pool authority (2006), another trader's account.
|
|
106
|
+
- Wrong vaults or LP mint on deposit (6004), the wrong token program.
|
|
107
|
+
- Swaps or deposits on a pool whose status disables them (6000).
|
|
108
|
+
- The admin instructions sent by anyone but the admin (2012, 6001).
|
|
109
|
+
|
|
110
|
+
## Cost
|
|
111
|
+
|
|
112
|
+
Compute units per transaction, mainnet original against the port, from that test:
|
|
113
|
+
|
|
114
|
+
| Instruction | Raydium (mainnet) | TypeSOL | |
|
|
115
|
+
| --- | ---: | ---: | ---: |
|
|
116
|
+
| `initialize` | 83,474 | 39,352 | −53% |
|
|
117
|
+
| `initialize`, Token-2022 transfer fees | 101,962 | 55,795 | −45% |
|
|
118
|
+
| `swap_base_input` | 24,142 | 5,734 | −76% |
|
|
119
|
+
| `swap_base_output` | 24,571 | 5,941 | −76% |
|
|
120
|
+
| `deposit` | 25,004 | 6,190 | −75% |
|
|
121
|
+
| `withdraw` | 25,211 | 6,201 | −75% |
|
|
122
|
+
| `collect_protocol_fee` | 20,205 | 4,189 | −79% |
|
|
123
|
+
| `swap_base_input`, Token-2022 transfer fees | 31,365 | 12,083 | −61% |
|
|
124
|
+
| `swap_base_output`, Token-2022 transfer fees | 32,542 | 14,101 | −57% |
|
|
125
|
+
| `deposit`, Token-2022 transfer fees | 33,237 | 14,482 | −56% |
|
|
126
|
+
|
|
127
|
+
The Token-2022 rows include the token program's own work, which is the same in both. Refusals cost far less. For
|
|
128
|
+
example, a swap through the wrong config costs 17,190 against 1,656.
|
|
129
|
+
|
|
130
|
+
On size, the port's binary is 143,560 bytes and the deployed original is 793,824 bytes. The original also contains the
|
|
131
|
+
14 instructions not ported here, so the size ratio overstates the gain for the same feature set.
|
|
132
|
+
|
|
133
|
+
Pool creation is mostly the token programs' and the System Program's own work (account creation, initialization,
|
|
134
|
+
transfers), which costs the same in both. The difference is the program's part. Its cost also varies from run to run
|
|
135
|
+
with the PDA bump searches of the random keys the test uses, in both programs alike.
|
|
136
|
+
|
|
137
|
+
Two general optimizations came out of profiling this port. u128 arithmetic now takes the native 64-bit instructions
|
|
138
|
+
when the values fit, and an instruction reads the Clock once. Together they took a swap from 7,478 to 5,734.
|
|
139
|
+
|
|
140
|
+
## Where they differ
|
|
141
|
+
|
|
142
|
+
- **Panics.** Where the original calls `unwrap()` or `assert!`, it aborts with `ProgramFailedToComplete`. The port
|
|
143
|
+
fails with a numbered error instead:
|
|
144
|
+
- an overflow or underflow, 5100: an exact-output swap for more than the vault holds;
|
|
145
|
+
- a division by zero, 5101: the price of an empty side, or an exact-output swap for exactly what the vault holds;
|
|
146
|
+
- invalid input, 6003: a fee rate out of range in the admin instructions, which only the admin can reach.
|
|
147
|
+
|
|
148
|
+
The swaps and liquidity instructions reach none of these with the amounts a pool can hold.
|
|
149
|
+
- **Check order on double faults.** Account checks run in Anchor's order, so a transaction breaking one check gets the
|
|
150
|
+
same code. The port keeps the pool's `address = …` and `token::…` constraints as `constraint(…)` calls in Anchor's
|
|
151
|
+
order. A transaction that breaks a token check and an account-type check at once can still be reported differently.
|
|
152
|
+
- **Logs.** Error messages are TypeSOL's. Codes and events are the original's.
|
package/docs/cli.md
CHANGED
|
@@ -7,10 +7,11 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
7
7
|
| Command | What it does |
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow]` | Create a project: `typesol.json`, `programs/<name>.ts`, `tests/<name>.test.ts` (LiteSVM), `package.json`, `tsconfig.json`, `programs/tsconfig.json` (with the editor plugin) and `.gitignore`. `<name>` must be snake_case; by default it is derived from `<dir>` (`my-app` → `my_app`). The template picks the program and its test: `counter` (default, a PDA counter per user), `vault` (SOL at a PDA: deposit, withdraw above rent, close) or `escrow` (SPL tokens: make, take, refund, the offer PDA signing for its vault). Refuses to overwrite files. It warns, with the install commands, when the platform-tools that building needs are missing. |
|
|
10
|
+
| `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name. |
|
|
10
11
|
| `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools, the Solana CLI, its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
|
|
11
|
-
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a
|
|
12
|
+
| `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json`. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. |
|
|
12
13
|
| `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile]` | Outside a project (or a file that is not one of its programs): build that file. A project program's `.ts` builds as that program. |
|
|
13
|
-
| `typesol check <file.ts> [--json] [--stdin]` | Type-check and validate without building. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk). |
|
|
14
|
+
| `typesol check [<program>… \| <file.ts>] [--json] [--stdin]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`; `--stdin` checks the text given on stdin as that file (its imports come from disk). |
|
|
14
15
|
| `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
|
|
15
16
|
| `typesol deploy [<program>…] [--url <rpc>] [--keypair <payer.json>] [--config <cli config>] [--dry-run] [--sbpf …]` | Build, then `solana program deploy --use-rpc` at the program keypair's address. Deploying again upgrades (the payer must be the upgrade authority). `--dry-run` builds and prints the commands. Before sending anything it checks that the RPC answers and that the payer holds enough for the rent (about twice the binary's on a first deploy, while the buffer exists), and says what to do if not (start `solana-test-validator`, `solana airdrop` on devnet or a local validator). Needs `solana` on PATH. |
|
|
16
17
|
| `typesol idl publish [<program>…] [--url <rpc>] [--keypair <authority.json>] [--config <cli config>] [--non-canonical]` | Compile (the binary is not rebuilt), then write each IDL to the Program Metadata program (seed `idl`). Canonical IDLs must be signed by the upgrade authority. Defaults come from the Solana CLI config (`~/.config/solana/cli/config.yml`). |
|
|
@@ -33,7 +34,8 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
|
|
|
33
34
|
```
|
|
34
35
|
|
|
35
36
|
`"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
|
|
36
|
-
safe and out of git: it is each program's address and its first upgrade authority must not lose it.
|
|
37
|
+
safe and out of git: it is each program's address and its first upgrade authority must not lose it. A clone without
|
|
38
|
+
it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
|
|
37
39
|
|
|
38
40
|
## Editor
|
|
39
41
|
|
package/docs/errors.md
CHANGED
|
@@ -21,7 +21,8 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
21
21
|
| 2021 / 2022 | token account / mint not owned by the token program `TokenOf` / `MintOf` names (ConstraintTokenTokenProgram / ConstraintMintTokenProgram) |
|
|
22
22
|
| 2024–2039 | an existing mint `createIfNeeded` found lacks a Token-2022 extension it was given, or holds other keys in it: group pointer 2024–2026, group member pointer 2027–2029, metadata pointer 2030–2032, close authority 2033–2034, permanent delegate 2035–2036, transfer hook 2037–2039 (the first code of each: the extension is missing; the next: the authority / address differs) (ConstraintMint…Extension…) |
|
|
23
23
|
| 2040 | the same account passed in two writable slots (ConstraintDuplicateMutableAccount) |
|
|
24
|
-
|
|
|
24
|
+
| 0 (from the System Program) | an `Init` / `create` on an address already in use (AccountAlreadyInUse): the System Program refuses it, as under Anchor's `init` |
|
|
25
|
+
| 3000 | `initAccount<T>` on an account whose discriminator is already set (AccountDiscriminatorAlreadySet) |
|
|
25
26
|
| 3002 | discriminator mismatch (AccountDiscriminatorMismatch) |
|
|
26
27
|
| 3003 | data too small, not an initialized token account / mint, a read past the end, or a `@layout borsh` account whose bytes are not a valid Borsh value (AccountDidNotDeserialize) |
|
|
27
28
|
| 3004 | a `@layout borsh` account too small for the value it would now hold (AccountDidNotSerialize) |
|
|
@@ -33,6 +34,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
|
|
|
33
34
|
| 3011 | a `SystemAccount` owned by another program (AccountNotSystemOwned) |
|
|
34
35
|
| 3012 | account not initialized: empty system account where a program account was expected (AccountNotInitialized) |
|
|
35
36
|
| 3016 | account would grow more than 10 KiB in one instruction, or grow without a payer (AccountReallocExceedsLimit) |
|
|
37
|
+
| 4101 | an `Init` / `create` whose payer is the account being created (TryingToInitPayerAsProgramAccount) |
|
|
36
38
|
| 4102 | cast overflow (InvalidNumericConversion) |
|
|
37
39
|
| 5100 / 5101 | arithmetic overflow (including shifts) / division by zero |
|
|
38
40
|
| 5103 | sysvar unavailable |
|
package/docs/language.md
CHANGED
|
@@ -12,7 +12,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
12
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)` |
|
|
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
|
-
| Casts | `u8(x)`, `u64(x)`, … abort if the value does not fit |
|
|
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) |
|
|
16
16
|
| Logging | `log("text")`, `log(value)`, `log(pubkey)` |
|
|
17
17
|
| Arrays | `scores: FixedArray<u64, 8>` in account data — `.get(i)`, `.set(i, v)`, `.length`, bounds-checked; elements can be structs or strings |
|
|
18
18
|
| Local arrays | `const xs = fixedArray<i64, 5>(0n)` — up to 256 elements on the stack |
|
|
@@ -28,6 +28,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
28
28
|
| Anchor's account bytes | `/** @layout borsh */` on an account struct stores it as Anchor does (Borsh: a `FixedString<N>` is a String, a `FixedVec<T, N>` or `Vec<T>` a Vec, an `Option` one byte when empty, and the fields after them move), so a TypeSOL program can take over accounts an Anchor program wrote and the IDL lists Anchor's own types. The instruction unpacks it into the usual fixed layout when it starts (bad bytes fail with 3003) and packs it back when it returns (3004 when the account is too small for the new value), so everything else works on it unchanged. A `Vec<T>` field (any position; integers, booleans, Pubkeys, unit enums or fixed-size structs) is Anchor's own: held on the heap while the instruction runs, growing as Rust's Vec does, bounded only by the account when it is written back (3004); its elements move when it grows, so a reference into one cannot outlive a `push` or an assignment. `Init` of such a struct takes its space, `create(payer, seeds, space)`. Programs invoked from the body (CPIs) see the account's bytes as they were when the instruction started. Costs more compute than the fixed layout (the whole account is read and written each time; see the benchmarks); nested structs and list elements must be fixed-size (FixedString elements allowed). The same struct is Borsh as a whole instruction argument (checked like Borsh deserialization, UTF-8 included), as return data and as an event; as those (not as account data) it may also hold `string` fields and data enums carrying strings, Anchor's `String` and enums in argument structs (account data takes data enums without strings); not inside list or enum arguments or `loadAccount`, and a struct holding a `Vec<T>` is account data or a whole argument, not return data or an event |
|
|
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
|
+
| 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 |
|
|
31
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
33
|
| Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
|
|
33
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 |
|
|
@@ -38,7 +39,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
38
39
|
| Option of structs | `home: Option<Point>` in account data — `=== null`, `p.home.x` after narrowing, `p.home = null` / `{ x, y }` |
|
|
39
40
|
| Strings at runtime | `"hello, " + name`, `` `#${n}` ``, `` `owner ${acct.owner}` `` (a Pubkey or Hash as base58) — built on the 32 KiB heap (5110 when full): a template is joined in one allocation, text known at compile time (literals, string and Pubkey constants) is folded in, and `s += …` grows the newest heap string in place |
|
|
40
41
|
| `switch` | on integers (128-bit ones too), enums and data-enum `.kind`, with JS `break` / fallthrough; case labels are literals, constants or enum members |
|
|
41
|
-
| Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
|
|
42
|
+
| Hashing & signatures | `sha256(...)`, `keccak256(...)` → `Hash`; `findProgramAddress(seeds, program)` → the canonical PDA of any program (Rust `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id) and `findProgramAddressBump(seeds, program)` its bump; `programId()` → this program's address; `a.compare(b)` orders Pubkeys as Rust does (-1 / 0 / 1); `merkleVerify(leaf, proof: Vec<Hash>, root)` (sorted-pair keccak, OpenZeppelin convention; inner nodes and leaves are hashed alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the arguments: an inner node would pass as a leaf); `verifyEd25519(instructionsSysvar, signer, message)` checks an Ed25519 precompile instruction in the same transaction; `stackHeight()` is 1 when the transaction calls the program directly, more under a CPI (`require(stackHeight() === 1n, …)` refuses CPI callers); `verifySecp256k1(keccak256(...message) | ethMessageHash(message), recoveryId, r, s, ethAddress)` (the hash must be computed in the program; a passed-in hash could be forged) |
|
|
42
43
|
| Oracles | `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` (fully verified, feed-matched, fresh; with `exponent`, a feed at another scale is refused); raw `update.price / conf / exponent / publishTime` are unchecked (any feed, partially verified or stale: check `feedId`, `fullyVerified` and the age yourself, or use `pythPrice`); `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)` (the feed must be the expected one: anyone can create feeds; `minSamples`, default 1, the fewest oracle samples accepted) (mainnet program unless `SwitchboardFeed<"devnet">`) |
|
|
43
44
|
| 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 |
|
|
44
45
|
| 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,7 +52,7 @@ The full reference. For a tour, start with the [README](../README.md).
|
|
|
51
52
|
| `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
|
|
52
53
|
| Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent) |
|
|
53
54
|
| Account size | `realloc(account, newSize, payer)` on a `Mut<Struct>` — growing charges the payer the extra rent (at most 10 KiB per instruction, 3016); shrinking keeps the lamports in the account; never below the struct. Refused on a struct with a growable `Vec` (its push / pop / clear size the account) |
|
|
54
|
-
| Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
|
|
55
|
+
| Token-2022 extensions | `transferFee(mint, amount)` (current-epoch TransferFeeConfig, ceil + cap like spl-token-2022), `transferFeeInverse(mint, amountReceived)` (the fee when the recipient is to get that much: spl-token-2022's `calculate_inverse_epoch_fee`), `transferFeeBasisPoints(mint)` / `transferFeeMaximum(mint)` (this epoch's; 0 without the extension), `extensionsWithin(account, [1n, 18n, …])` (every extension is one of those types), `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` (Option<Pubkey>), `hasExtension(account, type)`, `isTransferring(tokenAccount)` (inside a transfer hook: whether Token-2022 is transferring from it) |
|
|
55
56
|
| Events through CPI | `emitCpi<Paid>({ … }, eventAuthority, self)` with `eventAuthority: EventAuthority, self: SelfProgram` parameters — Anchor `emit_cpi!`: the event rides in a self-CPI (inner instruction), not in logs; the program accepts Anchor's event instruction (2002 / 2006 otherwise) |
|
|
56
57
|
| Heap | 32 KiB by default; `const HEAP_SIZE_KIB = 64n` (32–256) lets the program use more, when clients add ComputeBudget `requestHeapFrame` |
|
|
57
58
|
| Docs | JSDoc on instructions, `@param`, structs, fields and data enums becomes `docs` in the IDL |
|
|
@@ -107,11 +108,14 @@ with `i == j`) is refused with 2040 too, since the two views would alias.
|
|
|
107
108
|
|
|
108
109
|
## Built-ins
|
|
109
110
|
|
|
110
|
-
- `systemProgram.transfer(from
|
|
111
|
+
- `systemProgram.transfer(from, to, lamports, signerSeeds?)` (`from` is a `Mut<Signer>`, or a system-owned PDA of this
|
|
112
|
+
program, a SOL vault, with its seeds), `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
|
|
111
113
|
(the new account signs: a keypair `Mut<Signer>` or this program's PDA), `rentExempt(space)`, `MINT_SIZE`, `TOKEN_ACCOUNT_SIZE`
|
|
112
114
|
- Token programs (`TokenProgram`, `Token2022Program`, `TokenInterface`) — pass `signerSeeds` (with the bump) when the authority is a PDA:
|
|
113
115
|
`transfer`, `transferChecked(from, mint, to, authority, amount)` (required by Token-2022 mints with fees/hooks), `mintTo` (the mint may be one this instruction just created), `burn`, `closeAccount` (a token account, or a Token-2022 mint with a close authority),
|
|
114
|
-
`approve(source, delegate, owner, amount)`, `revoke`, `
|
|
116
|
+
`approve(source, delegate, owner, amount)`, `revoke`, the checked forms `mintToChecked(mint, to, authority, amount)`,
|
|
117
|
+
`burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
|
|
118
|
+
come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
|
|
115
119
|
`freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
|
|
116
120
|
`initializeAccount3(account, mint, owner)`, and on Token-2022 `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)` (metadata extension) and the extension initializers to call between `createAccount` and `initializeMint2` / `initializeAccount3`: `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`, `initializeMintCloseAuthority(mint, authority | null)`, `initializeNonTransferableMint(mint)`, `initializePermanentDelegate(mint, delegate)`, `initializeDefaultAccountState(mint, frozen)`, `initializeMetadataPointer` / `initializeGroupPointer` / `initializeGroupMemberPointer` / `initializeTransferHook(mint, authority | null, address | null)`, `initializeInterestBearingMint(mint, rateAuthority | null, rate)`, `initializeImmutableOwner(account)`; the extension instructions `updateDefaultAccountState(mint, freezeAuthority, frozen)`, `updateTransferHook(mint, authority, programId | null)`, `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`, `updateInterestRate(mint, rateAuthority, rate)`, `transferCheckedWithFee(from, mint, to, authority, amount, fee)`, `harvestWithheldTokensToMint(mint, remainingAccounts())`, `withdrawWithheldTokensFromMint(mint, destination, authority)`, `setTransferFee(mint, authority, basisPoints, maximumFee)`; and the Token Metadata interface `updateMetadataField(mint, updateAuthority, field, value)` ("name" / "symbol" / "uri" or any other key), `removeMetadataKey(mint, updateAuthority, key, idempotent)`, `updateMetadataAuthority(mint, updateAuthority, next | null)`, `emitMetadata(mint)`. Each takes optional signerSeeds
|
|
117
121
|
- `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
|
|
@@ -150,7 +154,10 @@ export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: M
|
|
|
150
154
|
- data (Borsh): integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
|
|
151
155
|
Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
|
|
152
156
|
`sighash("name")` (Anchor discriminator), `hex("0a0b")`. Up to 1024 bytes.
|
|
153
|
-
- `signerSeeds` (with the bump) signs for this program's PDA.
|
|
157
|
+
- `signerSeeds` (with the bump) signs for this program's PDA. When several PDAs sign one call, pass a list of seed
|
|
158
|
+
lists: `[["vault", owner.key, vaultBump], ["fees", feesBump]]` (at most 16).
|
|
159
|
+
- A seed list used more than once can be named: `const vault = signer(["vault", owner.key, bump])`, then pass `vault`
|
|
160
|
+
wherever signerSeeds go.
|
|
154
161
|
- After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from `program`.
|
|
155
162
|
|
|
156
163
|
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
|
@@ -110,6 +110,9 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
|
|
|
110
110
|
| `Rent::get()?.minimum_balance(n)` | `rentExempt(n)`, `minimumBalance(acct)` |
|
|
111
111
|
| `system_program::transfer(CpiContext::new(…), lamports)` | `systemProgram.transfer(from, to, lamports)` |
|
|
112
112
|
| `token::transfer_checked(CpiContext::new_with_signer(…, seeds), amount, decimals)` | `tokenProgram.transferChecked(from, mint, to, authority, amount, ["seed", key, bump])` |
|
|
113
|
+
| `token::mint_to_checked` / `burn_checked` / `approve_checked` | `tokenProgram.mintToChecked(mint, to, authority, amount)` / `burnChecked(from, mint, authority, amount)` / `approveChecked(source, mint, delegate, owner, amount)` |
|
|
114
|
+
| `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
|
|
115
|
+
| `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
|
|
113
116
|
| `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
|
|
114
117
|
| `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
|
|
115
118
|
| `multisig.owners = owners` (a `Vec` argument into account data) | the same |
|
|
@@ -43,15 +43,24 @@ instruction that takes the bump as an argument.
|
|
|
43
43
|
|
|
44
44
|
| Helper | Gives |
|
|
45
45
|
| --- | --- |
|
|
46
|
-
| `t.ok(res)` | the successful result, or throws with the program's logs |
|
|
46
|
+
| `t.ok(res)` | the successful result, or throws with the error, its name (`NotAdmin`) and the program's logs |
|
|
47
47
|
| `t.errorCode(res)` | the custom error code of a failed transaction: 6000 + the member's index in your error enum, or a framework code ([errors.md](errors.md)) |
|
|
48
48
|
| `t.account(type, address)` | the account decoded by its IDL type (bigints, address strings), or `null` once closed. TypeSOL fixed layouts come back as their IDL structs: a `FixedString<N>` as `{ len, bytes }`, a `FixedVec<T, N>` as `{ len, items }` (the generated client gives strings and arrays) |
|
|
49
49
|
| `t.returned(instruction, res)` | the instruction's return data: an integer, boolean, Pubkey or struct |
|
|
50
50
|
| `t.balance(address)` | lamports |
|
|
51
|
+
| `t.errorName(code)` | the name of an error code: your program's, TypeSOL's or Anchor's |
|
|
51
52
|
| `t.connection` | `{ rpc, rpcSubscriptions }` answered by this LiteSVM, for the generated client: `counter.sendInstructions(t.connection, alice, [ix])`, `counter.accounts.Counter.fetch(t.connection.rpc, address)`, views, `resolve`, `watch` and `watchEvents` (as on a cluster: `watch` yields when a later transaction changes the account, not at once; `watchEvents` gets transactions sent after it subscribed, failed ones included in the stream and skipped by the client) |
|
|
52
53
|
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
## Tokens and time
|
|
55
|
+
|
|
56
|
+
| Helper | Does |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `t.mint({ authority, decimals?, supply?, freezeAuthority?, tokenProgram?, address? })` | writes a mint straight into the VM, as CreateAccount + InitializeMint2 leave it (SPL Token unless `tokenProgram` is Token-2022; no extensions), and returns its address |
|
|
59
|
+
| `t.tokenAccount({ mint, owner, amount?, tokenProgram?, address? })` | writes a token account holding `amount`; pass `address` for an associated token account |
|
|
60
|
+
| `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
|
|
61
|
+
| `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
|
|
62
|
+
|
|
63
|
+
`t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else. `programHarness(svm, programId, idl)` gives the same helpers for a
|
|
55
64
|
program you loaded yourself, and `svmConnection(svm)` the RPC pair alone (for any LiteSVM, e.g. one with an Anchor
|
|
56
65
|
program loaded). Transactions sent through it run at once; `getProgramAccounts` (`fetchAll`) sees the accounts those
|
|
57
66
|
transactions named, plus any you `track(...)`.
|
package/docs/testing.md
CHANGED
|
@@ -9,7 +9,7 @@ run prints its seed; reproduce with `FUZZ_SEED=<n>`, widen with `FUZZ_RUNS` / `F
|
|
|
9
9
|
| `test/verification/fuzz-state.test.ts` | TypeScript state model | random honest + hostile actions on vault and escrow: every outcome as predicted, balances equal the model, SOL conserved up to fees, token supply exactly conserved; random filings/decisions/resets on ledgerbook: Vec contents, account size and rent exemption equal the model |
|
|
10
10
|
| `test/verification/fuzz-layout.test.ts` | TypeScript model | random pushes, pops, sets, in-place additions, moves and clears on an account with two growable Vecs (honest, out of range and by a stranger): the decoded account equals the model after every step; random `loadAccountMut` index pairs over remaining-account lists that repeat accounts: every alias refused (2040), balances conserved |
|
|
11
11
|
| `test/verification/differential.test.ts` | Anchor twins in `test/anchor-twins` | identical transactions to TypeSOL and Anchor programs: same outcomes, same account contents, same wallet and token balances after every step |
|
|
12
|
-
| `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](
|
|
12
|
+
| `test/porting/ports-*.test.ts` | the Anchor programs of solana-developers/program-examples and their tests | TypeSOL rewrites under `test/ports/` run the originals' flows and failure paths with the same outcomes, error codes and balances ([test/ports/README.md](https://github.com/typesol/typesol/blob/main/test/ports/README.md)) |
|
|
13
13
|
|
|
14
14
|
Compute-unit and binary-size comparisons with Anchor, native Rust and Pinocchio are in the README
|
|
15
15
|
([Numbers](../README.md#numbers)).
|
package/lib/typesol.d.ts
CHANGED
|
@@ -29,6 +29,8 @@ export type i128 = bigint;
|
|
|
29
29
|
export interface Pubkey {
|
|
30
30
|
readonly __pubkey: unique symbol;
|
|
31
31
|
equals(other: Pubkey): boolean;
|
|
32
|
+
/** Rust's order on the 32 bytes (lexicographic): -1, 0 or 1. `a.compare(b) < 0n` is Rust's `a < b`. */
|
|
33
|
+
compare(other: Pubkey): i64;
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
/**
|
|
@@ -394,6 +396,17 @@ export interface TokenMetadataProgram extends AccountMeta {
|
|
|
394
396
|
export declare function masterEditionAddress(mint: Pubkey): Pubkey;
|
|
395
397
|
/** The canonical program address of `seeds` under `program` (Rust `Pubkey::find_program_address(seeds, program).0`). */
|
|
396
398
|
export declare function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey;
|
|
399
|
+
/** The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. */
|
|
400
|
+
export declare function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8;
|
|
401
|
+
/** This program's address (`crate::ID`). */
|
|
402
|
+
export declare function programId(): Pubkey;
|
|
403
|
+
/**
|
|
404
|
+
* Anchor's `AccountLoader::load_init` on an account the instruction created itself (`systemProgram.createAccount`, or
|
|
405
|
+
* `allocate` + `assign` on a pre-funded address): it must be owned by this program (3007), writable (3006), hold the
|
|
406
|
+
* struct (3003) and have no discriminator yet (3000). The discriminator is written and the data is returned to fill.
|
|
407
|
+
* Takes a `Mut<AccountInfo>` parameter or a remaining account.
|
|
408
|
+
*/
|
|
409
|
+
export declare function initAccount<T>(account: AccountMeta | RemainingAccount): T;
|
|
397
410
|
/** The Metaplex metadata account address of a mint. */
|
|
398
411
|
export declare function metadataAddress(mint: Pubkey): Pubkey;
|
|
399
412
|
|
|
@@ -490,6 +503,21 @@ export declare function realloc(account: AccountMeta, newSize: u64, payer: Mut<S
|
|
|
490
503
|
* transferFee: the fee withheld when `amount` is sent now (TransferFeeConfig for the current epoch; 0 without it).
|
|
491
504
|
*/
|
|
492
505
|
export declare function transferFee(mint: AccountMeta | RemainingAccount, amount: u64): u64;
|
|
506
|
+
/**
|
|
507
|
+
* The fee withheld when the recipient is to get `amountReceived` (spl-token-2022's `calculate_inverse_epoch_fee`):
|
|
508
|
+
* send `amountReceived + transferFeeInverse(mint, amountReceived)`. 0 without TransferFeeConfig; fails (5100) where
|
|
509
|
+
* spl-token-2022 has no answer.
|
|
510
|
+
*/
|
|
511
|
+
export declare function transferFeeInverse(mint: AccountMeta | RemainingAccount, amountReceived: u64): u64;
|
|
512
|
+
/** The TransferFeeConfig in force this epoch: its basis points (0 without the extension). */
|
|
513
|
+
export declare function transferFeeBasisPoints(mint: AccountMeta | RemainingAccount): u16;
|
|
514
|
+
/** The TransferFeeConfig in force this epoch: its maximum fee (0 without the extension). */
|
|
515
|
+
export declare function transferFeeMaximum(mint: AccountMeta | RemainingAccount): u64;
|
|
516
|
+
/**
|
|
517
|
+
* Whether every Token-2022 extension of `account` is one of `types` (a list of u16 extension types, e.g.
|
|
518
|
+
* `[1n, 18n, 19n, 10n, 25n]`): a pool that accepts only mints it knows how to handle. True for legacy SPL Token accounts.
|
|
519
|
+
*/
|
|
520
|
+
export declare function extensionsWithin(account: AccountMeta | RemainingAccount, types: u16[]): boolean;
|
|
493
521
|
/** The TransferHook extension's program, if any. */
|
|
494
522
|
export declare function transferHookProgram(mint: AccountMeta | RemainingAccount): Option<Pubkey>;
|
|
495
523
|
/** The TransferHook extension's authority (who may change the hook program), if any. */
|
|
@@ -560,7 +588,7 @@ export type InitIfNeeded<T> = T extends TokenAccount
|
|
|
560
588
|
* associated token account when it does not exist yet, with `payer` funding rent; true when it created it now.
|
|
561
589
|
* An existing account must be that ATA, of that mint and owner.
|
|
562
590
|
*/
|
|
563
|
-
createIfNeeded(payer: Mut<Signer
|
|
591
|
+
createIfNeeded(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): boolean;
|
|
564
592
|
/**
|
|
565
593
|
* Anchor `init_if_needed` + `token::…`: create it as `create(payer, seeds, mint, authority)` does unless it exists;
|
|
566
594
|
* an existing one must be that PDA, a token account of `mint` owned by `authority`. True when it created it now.
|
|
@@ -1332,7 +1360,7 @@ export type Init<T> = T extends TokenAccount
|
|
|
1332
1360
|
* In `Ata<Init<TokenAccount>, "owner", "mint">` (Anchor `init` + `associated_token`): create the associated token
|
|
1333
1361
|
* account of those parameters, with `payer` funding rent. Fails if it already exists.
|
|
1334
1362
|
*/
|
|
1335
|
-
create(payer: Mut<Signer
|
|
1363
|
+
create(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): void;
|
|
1336
1364
|
/**
|
|
1337
1365
|
* Anchor `init` + `token::mint` / `token::authority`: create a token account of `mint` owned by `authority`, at the
|
|
1338
1366
|
* PDA of `seeds` (or, with `null`, a new keypair account that signs), under the instruction's token program, with
|
|
@@ -1425,12 +1453,17 @@ export interface Mint extends AccountMeta {
|
|
|
1425
1453
|
/** The System Program. Its address is checked. */
|
|
1426
1454
|
export interface SystemProgram extends AccountMeta {
|
|
1427
1455
|
readonly __system: void;
|
|
1428
|
-
|
|
1456
|
+
/** `from` signs: a `Mut<Signer>`, or a system-owned PDA of this program (a SOL vault) with its `signerSeeds`. */
|
|
1457
|
+
transfer(from: AccountMeta, to: AccountMeta, lamports: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1429
1458
|
/**
|
|
1430
1459
|
* Create `account` with `space` bytes owned by `owner`, funded by `payer`. The new account signs: a
|
|
1431
1460
|
* `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
|
|
1432
1461
|
*/
|
|
1433
1462
|
createAccount(payer: Mut<Signer>, account: AccountMeta, lamports: u64, space: u64, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1463
|
+
/** System Allocate: give `account` `space` bytes of data. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
|
|
1464
|
+
allocate(account: AccountMeta, space: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1465
|
+
/** System Assign: make `owner` the account's owner. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
|
|
1466
|
+
assign(account: AccountMeta, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1434
1467
|
}
|
|
1435
1468
|
|
|
1436
1469
|
/**
|
|
@@ -1448,6 +1481,10 @@ interface TokenOps {
|
|
|
1448
1481
|
/** Let `delegate` move up to `amount` from `source`. */
|
|
1449
1482
|
approve(source: TokenAccount, delegate: AccountMeta, owner: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1450
1483
|
revoke(source: TokenAccount, owner: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1484
|
+
/** The checked forms read the decimals from `mint`; Token-2022 mints with some extensions require them. */
|
|
1485
|
+
approveChecked(source: TokenAccount, mint: Mint, delegate: AccountMeta, owner: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1486
|
+
mintToChecked(mint: Mint, to: TokenAccount, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1487
|
+
burnChecked(from: TokenAccount, mint: Mint, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1451
1488
|
/** Change or remove (null) an authority of a mint or token account: `AuthorityType.MintTokens`, …. */
|
|
1452
1489
|
setAuthority(target: AccountMeta, currentAuthority: AccountMeta, authorityType: u8, newAuthority: Pubkey | null, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
1453
1490
|
freezeAccount(account: TokenAccount, mint: AccountMeta, freezeAuthority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
|
|
@@ -1618,7 +1655,8 @@ export declare function invoke(
|
|
|
1618
1655
|
program: Program<string> | UncheckedProgram | SystemProgram | TokenProgram | Token2022Program | TokenInterface | RemainingAccount,
|
|
1619
1656
|
accounts: CpiAccount[],
|
|
1620
1657
|
data: CpiData[],
|
|
1621
|
-
|
|
1658
|
+
/** One PDA's seeds (with its bump), or a list of them when several PDAs sign: `[["vault", key, b1], ["fees", b2]]`. */
|
|
1659
|
+
signerSeeds?: Seed[] | SignerSeeds | (Seed[] | SignerSeeds)[],
|
|
1622
1660
|
): void;
|
|
1623
1661
|
|
|
1624
1662
|
/** One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. */
|
|
@@ -1644,7 +1682,7 @@ export declare function invokeInstruction(
|
|
|
1644
1682
|
accounts: IndexedList<InstructionAccountMeta>,
|
|
1645
1683
|
data: IndexedList<u8>,
|
|
1646
1684
|
infos: RemainingAccounts | RemainingSlice,
|
|
1647
|
-
signerSeeds?: Seed[] | SignerSeeds,
|
|
1685
|
+
signerSeeds?: Seed[] | SignerSeeds | (Seed[] | SignerSeeds)[],
|
|
1648
1686
|
): void;
|
|
1649
1687
|
|
|
1650
1688
|
/**
|