@typesol/cli 0.28.0 → 0.29.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/analyze.d.ts +3 -1
  4. package/dist/compiler/analyze.js +21 -7
  5. package/dist/compiler/emit/alias.d.ts +48 -0
  6. package/dist/compiler/emit/alias.js +166 -0
  7. package/dist/compiler/emit/borsh.js +6 -3
  8. package/dist/compiler/emit/calls.js +21 -4
  9. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  10. package/dist/compiler/emit/cpi-core.js +356 -0
  11. package/dist/compiler/emit/cpi.d.ts +3 -177
  12. package/dist/compiler/emit/cpi.js +13 -2721
  13. package/dist/compiler/emit/create.d.ts +39 -0
  14. package/dist/compiler/emit/create.js +548 -0
  15. package/dist/compiler/emit/function.d.ts +11 -2
  16. package/dist/compiler/emit/function.js +42 -7
  17. package/dist/compiler/emit/metaplex.d.ts +78 -0
  18. package/dist/compiler/emit/metaplex.js +1345 -0
  19. package/dist/compiler/emit/program.js +24 -4
  20. package/dist/compiler/emit/shared.d.ts +5 -1
  21. package/dist/compiler/emit/shared.js +11 -2
  22. package/dist/compiler/emit/statements.d.ts +0 -9
  23. package/dist/compiler/emit/statements.js +2 -53
  24. package/dist/compiler/emit/storage.d.ts +5 -20
  25. package/dist/compiler/emit/storage.js +40 -106
  26. package/dist/compiler/emit/token.d.ts +8 -0
  27. package/dist/compiler/emit/token.js +493 -0
  28. package/dist/compiler/model.d.ts +10 -2
  29. package/dist/compiler/model.js +7 -1
  30. package/dist/tools/portgen.js +3 -0
  31. package/docs/architecture.md +29 -1
  32. package/docs/audit.md +3 -2
  33. package/docs/case-study-multisig.md +31 -29
  34. package/docs/errors.md +3 -2
  35. package/docs/language.md +4 -3
  36. package/docs/migrate-from-anchor.md +3 -3
  37. package/docs/security-model.md +1 -1
  38. package/lib/typesol.d.ts +17 -6
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -1
@@ -22,19 +22,21 @@ authority, a treasury.
22
22
  - `set_owners(owners)`, `change_threshold(threshold)` and `set_owners_and_change_threshold(...)` change the multisig;
23
23
  only its PDA can sign them, so they run as stored transactions the multisig executes on itself.
24
24
 
25
- Upstream it is 337 lines of Rust; the port is 184 lines of TypeScript, comments included.
25
+ Upstream it is 337 lines of Rust; the port is 183 lines of TypeScript, comments included.
26
26
 
27
27
  ## What it needed
28
28
 
29
- The port needed five features TypeSOL did not have. They are general features now, each with tests of its own
30
- (`test/language/dynamic-cpi.test.ts`):
29
+ The port needed seven features TypeSOL did not have. They are general features now, each with tests of its own
30
+ (`test/language/dynamic-cpi.test.ts`, `constraint.test.ts`, `borsh-vec.test.ts`):
31
31
 
32
32
  | Anchor | TypeSOL | |
33
33
  | --- | --- | --- |
34
34
  | `invoke_signed(&ix, ctx.remaining_accounts, …)` with `ix` built from account data | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` | A CPI decided at run time. Each meta is a struct with `pubkey`, `isSigner`, `isWritable`. The runtime finds each account among the infos by key and checks privileges, as it does for Rust. |
35
35
  | `#[account(zero, signer)] multisig: Box<Account<'info, Multisig>>` | `Signed<Zeroed<Multisig>>` of a `/** @layout borsh */` struct | `Zeroed` now takes Borsh structs (they start empty and are written as Borsh on return). `Signed<…>` is Anchor's `signer` constraint (2002). `Zeroed` now reports an already-set discriminator first, with Anchor's 2013. |
36
36
  | `seeds = [multisig.key().as_ref()], bump = multisig.nonce` | `Seeds<Signer, ["@multisig"], "@multisig.nonce">` | A bump stored in another account. |
