@typesol/cli 0.35.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 +14 -0
- package/README.md +1 -1
- package/dist/compiler/analyze.js +13 -0
- package/dist/compiler/emit/calls.js +23 -0
- package/dist/compiler/emit/expressions.js +14 -0
- package/dist/compiler/emit/function.d.ts +1 -1
- package/dist/compiler/emit/function.js +38 -3
- package/dist/compiler/idl.js +2 -0
- package/dist/compiler/model.d.ts +9 -0
- package/docs/language.md +3 -2
- package/docs/migrate-from-anchor.md +2 -0
- package/lib/typesol.d.ts +40 -1
- package/package.json +1 -1
- package/runtime/typesol_rt.h +41 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,20 @@ 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
|
+
|
|
9
23
|
## 0.35.0 — 2026-10-30
|
|
10
24
|
|
|
11
25
|
Token Metadata's Burn and the EpochSchedule and LastRestartSlot sysvars. Existing programs compile to the same binaries
|
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).
|
package/dist/compiler/analyze.js
CHANGED
|
@@ -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";
|
|
@@ -706,6 +706,29 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
706
706
|
return this.ataOp(node, target, method);
|
|
707
707
|
if (target?.kind.kind === "memoProgram")
|
|
708
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
|
+
}
|
|
709
732
|
if (target?.kind.kind === "stakeProgram")
|
|
710
733
|
return this.stakeOp(node, target, method);
|
|
711
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[]
|
|
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
|
-
|
|
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;
|
package/dist/compiler/idl.js
CHANGED
|
@@ -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")
|
package/dist/compiler/model.d.ts
CHANGED
|
@@ -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); `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` (EpochSchedule); `lastRestartSlot()` |
|
|
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.
|
|
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>` |
|
|
@@ -119,8 +119,10 @@ Anchor instruction that takes or returns a struct with `String` / `Vec` / `Optio
|
|
|
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
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)` |
|
|
122
123
|
| `EpochSchedule::get()?`, `LastRestartSlot::get()?` | `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()`; `lastRestartSlot()` |
|
|
123
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` |
|
|
124
126
|
| `pub fn fallback(program_id, accounts, data)` | `/** @fallback */ export function fallback(): void` with `instructionData()` and `remainingAccounts()` |
|
|
125
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 |
|
|
126
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
|
-
/**
|
|
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(
|
package/package.json
CHANGED
package/runtime/typesol_rt.h
CHANGED
|
@@ -1819,6 +1819,31 @@ static const uint8_t TS_SWITCHBOARD_FEED_DISC[8] = {196, 27, 108, 196, 10, 215,
|
|
|
1819
1819
|
#define TS_SB_RESULT_SAMPLES (8 + 2256 + 96)
|
|
1820
1820
|
#define TS_SB_RESULT_SLOT (8 + 2256 + 104)
|
|
1821
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
|
+
|
|
1822
1847
|
static inline uint64_t ts_check_switchboard(const TsAccount *a, bool devnet) {
|
|
1823
1848
|
if (!ts_key_eq(&a->owner, devnet ? &TS_SWITCHBOARD_DEVNET_ID : &TS_SWITCHBOARD_MAINNET_ID))
|
|
1824
1849
|
TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: not a Switchboard feed (owner)");
|
|
@@ -1854,6 +1879,22 @@ static inline uint64_t ts_switchboard_value(const TsAccount *a, uint64_t max_sta
|
|
|
1854
1879
|
/* ---- Associated token accounts, token metadata, transfer hooks ------------------- */
|
|
1855
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}};
|
|
1856
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
|
+
}
|
|
1857
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}};
|
|
1858
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}};
|
|
1859
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}};
|