@typesol/cli 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,29 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.36.0 — 2026-10-30
10
+
11
+ Verifiable randomness from Switchboard, Anchor's check order for instructions with account groups, and the
12
+ StakeHistory sysvar. Programs without account groups compile to the same binaries as in 0.35.0.
13
+
14
+ - New: `StakeHistorySysvar`, the StakeHistory sysvar read as an account: `count`, `latestEpoch`, `has(epoch)`,
15
+ `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)`.
16
+ - Changed: an instruction with an account group checks in Anchor's order: the arguments first, then the accounts in
17
+ order with each group's constraints right after its accounts, then the other constraints. A transaction failing
18
+ several checks gets Anchor's code. Instructions without groups are unchanged (decoding the arguments first would make
19
+ every binary larger).
20
+ - New: `SwitchboardRandomness`, Switchboard On-Demand's verifiable randomness (commit and reveal): `seedSlot`,
21
+ `revealSlot`, `value()` and `valueU64()`, which fail (5111) unless revealed in this slot, as `get_value` does.
22
+
23
+ ## 0.35.0 — 2026-10-30
24
+
25
+ Token Metadata's Burn and the EpochSchedule and LastRestartSlot sysvars. Existing programs compile to the same binaries
26
+ as in 0.34.0.
27
+
28
+ - New: Token Metadata `burnV1` (Burn), for an NFT (with its master edition) or fungible asset held by a wallet or this
29
+ program's PDA.
30
+ - New: the EpochSchedule and LastRestartSlot sysvars: `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`,
31
+ `firstNormalSlot()`, `lastRestartSlot()`.
9
32
  ## 0.34.0 — 2026-10-30
10
33
 
11
34
  More of anchor-spl and Anchor's tooling: Memo and Stake CPIs, Token Metadata updates, Token-2022 token groups, the