37
- | `multisig.owners = owners` | the same, into a `FixedVec<Pubkey, 34>` | A `Vec` argument copied whole into a list in account data. |
37
+ | `pub owners: Vec<Pubkey>` in an `#[account]` | `owners: Vec<Pubkey>` in a `/** @layout borsh */` struct | Anchor's Vec: any field, held on the heap while the instruction runs, bounded only by the account when it is written back (3004). |
38
+ | `multisig.owners = owners` | the same | A `Vec` argument copied whole into a list in account data. |
39
+ | `#[account(constraint = multisig.owner_set_seqno == transaction.owner_set_seqno)]` | `constraint(multisig, multisig.ownerSetSeqno === transaction.ownerSetSeqno)` | Runs with the account's checks, so a transaction breaking several gets Anchor's code. |
38
40
  | `TransactionAccount { pubkey, is_signer, is_writable }` | `interface TransactionAccount { pubkey; isSigner; isWritable }` | `isSigner` / `isWritable` were reserved field names everywhere; now only in structs held in an account, where they would shadow `acct.isSigner`. |
39
41
 
40
42
  ## Side by side
@@ -74,7 +76,7 @@ export function executeTransaction(
74
76
  multisigSigner: Seeds<AccountInfo, ["@multisig"], "@multisig.nonce">,
75
77
  transaction: HasOne<Mut<Transaction>, "multisig">,
76
78
  ): void {
77
- require(multisig.ownerSetSeqno === transaction.ownerSetSeqno, AnchorError.ConstraintRaw);
79
+ constraint(multisig, multisig.ownerSetSeqno === transaction.ownerSetSeqno);
78
80
  require(!transaction.didExecute, ErrorCode.AlreadyExecuted);
79
81
  let sigCount = 0n;
80
82
  for (const didSign of transaction.signers) if (didSign) sigCount++;
@@ -89,8 +91,8 @@ export function executeTransaction(
89
91
  }
90
92
  ```
91
93
 
92
- The `#[derive(Accounts)]` structs become parameter types. Anchor's `constraint = multisig.owner_set_seqno ==
93
- transaction.owner_set_seqno` becomes the first `require`, raising the same 2003. The error enum keeps its order and
94
+ The `#[derive(Accounts)]` structs become parameter types, and Anchor's `constraint = …` becomes `constraint(…)` at
95
+ the start of the body: it runs with the multisig's checks, raising the same 2003. The error enum keeps its order and
94
96
  messages, so the codes stay 6000–6008. Account and instruction names and the Borsh layout are the original's, so
95
97
  existing clients and existing accounts work with the port unchanged.
96
98
 
@@ -101,7 +103,7 @@ existing clients and existing accounts work with the port unchanged.
101
103
  another, both at `msigUdDB…`, then sends each transaction to both. After each one it requires the same outcome (success,
102
104
  or the same error down to the code) and the same lamports, owner and data bytes for every account involved.
103
105
 
104
- There are 43 transactions:
106
+ There are 52 transactions:
105
107
 
106
108
  - **The upstream test suite** (`tests/multisig.js`): create a 2-of-3 multisig, propose `set_owners`, approve, and
107
109
  execute through the PDA. Then `Assert Unique Owners` (6008).
@@ -114,7 +116,8 @@ There are 43 transactions:
114
116
  - too few approvals (6002);
115
117
  - a wrong PDA (2006);
116
118
  - executing twice (6006);
117
- - a changed owner set invalidating a proposal (2003);
119
+ - a changed owner set invalidating a proposal (2003), also when the proposal belongs to another multisig as well
120
+ (2003 under both: the constraint on `multisig` runs before the transaction's `has_one`);
118
121
  - `set_owners` sent directly, which the PDA cannot sign (3010);
119
122
  - a Transaction passed as a Multisig (3002);
120
123
  - the target program missing from the remaining accounts (the runtime's error).
@@ -125,6 +128,8 @@ There are 43 transactions:
125
128
  - a threshold too high, which fails inside the CPI and fails the whole execution with 6007.
126
129
  - **A real payout**: the PDA sends 1.5 SOL through a System transfer. A stored meta claiming the recipient signed is
127
130
  refused by the runtime under both programs.
131
+ - **An account larger than one transaction can fill**: a multisig with 40 owners in a 2,000-byte account, as the
132
+ original holds it after `set_owners` calls grew the set, proposed to, approved and executed under both.
128
133
 
129
134
  ## Cost
130
135
 
@@ -133,13 +138,13 @@ instruction it runs.
133
138
 
134
139
  | Instruction | Anchor 0.25 (mainnet) | TypeSOL | |
135
140
  | --- | ---: | ---: | ---: |
136
- | `create_multisig` | 3,591 | 564 | −84% |
137
- | `create_transaction` | 6,591 | 1,077 | −84% |
138
- | `approve` | 5,515 | 1,003 | −82% |
139
- | `execute_transaction` → `set_owners` | 15,227 | 4,133 | −73% |
140
- | `execute_transaction` → `change_threshold` | 14,723 | 3,781 | −74% |
141
- | `execute_transaction` → `set_owners_and_change_threshold` | 15,129 | 4,095 | −73% |
142
- | `execute_transaction` → System transfer | 9,961 | 3,182 | −68% |
141
+ | `create_multisig` | 3,591 | 560 | −84% |
142
+ | `create_transaction` | 6,591 | 1,125 | −83% |
143
+ | `approve` | 5,515 | 1,175 | −79% |
144
+ | `execute_transaction` → `set_owners` | 15,227 | 4,313 | −72% |
145
+ | `execute_transaction` → `change_threshold` | 14,723 | 3,972 | −73% |
146
+ | `execute_transaction` → `set_owners_and_change_threshold` | 15,129 | 4,273 | −72% |
147
+ | `execute_transaction` → System transfer | 9,961 | 3,358 | −66% |
143
148
 
144
149
  Refusals cost less too. For example, an already-initialized account costs 3,378 against 160, and a missing signature
145
150
  4,229 against 177. The binary is 526,688 bytes on mainnet and 29,984 bytes for the port, 18 times smaller. Deploying it
@@ -150,18 +155,15 @@ escrow case study and the benchmarks compare against Anchor 1.x.
150
155
 
151
156
  ## Where they differ
152
157
 
153
- - **List capacities.** Anchor's `Vec` fields are bounded only by the account's size. The port's lists are `FixedVec`s:
154
- - 34 owners;
155
- - 32 accounts and 1,100 data bytes per stored instruction;
156
- - 34 approvals.
157
-
158
- A transaction (1,232 bytes) cannot carry more than these, so a client never meets them. A program calling the
159
- multisig through a CPI can send more (CPI data may reach 10 KiB). The original would accept that if the account were
160
- large enough; the port refuses with 5104. Reading an account the original wrote with more elements fails with 3003.
161
- - **Check order on one double fault.** In `approve` and `execute_transaction` the original checks the owner-set
162
- sequence number (2003) with the multisig account, before the transaction's `has_one` (2001). The port checks
163
- `has_one` in the prologue and the sequence number first in the body. So a transaction that belongs to another
164
- multisig *and* has a stale sequence number gets 2001 here and 2003 there. A transaction breaking only one of the two
165
- gets the same code under both.
158
+ - **Accounts per stored instruction.** The port builds the signed metas in a list of 32 and keeps TypeSOL's default of
159
+ 32 accounts per instruction, so `execute_transaction` hands a stored instruction at most 29 remaining accounts. The
160
+ original takes as many as the runtime allows. `const MAX_ACCOUNTS = …n` (up to 255) and a larger list lift this for a
161
+ multisig that needs it.
162
+ - **Heap.** Both hold a Borsh account's lists on the heap (32 KiB by default) while the instruction runs. The port's
163
+ lists grow by doubling, as Rust's do, so both run out at about the same sizes: far beyond what these accounts hold.
166
164
  - **Logs.** Error messages are logged in TypeSOL's words and the original's error names are not logged; codes are the
167
165
  same.
166
+
167
+ Earlier versions of this port held its lists in `FixedVec`s with fixed capacities and checked the owner-set sequence
168
+ number in the body, after `has_one`. Both differences are gone: the lists are Anchor's `Vec`, bounded only by the account,
169
+ and `constraint(…)` runs where Anchor runs it.
package/docs/errors.md CHANGED
@@ -7,6 +7,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
7
7
  | 100 / 101 / 102 | instruction data missing / unknown instruction / malformed arguments (InstructionMissing / FallbackNotFound / DidNotDeserialize) |
8
8
  | 2000 | a `Mut<…>` / `Init<…>` account passed read-only (ConstraintMut) |
9
9
  | 2001 | HasOne constraint failed (ConstraintHasOne) |
10
+ | 2003 | a `constraint(acct, condition)` without its own error failed (ConstraintRaw) |
10
11
  | 2002 | a `Signed<…>` account (or the event authority) did not sign (ConstraintSigner) |
11
12
  | 2004 | Owner constraint failed (ConstraintOwner) |
12
13
  | 2005 | Zeroed account is not rent-exempt (ConstraintRentExempt) |
@@ -43,7 +44,7 @@ Framework errors use Anchor's numbers where Anchor has the same check, so client
43
44
  | 5110 | out of heap building strings |
44
45
  | 5111 | oracle check failed (unverified, stale, wrong feed, no samples) |
45
46
  | 5112 | data enum is not the variant the code expected |
46
- | 5113 | more than 32 accounts in one instruction |
47
+ | 5113 | more accounts in one instruction (or one CPI) than the program takes: 32, or its `MAX_ACCOUNTS` |
47
48
  | 5114 | a function with a result ended without returning one |
48
49
  | 5115 | an optional account that was left out was used |
49
50
  | 6000+ | your error enums' members, in declaration order (imported files first), then one `RequireFailed<N>` error (code 6000 + N) per distinct `require(cond, "message")` string |
@@ -61,7 +62,7 @@ the order Anchor's generated code runs them, so a transaction gets the same code
61
62
  2. Two writable parameters naming one account (2040).
62
63
  3. The instruction's arguments (102).
63
64
  4. Each account in parameter order, its constraints in Anchor's order: seeds (2006), associated token account (owner
64
- 2015, then address 2009), `has_one` (2001), owner (2004), executable (2007), address (2012), then `TokenOf` /
65
+ 2015, then address 2009), `has_one` (2001), `constraint(…)` (2003 or its error), owner (2004), executable (2007), address (2012), then `TokenOf` /
65
66
  `MintOf` (2015, 2014, 2021 / 2016, 2017, 2022).
66
67
 
67
68
  Where TypeSOL's order differs, only a transaction that breaks two of these checks at once sees it:
package/docs/language.md CHANGED
@@ -25,10 +25,10 @@ The full reference. For a tour, start with the [README](../README.md).
25
25
  | Enums | `export enum Status { Pending, Approved }` — unit variants stored as the Borsh u8 index; `Status.Approved`, `===` |
26
26
  | Options | `best: Option<u64>` (or `u64 \| null`) — `null`, `=== null`, TypeScript narrowing; `===` between options or with a value follows JS (null equals null, empty never equals a value); empty use aborts (5108); `acct?.field` on an optional account and `x.home?.field` on an `Option<struct>` give an Option (empty when the account was left out / the option is empty), `a ?? b` takes b only when a is empty (b runs only then; the result is an Option when b can be null), `x!` is the value or aborts with 5108; `${opt}` prints the value or `null`. Borsh `option` in arguments/events, fixed `{ is_some, value }` in account data |
27
27
  | Vecs | `entries: Vec<Entry>` in account data, any number of them, declared anywhere: they are stored after the fixed-size fields in the order declared (so every other field keeps its offset; the IDL lists that order), and a push, pop or clear moves the Vecs after it (a reference into one of those cannot be used across it). In a `@layout borsh` struct a Vec is the last field (Anchor's order) — `get`, `set`, `push(v, payer)`, `pop()`, `clear()`, `.length`; the account is resized (realloc) and rent topped up by `payer`; `Vec<u64>` arguments are read-only views; `Vec<string>` arguments (Anchor's `Vec<String>`) are views of the instruction data, each checked as UTF-8 on entry (102), and go back out as Borsh through `invoke`; `pop()` of a Vec of structs works as a statement |
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>` 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. 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, `loadAccount` or a growable `Vec<T>` |
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
- | 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 32 accounts (5113) |
31
+ | 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
32
  | Struct literals | `book.entries.push({ who: who.key, amount, status: Status.Pending, note }, who)` — every field required |
33
33
  | 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 |
34
34
  | 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) |
@@ -66,6 +66,7 @@ The full reference. For a tour, start with the [README](../README.md).
66
66
  | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
67
67
  | `Init<T>` | writable; `create(payer, seeds)` derives the PDA, verifies it, funds rent, writes the discriminator (up to 10 KiB); `create(payer, null)` creates a new keypair account that signs the transaction instead (3010 if it did not; a signer in the IDL); a third argument is Anchor's `space = …` (discriminator included, at least 8 + the struct's size) |
68
68
  | `InitIfNeeded<T>` | `const created = acct.createIfNeeded(payer, seeds)` — creates once; afterwards re-derives the PDA and checks owner, discriminator and size (Anchor `init_if_needed`); `acct.pdaBump` after create. An existing account is used as it is: check the fields you rely on |
69
+ | `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) |
69
70
  | `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 |
70
71
  | `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) |
