@typesol/cli 0.31.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/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
- | 3000 | account already exists (AccountDiscriminatorAlreadySet; an `Init` account) |
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 |
@@ -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: Mut<Signer>, to, lamports)`, `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`
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`, `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
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
- `t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else, e.g. writing a mint straight into the VM
54
- with `t.svm.setAccount` (see the escrow template). `programHarness(svm, programId, idl)` gives the same helpers for a
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](../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
 
@@ -575,7 +588,7 @@ export type InitIfNeeded<T> = T extends TokenAccount
575
588
  * associated token account when it does not exist yet, with `payer` funding rent; true when it created it now.
576
589
  * An existing account must be that ATA, of that mint and owner.
577
590
  */
578
- createIfNeeded(payer: Mut<Signer>): boolean;
591
+ createIfNeeded(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): boolean;
579
592
  /**
580
593
  * Anchor `init_if_needed` + `token::…`: create it as `create(payer, seeds, mint, authority)` does unless it exists;
581
594
  * an existing one must be that PDA, a token account of `mint` owned by `authority`. True when it created it now.
@@ -1347,7 +1360,7 @@ export type Init<T> = T extends TokenAccount
1347
1360
  * In `Ata<Init<TokenAccount>, "owner", "mint">` (Anchor `init` + `associated_token`): create the associated token
1348
1361
  * account of those parameters, with `payer` funding rent. Fails if it already exists.
1349
1362
  */
1350
- create(payer: Mut<Signer>): void;
1363
+ create(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): void;
1351
1364
  /**
1352
1365
  * Anchor `init` + `token::mint` / `token::authority`: create a token account of `mint` owned by `authority`, at the
1353
1366
  * PDA of `seeds` (or, with `null`, a new keypair account that signs), under the instruction's token program, with
@@ -1440,12 +1453,17 @@ export interface Mint extends AccountMeta {
1440
1453
  /** The System Program. Its address is checked. */
1441
1454
  export interface SystemProgram extends AccountMeta {
1442
1455
  readonly __system: void;
1443
- transfer(from: Mut<Signer>, to: AccountMeta, lamports: u64): void;
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;
1444
1458
  /**
1445
1459
  * Create `account` with `space` bytes owned by `owner`, funded by `payer`. The new account signs: a
1446
1460
  * `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
1447
1461
  */
1448
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;
1449
1467
  }
1450
1468
 
1451
1469
  /**
@@ -1463,6 +1481,10 @@ interface TokenOps {
1463
1481
  /** Let `delegate` move up to `amount` from `source`. */
1464
1482
  approve(source: TokenAccount, delegate: AccountMeta, owner: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1465
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;
1466
1488
  /** Change or remove (null) an authority of a mint or token account: `AuthorityType.MintTokens`, …. */
1467
1489
  setAuthority(target: AccountMeta, currentAuthority: AccountMeta, authorityType: u8, newAuthority: Pubkey | null, signerSeeds?: Seed[] | SignerSeeds): void;
1468
1490
  freezeAccount(account: TokenAccount, mint: AccountMeta, freezeAuthority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
@@ -1633,7 +1655,8 @@ export declare function invoke(
1633
1655
  program: Program<string> | UncheckedProgram | SystemProgram | TokenProgram | Token2022Program | TokenInterface | RemainingAccount,
1634
1656
  accounts: CpiAccount[],
1635
1657
  data: CpiData[],
1636
- signerSeeds?: Seed[] | SignerSeeds,
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)[],
1637
1660
  ): void;
1638
1661
 
1639
1662
  /** One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. */
@@ -1659,7 +1682,7 @@ export declare function invokeInstruction(
1659
1682
  accounts: IndexedList<InstructionAccountMeta>,
1660
1683
  data: IndexedList<u8>,
1661
1684
  infos: RemainingAccounts | RemainingSlice,
1662
- signerSeeds?: Seed[] | SignerSeeds,
1685
+ signerSeeds?: Seed[] | SignerSeeds | (Seed[] | SignerSeeds)[],
1663
1686
  ): void;
1664
1687
 
1665
1688
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,6 +37,7 @@
37
37
  #define TS_ERR_MINT_TOKEN_PROGRAM 2022 /* ConstraintMintTokenProgram */
38
38
  #define TS_ERR_DUPLICATE_MUT 2040 /* ConstraintDuplicateMutableAccount */
39
39
  #define TS_ERR_ALREADY_INITIALIZED 3000 /* AccountDiscriminatorAlreadySet */
40
+ #define TS_ERR_INIT_PAYER 4101 /* TryingToInitPayerAsProgramAccount */
40
41
  #define TS_ERR_DISCRIMINATOR 3002 /* AccountDiscriminatorMismatch */
41
42
  #define TS_ERR_ACCOUNT_TOO_SMALL 3003 /* AccountDidNotDeserialize */
42
43
  #define TS_ERR_DID_NOT_SERIALIZE 3004 /* AccountDidNotSerialize */
@@ -160,6 +161,31 @@ static inline __attribute__((always_inline)) bool ts_mul_overflow_u64(uint64_t a
160
161
  return __builtin_mul_overflow(a, b, out);
161
162
  }
162
163
 
164
+ /*
165
+ * u128 arithmetic: the 128-bit library routines (__muloti4, __udivti3) cost hundreds of CU on SBF. Values that fit in
166
+ * 64 bits (most amounts and rates) take the native 64-bit instructions instead; the results are the same.
167
+ */
168
+ static inline __attribute__((always_inline)) bool ts_mul_overflow_u128(unsigned __int128 a, unsigned __int128 b, unsigned __int128 *out) {
169
+ if (((a | b) >> 32) == 0) {
170
+ const uint64_t product = (uint64_t)a * (uint64_t)b; /* both below 2^32: the product fits in 64 bits */
171
+ *out = product;
172
+ return false;
173
+ }
174
+ if (((a | b) >> 64) == 0) {
175
+ *out = (unsigned __int128)(uint64_t)a * (uint64_t)b; /* below 2^128: cannot overflow */
176
+ return false;
177
+ }
178
+ return __builtin_mul_overflow(a, b, out);
179
+ }
180
+ static inline __attribute__((always_inline)) unsigned __int128 ts_div_u128(unsigned __int128 a, unsigned __int128 b) {
181
+ if (((a | b) >> 64) == 0) return (uint64_t)a / (uint64_t)b;
182
+ return a / b;
183
+ }
184
+ static inline __attribute__((always_inline)) unsigned __int128 ts_rem_u128(unsigned __int128 a, unsigned __int128 b) {
185
+ if (((a | b) >> 64) == 0) return (uint64_t)a % (uint64_t)b;
186
+ return a % b;
187
+ }
188
+
163
189
  /* ---- Well-known program ids --------------------------------------------- */
164
190
  static const SolPubkey TS_SYSTEM_PROGRAM_ID = {{0}};
165
191
  /* TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA */
@@ -687,6 +713,12 @@ static inline uint64_t ts_event_dispatch(TsParams *params) {
687
713
  return ts_check_event_authority(params->ka[0], params->program_id, &bump);
688
714
  }
689
715
 
716
+ /* The Clock sysvar into `clock` (an instruction keeps it: the Clock does not change within a transaction). */
717
+ static inline uint64_t ts_read_clock(uint64_t clock[5]) {
718
+ if (sol_get_clock_sysvar(clock) != SUCCESS) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: clock sysvar unavailable");
719
+ return SUCCESS;
720
+ }
721
+
690
722
  static inline uint64_t ts_now(int64_t *out) {
691
723
  /* Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp } */
692
724
  uint64_t clock[5] = {0};
@@ -716,6 +748,23 @@ static inline uint64_t ts_init_zeroed(TsAccount *a, const uint8_t disc[8]) {
716
748
  return SUCCESS;
717
749
  }
718
750
 
751
+ /* initAccount<T>: Anchor's AccountLoader::load_init on an account the body created. */
752
+ static inline uint64_t ts_init_account(TsAccount *a, const SolPubkey *program_id, const uint8_t disc[8], uint64_t size) {
753
+ if (!ts_key_eq(&a->owner, program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");
754
+ if (!a->is_writable) TS_FAIL(TS_ERR_NOT_WRITABLE, "TypeSOL: account is not writable");
755
+ if (a->data_len < 8 + size) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");
756
+ if (ts_ld64(a->data) != 0) TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already initialized");
757
+ ts_memcpy(a->data, disc, 8);
758
+ return SUCCESS;
759
+ }
760
+
761
+ /* Pubkey order: Rust's Ord on [u8; 32], lexicographic. */
762
+ static inline int64_t ts_key_cmp(const SolPubkey *a, const SolPubkey *b) {
763
+ for (int i = 0; i < 32; i++)
764
+ if (a->x[i] != b->x[i]) return a->x[i] < b->x[i] ? -1 : 1;
765
+ return 0;
766
+ }
767
+
719
768
  /* ---- PDA ----------------------------------------------------------------- */
720
769
  static inline uint64_t ts_require_pda(const TsAccount *a, const SolSignerSeed *seeds, int n,
721
770
  const SolPubkey *program_id) {
@@ -726,15 +775,22 @@ static inline uint64_t ts_require_pda(const TsAccount *a, const SolSignerSeed *s
726
775
  }
727
776
 
728
777
  /* ---- System program CPIs ------------------------------------------------- */
729
- static inline uint64_t ts_system_transfer(TsParams *params, TsAccount *from, TsAccount *to,
730
- uint64_t lamports) {
778
+ static inline uint64_t ts_system_transfer_signed(TsParams *params, TsAccount *from, TsAccount *to,
779
+ uint64_t lamports, const SolSignerSeed *seeds, int nseeds) {
731
780
  uint8_t data[12];
732
781
  uint32_t tag = 2;
733
782
  ts_memcpy(data, &tag, 4);
734
783
  ts_memcpy(data + 4, &lamports, 8);
735
784
  SolAccountMeta metas[2] = {{&from->key, true, true}, {&to->key, true, false}};
736
785
  SolInstruction ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, metas, 2, data, sizeof(data)};
737
- return ts_invoke(params, &ix, NULL, 0);
786
+ if (nseeds == 0) return ts_invoke(params, &ix, NULL, 0);
787
+ SolSignerSeeds signer = {seeds, (uint64_t)nseeds};
788
+ return ts_invoke(params, &ix, &signer, 1);
789
+ }
790
+
791
+ static inline uint64_t ts_system_transfer(TsParams *params, TsAccount *from, TsAccount *to,
792
+ uint64_t lamports) {
793
+ return ts_system_transfer_signed(params, from, to, lamports, NULL, 0);
738
794
  }
739
795
 
740
796
  /*
@@ -749,8 +805,8 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
749
805
  if (ts_find_pda(seeds, n, params->program_id, &derived, &bump) != SUCCESS ||
750
806
  !ts_key_eq(&derived, &acct->key))
751
807
  TS_FAIL(TS_ERR_SEEDS, "TypeSOL: PDA seeds do not match account");
752
- if (acct->data_len != 0 || !ts_key_eq(&acct->owner, &TS_SYSTEM_PROGRAM_ID))
753
- TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already exists");
808
+ /* No check that the address is free: as Anchor's init, the System Program refuses one in use (AccountAlreadyInUse,
809
+ custom 0), so a second create fails with the same error under both. */
754
810
  uint64_t lamports;
755
811
  TS_TRY(ts_minimum_balance(space, &lamports));
756
812
  seeds[n].addr = &bump;
@@ -769,6 +825,7 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
769
825
  TS_TRY(ts_invoke(params, &ix, &signer, 1));
770
826
  } else {
771
827
  /* Someone pre-funded the address (CreateAccount would fail): top up, allocate, assign. */
828
+ if (ts_key_eq(&payer->key, &acct->key)) TS_FAIL(TS_ERR_INIT_PAYER, "TypeSOL: the payer cannot be the account created");
772
829
  if (acct->lamports < lamports) TS_TRY(ts_system_transfer(params, payer, acct, lamports - acct->lamports));
773
830
  uint8_t alloc[12];
774
831
  uint32_t alloc_tag = 8; /* Allocate */
@@ -808,8 +865,8 @@ static inline uint64_t ts_create_owned(TsParams *params, TsAccount *payer, TsAcc
808
865
  } else if (!acct->is_signer) {
809
866
  TS_FAIL(TS_ERR_NOT_SIGNER, "TypeSOL: a new keypair account must sign");
810
867
  }
811
- if (acct->data_len != 0 || !ts_key_eq(&acct->owner, &TS_SYSTEM_PROGRAM_ID))
812
- TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already exists");
868
+ /* No check that the address is free: as Anchor's init, the System Program refuses one in use (AccountAlreadyInUse,
869
+ custom 0), so a second create fails with the same error under both. */
813
870
  uint64_t lamports;
814
871
  TS_TRY(ts_minimum_balance(space, &lamports));
815
872
  SolSignerSeeds signer = {seeds, (uint64_t)(n + 1)};
@@ -826,6 +883,7 @@ static inline uint64_t ts_create_owned(TsParams *params, TsAccount *payer, TsAcc
826
883
  SolInstruction ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, metas, 2, data, sizeof(data)};
827
884
  TS_TRY(ts_invoke(params, &ix, signers, nsigners));
828
885
  } else {
886
+ if (ts_key_eq(&payer->key, &acct->key)) TS_FAIL(TS_ERR_INIT_PAYER, "TypeSOL: the payer cannot be the account created");
829
887
  if (acct->lamports < lamports) TS_TRY(ts_system_transfer(params, payer, acct, lamports - acct->lamports));
830
888
  uint8_t alloc[12];
831
889
  uint32_t alloc_tag = 8; /* Allocate */