@typesol/cli 0.33.0 → 0.35.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.
@@ -0,0 +1,40 @@
1
+ export interface ClonedAccount {
2
+ address: string;
3
+ lamports: string;
4
+ owner: string;
5
+ executable: boolean;
6
+ data: string;
7
+ }
8
+ interface RpcAccount {
9
+ lamports: bigint | number;
10
+ owner: string;
11
+ executable: boolean;
12
+ data: [string, string];
13
+ }
14
+ /** What the clone needs of an RPC: kit's `getMultipleAccounts(…, { encoding: "base64" })`. */
15
+ export interface CloneRpc {
16
+ getMultipleAccounts(addresses: never[], config: {
17
+ encoding: "base64";
18
+ }): {
19
+ send(): Promise<{
20
+ value: (RpcAccount | null)[];
21
+ }>;
22
+ };
23
+ }
24
+ /** Fetch `addresses` and write them to `dir`. Returns what was written, one line per account. */
25
+ export declare function cloneAccounts(rpc: CloneRpc, addresses: string[], dir: string): Promise<string[]>;
26
+ /** What loading needs of a LiteSVM. */
27
+ export interface CloneSvm {
28
+ setAccount(account: {
29
+ address: never;
30
+ lamports: never;
31
+ programAddress: never;
32
+ executable: boolean;
33
+ data: Uint8Array;
34
+ space: bigint;
35
+ }): unknown;
36
+ addProgramFromFile(programId: never, path: string): unknown;
37
+ }
38
+ /** Load every account and program `cloneAccounts` wrote to `dir` into `svm`. Returns how many. */
39
+ export declare function loadClonedAccounts(svm: CloneSvm, dir: string): number;
40
+ export {};
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Copies of cluster accounts for tests (Anchor's `[test.validator.clone]`): `typesol clone` fetches them once and
3
+ * writes them under `tests/accounts/`, and `testProgram` loads that directory into its LiteSVM.
4
+ *
5
+ * - an account: `<address>.json` with its lamports, owner, executable flag and data (base64);
6
+ * - a program: `<address>.so`, its ELF (from the ProgramData account for the upgradeable loader), loaded with
7
+ * `addProgramFromFile`.
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
10
+ import path from "node:path";
11
+ const UPGRADEABLE_LOADER = "BPFLoaderUpgradeab1e11111111111111111111111";
12
+ const LOADERS = new Set(["BPFLoader2111111111111111111111111111111111", "BPFLoader1111111111111111111111111111111111"]);
13
+ /** ProgramData: u32 tag, u64 slot, Option<Pubkey> authority (1 + 32), then the ELF. */
14
+ const PROGRAM_DATA_HEADER = 45;
15
+ async function fetchAll(rpc, addresses) {
16
+ const out = [];
17
+ for (let i = 0; i < addresses.length; i += 100) {
18
+ const { value } = await rpc.getMultipleAccounts(addresses.slice(i, i + 100), { encoding: "base64" }).send();
19
+ out.push(...value);
20
+ }
21
+ return out;
22
+ }
23
+ /** Fetch `addresses` and write them to `dir`. Returns what was written, one line per account. */
24
+ export async function cloneAccounts(rpc, addresses, dir) {
25
+ mkdirSync(dir, { recursive: true });
26
+ const accounts = await fetchAll(rpc, addresses);
27
+ const missing = addresses.filter((_, i) => !accounts[i]);
28
+ if (missing.length)
29
+ throw new Error(`not found on the cluster: ${missing.join(", ")}`);
30
+ const written = [];
31
+ // Upgradeable programs: the ELF is in their ProgramData account (named in the program account's data).
32
+ const programData = new Map();
33
+ accounts.forEach((a, i) => {
34
+ if (a.executable && a.owner === UPGRADEABLE_LOADER) {
35
+ const raw = Buffer.from(a.data[0], "base64");
36
+ if (raw.length < 36 || raw.readUInt32LE(0) !== 2)
37
+ throw new Error(`${addresses[i]}: not an upgradeable program account`);
38
+ programData.set(addresses[i], base58(raw.subarray(4, 36)));
39
+ }
40
+ });
41
+ const datas = await fetchAll(rpc, [...programData.values()]);
42
+ const elfOf = new Map([...programData.keys()].map((p, i) => [p, datas[i]]));
43
+ accounts.forEach((a, i) => {
44
+ const address = addresses[i];
45
+ if (a.executable && (a.owner === UPGRADEABLE_LOADER || LOADERS.has(a.owner))) {
46
+ const pd = elfOf.get(address);
47
+ if (a.owner === UPGRADEABLE_LOADER && !pd)
48
+ throw new Error(`${address}: its ProgramData account is gone (the program was closed)`);
49
+ const elf = pd ? Buffer.from(pd.data[0], "base64").subarray(PROGRAM_DATA_HEADER) : Buffer.from(a.data[0], "base64");
50
+ writeFileSync(path.join(dir, `${address}.so`), elf);
51
+ written.push(`${address}.so program, ${elf.length} bytes`);
52
+ return;
53
+ }
54
+ const entry = { address, lamports: String(a.lamports), owner: a.owner, executable: a.executable, data: a.data[0] };
55
+ writeFileSync(path.join(dir, `${address}.json`), JSON.stringify(entry, null, 2) + "\n");
56
+ written.push(`${address}.json ${Buffer.from(a.data[0], "base64").length} bytes, owner ${a.owner}`);
57
+ });
58
+ return written;
59
+ }
60
+ /** Load every account and program `cloneAccounts` wrote to `dir` into `svm`. Returns how many. */
61
+ export function loadClonedAccounts(svm, dir) {
62
+ if (!existsSync(dir))
63
+ return 0;
64
+ let n = 0;
65
+ for (const f of readdirSync(dir).sort()) {
66
+ const file = path.join(dir, f);
67
+ if (f.endsWith(".so")) {
68
+ svm.addProgramFromFile(f.slice(0, -3), file);
69
+ n++;
70
+ }
71
+ else if (f.endsWith(".json")) {
72
+ const a = JSON.parse(readFileSync(file, "utf8"));
73
+ const data = new Uint8Array(Buffer.from(a.data, "base64"));
74
+ svm.setAccount({
75
+ address: a.address,
76
+ lamports: BigInt(a.lamports),
77
+ programAddress: a.owner,
78
+ executable: a.executable,
79
+ data,
80
+ space: BigInt(data.length),
81
+ });
82
+ n++;
83
+ }
84
+ }
85
+ return n;
86
+ }
87
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
88
+ function base58(bytes) {
89
+ let n = 0n;
90
+ for (const b of bytes)
91
+ n = (n << 8n) | BigInt(b);
92
+ let out = "";
93
+ while (n > 0n) {
94
+ out = ALPHABET[Number(n % 58n)] + out;
95
+ n /= 58n;
96
+ }
97
+ for (const b of bytes) {
98
+ if (b !== 0)
99
+ break;
100
+ out = "1" + out;
101
+ }
102
+ return out;
103
+ }
@@ -12,6 +12,10 @@ export interface Workspace {
12
12
  programs: Record<string, ProgramEntry>;
13
13
  out: string;
14
14
  sbpf: Sbpf;
15
+ /** Cluster accounts `typesol clone` copies for the tests (Anchor's `[test.validator.clone]`). */
16
+ clone: string[];
17
+ /** Where cloned accounts are kept and testProgram loads them from (default tests/accounts). */
18
+ accounts: string;
15
19
  }
16
20
  export declare function findWorkspace(dir: string): Workspace | undefined;
17
21
  export interface ProgramPaths {
package/dist/workspace.js CHANGED
@@ -48,7 +48,19 @@ function readWorkspace(file) {
48
48
  throw new Error(`${file}: program "${name}" needs a snake_case name and { "path": "…", "address"?: "…" } (or just the path)`);
49
49
  programs[name] = e;
50
50
  }
51
- return { root: path.dirname(file), file, programs, out: raw.out ?? "target", sbpf: raw.sbpf ?? "v0" };
51
+ if (raw.clone !== undefined && (!Array.isArray(raw.clone) || raw.clone.some((a) => typeof a !== "string")))
52
+ throw new Error(`${file}: "clone" must be a list of base58 addresses`);
53
+ if (raw.accounts !== undefined && typeof raw.accounts !== "string")
54
+ throw new Error(`${file}: "accounts" must be a directory path`);
55
+ return {
56
+ root: path.dirname(file),
57
+ file,
58
+ programs,
59
+ out: raw.out ?? "target",
60
+ sbpf: raw.sbpf ?? "v0",
61
+ clone: raw.clone ?? [],
62
+ accounts: path.resolve(path.dirname(file), raw.accounts ?? "tests/accounts"),
63
+ };
52
64
  }
53
65
  export function programPaths(ws, name) {
54
66
  const entry = ws.programs[name];
package/docs/cli.md CHANGED
@@ -12,6 +12,7 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
12
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. |
13
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. |
14
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). |
15
+ | `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
15
16
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
16
17
  | `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. |
17
18
  | `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
 
36
- `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
37
+ `"clone": ["<address>", …]` lists the cluster accounts `typesol clone` copies for the tests, and `"accounts"` where
38
+ they are kept (default `tests/accounts`). `"programs": { "vault": "programs/vault.ts" }` (a plain path) is accepted too. Keep `target/deploy/*-keypair.json`
37
39
  safe and out of git: it is each program's address and its first upgrade authority must not lose it. A clone without
38
40
  it still builds and tests (`npm test` builds first) at the recorded address; deploying needs it.
39
41
 
package/docs/language.md CHANGED
@@ -50,7 +50,7 @@ The full reference. For a tour, start with the [README](../README.md).
50
50
  | Generic helpers | `function max<T extends bigint>(a: T, b: T): T` — compiled once per set of types it is called with (`max(a, b)` with u64 arguments, or `max<u128>(x, 1n)` when only literals tell); a type parameter stands for an integer, boolean, Pubkey, enum or fixed-size struct (`pick<Point>(…)`, or from struct arguments; a struct `T` is copied like any struct value). Each instance is checked like any helper; one that is never called is not compiled (TypeScript still type-checks it). Arithmetic on `T` is a `bigint` to TypeScript: `return (a + b) as T` (`as` names a type the value already has; it never converts) |
51
51
  | Evaluation order | operands and arguments are read left to right, as in JS, even when a later one changes account data (`v.length + v.pop()`) |
52
52
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
53
- | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent) |
53
+ | Sysvars | `now()`, `currentSlot()`, `currentEpoch()` (clock), `minimumBalance(account)`, `rentExempt(space)` (rent); `slotHashes: SlotHashesSysvar` (an account, too large for the sysvar syscalls): `count`, `latestSlot`, `latestHash` (public: not a source of secret randomness); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()` |
54
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) |
55
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) |
56
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) |
@@ -67,7 +67,8 @@ The full reference. For a tour, start with the [README](../README.md).
67
67
  | `Account<T>` / `Mut<T>` | owned by this program, 8-byte discriminator matches, data large enough (and writable) |
68
68
  | `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) |