71
72
  | `Ata<TokenAccount, "owner", "mint">` | the account is the associated token account of those parameters (2009; ATA `pda` in the IDL) |
@@ -94,7 +95,7 @@ The full reference. For a tour, start with the [README](../README.md).
94
95
  | `AccountInfo` / `Mut<AccountInfo>` | nothing (writable for `Mut`); `owner`, `executable` |
95
96
  | `SystemAccount` / `Mut<SystemAccount>` | owned by the System Program, e.g. a wallet (Anchor `SystemAccount`, 3011) |
96
97
 
97
- Every account exposes `key`, `lamports`, `dataLen`, `isSigner`, `isWritable`. At most 32 accounts per instruction (more is refused, 5113).
98
+ Every account exposes `key`, `lamports`, `dataLen`, `isSigner`, `isWritable`. At most 32 accounts per instruction (more is refused, 5113); `export const MAX_ACCOUNTS = 128n` (up to 255, Anchor takes what the runtime allows) raises it for programs that take many remaining accounts, keeping the CPI scratch lists on the heap instead of the stack (programs that do not declare it compile exactly as before).
98
99
 
99
100
  Two writable parameters can never be the same account: aliasing is refused with error 2040 (also when a remaining
100
101
  account written through `.lamports` or `loadAccountMut` is another account of the instruction). `Dup<Mut<T>>`
