@typesol/cli 0.45.0 → 0.47.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 +250 -0
- package/README.md +63 -17
- package/SECURITY.md +9 -7
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.js +33 -15
- package/dist/compiler/analyze.js +57 -6
- package/dist/compiler/diagnostics.d.ts +4 -3
- package/dist/compiler/diagnostics.js +10 -6
- package/dist/compiler/emit/base.d.ts +1 -1
- package/dist/compiler/emit/calls.js +18 -5
- package/dist/compiler/emit/cpi-core.d.ts +3 -1
- package/dist/compiler/emit/cpi-core.js +8 -4
- package/dist/compiler/emit/expressions.d.ts +14 -0
- package/dist/compiler/emit/expressions.js +52 -4
- package/dist/compiler/emit/shared.d.ts +8 -1
- package/dist/compiler/emit/shared.js +8 -1
- package/dist/compiler/emit/statements.d.ts +8 -3
- package/dist/compiler/emit/statements.js +68 -3
- package/dist/compiler/emit/storage.js +5 -1
- package/dist/compiler/hints.d.ts +7 -0
- package/dist/compiler/hints.js +58 -9
- package/dist/compiler/index.d.ts +5 -0
- package/dist/compiler/index.js +10 -1
- package/dist/compiler/model.js +3 -2
- package/dist/compiler/toolchain.d.ts +50 -2
- package/dist/compiler/toolchain.js +96 -11
- package/dist/idl-coder.d.ts +110 -0
- package/dist/idl-coder.js +529 -0
- package/dist/node-version.d.ts +4 -0
- package/dist/node-version.js +12 -0
- package/dist/testing.d.ts +44 -7
- package/dist/testing.js +30 -19
- package/dist/tools/doctor.d.ts +41 -0
- package/dist/tools/doctor.js +96 -14
- package/dist/workspace.d.ts +9 -2
- package/dist/workspace.js +13 -4
- package/docker/deps/0.46.0.lock.json +1206 -0
- package/docker/deps/0.47.0.lock.json +1206 -0
- package/docs/ai.md +2 -1
- package/docs/architecture.md +7 -3
- package/docs/audit.md +6 -6
- package/docs/case-study-phoenix.md +1 -1
- package/docs/case-study-raydium-amm.md +1 -1
- package/docs/case-study-spl-stake-pool.md +1 -1
- package/docs/cli.md +42 -4
- package/docs/errors.md +22 -8
- package/docs/glossary.md +210 -0
- package/docs/language-accounts.md +499 -0
- package/docs/language-basics.md +389 -0
- package/docs/language-builtins.md +411 -0
- package/docs/language-chain.md +198 -0
- package/docs/language-cpi.md +470 -0
- package/docs/language-errors-events.md +184 -0
- package/docs/language-native.md +493 -0
- package/docs/language-pdas.md +198 -0
- package/docs/language-statements.md +620 -0
- package/docs/language-types.md +601 -0
- package/docs/language.md +190 -467
- package/docs/mainnet.md +18 -3
- package/docs/migrate-from-anchor.md +7 -6
- package/docs/security-model.md +3 -3
- package/docs/stability.md +3 -1
- package/docs/test-your-program.md +54 -15
- package/docs/troubleshooting.md +222 -100
- package/lib/typesol.d.ts +67 -22
- package/llms-full.txt +4920 -638
- package/llms.txt +12 -1
- package/package.json +2 -6
- package/releases/0.45.0.json +732 -0
- package/releases/0.46.0.json +817 -0
- package/ts-plugin/index.js +16 -5
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
# Built-ins
|
|
2
|
+
|
|
3
|
+
<!-- Generated by scripts/language-builtins.ts from lib/typesol.d.ts; do not edit by hand. -->
|
|
4
|
+
|
|
5
|
+
Every name `"typesol"` exports (216 names, 229 declarations), grouped, with its declaration and the first sentence of its doc
|
|
6
|
+
comment in `lib/typesol.d.ts`. Each group links to the part of the [language guide](language.md) that explains it;
|
|
7
|
+
your editor shows the full doc comment on hover. Methods of account and program types (`systemProgram.transfer`,
|
|
8
|
+
`acct.create`, …) are described with their types in the guide.
|
|
9
|
+
|
|
10
|
+
- [Integers and numbers](#integers-and-numbers)
|
|
11
|
+
- [Addresses, hashes, strings and options](#addresses-hashes-strings-and-options)
|
|
12
|
+
- [Lists](#lists)
|
|
13
|
+
- [Helpers](#helpers)
|
|
14
|
+
- [Account types](#account-types)
|
|
15
|
+
- [Constraints](#constraints)
|
|
16
|
+
- [Closing and resizing](#closing-and-resizing)
|
|
17
|
+
- [Accounts created by hand](#accounts-created-by-hand)
|
|
18
|
+
- [Remaining accounts and other programs' accounts](#remaining-accounts-and-other-programs-accounts)
|
|
19
|
+
- [PDAs](#pdas)
|
|
20
|
+
- [Errors](#errors)
|
|
21
|
+
- [Logs, events and return values](#logs-events-and-return-values)
|
|
22
|
+
- [Calling other programs](#calling-other-programs)
|
|
23
|
+
- [Tokens](#tokens)
|
|
24
|
+
- [Token-2022 extension reads](#token-2022-extension-reads)
|
|
25
|
+
- [Transfer hooks](#transfer-hooks)
|
|
26
|
+
- [Memo, Token Metadata and Stake](#memo-token-metadata-and-stake)
|
|
27
|
+
- [Metaplex Core](#metaplex-core)
|
|
28
|
+
- [Compressed NFTs](#compressed-nfts)
|
|
29
|
+
- [Sysvars](#sysvars)
|
|
30
|
+
- [Hashes, signatures and introspection](#hashes-signatures-and-introspection)
|
|
31
|
+
- [Oracles and randomness](#oracles-and-randomness)
|
|
32
|
+
- [Native programs](#native-programs)
|
|
33
|
+
|
|
34
|
+
## Integers and numbers
|
|
35
|
+
|
|
36
|
+
Explained in [Types: Integers](language-types.md#integers).
|
|
37
|
+
|
|
38
|
+
| Name | Declaration | What it is |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `u8` | `type u8 = bigint`<br>`function u8(value: bigint): u8` | Unsigned 8-bit integer (a `bigint` to TypeScript); literals are written `1n`. |
|
|
41
|
+
| `u16` | `type u16 = bigint`<br>`function u16(value: bigint): u16` | Unsigned 16-bit integer (a `bigint` to TypeScript); literals are written `1n`. |
|
|
42
|
+
| `u32` | `type u32 = bigint`<br>`function u32(value: bigint): u32` | Unsigned 32-bit integer (a `bigint` to TypeScript); literals are written `1n`. |
|
|
43
|
+
| `u64` | `type u64 = bigint`<br>`function u64(value: bigint): u64` | Unsigned 64-bit integer (a `bigint` to TypeScript); literals are written `1n`. |
|
|
44
|
+
| `u128` | `type u128 = bigint`<br>`function u128(value: bigint): u128` | Unsigned 128-bit integer (a `bigint` to TypeScript); literals are written `1n`. |
|
|
45
|
+
| `u256` | `type u256 = bigint`<br>`function u256(value: bigint): u256` | 256-bit unsigned integers for computation (sqrt-price and liquidity math): locals, helper parameters and results, `u256(x)` and back with `u128(x)` / `u64(x)` (checked). |
|
|
46
|
+
| `i8` | `type i8 = bigint`<br>`function i8(value: bigint): i8` | Signed 8-bit integer, two's complement (a `bigint` to TypeScript). |
|
|
47
|
+
| `i16` | `type i16 = bigint`<br>`function i16(value: bigint): i16` | Signed 16-bit integer, two's complement (a `bigint` to TypeScript). |
|
|
48
|
+
| `i32` | `type i32 = bigint`<br>`function i32(value: bigint): i32` | Signed 32-bit integer, two's complement (a `bigint` to TypeScript). |
|
|
49
|
+
| `i64` | `type i64 = bigint`<br>`function i64(value: bigint): i64` | Signed 64-bit integer, two's complement (a `bigint` to TypeScript). |
|
|
50
|
+
| `i128` | `type i128 = bigint`<br>`function i128(value: bigint): i128` | Signed 128-bit integer, two's complement (a `bigint` to TypeScript). |
|
|
51
|
+
| `mulDiv` | `function mulDiv(a: u64, b: u64, c: u64): u64` | floor(a * b / c) with a double-width intermediate (all u64, all u128, or all u256); aborts if c is 0 or the result does not fit. |
|
|
52
|
+
| `mulDivCeil` | `function mulDivCeil(a: u64, b: u64, c: u64): u64` | ceil(a * b / c), like mulDiv. |
|
|
53
|
+
| `isqrt` | `function isqrt<T>(x: T): T` | floor(sqrt(x)) for unsigned integers (u8 … u256). |
|
|
54
|
+
| `min` | `function min<T>(a: T, b: T): T` | The smaller of two integers of one type. |
|
|
55
|
+
| `max` | `function max<T>(a: T, b: T): T` | The larger of two integers of one type. |
|
|
56
|
+
| `f64` | `type f64 = bigint & { readonly __f64: unique symbol }` | A 64-bit float, held as its IEEE 754 bits (Borsh writes an f64 as those 8 bytes, little-endian); the IDL calls it f64. |
|
|
57
|
+
| `f64FromBits` | `function f64FromBits(bits: u64): f64` | An f64 from its IEEE 754 bits, computed with integers. |
|
|
58
|
+
| `f64Bits` | `function f64Bits(value: f64): u64` | An f64's IEEE 754 bits. |
|
|
59
|
+
|
|
60
|
+
## Addresses, hashes, strings and options
|
|
61
|
+
|
|
62
|
+
Explained in [Types: Pubkey and Hash](language-types.md#pubkey-and-hash).
|
|
63
|
+
|
|
64
|
+
| Name | Declaration | What it is |
|
|
65
|
+
| --- | --- | --- |
|
|
66
|
+
| `Pubkey` | `interface Pubkey` | A 32-byte Solana address. |
|
|
67
|
+
| `Hash` | `interface Hash` | 32 bytes of hash output (sha256 / keccak256, Merkle roots). |
|
|
68
|
+
| `pubkey` | `function pubkey(base58: string): Pubkey` | A 32-byte address written in base58, checked at compile time: `const ADMIN = pubkey("4Nd1…")`. |
|
|
69
|
+
| `FixedString` | `type FixedString<N> = string & { readonly __capacity?: N }` | A string stored inline in account data with room for N bytes (u32 length + N bytes). |
|
|
70
|
+
| `byteLength` | `function byteLength(value: string): u64` | UTF-8 byte length of a string. |
|
|
71
|
+
| `Option` | `type Option<T> = T \| null` | An optional value: `best: Option<u64>` (same as `u64 \| null`), also of a struct (`home: Option<Point>`). |
|
|
72
|
+
|
|
73
|
+
## Lists
|
|
74
|
+
|
|
75
|
+
Explained in [Types: Lists](language-types.md#lists).
|
|
76
|
+
|
|
77
|
+
| Name | Declaration | What it is |
|
|
78
|
+
| --- | --- | --- |
|
|
79
|
+
| `ListMethods` | `interface ListMethods<T>` | Callback methods of Vec, FixedArray and FixedVec. |
|
|
80
|
+
| `FixedArray` | `interface FixedArray<T, N>` | A fixed-length array stored inline in account data, e.g. `scores: FixedArray<u64, 8>`. |
|
|
81
|
+
| `fixedArray` | `function fixedArray<T, N>(fill: T): FixedArray<T, N>` | Create a local fixed-length array filled with `fill`: `const xs = fixedArray<u64, 4>(0n)`. |
|
|
82
|
+
| `FixedVec` | `interface FixedVec<T, N>` | A list stored inline with room for N elements: a u32 length, then N slots (Anchor `Vec<T>` with `#[max_len(N)]`, but always 4 + N × size(T) bytes). |
|
|
83
|
+
| `fixedVec` | `function fixedVec<T>(items: T[]): FixedVec<T, never>` | A FixedVec value holding these elements (`acct.owners = fixedVec([a, b])`, `{ owners: fixedVec([]) }`). |
|
|
84
|
+
| `Vec` | `interface Vec<T>` | A list whose length varies: as account data the account grows with it; as an argument it is a read-only view. |
|
|
85
|
+
| `IndexedList` | `interface IndexedList<T>` | A list read by index: a Vec or FixedVec in account data, a Vec argument, or a stored local list. |
|
|
86
|
+
|
|
87
|
+
## Helpers
|
|
88
|
+
|
|
89
|
+
Explained in [Statements and functions: Inout parameters](language-statements.md#inout-parameters).
|
|
90
|
+
|
|
91
|
+
| Name | Declaration | What it is |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| `Inout` | `type Inout<T> = T` | A helper parameter the helper may change in place (Rust's `&mut T`): `function addEvent(rec: Inout<Recorder>, e: Event): void`. |
|
|
94
|
+
|
|
95
|
+
## Account types
|
|
96
|
+
|
|
97
|
+
Explained in [Accounts: Account parameters and the checks they emit](language-accounts.md#account-parameters-and-the-checks-they-emit).
|
|
98
|
+
|
|
99
|
+
| Name | Declaration | What it is |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| `AccountMeta` | `interface AccountMeta` | Fields every account parameter exposes. |
|
|
102
|
+
| `Signer` | `interface Signer` | The account must have signed the transaction. |
|
|
103
|
+
| `SystemAccount` | `interface SystemAccount` | An account owned by the System Program, e.g. a wallet (Anchor `SystemAccount`; 3011 otherwise). |
|
|
104
|
+
| `AccountInfo` | `interface AccountInfo` | Any account, no ownership or data checks. |
|
|
105
|
+
| `Account` | `type Account<T> = Readonly<T> & AccountMeta` | An account owned by this program holding struct `T`. |
|
|
106
|
+
| `Mut` | `type Mut<T, E> = T & AccountMeta` | A writable account: `Mut<T>` is `Account<T>` whose fields may be written. |
|
|
107
|
+
| `Init` | `type Init<T>` | An account this instruction creates: at a PDA of this program, or, with `null` seeds, a new keypair account that signs. |
|
|
108
|
+
| `InitIfNeeded` | `type InitIfNeeded<T>` | Created on first use (like Anchor `init_if_needed`): `createIfNeeded(payer, seeds)` returns true when it created the account now. |
|
|
109
|
+
| `Zeroed` | `type Zeroed<T> = T & AccountMeta` | An account the client already allocated with System CreateAccount (any size up to 10 MiB; over 10 KiB a program cannot create it itself), owned by this program and still zeroed: Anchor's `zero`. |
|
|
110
|
+
| `Migrate` | `interface Migrate<From, To>` | Anchor 1.0's `Migration<From, To>`: an existing `From` account (owner, discriminator and size checked) that this instruction rewrites as `To` with `acct.migrate(payer, value)`, a top-level statement every path must reach. |
|
|
111
|
+
| `Dup` | `type Dup<A> = A & { readonly __dup?: true }` | Anchor's `dup`: this writable account may be the same account as another writable parameter (TypeSOL refuses that otherwise, 2040). |
|
|
112
|
+
| `Optional` | `type Optional<A> = A \| null` | An optional account (Anchor `Option<Account<…>>`): the client passes this program's id in its slot to leave it out. |
|
|
113
|
+
| `ProgramData` | `interface ProgramData` | This program's ProgramData account (BPF upgradeable loader). |
|
|
114
|
+
| `Program` | `interface Program<Address>` | Another program, pinned to its address: `Program<"Tokenz...">`. |
|
|
115
|
+
| `UncheckedProgram` | `interface UncheckedProgram` | Any executable account. |
|
|
116
|
+
| `SystemProgram` | `interface SystemProgram` | The System Program. |
|
|
117
|
+
| `EventAuthority` | `interface EventAuthority` | Anchor's event authority PDA ["__event_authority"] of this program (address checked), for emitCpi. |
|
|
118
|
+
| `SelfProgram` | `interface SelfProgram` | This program itself (its address is checked), for self-CPI. |
|
|
119
|
+
|
|
120
|
+
## Constraints
|
|
121
|
+
|
|
122
|
+
Explained in [Accounts: Constraints](language-accounts.md#constraints).
|
|
123
|
+
|
|
124
|
+
| Name | Declaration | What it is |
|
|
125
|
+
| --- | --- | --- |
|
|
126
|
+
| `HasOne` | `type HasOne<A, Field, E> = A & { readonly __hasOne?: [Field, E] }` | `HasOne<A, "field">`: the struct's `field` must be the key of the parameter with that name (Anchor's `has_one`; 2001). |
|
|
127
|
+
| `Seeds` | `type Seeds<A, Names, Bump, ProgramId>` | The account is this program's PDA for the seeds (Anchor's `seeds = […], bump`; 2006): `"@name"` is an account's key or an argument's bytes, `"@acct.field"` a field, other strings literals. |
|
|
128
|
+
| `CloseTo` | `type CloseTo<A, Destination> = A & { readonly __closeTo?: Destination }` | Close the account into the parameter `Destination` when the instruction succeeds (Anchor's `close = destination`). |
|
|
129
|
+
| `Address` | `type Address<A, Base58, E> = A & { readonly __address?: [Base58, E] }` | The account must be this exact address (Anchor `address = …`, error 2012): `Address<Mut<AccountInfo>, "4Nd1…">`. |
|
|
130
|
+
| `Owner` | `type Owner<A, Base58, E> = A & { readonly __owner?: [Base58, E] }` | The account's owner program must be this address (Anchor `owner = …`, 2004; a third argument: one of your errors). |
|
|
131
|
+
| `Executable` | `type Executable<A> = A & { readonly __executable?: true }` | The account must be an executable program (Anchor `executable`, 2007). |
|
|
132
|
+
| `Signed` | `type Signed<A, E> = A & { readonly __signed?: E \| true }` | The account must sign the transaction (Anchor's `signer` constraint on an account that is not a `Signer`; 2002), e.g. `Signed<Zeroed<Multisig>>` for an account the client creates with a fresh keypair in the same transaction. |
|
|
133
|
+
| `constraint` | `function constraint(account: AccountMeta \| RemainingAccount \| null, condition: boolean, error?: string \| AnchorError): void` | Anchor's `constraint = condition @ error` on `account`. |
|
|
134
|
+
|
|
135
|
+
## Closing and resizing
|
|
136
|
+
|
|
137
|
+
Explained in [Accounts: Closing and resizing](language-accounts.md#closing-and-resizing).
|
|
138
|
+
|
|
139
|
+
| Name | Declaration | What it is |
|
|
140
|
+
| --- | --- | --- |
|
|
141
|
+
| `close` | `function close(account: AccountMeta, destination: AccountMeta): void` | Close a program-owned account: move all lamports to `destination` and wipe it. |
|
|
142
|
+
| `realloc` | `function realloc(account: AccountMeta, newSize: u64, payer: Mut<Signer>): void` | Resize an account of this program (Anchor `realloc`, struct accounts only): growing charges `payer` the extra rent (never the account's own lamports, which may be deposits); shrinking keeps every lamport in the account — move freed rent out yourself if your program allows it. |
|
|
143
|
+
| `resizeAccount` | `function resizeAccount(account: RemainingAccount \| Mut<AccountInfo>, newSize: u64): void` | Resize a `Mut<AccountInfo>` or a remaining account of this program to `newSize` bytes (Rust's `AccountInfo::resize` / `realloc(newSize, true)`): the data length only, the new bytes zeroed. |
|
|
144
|
+
|
|
145
|
+
## Accounts created by hand
|
|
146
|
+
|
|
147
|
+
Explained in [Accounts: Accounts created by hand](language-accounts.md#accounts-created-by-hand).
|
|
148
|
+
|
|
149
|
+
| Name | Declaration | What it is |
|
|
150
|
+
| --- | --- | --- |
|
|
151
|
+
| `initAccount` | `function initAccount<T>(account: AccountMeta \| RemainingAccount): T` | Anchor's `AccountLoader::load_init` on an account the instruction created itself (`systemProgram.createAccount`, or `allocate` + `assign` on a pre-funded address): it must be owned by this program (3007), writable (3006), hold the struct (3003) and have no discriminator yet (3000). |
|
|
152
|
+
|
|
153
|
+
## Remaining accounts and other programs' accounts
|
|
154
|
+
|
|
155
|
+
Explained in [Accounts: Remaining accounts](language-accounts.md#remaining-accounts).
|
|
156
|
+
|
|
157
|
+
| Name | Declaration | What it is |
|
|
158
|
+
| --- | --- | --- |
|
|
159
|
+
| `remainingAccounts` | `function remainingAccounts(): RemainingAccounts` | The accounts passed after the declared ones, in order (see RemainingAccounts). |
|
|
160
|
+
| `RemainingAccount` | `interface RemainingAccount` | One extra account passed after the declared ones. |
|
|
161
|
+
| `RemainingAccounts` | `interface RemainingAccounts` | The accounts a client passed beyond the instruction's declared parameters. |
|
|
162
|
+
| `RemainingSlice` | `interface RemainingSlice` | Part of the remaining accounts (`rest.slice(a, b)`): spread it into a CPI's account list, directly or via readonly/writable. |
|
|
163
|
+
| `loadAccount` | `function loadAccount<T>(account: RemainingAccount \| AccountInfo): Account<T>` | Read a struct of this program from a remaining account or an `AccountInfo` parameter (Anchor's `AccountLoader::try_from` on an `UncheckedAccount`): owner, discriminator and size are checked. |
|
|
164
|
+
| `loadAccountMut` | `function loadAccountMut<T>(account: RemainingAccount \| AccountInfo): Mut<T>` | `loadAccount` for writing: also writable, and loaded mutably once per instruction (2040). |
|
|
165
|
+
| `loadForeign` | `function loadForeign<T>(account: AccountMeta \| RemainingAccount, owner: Pubkey): Readonly<T>` | View another program's Anchor account as a struct declared here (same field layout): the owner must be `owner` (3007), the data must start with the discriminator sha256("account:<T>")[..8] (3002) and be large enough (3003). |
|
|
166
|
+
| `readData` | `function readData<T>(account: AccountMeta \| RemainingAccount, offset: u64): T` | Read a little-endian value at `offset` in any account's data (bounds-checked, error 3003): `readData<u64>(pool, 72n)`, `readData<Pubkey>(pool, 8n)`. |
|
|
167
|
+
| `writeData` | `function writeData<T>(account: Mut<AccountInfo>, offset: u64, value: T): void` | Write a little-endian value at `offset` in a `Mut<AccountInfo>`'s data (bounds-checked, error 3003): `writeData<u64>(archive, 72n, count)`. |
|
|
168
|
+
|
|
169
|
+
## PDAs
|
|
170
|
+
|
|
171
|
+
Explained in [PDAs](language-pdas.md).
|
|
172
|
+
|
|
173
|
+
| Name | Declaration | What it is |
|
|
174
|
+
| --- | --- | --- |
|
|
175
|
+
| `Seed` | `type Seed = string \| Pubkey \| Hash \| bigint \| number` | A PDA seed: a string, a Pubkey, a Hash (its 32 bytes), an integer (at its width) or a unit enum value (one byte). |
|
|
176
|
+
| `SignerSeeds` | `interface SignerSeeds` | The seeds (with the bump) of one PDA signature, for helpers that sign CPIs: declare a `seeds: SignerSeeds` parameter, pass it where signerSeeds go, and call the helper with `signer(["vault", owner.key, bump])` (or `signer([])` when nothing needs to sign). |
|
|
177
|
+
| `signer` | `function signer(seeds: Seed[]): SignerSeeds` | Name one PDA signature's seeds (with the bump) for CPIs and helpers: `const vault = signer(["vault", owner.key, bump])`. |
|
|
178
|
+
| `requirePda` | `function requirePda(account: AccountMeta, seeds: Seed[], bump: u8): void` | Verify `account.key` is the PDA for `seeds` + `bump` under this program. |
|
|
179
|
+
| `bigEndian` | `function bigEndian(value: bigint): Seed` | An integer seed with its bytes most significant first (Rust's `x.to_be_bytes()`), inside a seeds list: `["tick_array", pool.key, bigEndian(startIndex)]`. |
|
|
180
|
+
| `findProgramAddress` | `function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey` | The canonical program address of `seeds` under `program` (Rust `Pubkey::find_program_address(seeds, program).0`). |
|
|
181
|
+
| `findProgramAddressBump` | `function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8` | The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. |
|
|
182
|
+
| `findProgramAddressWithBump` | `function findProgramAddressWithBump(seeds: Seed[], program: Pubkey): [address: Pubkey, bump: u8]` | The canonical program address and its bump from one search (Rust's `let (address, bump) = Pubkey::find_program_address(seeds, program)`), where `findProgramAddress` and `findProgramAddressBump` would search twice: bind both, `const [address, bump] = findProgramAddressWithBump(["seat", market, trader], PHOENIX_ID)`. |
|
|
183
|
+
| `createProgramAddress` | `function createProgramAddress(seeds: Seed[], program: Pubkey): Pubkey \| null` | `Pubkey::create_program_address(seeds, program)`: the address of these seeds with the bump given as the last seed, or null when they give no program address (a point on the curve, or too many / too long seeds). |
|
|
184
|
+
| `programId` | `function programId(): Pubkey` | This program's address (`crate::ID`). |
|
|
185
|
+
|
|
186
|
+
## Errors
|
|
187
|
+
|
|
188
|
+
Explained in [Errors, logs, events and return values: require](language-errors-events.md#require).
|
|
189
|
+
|
|
190
|
+
| Name | Declaration | What it is |
|
|
191
|
+
| --- | --- | --- |
|
|
192
|
+
| `require` | `function require(condition: boolean, error: string \| AnchorError \| ProgramError \| u32): asserts condition` | Abort with the given error unless `condition` holds. |
|
|
193
|
+
| `AnchorError` | `enum AnchorError` | Anchor's own error codes (anchor-lang `ErrorCode`): `require(condition, AnchorError.AccountDidNotDeserialize)` fails with that code, as `require!(condition, ErrorCode::AccountDidNotDeserialize)` does. |
|
|
194
|
+
| `ProgramError` | `enum ProgramError` | Solana's built-in program errors (`solana_program::program_error::ProgramError`, no custom code): a native program's `Err(ProgramError::InvalidInstructionData)`. |
|
|
195
|
+
|
|
196
|
+
## Logs, events and return values
|
|
197
|
+
|
|
198
|
+
Explained in [Errors, logs, events and return values: Events](language-errors-events.md#events).
|
|
199
|
+
|
|
200
|
+
| Name | Declaration | What it is |
|
|
201
|
+
| --- | --- | --- |
|
|
202
|
+
| `log` | `function log(value: string \| bigint \| Pubkey \| Hash): void` | Write a string, integer, Pubkey or Hash to the program log (a Pubkey or Hash as base58). |
|
|
203
|
+
| `emit` | `function emit<T>(event: T): void` | Emit an Anchor-compatible event ("Program data: <base64>") built from an exported interface: `emit<Deposited>({ owner: owner.key, amount })`. |
|
|
204
|
+
| `emitCpi` | `function emitCpi<T>(event: T, eventAuthority: EventAuthority, self: SelfProgram): void` | Like emit, but the event travels in the data of a CPI to this program (Anchor `emit_cpi!`): indexers read it from inner instructions, and it cannot be cut off by log truncation. |
|
|
205
|
+
|
|
206
|
+
## Calling other programs
|
|
207
|
+
|
|
208
|
+
Explained in [Calling other programs: invoke](language-cpi.md#invoke).
|
|
209
|
+
|
|
210
|
+
| Name | Declaration | What it is |
|
|
211
|
+
| --- | --- | --- |
|
|
212
|
+
| `invoke` | `function invoke(program: Program<string> \| UncheckedProgram \| SystemProgram \| TokenProgram \| Token2022Program \| TokenInterface \| RemainingAccount, accounts: CpiAccount[], data: CpiData[], signerSeeds?: Seed[] \| SignerSeeds \| (Seed[] \| SignerSeeds)[]): void` | Call any program (a cross-program invocation) with an account list and instruction data. |
|
|
213
|
+
| `CpiAccount` | `interface CpiAccount` | An account entry for `invoke`, built with readonly()/writable()/readonlySigner()/writableSigner(). |
|
|
214
|
+
| `readonly` | `function readonly(account: AccountMeta \| RemainingAccount \| null): CpiAccount`<br>`function readonly(accounts: RemainingAccounts \| RemainingSlice): Iterable<CpiAccount>` | A read-only entry of `invoke`'s account list: an account, or remaining accounts spread (`...readonly(rest)`). |
|
|
215
|
+
| `writable` | `function writable(account: AccountMeta \| RemainingAccount \| null): CpiAccount`<br>`function writable(accounts: RemainingAccounts \| RemainingSlice): Iterable<CpiAccount>` | A writable account entry for `invoke` (the parameter must be `Mut<…>`); an optional account as for `readonly`. |
|
|
216
|
+
| `readonlySigner` | `function readonlySigner(account: AccountMeta \| RemainingAccount): CpiAccount` | A read-only signer entry for `invoke`: the account signed, or signerSeeds sign for it. |
|
|
217
|
+
| `writableSigner` | `function writableSigner(account: AccountMeta \| RemainingAccount): CpiAccount` | A writable signer entry for `invoke`: the account signed, or signerSeeds sign for it. |
|
|
218
|
+
| `CpiData` | `type CpiData` | Instruction data pieces, Borsh-encoded: integers little-endian at their declared width, booleans 1 byte, Pubkeys/Hashes 32 bytes, strings u32 length + UTF-8, Options a tag byte + value, structs and FixedArrays their fixed layout, unit enum values 1 byte, data enums as Borsh enums, Vec arguments u32 length + elements. |
|
|
219
|
+
| `Bytes` | `interface Bytes` | Raw bytes for instruction data. |
|
|
220
|
+
| `sighash` | `function sighash(name: string): Bytes` | The 8-byte Anchor instruction discriminator for `name` (sha256("global:<snake_case name>")[..8]). |
|
|
221
|
+
| `hex` | `function hex(literal: string): Bytes` | Bytes from a hex string literal, e.g. hex("0a0b"). |
|
|
222
|
+
| `returnData` | `function returnData<T>(program: AccountMeta): T` | Read the return data the last invoke() left behind, checking it came from `program` and has exactly the size of T: `const n = returnData<u64>(counterProgram)`. |
|
|
223
|
+
| `invokeInstruction` | `function invokeInstruction(programId: Pubkey, accounts: IndexedList<InstructionAccountMeta>, data: IndexedList<u8>, infos: RemainingAccounts \| RemainingSlice, signerSeeds?: Seed[] \| SignerSeeds \| (Seed[] \| SignerSeeds)[]): void` | A CPI decided at run time, e.g. one stored in account data (Rust's `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`). |
|
|
224
|
+
| `InstructionAccountMeta` | `interface InstructionAccountMeta` | One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. |
|
|
225
|
+
| `programAt` | `function programAt<P>(account: RemainingAccount \| AccountInfo): P` | A remaining account (or an AccountInfo parameter) as a typed program: `const stake = programAt<StakeProgram>(rest.get(12n))`, then `stake.split(…)`, `token.mintTo(…)`, `system.transfer(…)` as on a declared program parameter, and passed to helpers that take that program type. |
|
|
226
|
+
| `sysvarAt` | `function sysvarAt<S>(account: RemainingAccount \| AccountInfo): S` | A remaining account (or an AccountInfo parameter) as a sysvar read in place: `sysvarAt<StakeHistorySysvar>(acct)`, bound to a const, then `.count`, `.latestEpoch`, `.effective(epoch)` …. |
|
|
227
|
+
| `named` | `function named(account: AccountMeta, address: Pubkey): NamedAccount` | A Stake CPI's sysvar or stake config argument as solana_program's stake instruction builders write it: the instruction's account list names `address` (`SysvarC1ock…`), and `account` (the slot's account, whatever its key) is the account handed to the runtime, as Rust's `invoke_signed(&ix, &[stake, clock_info, …])` hands it. |
|
|
228
|
+
| `NamedAccount` | `interface NamedAccount` | An account whose slot in a Stake CPI names another address: what `named(account, address)` gives. |
|
|
229
|
+
|
|
230
|
+
## Tokens
|
|
231
|
+
|
|
232
|
+
Explained in [Calling other programs: Tokens](language-cpi.md#tokens).
|
|
233
|
+
|
|
234
|
+
| Name | Declaration | What it is |
|
|
235
|
+
| --- | --- | --- |
|
|
236
|
+
| `TokenAccount` | `interface TokenAccount` | A token account of SPL Token or Token-2022 (extensions allowed). |
|
|
237
|
+
| `Mint` | `interface Mint` | A mint of SPL Token or Token-2022. |
|
|
238
|
+
| `TokenProgram` | `interface TokenProgram` | The SPL Token program (Tokenkeg). |
|
|
239
|
+
| `Token2022Program` | `interface Token2022Program` | The Token-2022 program (TokenzQdB...). |
|
|
240
|
+
| `TokenInterface` | `interface TokenInterface` | Either token program. |
|
|
241
|
+
| `TokenOf` | `type TokenOf<A, MintParam, AuthorityParam, TokenProgramParam>` | Anchor's `token::mint = mintParam, token::authority = authorityParam, token::token_program = tokenProgramParam` on an existing token account, naming the parameters (2014 / 2015 / 2021: owned by that token program); `never` leaves one out. |
|
|
242
|
+
| `MintOf` | `type MintOf<A, AuthorityParam, FreezeAuthorityParam, TokenProgramParam>` | Anchor's `mint::authority = a, mint::freeze_authority = f, mint::token_program = tp` on an existing mint, naming the parameters (2016 / 2017 / 2022: owned by that token program); `never` leaves one out. |
|
|
243
|
+
| `Ata` | `type Ata<A, Owner, MintParam> = A & { readonly __ata?: [Owner, MintParam] }` | `Ata<A, "owner", "mint">`: the account must be the associated token account of those parameters (2009). |
|
|
244
|
+
| `MintExtensions` | `interface MintExtensions` | Token-2022 extensions for `mint.create(…, extensions)`: Anchor's `extensions::…` constraints. |
|
|
245
|
+
| `AuthorityType` | `const AuthorityType` | Token authority kinds for setAuthority (SPL Token AuthorityType). |
|
|
246
|
+
| `AssociatedTokenProgram` | `interface AssociatedTokenProgram` | The Associated Token Account program (ATokenGP…). |
|
|
247
|
+
| `associatedTokenAddress` | `function associatedTokenAddress(owner: Pubkey, mint: Pubkey, tokenProgram: Pubkey): Pubkey` | The associated token account address of `owner` for `mint` under `tokenProgram`. |
|
|
248
|
+
| `rentExempt` | `function rentExempt(space: u64): u64` | Rent-exempt minimum balance for an account of `space` bytes. |
|
|
249
|
+
| `TOKEN_ACCOUNT_SIZE` | `const TOKEN_ACCOUNT_SIZE: u64` | SPL Token's token account size, 165 bytes, for systemProgram.createAccount. |
|
|
250
|
+
| `MINT_SIZE` | `const MINT_SIZE: u64` | SPL Token's mint size, 82 bytes. |
|
|
251
|
+
|
|
252
|
+
## Token-2022 extension reads
|
|
253
|
+
|
|
254
|
+
Explained in [Calling other programs: Token-2022 extension reads](language-cpi.md#token-2022-extension-reads).
|
|
255
|
+
|
|
256
|
+
| Name | Declaration | What it is |
|
|
257
|
+
| --- | --- | --- |
|
|
258
|
+
| `transferFee` | `function transferFee(mint: AccountMeta \| RemainingAccount, amount: u64): u64` | The fee withheld when `amount` is sent now: the mint's Token-2022 TransferFeeConfig for the current epoch, 0 without it. |
|
|
259
|
+
| `transferFeeInverse` | `function transferFeeInverse(mint: AccountMeta \| RemainingAccount, amountReceived: u64): u64` | The fee withheld when the recipient is to get `amountReceived` (spl-token-2022's `calculate_inverse_epoch_fee`): send `amountReceived + transferFeeInverse(mint, amountReceived)`. 0 without TransferFeeConfig; fails (5100) where spl-token-2022 has no answer. |
|
|
260
|
+
| `transferFeeBasisPoints` | `function transferFeeBasisPoints(mint: AccountMeta \| RemainingAccount): u16` | The TransferFeeConfig in force this epoch: its basis points (0 without the extension). |
|
|
261
|
+
| `transferFeeMaximum` | `function transferFeeMaximum(mint: AccountMeta \| RemainingAccount): u64` | The TransferFeeConfig in force this epoch: its maximum fee (0 without the extension). |
|
|
262
|
+
| `extensionsWithin` | `function extensionsWithin(account: AccountMeta \| RemainingAccount, types: u16[]): boolean` | Whether every Token-2022 extension of `account` is one of `types` (a list of u16 extension types, e.g. `[1n, 18n, 19n, 10n, 25n]`): a pool that accepts only mints it knows how to handle. |
|
|
263
|
+
| `hasExtension` | `function hasExtension(account: AccountMeta \| RemainingAccount, extensionType: u16): boolean` | Whether a Token-2022 mint or token account carries extension `extensionType` (e.g. 9 NonTransferable, 7 ImmutableOwner). |
|
|
264
|
+
| `transferHookProgram` | `function transferHookProgram(mint: AccountMeta \| RemainingAccount): Option<Pubkey>` | The TransferHook extension's program, if any. |
|
|
265
|
+
| `transferHookAuthority` | `function transferHookAuthority(mint: AccountMeta \| RemainingAccount): Option<Pubkey>` | The TransferHook extension's authority (who may change the hook program), if any. |
|
|
266
|
+
| `permanentDelegate` | `function permanentDelegate(mint: AccountMeta \| RemainingAccount): Option<Pubkey>` | The PermanentDelegate extension's delegate, if any (it can move or burn anyone's tokens). |
|
|
267
|
+
| `mintCloseAuthority` | `function mintCloseAuthority(mint: AccountMeta \| RemainingAccount): Option<Pubkey>` | The MintCloseAuthority extension's authority, if any. |
|
|
268
|
+
| `isTransferring` | `function isTransferring(tokenAccount: AccountMeta \| RemainingAccount): boolean` | Whether Token-2022 is transferring from this token account right now (its TransferHookAccount `transferring` flag): true inside a transfer hook called by Token-2022, false when the hook is invoked directly. |
|
|
269
|
+
|
|
270
|
+
## Transfer hooks
|
|
271
|
+
|
|
272
|
+
Explained in [Calling other programs: Implementing another program's interface (transfer hooks)](language-cpi.md#implementing-another-programs-interface-transfer-hooks).
|
|
273
|
+
|
|
274
|
+
| Name | Declaration | What it is |
|
|
275
|
+
| --- | --- | --- |
|
|
276
|
+
| `initExtraAccountMetas` | `function initExtraAccountMetas(payer: Mut<Signer>, account: AccountMeta, mint: AccountMeta, systemProgram: SystemProgram, extraAccounts?: ExtraAccountMeta[]): void` | Create the transfer-hook validation account (an ExtraAccountMetaList) at PDA ["extra-account-metas", mint], listing the extra accounts Token-2022 passes to the hook after the standard four and this account (so the first extra account has index 5). |
|
|
277
|
+
| `updateExtraAccountMetas` | `function updateExtraAccountMetas(payer: Mut<Signer>, account: AccountMeta, mint: AccountMeta, systemProgram: SystemProgram, extraAccounts?: ExtraAccountMeta[]): void` | Rewrite this program's existing ExtraAccountMetaList for `mint` (Rust `ExtraAccountMetaList::update`), resizing it to the new list; `payer` tops it up to the rent of the new size when needed. |
|
|
278
|
+
| `ExtraAccountMeta` | `type ExtraAccountMeta` | One extra account of a transfer hook's ExtraAccountMetaList: a fixed address, or a PDA from seeds (see initExtraAccountMetas). |
|
|
279
|
+
| `ExtraAccountSeed` | `interface ExtraAccountSeed` | A seed of an extra account resolved by Token-2022 at transfer time (seedAccountKey, seedAccountData, seedInstructionData). |
|
|
280
|
+
| `seedAccountKey` | `function seedAccountKey(index: bigint): ExtraAccountSeed` | Seed::AccountKey: the key of the account at this index of the execute instruction. |
|
|
281
|
+
| `seedAccountData` | `function seedAccountData(index: bigint, offset: bigint, length: bigint): ExtraAccountSeed` | Seed::AccountData: `length` bytes at `offset` of the data of the account at `index`. |
|
|
282
|
+
| `seedInstructionData` | `function seedInstructionData(offset: bigint, length: bigint): ExtraAccountSeed` | Seed::InstructionData: `length` bytes at `offset` of the execute instruction's data. |
|
|
283
|
+
|
|
284
|
+
## Memo, Token Metadata and Stake
|
|
285
|
+
|
|
286
|
+
Explained in [Calling other programs: Associated Token, Memo, Metadata and Stake](language-cpi.md#associated-token-memo-metadata-and-stake).
|
|
287
|
+
|
|
288
|
+
| Name | Declaration | What it is |
|
|
289
|
+
| --- | --- | --- |
|
|
290
|
+
| `MemoProgram` | `interface MemoProgram` | The SPL Memo program (v2, `MemoSq4g…`). |
|
|
291
|
+
| `TokenMetadataProgram` | `interface TokenMetadataProgram` | Metaplex Token Metadata (metaqbxx…). |
|
|
292
|
+
| `MetadataCreator` | `interface MetadataCreator` | A creator in Metaplex metadata. |
|
|
293
|
+
| `metadataAddress` | `function metadataAddress(mint: Pubkey): Pubkey` | The Metaplex metadata account address of a mint. |
|
|
294
|
+
| `masterEditionAddress` | `function masterEditionAddress(mint: Pubkey): Pubkey` | The Metaplex master edition address of a mint (PDA ["metadata", program, mint, "edition"]). |
|
|
295
|
+
| `StakeProgram` | `interface StakeProgram` | The native Stake program (`Stake1111…`). |
|
|
296
|
+
|
|
297
|
+
## Metaplex Core
|
|
298
|
+
|
|
299
|
+
Explained in [Calling other programs: Metaplex Core](language-cpi.md#metaplex-core).
|
|
300
|
+
|
|
301
|
+
| Name | Declaration | What it is |
|
|
302
|
+
| --- | --- | --- |
|
|
303
|
+
| `MplCoreProgram` | `interface MplCoreProgram` | Metaplex Core (CoREEN…), address checked. |
|
|
304
|
+
| `CorePlugin` | `type CorePlugin` | A Metaplex Core plugin, written as an object literal (Core's Plugin enum, with its authority when it is added). |
|
|
305
|
+
| `CorePluginKind` | `type CorePluginKind = CorePlugin["kind"] \| "Groups"` | The name of a Metaplex Core plugin, as `removePlugin` and the plugin readers take it. |
|
|
306
|
+
| `CorePluginAuthority` | `type CorePluginAuthority = "none" \| "owner" \| "updateAuthority" \| Pubkey` | Who manages a Metaplex Core plugin: `"owner"`, `"updateAuthority"`, `"none"` (nobody: fixed), or an address. |
|
|
307
|
+
| `CoreExternalPlugin` | `type CoreExternalPlugin` | A Metaplex Core external plugin adapter, written as an object literal: data a third party writes (`AppData`), an account that approves or rejects lifecycle events (`Oracle`), or a program called on them (`LifecycleHook`); the `Linked` forms go on a collection, for each of its assets. |
|
|
308
|
+
| `CoreExternalPluginKey` | `type CoreExternalPluginKey` | Which external plugin: an AppData by its data authority, an Oracle by its base address, a LifecycleHook by its program. |
|
|
309
|
+
| `CoreLifecycleCheck` | `interface CoreLifecycleCheck` | When a Core lifecycle event reaches an external plugin, and what the plugin may do about it. |
|
|
310
|
+
| `CoreExtraAccount` | `type CoreExtraAccount` | An account Core passes to an external plugin: one it already has, or an address. |
|
|
311
|
+
| `coreAssetOwner` | `function coreAssetOwner(asset: AccountMeta \| RemainingAccount): Pubkey` | The owner of a Metaplex Core asset (owner program and account type checked). |
|
|
312
|
+
| `coreAssetCollection` | `function coreAssetCollection(asset: AccountMeta \| RemainingAccount): Option<Pubkey>` | The collection a Metaplex Core asset belongs to, if any. |
|
|
313
|
+
|
|
314
|
+
## Compressed NFTs
|
|
315
|
+
|
|
316
|
+
Explained in [Calling other programs: Compressed NFTs (Bubblegum)](language-cpi.md#compressed-nfts-bubblegum).
|
|
317
|
+
|
|
318
|
+
| Name | Declaration | What it is |
|
|
319
|
+
| --- | --- | --- |
|
|
320
|
+
| `BubblegumProgram` | `interface BubblegumProgram` | Metaplex Bubblegum (BGUMAp…), compressed NFTs on SPL Account Compression. |
|
|
321
|
+
| `CompressedLeaf` | `interface CompressedLeaf` | The leaf a transfer or burn replaces, as an indexer (DAS getAssetProof / getAsset) reports it. |
|
|
322
|
+
| `CompressedLeafRef` | `interface CompressedLeafRef` | A leaf whose data and creator hashes the instruction computes from the metadata passed with it. |
|
|
323
|
+
| `CompressedLeafV1` | `interface CompressedLeafV1` | A V1 tree's leaf. |
|
|
324
|
+
| `CompressedMetadata` | `interface CompressedMetadata` | Bubblegum V2 leaf metadata (MetadataArgsV2): non-fungible, primary sale not happened, mutable unless `isMutable: false`. |
|
|
325
|
+
| `CompressedMetadataV2` | `interface CompressedMetadataV2` | A leaf's full MetadataArgsV2, as it is now (with its creators' verified flags and its collection). |
|
|
326
|
+
| `CompressedMetadataUpdate` | `interface CompressedMetadataUpdate` | UpdateArgs: what to change (left out: unchanged). |
|
|
327
|
+
|
|
328
|
+
## Sysvars
|
|
329
|
+
|
|
330
|
+
Explained in [Sysvars, hashes, signatures and oracles: Sysvars](language-chain.md#sysvars).
|
|
331
|
+
|
|
332
|
+
| Name | Declaration | What it is |
|
|
333
|
+
| --- | --- | --- |
|
|
334
|
+
| `now` | `function now(): i64` | Current cluster unix timestamp (Clock sysvar). |
|
|
335
|
+
| `currentSlot` | `function currentSlot(): u64` | The current slot (Clock sysvar). |
|
|
336
|
+
| `currentEpoch` | `function currentEpoch(): u64` | The current epoch (Clock sysvar). |
|
|
337
|
+
| `epochStartTimestamp` | `function epochStartTimestamp(): i64` | The Unix time the current epoch started at (Clock.epoch_start_timestamp). |
|
|
338
|
+
| `slotsPerEpoch` | `function slotsPerEpoch(): u64` | The number of slots in an epoch after warmup (EpochSchedule sysvar). |
|
|
339
|
+
| `epochWarmup` | `function epochWarmup(): boolean` | Whether epochs warm up (EpochSchedule sysvar). |
|
|
340
|
+
| `firstNormalEpoch` | `function firstNormalEpoch(): u64` | The first epoch after warmup (EpochSchedule sysvar). |
|
|
341
|
+
| `firstNormalSlot` | `function firstNormalSlot(): u64` | The first slot after warmup (EpochSchedule sysvar). |
|
|
342
|
+
| `lastRestartSlot` | `function lastRestartSlot(): u64` | The LastRestartSlot sysvar: the last slot the cluster restarted at (0 if never). |
|
|
343
|
+
| `epochRewards` | `function epochRewards(): EpochRewards` | The EpochRewards sysvar through the `sol_get_epoch_rewards_sysvar` syscall, Rust's `EpochRewards::get()` (no account needed). |
|
|
344
|
+
| `EpochRewards` | `interface EpochRewards` | The EpochRewards sysvar, as `epochRewards()` reads it: read-only; keep it in a local (`const er = epochRewards()`). |
|
|
345
|
+
| `minimumBalance` | `function minimumBalance(account: AccountMeta): u64` | Rent-exempt minimum for `account`'s current data length. |
|
|
346
|
+
| `SlotHashesSysvar` | `interface SlotHashesSysvar` | The SlotHashes sysvar (`SysvarS1otHashes…`), read as an account: it is too large for the sysvar syscalls (Anchor's `Sysvar<SlotHashes>` cannot load it either). |
|
|
347
|
+
| `StakeHistorySysvar` | `interface StakeHistorySysvar` | The StakeHistory sysvar (`SysvarStakeHistory…`), read as an account: the cluster's stake per recent epoch (up to 512, newest first), as the Stake program uses it for warmup and cooldown. |
|
|
348
|
+
| `stackHeight` | `function stackHeight(): u64` | How deep in cross-program calls this program runs: 1 when the transaction calls it directly, more when another program invoked it. |
|
|
349
|
+
|
|
350
|
+
## Hashes, signatures and introspection
|
|
351
|
+
|
|
352
|
+
Explained in [Sysvars, hashes, signatures and oracles: Hashing](language-chain.md#hashing).
|
|
353
|
+
|
|
354
|
+
| Name | Declaration | What it is |
|
|
355
|
+
| --- | --- | --- |
|
|
356
|
+
| `sha256` | `function sha256(...parts: (string \| Pubkey \| Hash \| bigint \| boolean)[]): Hash` | sha256 over the parts concatenated: strings (UTF-8), Pubkeys/Hashes (32 bytes), integers (LE), booleans (1 byte). |
|
|
357
|
+
| `keccak256` | `function keccak256(...parts: (string \| Pubkey \| Hash \| bigint \| boolean)[]): Hash` | keccak256 over the parts concatenated, encoded as for sha256. |
|
|
358
|
+
| `merkleVerify` | `function merkleVerify(leaf: Hash, proof: Vec<Hash>, root: Hash): boolean` | Whether `proof` places `leaf` under `root` (keccak256, sorted pairs: the OpenZeppelin convention most airdrop tools use). |
|
|
359
|
+
| `verifyEd25519` | `function verifyEd25519(instructions: InstructionsSysvar, signer: Pubkey, message: string \| Hash \| Pubkey): boolean` | Whether this transaction contains an Ed25519 precompile instruction that verified `message` signed by `signer` (offsets inside the precompile's own data). |
|
|
360
|
+
| `verifySecp256k1` | `function verifySecp256k1(hash: Hash, recoveryId: u8, r: Hash, s: Hash, ethAddress: Hash): boolean` | Whether the secp256k1 signer of `hash`, recovered from (r, s, recoveryId), is an Ethereum address given left-padded to 32 bytes (12 zero bytes + 20 address bytes). |
|
|
361
|
+
| `ethMessageHash` | `function ethMessageHash(message: string): Hash` | The hash an Ethereum wallet signs for `personal_sign` (EIP-191): keccak256("\x19Ethereum Signed Message:\n" + length + message). |
|
|
362
|
+
| `InstructionsSysvar` | `interface InstructionsSysvar` | The Instructions sysvar (Sysvar1nstructions…): every instruction of the transaction being executed. |
|
|
363
|
+
| `TransactionInstruction` | `interface TransactionInstruction` | One instruction of the transaction, read from the Instructions sysvar. |
|
|
364
|
+
|
|
365
|
+
## Oracles and randomness
|
|
366
|
+
|
|
367
|
+
Explained in [Sysvars, hashes, signatures and oracles: Oracles](language-chain.md#oracles).
|
|
368
|
+
|
|
369
|
+
| Name | Declaration | What it is |
|
|
370
|
+
| --- | --- | --- |
|
|
371
|
+
| `PythPriceUpdate` | `interface PythPriceUpdate` | A Pyth `PriceUpdateV2` account (Pyth Solana Receiver, rec5EKMG…). |
|
|
372
|
+
| `pythPrice` | `function pythPrice(update: PythPriceUpdate, feedId: Hash, maxAgeSeconds: u64, exponent?: i32): i64` | Like Pyth's get_price_no_older_than: fully verified, `feedId` matches, published within `maxAgeSeconds` (5111 otherwise). |
|
|
373
|
+
| `SwitchboardFeed` | `interface SwitchboardFeed<Cluster>` | A Switchboard On-Demand pull feed (PullFeedAccountData). |
|
|
374
|
+
| `switchboardValue` | `function switchboardValue(feed: SwitchboardFeed<"mainnet" \| "devnet">, expectedFeed: Pubkey, maxStaleSlots: u64, decimals: u8, minSamples?: u8): i64` | The feed's current result scaled to `decimals` (from 18), if `feed` is `expectedFeed` (anyone can create feeds), it has samples and it is at most `maxStaleSlots` old. |
|
|
375
|
+
| `SwitchboardRandomness` | `interface SwitchboardRandomness<Cluster>` | A Switchboard On-Demand randomness account (RandomnessAccountData): verifiable randomness by commit and reveal. |
|
|
376
|
+
|
|
377
|
+
## Native programs
|
|
378
|
+
|
|
379
|
+
Explained in [Porting a native program (advanced)](language-native.md).
|
|
380
|
+
|
|
381
|
+
| Name | Declaration | What it is |
|
|
382
|
+
| --- | --- | --- |
|
|
383
|
+
| `instructionData` | `function instructionData(): InstructionBytes` | The instruction data as sent, discriminator included: `const data = instructionData()`, then `data.length`, `data.get(i)`, or pass it on to `invokeInstruction`. |
|
|
384
|
+
| `InstructionBytes` | `interface InstructionBytes` | The instruction data, read in place: its bytes, and little-endian values at a byte offset. |
|
|
385
|
+
| `loadRaw` | `function loadRaw<T>(account: RemainingAccount \| AccountInfo): Account<T>` | A native (non-Anchor) program's own account as a fixed-layout struct, as a `#[repr(C)]` type's `load_checked` / `load_mut_checked` reads it: owned by this program (3007) and at least as large as the struct (3003). |
|
|
386
|
+
| `loadRawMut` | `function loadRawMut<T>(account: RemainingAccount \| AccountInfo): Mut<T>` | `loadRaw` for writing: also writable and loaded mutably once per instruction (2040). |
|
|
387
|
+
| `loadBorsh` | `function loadBorsh<T>(account: RemainingAccount \| AccountInfo): T` | A native program's Borsh account, as Rust's `try_from_slice_unchecked::<T>(&data)` reads it: the data from byte 0 decoded into a local `T` (a copy; write it back with `storeBorsh`). |
|
|
388
|
+
| `storeBorsh` | `function storeBorsh<T>(account: RemainingAccount \| Mut<AccountInfo>, value: T): void` | Write `value` into the account's data from byte 0 as Borsh, as Rust's `value.serialize(&mut *data)` does: only the encoded bytes are written (an Option that became None leaves the old bytes after it as they were); an account too small for the encoding fails with `ProgramError.BorshIoError`. |
|
|
389
|
+
| `BigVec` | `interface BigVec<T>` | A native program's zero-copy list over the rest of an account (SPL's `big_vec::BigVec`, the stake pool's validator list): a u32 length, then the elements back to back, in an account allocated up front. |
|
|
390
|
+
| `BigVecSlice` | `interface BigVecSlice<T>` | Some elements of a BigVec, in place: `bigVec.slice(start, end)`. |
|
|
391
|
+
| `loadRawAt` | `function loadRawAt<T>(account: RemainingAccount \| AccountInfo, offset: u64): Account<T>` | `loadRaw` / `loadRawMut` at a byte offset known only at run time (a native account whose parts start where its header says: Phoenix's market at byte 576). |
|
|
392
|
+
| `loadRawMutAt` | `function loadRawMutAt<T>(account: RemainingAccount \| AccountInfo, offset: u64): Mut<T>` | `loadRawAt` for writing: writable and claimed as `loadRawMut` is. |
|
|
393
|
+
| `rawArrayAt` | `function rawArrayAt<T>(account: RemainingAccount \| AccountInfo, offset: u64, capacity: u64): ReadonlyRawArray<T>` | A read-only view of `capacity` elements of `T` at `offset` in an account (see RawArray); `rawArrayMutAt` writes. |
|
|
394
|
+
| `rawArrayMutAt` | `function rawArrayMutAt<T>(account: RemainingAccount \| AccountInfo, offset: u64, capacity: u64): RawArray<T>` | `rawArrayAt` for writing: elements set in place (see RawArray). |
|
|
395
|
+
| `RawArray` | `interface RawArray<T>` | `capacity` elements of a fixed-size type packed in place from a run-time byte offset, the count known only at run time (a slab sized by its header). |
|
|
396
|
+
| `ReadonlyRawArray` | `interface ReadonlyRawArray<T>` | A RawArray of a read-only view (`rawArrayAt`): elements are read, not written. |
|
|
397
|
+
| `rbTreeAt` | `function rbTreeAt<K, V>(account: RemainingAccount \| AccountInfo, offset: u64, capacity: u64, compare?: (a: K, b: K) => bigint): ReadonlyRedBlackTree<K, V>` | lib-sokoban 0.3's RedBlackTree<K, V, capacity> at a run-time byte offset (see RedBlackTree): owned by this program (3007), its 32 + capacity × (16 + size(K) + size(V)) bytes within the data (ProgramError::AccountDataTooSmall), `rbTreeMutAt` writable and claimed as `loadRawMut` is. |
|
|
398
|
+
| `rbTreeMutAt` | `function rbTreeMutAt<K, V>(account: RemainingAccount \| AccountInfo, offset: u64, capacity: u64, compare?: (a: K, b: K) => bigint): RedBlackTree<K, V>` | `rbTreeAt` for writing: insert, remove and initialize with lib-sokoban's own writes (see RedBlackTree). |
|
|
399
|
+
| `RedBlackTree` | `interface RedBlackTree<K, V>` | lib-sokoban 0.3's `RedBlackTree<K, V, N>` in account data, byte for byte (Phoenix's order books and trader seats): at the offset, root u32, padding, the allocator (size u64, bump index u32, free list head u32), then `capacity` nodes of 16 register bytes + K + V, 1-based. |
|
|
400
|
+
| `ReadonlyRedBlackTree` | `interface ReadonlyRedBlackTree<K, V>` | A RedBlackTree of a read-only view (`rbTreeAt`): read, never changed. |
|
|
401
|
+
| `RbEntry` | `interface RbEntry<K, V>` | A node of a RedBlackTree: its key (read-only), its value (in place) and its index in the tree's node array (1-based). |
|
|
402
|
+
| `closeRaw` | `function closeRaw(account: RemainingAccount \| Mut<AccountInfo>, receiver: RemainingAccount \| Mut<AccountInfo>): void` | Close an account of this program as a native program does it by hand (Phoenix's Tombstone), in this order: `receiver.lamports += account.lamports`, `account.lamports = 0`, the owner set to the System Program, the data length set to 0 (`realloc(0, false)`: the bytes are not zeroed, the runtime drops them with the length). |
|
|
403
|
+
| `assignOwner` | `function assignOwner(account: RemainingAccount \| Mut<AccountInfo>, owner: Pubkey): void` | Set an account's owner in place (Rust's `AccountInfo::assign`). |
|
|
404
|
+
| `setReturnData` | `function setReturnData(bytes: IndexedList<u8>): void` | Set this instruction's return data to `bytes` as they are (Rust's `set_return_data(&bytes)`): a list of u8 such as a local `FixedVec<u8, N>`, a Vec or FixedVec in account data, or the instruction data or a slice of it. |
|
|
405
|
+
| `panic` | `function panic(message?: string \| null, location?: string): never` | Stop the program as a Rust `panic!` / `unwrap()` on `None` / `unreachable!()` does: the message is logged and the instruction fails with ProgramFailedToComplete (no error code). |
|
|
406
|
+
| `panicsAt` | `function panicsAt<T>(location: string, value: T): T` | `value`, with its checked arithmetic panicking as Rust's overflow checks do at `location` ("file:line:column", where the original's expression is): `panicsAt("src/quantities.rs:233:1", a + b)` logs "attempt to add with overflow" there (also "attempt to subtract / multiply with overflow", "attempt to divide by zero", "attempt to calculate the remainder with a divisor of zero", "attempt to negate with overflow", "attempt to divide with overflow", "attempt to shift left / right with overflow" for a shift amount past the width), as `panic` logs (see `PANIC_STYLE`), instead of failing with 5100 / 5101. |
|
|
407
|
+
| `abort` | `function abort(): never` | Stop the program as Rust's `abort` does on SBF (the allocator's out-of-memory error, `std::process::abort`): the runtime's `abort` syscall, which fails the instruction with ProgramFailedToComplete and logs "SBF program panicked" (no location, nothing else). |
|
|
408
|
+
| `logBase64` | `function logBase64(prefix: string, value: object): void` | Log `prefix` followed by the base64 (standard, padded) of a struct value's bytes, as a native program's `msg!("ray_log: {}", base64(bincode(log)))` does. |
|
|
409
|
+
| `logComputeUnits` | `function logComputeUnits(): void` | Log the compute units left (Rust's `sol_log_compute_units()`): the runtime writes "Program consumption: <N> units remaining", as the original's line, at the same place. |
|
|
410
|
+
|
|
411
|
+
**Next:** [Glossary](glossary.md): the Solana and TypeSOL terms the guide uses.
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Sysvars, hashes, signatures and oracles
|
|
2
|
+
|
|
3
|
+
What a program can read from the chain besides its accounts: the clock ([slot and epoch](glossary.md#slot-and-epoch))
|
|
4
|
+
and other sysvars, hashes and signature checks, the transaction's other instructions, price oracles and randomness.
|
|
5
|
+
Part of the [language guide](language.md).
|
|
6
|
+
|
|
7
|
+
## Sysvars
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { type Mut, type i64, type u64, currentEpoch, currentSlot, minimumBalance, now, rentExempt } from "typesol";
|
|
11
|
+
|
|
12
|
+
export interface Stamp {
|
|
13
|
+
at: i64;
|
|
14
|
+
slot: u64;
|
|
15
|
+
epoch: u64;
|
|
16
|
+
rent: u64;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function stamp(s: Mut<Stamp>): void {
|
|
20
|
+
s.at = now();
|
|
21
|
+
s.slot = currentSlot();
|
|
22
|
+
s.epoch = currentEpoch();
|
|
23
|
+
s.rent = rentExempt(100n) + minimumBalance(s);
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
| Function or parameter | Reads |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `now()`, `currentSlot()`, `currentEpoch()`, `epochStartTimestamp()` | the Clock sysvar (`now()` is the unix timestamp) |
|
|
30
|
+
| `minimumBalance(account)`, `rentExempt(space)` | Rent: the rent-exempt minimum for an account, or for `space` bytes |
|
|
31
|
+
| `slotsPerEpoch()`, `epochWarmup()`, `firstNormalEpoch()`, `firstNormalSlot()` | EpochSchedule |
|
|
32
|
+
| `lastRestartSlot()` | LastRestartSlot |
|
|
33
|
+
| `epochRewards()` | EpochRewards, through its [syscall](glossary.md#syscall) (Rust's `EpochRewards::get()`, no account) |
|
|
34
|
+
| `slotHashes: SlotHashesSysvar` | SlotHashes, as an account (too large for the sysvar syscalls) |
|
|
35
|
+
| `history: StakeHistorySysvar` | StakeHistory, as an account |
|
|
36
|
+
|
|
37
|
+
- The sysvar functions use the runtime's syscalls; a sysvar the runtime cannot give fails with 5103.
|
|
38
|
+
- `epochRewards()` is a read-only copy with `distributionStartingBlockHeight`, `numPartitions`, `parentBlockhash`
|
|
39
|
+
(`Hash`), `totalPoints` (`u128`), `totalRewards`, `distributedRewards` and `active`. Bind it, `const er =
|
|
40
|
+
epochRewards()`, or read one field inline, `epochRewards().active`; it is not a helper parameter.
|
|
41
|
+
- `slotHashes: SlotHashesSysvar`: `count`, `latestSlot`, `latestHash`. They are public: slot hashes are not a source of
|
|
42
|
+
secret randomness.
|
|
43
|
+
- `history: StakeHistorySysvar`: `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)`, `activating(epoch)`,
|
|
44
|
+
`deactivating(epoch)` (0 for an epoch not listed). A native port reads it from a remaining account with
|
|
45
|
+
`sysvarAt<StakeHistorySysvar>(account)` ([remaining accounts in
|
|
46
|
+
CPIs](language-cpi.md#programs-and-sysvars-passed-as-remaining-accounts)).
|
|
47
|
+
- `stackHeight()` is 1 when the transaction calls the program directly and more under a CPI:
|
|
48
|
+
`require(stackHeight() === 1n, …)` refuses CPI callers.
|
|
49
|
+
|
|
50
|
+
## Hashing
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { type Hash, type Mut, type Pubkey, type u64, keccak256, sha256 } from "typesol";
|
|
54
|
+
|
|
55
|
+
export interface Commit {
|
|
56
|
+
digest: Hash;
|
|
57
|
+
other: Hash;
|
|
58
|
+
order: u64;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function commit(c: Mut<Commit>, owner: Pubkey, text: string, n: u64): void {
|
|
62
|
+
c.digest = sha256(text, owner, n);
|
|
63
|
+
c.other = keccak256(c.digest, true);
|
|
64
|
+
c.order = c.digest.compare(c.other) < 0n ? 0n : 1n;
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- `sha256(...parts)` and `keccak256(...parts)` hash the concatenation of 1 to 16 parts (strings as UTF-8, Pubkeys and
|
|
69
|
+
Hashes as 32 bytes, integers little-endian at their width, a bare literal as a u64, booleans as one byte) and return
|
|
70
|
+
a `Hash`.
|
|
71
|
+
- A `Hash` is a PDA seed too (its 32 bytes), as Marginfi seeds an order with the hash of its bank keys.
|
|
72
|
+
- `a.compare(b)` orders Pubkeys and Hashes as Rust orders their 32 bytes (-1, 0 or 1).
|
|
73
|
+
- `merkleVerify(leaf, proof, root)`, with `proof` a `Vec<Hash>` instruction argument, returns whether the proof
|
|
74
|
+
places `leaf` under `root`, with sorted-pair keccak (OpenZeppelin's convention). Inner nodes and leaves are hashed
|
|
75
|
+
alike, so hash leaves as OpenZeppelin does, `keccak256(keccak256(data))`, and never take the leaf itself from the
|
|
76
|
+
arguments: an inner node would pass as a leaf.
|
|
77
|
+
|
|
78
|
+
## Signatures
|
|
79
|
+
|
|
80
|
+
`merkleVerify`, `verifyEd25519` and `verifySecp256k1` return whether the proof or signature holds; they do not fail by
|
|
81
|
+
themselves. Unlike a check such as `HasOne`, nothing happens when the answer is false: wrap them in
|
|
82
|
+
`require(…, error)`. The compiler refuses a call used as a statement, one that is the
|
|
83
|
+
condition of an `if` with an empty body and no `else` or an empty one, and one whose result is kept in a local the function never
|
|
84
|
+
reads. It does not catch a helper that returns the result and is itself called as a statement.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { type Account, type Hash, type Init, type InstructionsSysvar, type Mut, type Pubkey, type Signer, type SystemProgram, type u8, type u64, type Vec, keccak256, merkleVerify, require, verifyEd25519, verifySecp256k1 } from "typesol";
|
|
88
|
+
|
|
89
|
+
export interface Drop {
|
|
90
|
+
root: Hash;
|
|
91
|
+
issuer: Pubkey;
|
|
92
|
+
ethIssuer: Hash;
|
|
93
|
+
claimed: u64;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface Receipt {
|
|
97
|
+
amount: u64;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function claim(claimer: Mut<Signer>, drop: Mut<Drop>, receipt: Init<Receipt>, systemProgram: SystemProgram, amount: u64, proof: Vec<Hash>): void {
|
|
101
|
+
require(merkleVerify(keccak256(keccak256(claimer.key, amount)), proof, drop.root), "not in the list");
|
|
102
|
+
receipt.create(claimer, ["claimed", drop.key, claimer.key]);
|
|
103
|
+
receipt.amount = amount;
|
|
104
|
+
drop.claimed += amount;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function approved(drop: Account<Drop>, ixs: InstructionsSysvar, who: Pubkey, r: Hash, s: Hash, v: u8): void {
|
|
108
|
+
require(verifyEd25519(ixs, drop.issuer, `allow:${who}`), "not signed by the issuer");
|
|
109
|
+
require(verifySecp256k1(keccak256(who), v, r, s, drop.ethIssuer), "not signed by the Ethereum issuer");
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- The receipt, seeded with the drop and the claimer, makes a second claim fail: its address is already in use.
|
|
114
|
+
- `verifyEd25519(instructionsSysvar, signer, message)` returns whether the transaction holds an Ed25519
|
|
115
|
+
[precompile](glossary.md#precompile) instruction verifying `message` signed by `signer`. The client adds that
|
|
116
|
+
instruction; the runtime rejects the transaction if its signature is wrong.
|
|
117
|
+
- `verifySecp256k1(hash, recoveryId, r, s, ethAddress)` recovers the secp256k1 signer of `hash` and returns whether it
|
|
118
|
+
is `ethAddress` (an Ethereum address left-padded to 32 bytes), where `hash` is `keccak256(...message)` or
|
|
119
|
+
`ethMessageHash(message)`. The hash must be computed in the program: a passed-in hash could be forged.
|
|
120
|
+
- In `approved` a signature proves who signed the message, not for which drop or when: a real message binds the
|
|
121
|
+
program, the account and a nonce or expiry.
|
|
122
|
+
|
|
123
|
+
## Instruction introspection
|
|
124
|
+
|
|
125
|
+
`ixs: InstructionsSysvar` (its address checked, 3008) reads the transaction's other instructions:
|
|
126
|
+
|
|
127
|
+
- `ixs.length`, `ixs.currentIndex()` (the top-level instruction being executed), and `ixs.get(i)`, a
|
|
128
|
+
`TransactionInstruction`: `programId`, `accountsLength`, `dataLength`, `accountKey(j)` / `accountIsSigner(j)` /
|
|
129
|
+
`accountIsWritable(j)`, `readU8` / `readU16` / `readU32` / `readU64` / `readPubkey(offset)` (little-endian), and
|
|
130
|
+
`is(program, "name")` (that program's instruction by its default Anchor discriminator, sha256("global:<name>"); an
|
|
131
|
+
instruction with its own `@discriminator` is matched with `programId` and `readU64(0)` instead).
|
|
132
|
+
- Every read is bounds-checked (5104).
|
|
133
|
+
- It is the transaction author's data: require things of the transaction with it (a repay instruction after a flash
|
|
134
|
+
loan), never treat it as proof.
|
|
135
|
+
|
|
136
|
+
## Oracles
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { type Hash, type i64, type Pubkey, type PythPriceUpdate, type SwitchboardFeed, type u64, pythPrice, switchboardValue } from "typesol";
|
|
140
|
+
|
|
141
|
+
export function pythUsd(update: PythPriceUpdate, feedId: Hash, maxAge: u64): i64 {
|
|
142
|
+
return pythPrice(update, feedId, maxAge, -8n);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function feedValue(feed: SwitchboardFeed, expected: Pubkey, maxStaleSlots: u64): i64 {
|
|
146
|
+
return switchboardValue(feed, expected, maxStaleSlots, 6n);
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **Pyth**: `pythPrice(update: PythPriceUpdate, feedId, maxAgeSeconds, exponent?)` returns a price that is fully
|
|
151
|
+
verified, of that feed and fresh (5111 otherwise). With `exponent`, a feed at another scale is refused. The raw fields
|
|
152
|
+
`update.price`, `conf`, `exponent`, `publishTime` are unchecked (any feed, partially verified or stale): check
|
|
153
|
+
`feedId`, `fullyVerified` and the age yourself, or use `pythPrice`.
|
|
154
|
+
- **Switchboard**: `switchboardValue(feed: SwitchboardFeed, expectedFeed, maxStaleSlots, decimals, minSamples?)`. The
|
|
155
|
+
feed must be the expected one (anyone can create feeds); `minSamples`, default 1, is the fewest oracle samples
|
|
156
|
+
accepted; staleness counts slots from the feed's `result.slot`; the 18-decimal result is scaled to `decimals`,
|
|
157
|
+
rounding toward zero. It reads the mainnet program's feeds unless the parameter is `SwitchboardFeed<"devnet">`.
|
|
158
|
+
Failures are 5111.
|
|
159
|
+
- Neither reader checks the price's sign or zero, the confidence (Pyth's `conf`, Switchboard's spread of samples), or a
|
|
160
|
+
publish time or result slot in the future (it counts as fresh): check what your program relies on.
|
|
161
|
+
|
|
162
|
+
## Randomness
|
|
163
|
+
|
|
164
|
+
A chain has no secret randomness of its own: slot hashes and timestamps are known to, or chosen by, the block producer.
|
|
165
|
+
`SwitchboardRandomness` (Switchboard On-Demand's RandomnessAccountData; owner, discriminator and size checked) gives
|
|
166
|
+
verifiable randomness by commit and reveal:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { type Init, type Mut, type Pubkey, type Signer, type SwitchboardRandomness, type SystemProgram, type u64, currentSlot, require } from "typesol";
|
|
170
|
+
|
|
171
|
+
export interface Bet {
|
|
172
|
+
randomness: Pubkey;
|
|
173
|
+
seedSlot: u64;
|
|
174
|
+
guess: u64;
|
|
175
|
+
won: boolean;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function commit(player: Mut<Signer>, bet: Init<Bet>, randomness: SwitchboardRandomness, systemProgram: SystemProgram, guess: u64): void {
|
|
179
|
+
bet.create(player, ["bet", player.key]);
|
|
180
|
+
require(randomness.seedSlot === currentSlot() - 1n, "randomness already revealed or stale");
|
|
181
|
+
bet.randomness = randomness.key;
|
|
182
|
+
bet.seedSlot = randomness.seedSlot;
|
|
183
|
+
bet.guess = guess % 2n;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function settle(player: Signer, bet: Mut<Bet>, randomness: SwitchboardRandomness): void {
|
|
187
|
+
require(bet.randomness === randomness.key && randomness.seedSlot === bet.seedSlot, "not the committed randomness");
|
|
188
|
+
bet.won = randomness.valueU64() % 2n === bet.guess;
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Commit while `randomness.seedSlot === currentSlot() - 1n` and store `randomness.key` and `randomness.seedSlot`.
|
|
193
|
+
Settle in a later transaction after checking both, with `randomness.value()` (32 bytes) or `randomness.valueU64()`,
|
|
194
|
+
which fail (5111) unless the value was revealed in this slot. Anyone may settle a bet (`player` is any signer): the
|
|
195
|
+
result depends only on the committed randomness and the stored guess, so who sends the transaction changes nothing.
|
|
196
|
+
The example is [`test/fixtures/coinflip.ts`](https://github.com/typesol-lang/typesol/blob/main/test/fixtures/coinflip.ts), shortened.
|
|
197
|
+
|
|
198
|
+
**Next:** [Porting a native program](language-native.md) (advanced), or [test your program](test-your-program.md).
|