69
69
  | `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 |
70
- | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`); a group may not be optional, nest another group, or be a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
70
+ | `/** @fallback */ export function legacy(): void` | Anchor's `fallback`: runs when no instruction's discriminator matches the data (short data too) instead of failing with 101; it takes no parameters and reads `const data = instructionData()` (the whole data: `data.length`, `data.get(i)`, or passed on to `invokeInstruction`) and `remainingAccounts()`. Not in the IDL |
71
+ | Account groups: `p: PoolAccounts`, where `export interface PoolAccounts { pool: HasOne<Mut<Pool>, "vault">; vault: Mut<TokenAccount>; … }` | Anchor's composite accounts (a `#[derive(Accounts)]` struct as a field of another): an interface whose fields are accounts is one parameter, its accounts the instruction's in field order. The body uses `p.pool.reserve`, passes `p.vault` to CPIs and helpers, and creates `p.pool.create(…)`. Constraints inside name the group's own fields first (`HasOne<…, "vault">`, `Seeds<…, ["pool", "@mint"]>`, `TokenOf<…, "mint", "pool">`), then the instruction's. The IDL nests them (`{ name: "p", accounts: [...] }`, seeds relative to the group); the client and `t.ix` flatten them (`pPool`, `pVault`). A field may be optional (`A \| null`) or another group (`p.fees.vault`; the IDL nests it too, the client flattens it to `pFeesVault`); a group may not be optional or a helper parameter. Its checks run with the instruction's, in order, after every account's type checks (Anchor runs a group's constraints before later accounts' type checks: only a transaction failing both sees a different code) |
71
72
  | `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) |
72
73
  | `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 |