package/README.md CHANGED
@@ -210,7 +210,7 @@ Runtime failures point back to your source: `Error 6000 Unauthorized (counter.ts
210
210
  | **Control flow** | `if`, `for`, `for … of`, `while`, `switch` (with narrowing on data enums), ternaries, `??`, destructuring, helper functions (returning structs too, arrow functions, closures, function arguments, generics), list callbacks (`some`, `find`, `reduce`, …) across multiple files |
211
211
  | **CPIs** | System, SPL Token, Token-2022 (including extension reads, metadata and token groups), ATA, Memo, Stake, Metaplex Token Metadata, Core, Bubblegum. Generic `invoke` with PDA signing (one or several PDAs per call), return data, and typed bindings generated from any Anchor IDL (`typesol cpi`) |
212
212
  | **Events** | `emit` (log-based) and `emitCpi` (Anchor `emit_cpi!`, through a self-CPI) |
213
- | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard |
213
+ | **Crypto & oracles** | `sha256`, `keccak256`, Merkle proofs, Ed25519 and secp256k1 signature checks, Pyth pull oracle, Switchboard feeds and verifiable randomness |
214
214
  | **Interfaces** | custom discriminators (`@discriminator`), so a TypeSOL program can be a Token-2022 transfer hook, with extra accounts (ExtraAccountMetaList) |
215
215
 
216
216
  The full reference, with every type, check and built-in, is in [docs/language.md](docs/language.md).
@@ -97,7 +97,9 @@ const TYPE_EXPORTS = new Set([
97
97
  "MemoProgram",
98
98
  "StakeProgram",
99
99
  "SlotHashesSysvar",
100
+ "StakeHistorySysvar",
100
101
  "SwitchboardFeed",
102
+ "SwitchboardRandomness",
101
103
  "HasOne",
102
104
  "TokenOf",
103
105
  "MintOf",
@@ -1510,7 +1512,9 @@ const ACCOUNT_TYPES = new Set([
1510
1512
  "MemoProgram",
1511
1513
  "StakeProgram",
1512
1514
  "SlotHashesSysvar",
1515
+ "StakeHistorySysvar",
1513
1516
  "SwitchboardFeed",
1517
+ "SwitchboardRandomness",
1514
1518
  "HasOne",
1515
1519
  "TokenOf",
1516
1520
  "MintOf",
@@ -2005,8 +2009,17 @@ function resolveAccountKind(node, reporter, imports, structs) {
2005
2009
  return { kind: "stakeProgram" };
2006
2010
  case "SlotHashesSysvar":
2007
2011
  return { kind: "slotHashes" };
2012
+ case "StakeHistorySysvar":
2013
+ return { kind: "stakeHistory" };
2008
2014
  case "TokenMetadataProgram":
2009
2015
  return { kind: "metadataProgram" };
2016
+ case "SwitchboardRandomness": {
2017
+ const arg = ref.typeArguments?.[0];
2018
+ const cluster = arg && ts.isLiteralTypeNode(arg) && ts.isStringLiteral(arg.literal) ? arg.literal.text : "mainnet";
2019
+ if (cluster !== "mainnet" && cluster !== "devnet")
2020
+ reporter.fail(node, 'SwitchboardRandomness<"mainnet" | "devnet">');
2021
+ return { kind: "sbRandomness", devnet: cluster === "devnet" };
2022
+ }
2010
2023
  case "SwitchboardFeed": {
2011
2024
  const arg = ref.typeArguments?.[0];
2012
2025
  const cluster = arg && ts.isLiteralTypeNode(arg) && ts.isStringLiteral(arg.literal) ? arg.literal.text : "mainnet";
@@ -107,6 +107,21 @@ export class CallEmitter extends ExpressionEmitter {
107
107
  this.line(`TS_TRY(ts_minimum_balance(a_${a.name}->data_len, &${t}));`);
108
108
  return { c: t, type: U64 };
109
109
  }
110
+ case "slotsPerEpoch":
111
+ case "firstNormalEpoch":
112
+ case "firstNormalSlot":
113
+ case "epochWarmup":
114
+ case "lastRestartSlot": {
115
+ if (args.length !== 0)
116
+ this.fail(node, `${builtin}() takes no arguments`);
117
+ const t = this.tmp();
118
+ this.line(`uint64_t ${t};`);
119
+ if (builtin === "lastRestartSlot")
120
+ this.line(`TS_TRY(ts_last_restart_slot(&${t}));`);
121
+ else
122
+ this.line(`TS_TRY(ts_epoch_schedule(${{ slotsPerEpoch: 0, epochWarmup: 2, firstNormalEpoch: 3, firstNormalSlot: 4 }[builtin]}, &${t}));`);
123
+ return builtin === "epochWarmup" ? { c: `(${t} != 0)`, type: BOOL } : { c: t, type: U64 };
124
+ }
110
125
  case "currentSlot":
111
126
  case "currentEpoch":
112
127
  case "now": {
@@ -691,6 +706,29 @@ export class CallEmitter extends ExpressionEmitter {
691
706
  return this.ataOp(node, target, method);
692
707
  if (target?.kind.kind === "memoProgram")
693
708
  return this.memoOp(node, target, method);
709
+ if (target?.kind.kind === "stakeHistory") {
710
+ const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
711
+ if (!(method in fields))
712
+ this.fail(callee.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
713
+ if (args.length !== 1)
714
+ this.fail(node, `${method}(epoch) takes the epoch`);
715
+ const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
716
+ const f = this.tmp("shf");
717
+ const v = this.tmp("shv");
718
+ this.line(`bool ${f};`);
719
+ this.line(`uint64_t ${v} = ts_stake_history(a_${target.name}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
720
+ return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
721
+ }
722
+ if (target?.kind.kind === "sbRandomness") {
723
+ if (method !== "value" && method !== "valueU64")
724
+ this.fail(callee.name, "SwitchboardRandomness has value() and valueU64()");
725
+ if (args.length)
726
+ this.fail(node, `${method}() takes no arguments`);
727
+ const t = this.tmp("rand");
728
+ this.line(`const uint8_t *${t};`);
729
+ this.line(`TS_TRY(ts_sb_randomness_value(a_${target.name}, &${t}));`);
730
+ return method === "value" ? { c: `((const SolPubkey *)${t})`, type: HASH } : { c: `ts_read_le(${t}, 8)`, type: U64 };
731
+ }
694
732
  if (target?.kind.kind === "stakeProgram")
695
733
  return this.stakeOp(node, target, method);
696
734
  if (target?.kind.kind === "metadataProgram")
@@ -373,6 +373,20 @@ export class ExpressionEmitter extends StorageEmitter {
373
373
  if (field === "tokenProgram")
374
374
  return { c: `&${v}->owner`, type: PUBKEY };
375
375
  }