@@ -41,7 +41,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
41
41
  | `close = destination` | `CloseTo<Mut<T>, "destination">`, or `close(acct, destination)` in the body |
42
42
  | `address = ADMIN` | `Address<AccountInfo, "Admin1111…">` |
43
43
  | `owner = program`, `executable` | `Owner<A, "…">`, `Executable<A>` |
44
- | `constraint = expr @ MyError::X` | `require(expr, MyError.X)` at the start of the body |
44
+ | `constraint = expr @ MyError::X` (or without an error: 2003) | `constraint(acct, expr, MyError.X)` (or `constraint(acct, expr)`) at the start of the body: it runs with `acct`'s checks, where Anchor runs it |
45
45
  | `realloc = n, realloc::payer = p` | `realloc(acct, n, p)` |
46
46
  | `Option<Account<'info, T>>` | `Mut<T> \| null` (the client passes the program id to leave it out) |
47
47
  | `UncheckedAccount` / `AccountInfo` | `AccountInfo` / `Mut<AccountInfo>`: check what you rely on yourself |
@@ -74,7 +74,7 @@ and error codes. Its notes (on stderr) list what an existing Anchor client would
74
74
  | `u8` … `u128`, `i8` … `i128`, `bool`, `Pubkey` | `u8` … `u128`, `i8` … `i128`, `boolean`, `Pubkey` |