73
74
  | `HasOne<A, "owner", ErrorCode.NotOwner>`, `Address<A, "…", E.X>`, `Owner<A, "…", E.X>`, `Signed<A, E.X>`, `Mut<T, E.X>` | one of your errors instead of Anchor's code, as Anchor's `has_one = owner @ ErrorCode.NotOwner`, `address = … @ …`, `owner = … @ …`, `signer @ …` and `mut @ …` (the constraints Anchor lets you name an error for); a member of one of the program's error enums. For several `HasOne` fields with different errors, nest them: `HasOne<HasOne<Mut<V>, "owner", E.A>, "admin", E.B>` |
@@ -90,7 +91,9 @@ The full reference. For a tour, start with the [README](../README.md).
90
91
  | `SystemProgram`, `TokenProgram`, `Token2022Program` | exact program address |
91
92
  | `TokenInterface` | either token program |
92
93
  | `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
93
- | `TokenMetadataProgram` | Metaplex `createV3(...)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection: mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be `verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection); `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply \| null)`; `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar)` (Verify with CollectionV1); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
94
+ | `MemoProgram` | SPL Memo v2: `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA of this program with its seeds) |
95
+ | `TokenMetadataProgram` | Metaplex `createV3(...)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection: mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be `verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection); `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply \| null)`; `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar)` (Verify with CollectionV1); `updateMetadataAccountsV2(metadata, updateAuthority, data \| null, newUpdateAuthority \| null, primarySaleHappened \| null, isMutable \| null)` (`data` replaces the whole DataV2: `{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`; each null leaves that part); `burnV1(authority, metadata, edition \| null, mint, token, collectionMetadata \| null, systemProgram, instructionsSysvar, tokenProgram, amount)` (Burn: the holder signs and gets the rent back; the token account and edition close, the metadata is cleared to one byte); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
96
+ | `StakeProgram` | `initialize(stake, rentSysvar, staker, withdrawer)` (no lockup), `authorize(stake, clockSysvar, authority, newAuthority, "staker" \| "withdrawer")`, `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`, `deactivate(stake, clockSysvar, staker)`, `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports)`; the sysvar and config accounts are parameters, as in anchor-spl's stake module; authorities sign (PDAs with signerSeeds) |
94
97
  | `InstructionsSysvar`, `PythPriceUpdate`, `SwitchboardFeed` | exact address / owner program + discriminator |