376
+ if (k.kind === "sbRandomness") {
377
+ if (field === "seedSlot")
378
+ return { c: `ts_read_le(${v}->data + TS_SB_RAND_SEED_SLOT, 8)`, type: U64 };
379
+ if (field === "revealSlot")
380
+ return { c: `ts_read_le(${v}->data + TS_SB_RAND_REVEAL_SLOT, 8)`, type: U64 };
381
+ this.fail(node.name, "SwitchboardRandomness has seedSlot, revealSlot, value() and valueU64()");
382
+ }
383
+ if (k.kind === "stakeHistory") {
384
+ if (field === "count")
385
+ return { c: `ts_read_le(${v}->data, 8)`, type: U64 };
386
+ if (field === "latestEpoch")
387
+ return { c: `(${v}->data_len >= 16 && ts_read_le(${v}->data, 8) ? ts_read_le(${v}->data + 8, 8) : 0)`, type: U64 };
388
+ this.fail(node.name, "StakeHistorySysvar has count, latestEpoch, has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
389
+ }
376
390
  if (k.kind === "slotHashes") {
377
391
  // u64 count, then (u64 slot, 32-byte hash) entries, newest first; the entry check ran at entry.
378
392
  if (field === "count")
@@ -25,7 +25,7 @@ export declare class FunctionEmitter extends StatementEmitter {
25
25
  lines: Map<string, string[]>;
26
26
  count: number;
27
27
  };
28
- protected constraintChecks(ix: Instruction, raw?: Map<string, string[]>): string[];
28
+ protected constraintChecks(ix: Instruction, raw?: Map<string, string[]>, only?: (a: AccountParam) => boolean): string[];
29
29
  /** Ata<…>: the account's owner (2015) and address (2009) as Anchor checks them, then its mint. */
30
30
  private ataCheck;
31
31
  /** Seeds<…>: the account is the PDA of its seeds (with the stored bump, or the canonical one found here). */
@@ -32,7 +32,11 @@ export class FunctionEmitter extends StatementEmitter {
32
32
  if (n > limit)
33
33
  this.reporter.fail(ix.node, `instructions may take at most ${limit} accounts (const MAX_ACCOUNTS = …n raises it, up to 255)`);
34
34
  head.push(` if (params->ka_num < ${n}) TS_FAIL(TS_ERR_NOT_ENOUGH_ACCOUNTS, "TypeSOL: not enough accounts");`);
35
+ // Where each account's checks start in `head` (account groups move their constraints in between, below).
36
+ const loopStart = head.length;
37
+ const startOf = new Map();
35
38
  for (const a of ix.accounts) {
39
+ startOf.set(a.name, head.length);
36
40
  const v = `a_${a.name}`;
37
41
  head.push(` TsAccount *${v} = params->ka[${a.index}];`);
38
42
  const start = head.length;
@@ -74,12 +78,16 @@ export class FunctionEmitter extends StatementEmitter {
74
78
  head.push(` uint64_t pm_${a.name}; bool pf_${a.name};`, ` TS_TRY(ts_pyth_message(${v}, &pm_${a.name}, &pf_${a.name}));`);
75
79
  if (k.kind === "switchboard")
76
80
  head.push(` TS_TRY(ts_check_switchboard(${v}, ${k.devnet}));`);
81
+ if (k.kind === "sbRandomness")
82
+ head.push(` TS_TRY(ts_check_sb_randomness(${v}, ${k.devnet}));`);
77
83
  if (k.kind === "ataProgram")
78
84
  head.push(` TS_TRY(ts_check_address(${v}, &TS_ATA_PROGRAM_ID));`);
79
85
  if (k.kind === "memoProgram")
80
86
  head.push(` TS_TRY(ts_check_address(${v}, &TS_MEMO_PROGRAM_ID));`);
81
87
  if (k.kind === "stakeProgram")
82
88
  head.push(` TS_TRY(ts_check_address(${v}, &TS_STAKE_PROGRAM_ID));`);
89
+ if (k.kind === "stakeHistory")
90
+ head.push(` TS_TRY(ts_check_address(${v}, &TS_STAKE_HISTORY_ID));`, ` if (${v}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
83
91
  // SlotHashes: the address, and room for its length and one entry (u64 count, then (u64 slot, hash) newest first).
84
92
  if (k.kind === "slotHashes")
85
93
  head.push(` TS_TRY(ts_check_address(${v}, &TS_SLOT_HASHES_ID));`, ` if (${v}->data_len < 48 || ts_read_le(${v}->data, 8) == 0) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: SlotHashes has no entries");`);
@@ -161,6 +169,7 @@ export class FunctionEmitter extends StatementEmitter {
161
169
  head.push(` if (${v} != NULL) {`, ...inside, ` }`);
162
170
  }
163
171
  }
172
+ const loopEnd = head.length;
164
173
  // Writable accounts must be distinct: aliasing two mutable views of one account is the classic drain.
165
174
  // The loader passes each account once and marks repeats as duplicates, which share its record (ts_deserialize),
166
175
  // so two parameters name the same account exactly when their pointers are equal.
@@ -199,6 +208,7 @@ export class FunctionEmitter extends StatementEmitter {
199
208
  // Arguments: Borsh, read sequentially (strings make later offsets dynamic). Anchor decodes them before the accounts;
200
209
  // here they come after the account types (decoding first keeps them live across the checks: larger binaries), so
201
210
  // only a transaction wrong in both ways sees a different error.
211
+ const argsStart = head.length;
202
212
  if (ix.args.length)
203
213
  head.push(` uint64_t off = ${ix.discriminator.length};`);
204
214
  const need = (bytes) => head.push(` if (params->data_len < off + ${bytes}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
@@ -354,9 +364,34 @@ export class FunctionEmitter extends StatementEmitter {
354
364
  }
355
365
  if (ix.args.length)
356
366
  head.push(` (void)off;`);
367
+ const argsEnd = head.length;
357
368
  this.scopes = [new Map()];
358
369
  const raw = this.rawConstraints(ix);
359
- head.push(...this.constraintChecks(ix, raw.lines));
370
+ const grouped = ix.accounts.filter((a) => a.group);
371
+ if (!grouped.length)
372
+ head.push(...this.constraintChecks(ix, raw.lines));
373
+ else {
374
+ // With account groups, Anchor's order: the arguments first, then each account in order, a group's constraints
375
+ // right after its accounts (a composite's try_accounts runs its own constraints), the others last.
376
+ const groups = [...new Set(grouped.map((a) => a.group.path[0]))];
377
+ const after = new Map();
378
+ for (const g of groups) {
379
+ const members = ix.accounts.filter((a) => a.group?.path[0] === g);
380
+ const last = members[members.length - 1];
381
+ const next = ix.accounts[ix.accounts.indexOf(last) + 1];
382
+ const at = next ? startOf.get(next.name) : loopEnd;
383
+ after.set(at, [...(after.get(at) ?? []), ...this.constraintChecks(ix, raw.lines, (a) => a.group?.path[0] === g)]);
384
+ }
385
+ const accountsPart = [];
386
+ for (let i = loopStart; i <= loopEnd; i++) {
387
+ accountsPart.push(...(after.get(i) ?? []));
388
+ if (i < loopEnd)
389
+ accountsPart.push(head[i]);
390
+ }
391
+ const rest = this.constraintChecks(ix, raw.lines, (a) => !a.group);
392
+ head.splice(loopStart, argsEnd - loopStart, ...head.slice(argsStart, argsEnd), ...accountsPart, ...head.slice(loopEnd, argsStart));
393
+ head.push(...rest);
394
+ }
360
395
  this.scopes = [new Map()];
361
396
  // Two back-to-back markers measure what one marker costs, so the profiler can subtract it.
362
397
  if (this.profile)
@@ -455,11 +490,11 @@ export class FunctionEmitter extends StatementEmitter {
455
490
  }
456
491
  return { lines, count };
457
492
  }
458
- constraintChecks(ix, raw = new Map()) {
493
+ constraintChecks(ix, raw = new Map(), only = () => true) {
459
494
  const out = [];
460
495
  // Bumps found by Seeds<…> checks, declared ahead of the (possibly optional-guarded) checks for `acct.pdaBump`.
461
496
  const bumpDecls = [];
462
- for (const a of ix.accounts) {
497
+ for (const a of ix.accounts.filter(only)) {
463
498
  const start = out.length;
464
499
  const c = a.constraints;
465
500
  const k = a.kind.kind;
@@ -25,6 +25,12 @@ export declare abstract class MetaplexEmitter extends TokenEmitter {
25
25
  * (`{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`); each null leaves that part as it is.
26
26
  */
27
27
  protected metadataUpdate(node: ts.CallExpression, program: AccountParam): undefined;
28
+ /**
29
+ * burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram,
30
+ * instructionsSysvar, tokenProgram, amount, signerSeeds?): Token Metadata's Burn (41, BurnArgs::V1) of a
31
+ * non-fungible (its master edition) or fungible asset held in `token`. The holder signs and gets the rent back.
32
+ */
33
+ protected metadataBurn(node: ts.CallExpression, program: AccountParam): undefined;
28
34
  /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
29
35
  protected metadataCollectionOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
30
36
  /**
@@ -189,8 +189,10 @@ export class MetaplexEmitter extends TokenEmitter {
189
189
  return this.metadataCollectionOp(node, program, method);
190
190
  if (method === "updateMetadataAccountsV2")
191
191
  return this.metadataUpdate(node, program);
192
+ if (method === "burnV1")
193
+ return this.metadataBurn(node, program);
192
194
  if (method !== "createV3")
193
- this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3, verifyCollection and updateMetadataAccountsV2, not ${method}`);
195
+ this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3, verifyCollection, updateMetadataAccountsV2 and burnV1, not ${method}`);
194
196
  const a = node.arguments;
195
197
  const usage = "createV3(metadata, mint, mintAuthority, payer, updateAuthority, systemProgram, name, symbol, uri, sellerFeeBasisPoints, isMutable, { creators?, collection?, isCollection? }?, signerSeeds?)";
196
198
  // An object literal after isMutable carries the optional creators / collection; signerSeeds stays last.
@@ -358,6 +360,44 @@ export class MetaplexEmitter extends TokenEmitter {
358
360
  this.line(`TS_TRY(ts_mpl_update_v2(params, a_${program.name}, a_${metadata.name}, a_${ua.name}, ${hasData}, ${name}, ${symbol}, ${uri}, ${fee}, ${creators}, ${ncreators}, ${collection}, ${next}, ${primary}, ${mutable}, ${seeds.name}, ${seeds.count}));`);
359
361
  return undefined;
360
362
  }
363
+ /**
364
+ * burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram,
365
+ * instructionsSysvar, tokenProgram, amount, signerSeeds?): Token Metadata's Burn (41, BurnArgs::V1) of a
366
+ * non-fungible (its master edition) or fungible asset held in `token`. The holder signs and gets the rent back.
367
+ */
368
+ metadataBurn(node, program) {
369
+ const a = node.arguments;
370
+ if (a.length !== 10 && a.length !== 11)
371
+ this.fail(node, "burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram, instructionsSysvar, tokenProgram, amount, signerSeeds?)");
372
+ const p = `a_${program.name}`;
373
+ const none = [p, false, false];
374
+ const authority = this.accountParam(a[0], "the authority (the holder)");
375
+ if (!isWritable(authority.kind))
376
+ this.fail(a[0], "the authority must be writable (Mut<...>): it gets the rent back");
377
+ // Burn: authority, collection metadata, metadata, edition, mint, token, master edition, master edition mint,
378
+ // master edition token, edition marker, token record (optional ones: the program id), system program,
379
+ // instructions sysvar, token program.
380
+ const metas = [
381
+ [`a_${authority.name}`, true, true],
382
+ this.mplMeta(a[5], program, "the collection metadata", true, false),
383
+ this.mplMeta(a[1], program, "the metadata", true, false),
384
+ this.mplMeta(a[2], program, "the edition", true, false),
385
+ this.mplMeta(a[3], program, "the mint", true, false),
386
+ this.mplMeta(a[4], program, "the token account", true, false),
387
+ none,
388
+ none,
389
+ none,
390
+ none,
391
+ none,
392
+ this.mplMeta(a[6], program, "the system program", false, false),
393
+ this.mplMeta(a[7], program, "the instructions sysvar", false, false),
394
+ this.mplMeta(a[8], program, "the token program", false, false),
395
+ ];
396
+ const data = this.mplData(node, 10, [{ bytes: [41, 0] }, { value: a[9], type: U64 }]);
397
+ const seeds = this.signerSeeds(a[10], authority, a[0]);
398
+ this.cpi(p, metas, data.buf, data.len, seeds);
399
+ return undefined;
400
+ }
361
401
  /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
362
402
  metadataCollectionOp(node, program, method) {
363
403
  const a = node.arguments;
@@ -132,6 +132,8 @@ function accountEntry(ix, name, k, programAddress) {
132
132
  entry.address = "Stake11111111111111111111111111111111111111";
133
133
  if (k.kind === "slotHashes")
134
134
  entry.address = "SysvarS1otHashes111111111111111111111111111";
135
+ if (k.kind === "stakeHistory")
136
+ entry.address = "SysvarStakeHistory1111111111111111111111111";
135
137
  if (k.kind === "metadataProgram")
136
138
  entry.address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s";
137
139
  if (k.kind === "coreProgram")
@@ -254,11 +254,20 @@ export type ParamKind = {
254
254
  /** The SlotHashes sysvar account (too large for the sysvar syscalls, so read as an account). */
255
255
  | {
256
256
  kind: "slotHashes";
257
+ }
258
+ /** The StakeHistory sysvar account. */
259
+ | {
260
+ kind: "stakeHistory";
257
261
  } | {
258
262
  kind: "metadataProgram";
259
263
  } | {
260
264
  kind: "switchboard";
261
265
  devnet: boolean;
266
+ }
267
+ /** A Switchboard On-Demand randomness account (RandomnessAccountData). */
268
+ | {
269
+ kind: "sbRandomness";
270
+ devnet: boolean;
262
271
  } | {
263
272
  kind: "tokenProgram";
264
273
  flavor: TokenProgramKind;
package/docs/language.md CHANGED
@@ -41,6 +41,7 @@ The full reference. For a tour, start with the [README](../README.md).
41
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 |
42
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) |
43
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">`) |
44
+ | Randomness | A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer. `SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives verifiable randomness by commit and reveal: commit while `r.seedSlot === currentSlot() - 1n` and store `r.key` and `r.seedSlot`; settle in a later transaction after checking both, with `r.value()` (32 bytes) or `r.valueU64()`, which fail (5111) unless the value was revealed in this slot. See test/fixtures/coinflip.ts |
44
45
  | 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 |
45
46
  | 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 |
46
47
  | Helpers | non-exported functions (and every function of an imported file): take values, structs, Vec arguments, `SignerSeeds` and accounts the instruction already checked (`Signer`, `AccountInfo`/`AccountMeta`, `Mut<T>`, token accounts, programs); return `void`, a scalar, a `string`, a function (see below) or a fixed-size struct (`function at(x: u64, y: u64): Point { return { x, y }; }`: the caller gets its own copy, to bind, store with `acct.home = at(…)` / `arr.set(i, at(…))` or read as `at(…).x`); no recursion. A helper that takes a struct account as `Mut<T>` can grow its Vec (`push(value, payer)`: the account's size at instruction entry is passed along) |
@@ -50,7 +51,7 @@ The full reference. For a tour, start with the [README](../README.md).
50
51
  | 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
52
  | 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
53
  | `++` `--` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | all checked |
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) |
54
+ | 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()`; `history: StakeHistorySysvar` (an account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)` (0 for an epoch not listed) |
54
55
  | 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
56
  | 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
57
  | 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) |
@@ -68,7 +69,7 @@ The full reference. For a tour, start with the [README](../README.md).
68
69
  | `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
70
  | `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
71
  | `/** @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) |
72
+ | 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. An instruction with a group checks in Anchor's order: its arguments first (102), then each account in order, a group's constraints right after the group's accounts (as a composite's `try_accounts` does), the other constraints last |
72
73
  | `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) |
73
74
  | `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 |
74
75
  | `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>` |
@@ -92,7 +93,7 @@ The full reference. For a tour, start with the [README](../README.md).
92
93
  | `TokenInterface` | either token program |
93
94
  | `AssociatedTokenProgram` | `create` / `createIdempotent` CPIs; `associatedTokenAddress(owner, mint, tokenProgram)` |
94
95
  | `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); `metadataAddress(mint)`, `masterEditionAddress(mint)` |
96
+ | `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
97
  | `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) |
97
98
  | `InstructionsSysvar`, `PythPriceUpdate`, `SwitchboardFeed` | exact address / owner program + discriminator |
98
99
  | `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 |
@@ -118,7 +118,11 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
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
119
  | `[test.validator.clone]` in Anchor.toml | `"clone": [...]` in typesol.json and `typesol clone` (loaded by `testProgram`) |
120
120
  | `anchor_spl::metadata::update_metadata_accounts_v2` | `metadataProgram.updateMetadataAccountsV2(…)` |
121
+ | `anchor_spl::metadata::burn_nft` / mpl `BurnV1` | `metadataProgram.burnV1(…)` |
122
+ | `Sysvar<StakeHistory>` / `StakeHistory::get(epoch)` | `StakeHistorySysvar`: `effective(epoch)`, `activating(epoch)`, `deactivating(epoch)`, `has(epoch)` |
123
+ | `EpochSchedule::get()?`, `LastRestartSlot::get()?` | `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()`; `lastRestartSlot()` |
121
124
  | `anchor_spl::stake::{authorize, deactivate_stake, withdraw}`, `delegate_stake` | `stakeProgram.authorize / deactivate / withdraw / delegate(…)` |
125
+ | `RandomnessAccountData::parse(…)?.get_value(&clock)?` (switchboard-on-demand) | `randomness: SwitchboardRandomness`, `randomness.value()` / `valueU64()`, `randomness.seedSlot` |
122
126
  | `pub fn fallback(program_id, accounts, data)` | `/** @fallback */ export function fallback(): void` with `instructionData()` and `remainingAccounts()` |
123
127
  | `#[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 |
124
128
  | `spl_memo::build_memo` + `invoke` | `memoProgram.memo(text, [signers])` |
package/lib/typesol.d.ts CHANGED
@@ -293,7 +293,27 @@ export declare function switchboardValue(
293
293
  minSamples?: u8,
294
294
  ): i64;
295
295
 
296
- /** The Associated Token Account program (ATokenGP…). Its address is checked. */
296
+ /**
297
+ * A Switchboard On-Demand randomness account (RandomnessAccountData): verifiable randomness by commit and reveal.
298
+ * Blockchains have no secret randomness of their own (slot hashes and timestamps are known to, or chosen by, the
299
+ * block producer), so the value comes from an oracle that commits to a future slot hash and reveals the result in a
300
+ * later transaction. Mainnet program unless `SwitchboardRandomness<"devnet">`; owner, discriminator and size checked.
301
+ *
302
+ * The pattern: in a commit instruction, require `seedSlot === currentSlot() - 1n` (committed just now, not yet
303
+ * revealed) and store the account's key and seedSlot; in the settle instruction, check both again and read `value()`.
304
+ */
305
+ export interface SwitchboardRandomness<Cluster extends "mainnet" | "devnet" = "mainnet"> extends AccountMeta {
306
+ readonly __switchboard_randomness: Cluster;
307
+ /** The slot whose hash seeds this randomness (set when it is committed). */
308
+ readonly seedSlot: u64;
309
+ /** The slot it was revealed in (0 before). */
310
+ readonly revealSlot: u64;
311
+ /** The revealed 32 bytes. Fails (5111) unless revealed in this slot, as Switchboard's `get_value`. */
312
+ value(): Hash;
313
+ /** The first 8 bytes of value() as a little-endian u64 (`value % 6n` for a die). */
314
+ valueU64(): u64;
315
+ }
316
+
297
317
  /** The SPL Memo program (v2, `MemoSq4g…`). Its address is checked. */
298
318
  export interface MemoProgram extends AccountMeta {
299
319
  readonly __memo_program: void;
@@ -343,6 +363,24 @@ export interface StakeProgram extends AccountMeta {
343
363
  ): void;
344
364
  }
345
365
 
366
+ /**
367
+ * The StakeHistory sysvar (`SysvarStakeHistory…`), read as an account: the cluster's stake per recent epoch (up to
368
+ * 512, newest first), as the Stake program uses it for warmup and cooldown. The address is checked.
369
+ */
370
+ export interface StakeHistorySysvar extends AccountMeta {
371
+ readonly __stake_history: void;
372
+ /** How many epochs it lists. */
373
+ readonly count: u64;
374
+ /** The newest epoch it lists (0 when empty). */
375
+ readonly latestEpoch: u64;
376
+ /** Whether `epoch` is listed; the readers below give 0 for an epoch that is not. */
377
+ has(epoch: u64): boolean;
378
+ /** Lamports of effective, activating and deactivating stake in `epoch`. */
379
+ effective(epoch: u64): u64;
380
+ activating(epoch: u64): u64;
381
+ deactivating(epoch: u64): u64;
382
+ }
383
+
346
384
  /**
347
385
  * The SlotHashes sysvar (`SysvarS1otHashes…`), read as an account: it is too large for the sysvar syscalls (Anchor's
348
386
  * `Sysvar<SlotHashes>` cannot load it either). The address is checked, and that it holds an entry (5103).
@@ -356,6 +394,7 @@ export interface SlotHashesSysvar extends AccountMeta {
356
394
  readonly latestHash: Hash;
357
395
  }
358
396
 
397
+ /** The Associated Token Account program (ATokenGP…). Its address is checked. */
359
398
  export interface AssociatedTokenProgram extends AccountMeta {
360
399
  readonly __ata_program: void;
361
400
  create(
@@ -458,6 +497,24 @@ export interface TokenMetadataProgram extends AccountMeta {
458
497
  * collection left out become none; a verified collection or creator cannot be changed this way, Metaplex refuses);
459
498
  * each `null` leaves that part as it is. The update authority signs (a PDA of this program with `signerSeeds`).
460
499
  */
500
+ /**
501
+ * Burn (BurnV1) a non-fungible asset (pass its master edition as `edition`) or a fungible one (`edition` null) held in
502
+ * `token`: the token account and edition close (the metadata is cleared to one byte, as Token Metadata does), the
503
+ * holder signs and gets the rent back. `collectionMetadata` is the collection's when the asset is a verified member, else null.
504
+ */
505
+ burnV1(
506
+ authority: AccountMeta,
507
+ metadata: AccountMeta,
508
+ edition: AccountMeta | null,
509
+ mint: AccountMeta,
510
+ token: AccountMeta,
511
+ collectionMetadata: AccountMeta | null,
512
+ systemProgram: SystemProgram,
513
+ instructionsSysvar: AccountMeta,
514
+ tokenProgram: TokenProgram | Token2022Program | TokenInterface,
515
+ amount: u64,
516
+ signerSeeds?: Seed[] | SignerSeeds,
517
+ ): void;
461
518
  updateMetadataAccountsV2(
462
519
  metadata: AccountMeta,
463
520
  updateAuthority: AccountMeta,
@@ -1444,6 +1501,13 @@ export interface CompressedLeaf {
1444
1501
  /** The current slot and epoch (Clock sysvar). */
1445
1502
  export declare function currentSlot(): u64;
1446
1503
  export declare function currentEpoch(): u64;
1504
+ /** The EpochSchedule sysvar: slots per epoch (after warmup), whether epochs warm up, and where normal epochs start. */
1505
+ export declare function slotsPerEpoch(): u64;
1506
+ export declare function epochWarmup(): boolean;
1507
+ export declare function firstNormalEpoch(): u64;
1508
+ export declare function firstNormalSlot(): u64;
1509
+ /** The LastRestartSlot sysvar: the last slot the cluster restarted at (0 if never). */
1510
+ export declare function lastRestartSlot(): u64;
1447
1511
  export type CloseTo<A, Destination extends string> = A & { readonly __closeTo?: Destination };
1448
1512
 
1449
1513
  /** A program-owned account that this instruction creates as a PDA. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.34.0",
3
+ "version": "0.36.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
@@ -1804,6 +1819,31 @@ static const uint8_t TS_SWITCHBOARD_FEED_DISC[8] = {196, 27, 108, 196, 10, 215,
1804
1819
  #define TS_SB_RESULT_SAMPLES (8 + 2256 + 96)
1805
1820
  #define TS_SB_RESULT_SLOT (8 + 2256 + 104)
1806
1821
 
1822
+ /* RandomnessAccountData: discriminator, authority, queue, seed slot hash, seed_slot @104, oracle, reveal_slot @144,
1823
+ value[32] @152, reserved; 384 bytes. */
1824
+ static const uint8_t TS_SWITCHBOARD_RANDOMNESS_DISC[8] = {10, 66, 229, 135, 220, 239, 217, 114};
1825
+ #define TS_SB_RAND_SEED_SLOT 104
1826
+ #define TS_SB_RAND_REVEAL_SLOT 144
1827
+ #define TS_SB_RAND_VALUE 152
1828
+
1829
+ static inline uint64_t ts_check_sb_randomness(const TsAccount *a, bool devnet) {
1830
+ if (!ts_key_eq(&a->owner, devnet ? &TS_SWITCHBOARD_DEVNET_ID : &TS_SWITCHBOARD_MAINNET_ID))
1831
+ TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: not a Switchboard randomness account (owner)");
1832
+ if (a->data_len < 384 || !ts_mem_eq(a->data, TS_SWITCHBOARD_RANDOMNESS_DISC, 8))
1833
+ TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: not a Switchboard RandomnessAccountData account");
1834
+ return SUCCESS;
1835
+ }
1836
+
1837
+ /* The revealed value, only in the slot it was revealed in (Switchboard's get_value). */
1838
+ static inline uint64_t ts_sb_randomness_value(const TsAccount *a, const uint8_t **out) {
1839
+ uint64_t clock[5];
1840
+ if (sol_get_clock_sysvar(clock) != SUCCESS) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: clock sysvar unavailable");
1841
+ if (ts_read_le(a->data + TS_SB_RAND_REVEAL_SLOT, 8) != clock[0])
1842
+ TS_FAIL(TS_ERR_ORACLE, "TypeSOL: the randomness was not revealed in this slot");
1843
+ *out = a->data + TS_SB_RAND_VALUE;
1844
+ return SUCCESS;
1845
+ }
1846
+
1807
1847
  static inline uint64_t ts_check_switchboard(const TsAccount *a, bool devnet) {
1808
1848
  if (!ts_key_eq(&a->owner, devnet ? &TS_SWITCHBOARD_DEVNET_ID : &TS_SWITCHBOARD_MAINNET_ID))
1809
1849
  TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: not a Switchboard feed (owner)");
@@ -1839,6 +1879,22 @@ static inline uint64_t ts_switchboard_value(const TsAccount *a, uint64_t max_sta
1839
1879
  /* ---- Associated token accounts, token metadata, transfer hooks ------------------- */
1840
1880
  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}};
1841
1881
  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}};
1882
+ static const SolPubkey TS_STAKE_HISTORY_ID = {{6,167,213,23,25,53,132,208,254,237,155,179,67,29,19,32,107,229,68,40,27,87,184,86,108,197,55,95,244,0,0,0}};
1883
+ /* StakeHistory: u64 count, then (epoch, effective, activating, deactivating) u64 entries, newest first. The entry for
1884
+ `epoch` (field 1..3 of it), or 0 when it is not listed; `found` says which. */
1885
+ static inline uint64_t ts_stake_history(const TsAccount *a, uint64_t epoch, int field, bool *found) {
1886
+ uint64_t n = ts_read_le(a->data, 8);
1887
+ if (n > (a->data_len - 8) / 32) n = (a->data_len - 8) / 32;
1888
+ for (uint64_t i = 0; i < n; i++) {
1889
+ const uint8_t *e = a->data + 8 + 32 * i;
1890
+ if (ts_read_le(e, 8) == epoch) {
1891
+ *found = true;
1892
+ return ts_read_le(e + 8 * field, 8);
1893
+ }
1894
+ }
1895
+ *found = false;
1896
+ return 0;
1897
+ }
1842
1898
  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}};
1843
1899
  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}};
1844
1900
  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}};