75
75
  | `[T; N]` | `FixedArray<T, N>` |
76
76
  | `String` with `#[max_len(n)]` | `FixedString<N>`: a u32 length and N bytes, always N bytes long |
77
- | `Vec<T>` with `#[max_len(n)]` | `Vec<T>` (any number, declared anywhere, stored after the fixed-size fields; it grows with `push(v, payer)`), or `FixedVec<T, n>`: a u32 length and room for n, always 4 + n × size bytes |
77
+ | `Vec<T>` with `#[max_len(n)]` | `Vec<T>` (any number, declared anywhere, stored after the fixed-size fields; it grows with `push(v, payer)`), or `FixedVec<T, n>`: a u32 length and room for n, always 4 + n × size bytes; in a `@layout borsh` struct, `Vec<T>` is Anchor's own, bounded only by the account |
78
78
  | `Option<T>` | `Option<T>`: fixed size (1 + size of T) |
79
79
  | `#[derive(AnchorSerialize…)] enum` | `export enum` (unit variants) or a data enum `type A = { kind: "X"; … } \| …` |
80
80
 
@@ -112,7 +112,7 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
112
112
  | `token::transfer_checked(CpiContext::new_with_signer(…, seeds), amount, decimals)` | `tokenProgram.transferChecked(from, mint, to, authority, amount, ["seed", key, bump])` |
113
113
  | `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
114
114
  | `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
115
- | `multisig.owners = owners` (a `Vec` argument into account data) | the same, into a `FixedVec<Pubkey, N>` |
115
+ | `multisig.owners = owners` (a `Vec` argument into account data) | the same |
116
116
  | `declare_program!(other)` / CPI to another Anchor program | `typesol cpi other.json` generates typed helpers |