95
98
  | `InstructionsSysvar` (introspection) | `ixs.length`, `ixs.currentIndex()` (the top-level instruction being executed), `ixs.get(i)` → a `TransactionInstruction`: `programId`, `accountsLength`, `dataLength`, `accountKey(j)` / `accountIsSigner(j)` / `accountIsWritable(j)`, `readU8/U16/U32/U64/readPubkey(offset)` (little-endian), `is(program, "name")` (that program's instruction by its default Anchor discriminator, sha256("global:<name>"); an instruction with its own `@discriminator` is matched with `programId` and `readU64(0)` instead). Every read is bounds-checked (5104). It is the transaction author's data: require things of the transaction with it (a repay instruction after a flash loan), never treat it as proof |
96
99
  | `Program<"Address…">` | exact program address + executable |
@@ -119,7 +122,7 @@ with `i == j`) is refused with 2040 too, since the two views would alias.
119
122
  `burnChecked(from, mint, authority, amount)` and `approveChecked(source, mint, delegate, owner, amount)` (the decimals
120
123
  come from the mint), `setAuthority(target, current, AuthorityType.MintTokens, next | null)`,
121
124
  `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)`, `initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)`,
122
- `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
125
+ `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)`; and the Token Group interface: `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)` (a collection mint with a GroupPointer to itself; fund the rent for the group, which Token-2022 adds to the account), `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`, `updateGroupMaxSize(group, authority, maxSize)`, `updateGroupAuthority(group, authority, next | null)`. Each takes optional signerSeeds
123
126
  - `account.lamports` read/write on `Mut` accounts, `close(account, destination)` for program accounts
124
127
  - `requirePda(account, seeds, bump)`: any bump that gives a valid PDA passes, as with Anchor's `bump = expr`. Use a bump
125
128
  stored when the account was created (or `Seeds<…>`); one taken from the instruction's arguments lets the caller pick
@@ -116,6 +116,16 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
116
116
  | `system_program::transfer(CpiContext::new_with_signer(…, &[vault_seeds]), lamports)` | `systemProgram.transfer(vault, to, lamports, ["vault", owner.key, bump])` |
117
117
  | `invoke_signed(&ix, infos, &[seeds_a, seeds_b])` | `invoke(program, accounts, data, [seedsA, seedsB])` |
118
118
  | `let (_, data) = get_return_data().unwrap(); Quote::try_from_slice(&data)?` | `const quote = returnData<Quote>(program)` (a `@layout borsh` struct when it holds Options, strings or Vecs) |
119
+ | `[test.validator.clone]` in Anchor.toml | `"clone": [...]` in typesol.json and `typesol clone` (loaded by `testProgram`) |
120
+ | `anchor_spl::metadata::update_metadata_accounts_v2` | `metadataProgram.updateMetadataAccountsV2(…)` |
121
+ | `anchor_spl::metadata::burn_nft` / mpl `BurnV1` | `metadataProgram.burnV1(…)` |
122
+ | `EpochSchedule::get()?`, `LastRestartSlot::get()?` | `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()`; `lastRestartSlot()` |
123
+ | `anchor_spl::stake::{authorize, deactivate_stake, withdraw}`, `delegate_stake` | `stakeProgram.authorize / deactivate / withdraw / delegate(…)` |
124
+ | `pub fn fallback(program_id, accounts, data)` | `/** @fallback */ export function fallback(): void` with `instructionData()` and `remainingAccounts()` |
125
+ | `#[access_control(check(&ctx))]` | call the check first in the body (`check(vault, owner)`), or `constraint(acct, …)` for one that belongs with an account's checks |
126
+ | `spl_memo::build_memo` + `invoke` | `memoProgram.memo(text, [signers])` |
127
+ | `UncheckedAccount` at the SlotHashes address | `SlotHashesSysvar`: `latestSlot`, `latestHash` |
128
+ | `spl_token_group_interface` CPIs (`initialize_group`, `initialize_member`, …) | `token.initializeTokenGroup(…)`, `initializeGroupMember(…)`, `updateGroupMaxSize(…)`, `updateGroupAuthority(…)` |
119
129
  | `invoke_signed(&ix, &accounts, &[seeds])` | `invoke(program, [writable(a), readonly(b)], [data…], seeds)` |