117
117
  | `for x in v.iter()` | `for (const x of v)` |
118
118
  | `v.iter().any(\|x\| …)`, `.all`, `.position`, `.find`, `.fold(init, …)`, `.contains(&x)` | `v.some((x) => …)`, `every`, `findIndex`, `find`, `reduce((acc, x) => …, init)`, `includes(x)` |
@@ -24,7 +24,7 @@ Each holds for every instruction of every program the compiler accepts. A break
24
24
 
25
25
  ### Before the body runs
26
26
 
27
- 1. **Account count.** Fewer accounts than parameters fail (3005); more than 32 in total fail before parsing (5113).
27
+ 1. **Account count.** Fewer accounts than parameters fail (3005); more than the program takes (32, or its `MAX_ACCOUNTS`) fail before parsing (5113).
28
28
  2. **Account types.** Each parameter is checked for what its type says: `Signer` signed (3010); `Mut<…>` writable
29
29
  (2000); a program account (`Account<T>`, `Mut<T>`) owned by this program (3007), initialized (3012), with `T`'s
30
30
  discriminator (3002) and at least its size (3003); `TokenAccount` / `Mint` owned by SPL Token or Token-2022 and an
package/lib/typesol.d.ts CHANGED
@@ -97,15 +97,20 @@ export type Option<T> = T | null;
97
97
  /**
98
98
  * A growable list. As an account struct field it is stored Borsh-style (u32 length + elements) and the account is
99
99
  * resized as it grows. An account may have any number of them, declared anywhere: they are stored after the
100
- * fixed-size fields, in the order declared (in a `@layout borsh` struct, a Vec must be the last field). As an
101
- * instruction argument it is a read-only view.
100
+ * fixed-size fields, in the order declared. In a `@layout borsh` struct it is Anchor's `Vec<T>`: anywhere among the
101
+ * fields, held on the heap while the instruction runs, and bounded only by the account when it is written back
102
+ * (3004). As an instruction argument it is a read-only view.
102
103
  */
103
104
  export interface Vec<T> extends ListMethods<T> {
104
105
  readonly length: u64;
105
106
  get(index: bigint): T;
106
107
  set(index: bigint, value: T): void;
107
- /** Append, growing the account by one element; `payer` tops up rent when needed. */
108
- push(value: T, payer: Mut<Signer>): void;
108
+ /**
109
+ * Append. In account data the account grows by one element and `payer` (required there) tops up rent; in a
110
+ * `@layout borsh` struct the list grows on the heap and takes no payer (the account must hold it when it is written
111
+ * back: 3004, as under Anchor).
112
+ */
113
+ push(value: T, payer?: Mut<Signer>): void;
109
114
  /** Remove and return the last element, shrinking the account. */
110
115
  pop(): T;
111
116
  /** Remove every element, shrinking the account. */
@@ -123,8 +128,7 @@ export interface FixedVec<T, N extends number> extends ListMethods<T> {
123
128
  readonly length: u64;
124
129
  get(index: bigint): T;
125
130
  set(index: bigint, value: T): void;
126
- // `...rest: never[]` takes nothing, but lets a Vec (whose push takes a payer) be assigned to a FixedVec: `acct.owners = owners`.
127
- push(value: T, ...rest: never[]): void;
131
+ push(value: T): void;
128
132
  pop(): T;
129
133
  clear(): void;
130
134
  [Symbol.iterator](): Iterator<T>;
@@ -1732,6 +1736,13 @@ export declare enum AnchorError {
1732
1736
  * 6000 + N, numbered after the program's error enums and listed in the IDL.
1733
1737
  */
1734
1738
  export declare function require(condition: boolean, error: string | AnchorError): asserts condition;
1739
+ /**
1740
+ * Anchor's `constraint = condition @ error` on `account`. Written at the start of an instruction's body (before any
1741
+ * other statement), it runs with that account's checks, after its has_one and before its owner check, so a transaction
1742
+ * that breaks several checks fails with the same code as under Anchor. It may read every account and argument. The
1743
+ * default error is `AnchorError.ConstraintRaw` (2003); `error` is an error-enum member, an `AnchorError` or a string.
1744
+ */
1745
+ export declare function constraint(account: AccountMeta | RemainingAccount | null, condition: boolean, error?: string | AnchorError): void;
1735
1746
 
1736
1747
  /** Write a string, integer or pubkey to the program log. */
1737
1748
  export declare function log(value: string | bigint | Pubkey | Hash): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -268,8 +268,14 @@ _Static_assert(__builtin_offsetof(TsAccount, key) == 8 && __builtin_offsetof(TsA
268
268
  __builtin_offsetof(TsAccount, data) == 88,
269
269
  "TsAccount layout");
270
270
 
271
- /* Accounts per instruction: the entry point refuses more (5113). */
271
+ /* Accounts per instruction: the entry point refuses more (5113). 32 unless the program declares
272
+ `const MAX_ACCOUNTS = …n` (up to 255); above 32 the CPI scratch lists live on the heap (the frame stays small). */
273
+ #ifndef TS_MAX_ACCOUNTS
272
274
  #define TS_MAX_ACCOUNTS 32
275
+ #endif
276
+ #if TS_MAX_ACCOUNTS > 32
277
+ #define TS_SCRATCH_ON_HEAP 1
278
+ #endif
273
279
 
274
280
  /* Lives in the entry point's frame; the arrays are inline so setting it up stores nothing. */
275
281
  typedef struct {
@@ -278,10 +284,43 @@ typedef struct {
278
284
  uint64_t data_len;
279
285
  const SolPubkey *program_id;
280
286
  TsAccount *ka[TS_MAX_ACCOUNTS]; /* ka_num entries */
287
+ #ifdef TS_SCRATCH_ON_HEAP
288
+ SolAccountInfo *infos; /* scratch for CPI account lists, grown on the heap (ts_infos_reserve) */
289
+ uint64_t infos_cap;
290
+ SolAccountMeta *metas; /* scratch for CPI meta lists with remaining accounts (TS_METAS) */
291
+ #else
281
292
  SolAccountInfo infos[TS_MAX_ACCOUNTS]; /* scratch for CPI account lists (ts_invoke) */
293
+ #endif
294
+ #if TS_MAX_ACCOUNTS > 64
295
+ uint64_t loaded_mut[(TS_MAX_ACCOUNTS + 63) / 64]; /* bit i: ka[i] loaded with loadAccountMut */
296
+ #else
282
297
  uint64_t loaded_mut; /* bit i: ka[i] loaded with loadAccountMut (zeroed by the entrypoint of a program that uses it) */
298
+ #endif
283
299
  } TsParams;
284
300
 
301
+ #ifdef TS_SCRATCH_ON_HEAP
302
+ static uint64_t ts_infos_reserve(TsParams *params, uint64_t n);
303
+ static uint64_t ts_metas_scratch(TsParams *params, SolAccountMeta **out);
304
+ #define TS_INFOS_RESERVE(params, n) TS_TRY(ts_infos_reserve(params, n))
305
+ #define TS_METAS_ROOM(m) \
306
+ SolAccountMeta *m; \
307
+ TS_TRY(ts_metas_scratch(params, &m))
308
+ /* A CPI's meta list with room for every account: on the heap, reused by each such CPI. */
309
+ #define TS_METAS(m, ...) \
310
+ SolAccountMeta *m; \
311
+ TS_TRY(ts_metas_scratch(params, &m)); \
312
+ { \
313
+ const SolAccountMeta m##_init[] = {__VA_ARGS__}; \
314
+ ts_memcpy(m, m##_init, sizeof(m##_init)); \
315
+ }
316
+ #else
317
+ #define TS_INFOS_RESERVE(params, n) \
318
+ do { \
319
+ } while (0)
320
+ #define TS_METAS(m, ...) SolAccountMeta m[TS_MAX_ACCOUNTS] = {__VA_ARGS__}
321
+ #define TS_METAS_ROOM(m) SolAccountMeta m[TS_MAX_ACCOUNTS]
322
+ #endif
323
+
285
324
  /*
286
325
  * Same bounds as the SDK's sol_deserialize, minus its per-account "past the array" branch: the entry point has
287
326
  * already refused counts above TS_MAX_ACCOUNTS (the size of `params->ka`), so every account fits.
@@ -331,6 +370,7 @@ static inline __attribute__((always_inline)) void ts_info(const TsAccount *a, So
331
370
  static inline __attribute__((always_inline)) uint64_t ts_invoke(TsParams *params, const SolInstruction *ix, const SolSignerSeeds *signers, int nsigners) {
332
371
  /* At most TS_MAX_ACCOUNTS metas (the compiler refuses longer lists), the size of `params->infos`. A repeated
333
372
  account gets a record per mention, which the runtime accepts. */
373
+ TS_INFOS_RESERVE(params, ix->account_len);
334
374
  SolAccountInfo *infos = params->infos;
335
375
  for (uint64_t i = 0; i < ix->account_len; i++) ts_info((const TsAccount *)((const uint8_t *)ix->accounts[i].pubkey - 8), &infos[i]);
336
376
  return sol_invoke_signed(ix, infos, ix->account_len, signers, nsigners);
@@ -455,8 +495,13 @@ static inline uint64_t ts_claim_mut(TsParams *params, const TsAccount *a) {
455
495
  for (uint64_t i = 0; i < params->ka_num; i++)
456
496
  if (params->ka[i] == a) seen++, at = i;
457
497
  if (seen > 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account passed more than once");
498
+ #if TS_MAX_ACCOUNTS > 64
499
+ if (params->loaded_mut[at >> 6] >> (at & 63) & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
500
+ params->loaded_mut[at >> 6] |= (uint64_t)1 << (at & 63);
501
+ #else
458
502
  if (params->loaded_mut >> at & 1) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: account already loaded with loadAccountMut");
459
503
  params->loaded_mut |= (uint64_t)1 << at;
504
+ #endif
460
505
  return SUCCESS;
461
506
  }
462
507
 
@@ -1272,6 +1317,45 @@ static inline uint64_t ts_alloc(uint64_t n, uint8_t **out) {
1272
1317
  return SUCCESS;
1273
1318
  }
1274
1319
 
1320
+ /* A heap Vec (a Vec<T> in a @layout borsh struct, held on the heap while the instruction runs): room for at least
1321
+ `need` elements of `size` bytes, doubling as Rust's Vec does. Elements move when it grows (the compiler refuses
1322
+ references into it that would outlive a push). Bounded by the heap; the account bounds it when it is packed (3004). */
1323
+ typedef struct __attribute__((packed)) {
1324
+ uint32_t len;
1325
+ uint32_t cap;
1326
+ uint8_t *items;
1327
+ } TsHeapVec;
1328
+ static uint64_t ts_hvec_reserve(void *vec, uint64_t need, uint64_t size) {
1329
+ TsHeapVec *v = (TsHeapVec *)vec;
1330
+ if (need <= v->cap) return SUCCESS;
1331
+ uint64_t cap = v->cap ? (uint64_t)v->cap * 2 : 4;
1332
+ if (cap < need) cap = need;
1333
+ if (cap > 0xffffffffULL) TS_FAIL(TS_ERR_HEAP, "TypeSOL: out of heap");
1334
+ uint8_t *items;
1335
+ TS_TRY(ts_alloc(cap * size, &items));
1336
+ if (v->len) ts_memcpy(items, v->items, (uint64_t)v->len * size);
1337
+ v->items = items;
1338
+ v->cap = (uint32_t)cap;
1339
+ return SUCCESS;
1340
+ }
1341
+
1342
+ #ifdef TS_SCRATCH_ON_HEAP
1343
+ /* Room for `n` SolAccountInfo records in the CPI scratch, doubling (the heap is never freed). */
1344
+ static uint64_t ts_infos_reserve(TsParams *params, uint64_t n) {
1345
+ if (n <= params->infos_cap) return SUCCESS;
1346
+ uint64_t cap = params->infos_cap ? params->infos_cap * 2 : 16;
1347
+ if (cap < n) cap = n;
1348
+ TS_TRY(ts_alloc(cap * sizeof(SolAccountInfo), (uint8_t **)&params->infos));
1349
+ params->infos_cap = cap;
1350
+ return SUCCESS;
1351
+ }
1352
+ static uint64_t ts_metas_scratch(TsParams *params, SolAccountMeta **out) {
1353
+ if (!params->metas) TS_TRY(ts_alloc(TS_MAX_ACCOUNTS * sizeof(SolAccountMeta), (uint8_t **)&params->metas));
1354
+ *out = params->metas;
1355
+ return SUCCESS;
1356
+ }
1357
+ #endif
1358
+
1275
1359
  /* Base58 text of a 32-byte value (a Pubkey or Hash in a template), on the heap. The value is eight big-endian u32
1276
1360
  limbs divided by 58^5 at a time, so each pass gives five digits with one 64-bit division per limb. */
1277
1361
  static uint64_t ts_base58_32(const uint8_t *in, TS_Str *out) {