120
130
  | `invoke_signed(&Instruction { program_id, accounts, data }, ctx.remaining_accounts, …)` built at run time | `invokeInstruction(programId, metas, data, remainingAccounts(), seeds)` |
121
131
  | `multisig.owners = owners` (a `Vec` argument into account data) | the same |
@@ -60,6 +60,13 @@ instruction that takes the bump as an argument.
60
60
  | `t.tokenBalance(address)` | the amount a token account holds, or `null` when it does not exist |
61
61
  | `t.warp({ unixTimestamp?, slot?, seconds? })` | moves the Clock: to a timestamp or slot, or forward by `seconds` |
62
62
 
63
+ ## Accounts from a cluster
64
+
65
+ To test against accounts that exist on mainnet (a mint, an oracle, another program), list them in `typesol.json` as
66
+ `"clone": ["<address>", …]` and run `typesol clone --url mainnet-beta` once (or `typesol clone <address>…`). They are
67
+ written to `tests/accounts/`, which `testProgram` loads into its LiteSVM before your first test; commit the directory so
68
+ the tests run offline. `loadClonedAccounts(svm, dir)` does the same for a LiteSVM of your own.
69
+
63
70
  `t.svm`, `t.programId`, `t.idl` and `t.coder` are there for anything else. `programHarness(svm, programId, idl)` gives the same helpers for a
64
71
  program you loaded yourself, and `svmConnection(svm)` the RPC pair alone (for any LiteSVM, e.g. one with an Anchor
65
72
  program loaded). Transactions sent through it run at once; `getProgramAccounts` (`fetchAll`) sees the accounts those
package/lib/typesol.d.ts CHANGED
@@ -294,6 +294,68 @@ export declare function switchboardValue(
294
294
  ): i64;
295
295
 
296
296
  /** The Associated Token Account program (ATokenGP…). Its address is checked. */
297
+ /** The SPL Memo program (v2, `MemoSq4g…`). Its address is checked. */
298
+ export interface MemoProgram extends AccountMeta {
299
+ readonly __memo_program: void;
300
+ /**
301
+ * Record a UTF-8 memo in the transaction (Anchor's `spl_memo::build_memo`). Each account in `signers` must sign it:
302
+ * a `Signer`, or a PDA of this program with `signerSeeds`.
303
+ */
304
+ memo(text: string, signers?: AccountMeta[], signerSeeds?: Seed[] | SignerSeeds): void;
305
+ }
306
+
307
+ /**
308
+ * The native Stake program (`Stake1111…`). Its address is checked. The sysvar and config accounts it reads are
309
+ * passed in, as anchor-spl's stake module does (`SysvarRent…`, `SysvarC1ock…`, `SysvarStakeHistory…`,
310
+ * `StakeConfig…`). Each authority signs: a wallet, or a PDA of this program with `signerSeeds`.
311
+ */
312
+ export interface StakeProgram extends AccountMeta {
313
+ readonly __stake_program: void;
314
+ /** Initialize a stake account (created with 200 bytes, owned by the Stake program), with no lockup. */
315
+ initialize(stake: AccountMeta, rentSysvar: AccountMeta, staker: Pubkey, withdrawer: Pubkey): void;
316
+ /** Hand the staker or the withdrawer authority to `newAuthority`. */
317
+ authorize(
318
+ stake: AccountMeta,
319
+ clockSysvar: AccountMeta,
320
+ authority: AccountMeta,
321
+ newAuthority: Pubkey,
322
+ which: "staker" | "withdrawer",
323
+ signerSeeds?: Seed[] | SignerSeeds,
324
+ ): void;
325
+ delegate(
326
+ stake: AccountMeta,
327
+ vote: AccountMeta,
328
+ clockSysvar: AccountMeta,
329
+ stakeHistorySysvar: AccountMeta,
330
+ stakeConfig: AccountMeta,
331
+ staker: AccountMeta,
332
+ signerSeeds?: Seed[] | SignerSeeds,
333
+ ): void;
334
+ deactivate(stake: AccountMeta, clockSysvar: AccountMeta, staker: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
335
+ withdraw(
336
+ stake: AccountMeta,
337
+ to: AccountMeta,
338
+ clockSysvar: AccountMeta,
339
+ stakeHistorySysvar: AccountMeta,
340
+ withdrawer: AccountMeta,
341
+ lamports: u64,
342
+ signerSeeds?: Seed[] | SignerSeeds,
343
+ ): void;
344
+ }
345
+
346
+ /**
347
+ * The SlotHashes sysvar (`SysvarS1otHashes…`), read as an account: it is too large for the sysvar syscalls (Anchor's
348
+ * `Sysvar<SlotHashes>` cannot load it either). The address is checked, and that it holds an entry (5103).
349
+ */
350
+ export interface SlotHashesSysvar extends AccountMeta {
351
+ readonly __slot_hashes: void;
352
+ /** How many recent slots it lists (up to 512). */
353
+ readonly count: u64;
354
+ /** The most recent slot it lists, and that slot's bank hash: known to everyone, so not a secret source of randomness. */
355
+ readonly latestSlot: u64;
356
+ readonly latestHash: Hash;
357
+ }
358
+
297
359
  export interface AssociatedTokenProgram extends AccountMeta {
298
360
  readonly __ata_program: void;
299
361
  create(
@@ -391,6 +453,45 @@ export interface TokenMetadataProgram extends AccountMeta {
391
453
  instructionsSysvar: AccountMeta,
392
454
  signerSeeds?: Seed[] | SignerSeeds,
393
455
  ): void;
456
+ /**
457
+ * UpdateMetadataAccountV2 (Anchor's `update_metadata_accounts_v2`): `data` replaces the whole DataV2 (creators and
458
+ * collection left out become none; a verified collection or creator cannot be changed this way, Metaplex refuses);
459
+ * each `null` leaves that part as it is. The update authority signs (a PDA of this program with `signerSeeds`).
460
+ */
461
+ /**
462
+ * Burn (BurnV1) a non-fungible asset (pass its master edition as `edition`) or a fungible one (`edition` null) held in
463
+ * `token`: the token account and edition close (the metadata is cleared to one byte, as Token Metadata does), the
464
+ * holder signs and gets the rent back. `collectionMetadata` is the collection's when the asset is a verified member, else null.
465
+ */
466
+ burnV1(
467
+ authority: AccountMeta,
468
+ metadata: AccountMeta,
469
+ edition: AccountMeta | null,
470
+ mint: AccountMeta,
471
+ token: AccountMeta,
472
+ collectionMetadata: AccountMeta | null,
473
+ systemProgram: SystemProgram,
474
+ instructionsSysvar: AccountMeta,
475
+ tokenProgram: TokenProgram | Token2022Program | TokenInterface,
476
+ amount: u64,
477
+ signerSeeds?: Seed[] | SignerSeeds,
478
+ ): void;
479
+ updateMetadataAccountsV2(
480
+ metadata: AccountMeta,
481
+ updateAuthority: AccountMeta,
482
+ data: {
483
+ name: string;
484
+ symbol: string;
485
+ uri: string;
486
+ sellerFeeBasisPoints: u16;
487
+ creators?: { address: Pubkey; verified: boolean; share: u8 }[];
488
+ collection?: Pubkey;
489
+ } | null,
490
+ newUpdateAuthority: Pubkey | null,
491
+ primarySaleHappened: boolean | null,
492
+ isMutable: boolean | null,
493
+ signerSeeds?: Seed[] | SignerSeeds,
494
+ ): void;
394
495
  }
395
496
  /** The Metaplex master edition address of a mint (PDA ["metadata", program, mint, "edition"]). */
396
497
  export declare function masterEditionAddress(mint: Pubkey): Pubkey;
@@ -1361,6 +1462,13 @@ export interface CompressedLeaf {
1361
1462
  /** The current slot and epoch (Clock sysvar). */
1362
1463
  export declare function currentSlot(): u64;
1363
1464
  export declare function currentEpoch(): u64;
1465
+ /** The EpochSchedule sysvar: slots per epoch (after warmup), whether epochs warm up, and where normal epochs start. */
1466
+ export declare function slotsPerEpoch(): u64;
1467
+ export declare function epochWarmup(): boolean;
1468
+ export declare function firstNormalEpoch(): u64;
1469
+ export declare function firstNormalSlot(): u64;
1470
+ /** The LastRestartSlot sysvar: the last slot the cluster restarted at (0 if never). */
1471
+ export declare function lastRestartSlot(): u64;
1364
1472
  export type CloseTo<A, Destination extends string> = A & { readonly __closeTo?: Destination };
1365
1473
 
1366
1474
  /** A program-owned account that this instruction creates as a PDA. */
@@ -1538,6 +1646,29 @@ interface Token2022Ops {
1538
1646
  initializeGroupPointer(mint: AccountMeta, authority: Pubkey | null, groupAddress: Pubkey | null): void;
1539
1647
  /** GroupMemberPointer: where the mint's group-member data lives. */
1540
1648
  initializeGroupMemberPointer(mint: AccountMeta, authority: Pubkey | null, memberAddress: Pubkey | null): void;
1649
+ /**
1650
+ * The Token Group interface on Token-2022 mints (a collection of mints): make `group` (usually the mint itself, with
1651
+ * a GroupPointer to it, its space allocated) a group of at most `maxSize` members. The mint authority signs.
1652
+ */
1653
+ initializeTokenGroup(
1654
+ group: AccountMeta,
1655
+ mint: AccountMeta,
1656
+ mintAuthority: AccountMeta,
1657
+ updateAuthority: Pubkey | null,
1658
+ maxSize: u64,
1659
+ signerSeeds?: Seed[] | SignerSeeds,
1660
+ ): void;
1661
+ /** Add `memberMint` to `group` (`member` holds the membership, usually the member mint itself). Both authorities sign. */
1662
+ initializeGroupMember(
1663
+ member: AccountMeta,
1664
+ memberMint: AccountMeta,
1665
+ memberMintAuthority: AccountMeta,
1666
+ group: AccountMeta,
1667
+ groupUpdateAuthority: AccountMeta,
1668
+ signerSeeds?: Seed[] | SignerSeeds,
1669
+ ): void;
1670
+ updateGroupMaxSize(group: AccountMeta, updateAuthority: AccountMeta, maxSize: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1671
+ updateGroupAuthority(group: AccountMeta, updateAuthority: AccountMeta, next: Pubkey | null, signerSeeds?: Seed[] | SignerSeeds): void;
1541
1672
  /** TransferHook: `programId` is invoked on every transfer of this mint. */
1542
1673
  initializeTransferHook(mint: AccountMeta, authority: Pubkey | null, programId: Pubkey | null): void;
1543
1674
  /** InterestBearingConfig: `rate` in basis points per year (UI amounts only; balances do not change). */
@@ -1792,6 +1923,13 @@ export declare function require(condition: boolean, error: string | AnchorError)
1792
1923
  */
1793
1924
  export declare function constraint(account: AccountMeta | RemainingAccount | null, condition: boolean, error?: string | AnchorError): void;
1794
1925
 
1926
+ /**
1927
+ * The instruction data as sent, discriminator included: `const data = instructionData()`, then `data.length`,
1928
+ * `data.get(i)`, or pass it on to `invokeInstruction`. A `/** @fallback *\/` instruction (Anchor's fallback: no
1929
+ * parameters, run when no instruction matches) reads its input this way, and its accounts with remainingAccounts().
1930
+ */
1931
+ export declare function instructionData(): IndexedList<u8>;
1932
+
1795
1933
  /** Write a string, integer or pubkey to the program log. */
1796
1934
  export declare function log(value: string | bigint | Pubkey | Hash): void;
1797
1935
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -597,6 +597,21 @@ static inline void ts_write_le(uint8_t *p, uint64_t v, int n) { ts_memcpy(p, &v,
597
597
  /* ---- Sysvars --------------------------------------------------------------- */
598
598
  uint64_t sol_get_rent_sysvar(void *ret);
599
599
  uint64_t sol_get_clock_sysvar(void *ret);
600
+ uint64_t sol_get_epoch_schedule_sysvar(void *ret);
601
+ uint64_t sol_get_last_restart_slot(void *ret);
602
+
603
+ /* EpochSchedule { slots_per_epoch, leader_schedule_slot_offset, warmup (bool, padded), first_normal_epoch,
604
+ first_normal_slot }: one u64 of it by index (2 is warmup's word, whose first byte is the bool). */
605
+ static inline uint64_t ts_epoch_schedule(int field, uint64_t *out) {
606
+ uint64_t es[5];
607
+ if (sol_get_epoch_schedule_sysvar(es) != SUCCESS) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: epoch schedule sysvar unavailable");
608
+ *out = field == 2 ? (es[2] & 0xff) : es[field];
609
+ return SUCCESS;
610
+ }
611
+ static inline uint64_t ts_last_restart_slot(uint64_t *out) {
612
+ if (sol_get_last_restart_slot(out) != SUCCESS) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: last restart slot sysvar unavailable");
613
+ return SUCCESS;
614
+ }
600
615
 
601
616
  /* The general case, in integers: exactly (uint64_t)((double)per_year * threshold) as soft-float computes it (the
602
617
  conversion and the product rounded to nearest, ties to even; NaN, negative and < 1 give 0), or UINT64_MAX when that
@@ -1837,6 +1852,9 @@ static inline uint64_t ts_switchboard_value(const TsAccount *a, uint64_t max_sta
1837
1852
  }
1838
1853
 
1839
1854
  /* ---- Associated token accounts, token metadata, transfer hooks ------------------- */
1855
+ static const SolPubkey TS_STAKE_PROGRAM_ID = {{6,161,216,23,145,55,84,42,152,52,55,189,254,42,122,178,85,127,83,92,138,120,114,43,104,164,157,192,0,0,0,0}};
1856
+ static const SolPubkey TS_MEMO_PROGRAM_ID = {{5,74,83,90,153,41,33,6,77,36,232,113,96,218,56,124,124,53,181,221,188,146,187,129,228,31,168,64,65,5,68,141}};
1857
+ static const SolPubkey TS_SLOT_HASHES_ID = {{6,167,213,23,25,47,10,175,198,242,101,227,251,119,204,122,218,130,197,41,208,190,59,19,110,45,0,85,32,0,0,0}};
1840
1858
  static const SolPubkey TS_ATA_PROGRAM_ID = {{140,151,37,143,78,36,137,241,187,61,16,41,20,142,13,131,11,90,19,153,218,255,16,132,4,142,123,216,219,233,248,89}};
1841
1859
  static const SolPubkey TS_MPL_METADATA_ID = {{11,112,101,177,227,209,124,69,56,157,82,127,107,4,195,205,88,184,108,115,26,160,253,181,73,182,209,188,3,248,41,70}};
1842
1860
 
@@ -1971,6 +1989,66 @@ static inline uint64_t ts_mpl_create_v3(TsParams *params, const TsAccount *progr
1971
1989
  return ts_invoke(params, &ix, &signer, n > 0 ? 1 : 0);
1972
1990
  }
1973
1991
 
1992
+ /*
1993
+ * UpdateMetadataAccountV2 (15): each part optional. `has_data` sets the whole DataV2 (name, symbol, uri, fee, creators
1994
+ * (ncreators < 0: None), collection (NULL: None), uses None); `new_ua` NULL leaves the update authority; `primary` and
1995
+ * `mutable` are -1 to leave them, else 0 / 1. The update authority signs.
1996
+ */
1997
+ static inline uint64_t ts_mpl_update_v2(TsParams *params, const TsAccount *program, TsAccount *metadata,
1998
+ TsAccount *update_authority, bool has_data, TS_Str name, TS_Str symbol, TS_Str uri,
1999
+ uint16_t fee_bps, const uint8_t *creators, int ncreators, const SolPubkey *collection,
2000
+ const SolPubkey *new_ua, int primary, int mutable_, const SolSignerSeed *seeds, int n) {
2001
+ uint8_t *data;
2002
+ uint64_t ncr = ncreators > 0 ? (uint64_t)ncreators : 0;
2003
+ TS_TRY(ts_alloc(1 + 1 + 12 + name.len + symbol.len + uri.len + 2 + (1 + 4 + 34 * ncr) + (1 + 33) + 1 + 33 + 2 + 2, &data));
2004
+ uint64_t at = 0;
2005
+ data[at++] = 15;
2006
+ if (!has_data) {
2007
+ data[at++] = 0;
2008
+ } else {
2009
+ data[at++] = 1;
2010
+ ts_put_str(data, &at, name);
2011
+ ts_put_str(data, &at, symbol);
2012
+ ts_put_str(data, &at, uri);
2013
+ ts_memcpy(data + at, &fee_bps, 2);
2014
+ at += 2;
2015
+ if (ncreators < 0) {
2016
+ data[at++] = 0;
2017
+ } else {
2018
+ data[at++] = 1;
2019
+ uint32_t count = (uint32_t)ncreators;
2020
+ ts_memcpy(data + at, &count, 4);
2021
+ at += 4;
2022
+ ts_memcpy(data + at, creators, 34 * ncr);
2023
+ at += 34 * ncr;
2024
+ }
2025
+ if (collection) {
2026
+ data[at++] = 1;
2027
+ data[at++] = 0; /* verified: false */
2028
+ ts_memcpy(data + at, collection, 32);
2029
+ at += 32;
2030
+ } else {
2031
+ data[at++] = 0;
2032
+ }
2033
+ data[at++] = 0; /* uses: None */
2034
+ }
2035
+ if (new_ua) {
2036
+ data[at++] = 1;
2037
+ ts_memcpy(data + at, new_ua, 32);
2038
+ at += 32;
2039
+ } else {
2040
+ data[at++] = 0;
2041
+ }
2042
+ if (primary < 0) data[at++] = 0;
2043
+ else data[at++] = 1, data[at++] = (uint8_t)primary;
2044
+ if (mutable_ < 0) data[at++] = 0;
2045
+ else data[at++] = 1, data[at++] = (uint8_t)mutable_;
2046
+ SolAccountMeta metas[2] = {{&metadata->key, true, false}, {&update_authority->key, false, true}};
2047
+ SolInstruction ix = {(SolPubkey *)&program->key, metas, 2, data, at};
2048
+ SolSignerSeeds signer = {seeds, (uint64_t)n};
2049
+ return ts_invoke(params, &ix, &signer, n > 0 ? 1 : 0);
2050
+ }
2051
+
1974
2052
  /*
1975
2053
  * Transfer hook validation account (ExtraAccountMetaList with no extra accounts) at PDA
1976
2054
  * ["extra-account-metas", mint]: TLV = execute discriminator | u32 length 4 | u32 count 0.