@typesol/cli 0.45.0 → 0.46.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 +227 -0
- package/README.md +64 -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/node-version.d.ts +4 -0
- package/dist/node-version.js +12 -0
- 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 -3
- package/docker/deps/0.46.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 +52 -15
- package/docs/troubleshooting.md +222 -100
- package/lib/typesol.d.ts +67 -22
- package/llms-full.txt +4915 -634
- package/llms.txt +12 -1
- package/package.json +2 -2
- package/releases/0.45.0.json +732 -0
- package/ts-plugin/index.js +16 -5
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
# Calling other programs
|
|
2
|
+
|
|
3
|
+
A program calls another one with a cross-program invocation (CPI). TypeSOL has typed methods for the System, SPL
|
|
4
|
+
Token, Token-2022, Associated Token, Memo, Stake and Metaplex programs, typed helpers generated from any Anchor IDL,
|
|
5
|
+
and `invoke` / `invokeInstruction` for everything else. Part of the [language guide](language.md). Signing as a PDA is
|
|
6
|
+
on the [PDAs](language-pdas.md#signing-as-a-pda) page.
|
|
7
|
+
|
|
8
|
+
## The System Program
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { type Mut, type Signer, type SystemAccount, type SystemProgram, type u64 } from "typesol";
|
|
12
|
+
|
|
13
|
+
export function tip(from: Mut<Signer>, to: Mut<SystemAccount>, systemProgram: SystemProgram, lamports: u64): void {
|
|
14
|
+
systemProgram.transfer(from, to, lamports);
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- `systemProgram.transfer(from, to, lamports, signerSeeds?)`: `from` is a `Mut<Signer>`, or a system-owned PDA of this
|
|
19
|
+
program (a SOL vault) with its seeds.
|
|
20
|
+
- `systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?)`: the new account signs, a keypair
|
|
21
|
+
`Mut<Signer>` or this program's PDA.
|
|
22
|
+
- `systemProgram.createPda(payer, account, space, owner, seeds)` ([PDAs](language-pdas.md#createpda)).
|
|
23
|
+
- `systemProgram.allocate(account, space, seeds?)` and `systemProgram.assign(account, owner, seeds?)`, for an address
|
|
24
|
+
someone pre-funded ([accounts created by hand](language-accounts.md#accounts-created-by-hand)).
|
|
25
|
+
- `rentExempt(space)` is the rent-exempt minimum for `space` bytes; `MINT_SIZE` and `TOKEN_ACCOUNT_SIZE` are SPL
|
|
26
|
+
Token's sizes.
|
|
27
|
+
|
|
28
|
+
## Tokens
|
|
29
|
+
|
|
30
|
+
A mint defines a token: its supply, its decimals and the mint authority that may create more. A token account holds an
|
|
31
|
+
amount of one mint for its owner, the authority that may move it; a wallet's usual one is its associated token
|
|
32
|
+
account. For a complete program, see [`examples/escrow.ts`](https://github.com/typesol-lang/typesol/blob/main/examples/escrow.ts), which `typesol init my-app
|
|
33
|
+
--template escrow` scaffolds with its tests.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { type Mint, type Mut, type Seeds, type Signer, type TokenAccount, type TokenInterface, type u64 } from "typesol";
|
|
37
|
+
|
|
38
|
+
export function pay(owner: Signer, from: Mut<TokenAccount>, mint: Mint, to: Mut<TokenAccount>, tokenProgram: TokenInterface, amount: u64): void {
|
|
39
|
+
tokenProgram.transferChecked(from, mint, to, owner, amount);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function payOut(owner: Signer, vault: Seeds<Mut<TokenAccount>, ["vault", "@owner", "@mint"]>, mint: Mint, to: Mut<TokenAccount>, tokenProgram: TokenInterface, amount: u64): void {
|
|
43
|
+
tokenProgram.transferChecked(vault, mint, to, vault, amount, ["vault", owner.key, mint.key, vault.pdaBump]);
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The token programs (`TokenProgram`, `Token2022Program`, `TokenInterface` for either) have one method per instruction.
|
|
48
|
+
Pass signer seeds (with the bump) as the last argument when the authority is a PDA.
|
|
49
|
+
|
|
50
|
+
- In `pay` the token program checks that `owner` signed and owns `from`. In `payOut` the vault is its own authority,
|
|
51
|
+
so the program signs for it: the `Seeds` constraint puts the signing `owner` in the vault's address, and anyone else
|
|
52
|
+
names another account (2006). Without such a check, anyone could empty the vault.
|
|
53
|
+
|
|
54
|
+
| Methods | Notes |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `transfer`, `transferChecked(from, mint, to, authority, amount)` | Token-2022 mints with fees or hooks require `transferChecked` |
|
|
57
|
+
| `mintTo`, `mintToChecked(mint, to, authority, amount)` | the mint may be one this instruction just created |
|
|
58
|
+
| `burn`, `burnChecked(from, mint, authority, amount)` | |
|
|
59
|
+
| `approve(source, delegate, owner, amount)`, `approveChecked(source, mint, delegate, owner, amount)`, `revoke` | the checked forms take the decimals from the mint |
|
|
60
|
+
| `closeAccount` | a token account, or a Token-2022 mint with a close authority |
|
|
61
|
+
| `setAuthority(target, current, AuthorityType.MintTokens, next \| null)` | |
|
|
62
|
+
| `freezeAccount` / `thawAccount(account, mint, freezeAuthority)`, `syncNative(account)` | |
|
|
63
|
+
| `initializeMint2(mint, decimals, mintAuthority, freezeAuthority \| null)`, `initializeAccount3(account, mint, owner)` | after `createAccount` |
|
|
64
|
+
|
|
65
|
+
Token-2022 only:
|
|
66
|
+
|
|
67
|
+
- **Extension initializers**, called between `createAccount` and `initializeMint2` / `initializeAccount3`:
|
|
68
|
+
- `initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)`
|
|
69
|
+
- `initializeMintCloseAuthority(mint, authority | null)`
|
|
70
|
+
- `initializeNonTransferableMint(mint)`
|
|
71
|
+
- `initializePermanentDelegate(mint, delegate)`
|
|
72
|
+
- `initializeDefaultAccountState(mint, frozen)`
|
|
73
|
+
- `initializeMetadataPointer`, `initializeGroupPointer`, `initializeGroupMemberPointer`,
|
|
74
|
+
`initializeTransferHook(mint, authority | null, address | null)`
|
|
75
|
+
- `initializeInterestBearingMint(mint, rateAuthority | null, rate)`
|
|
76
|
+
- `initializeImmutableOwner(account)`
|
|
77
|
+
- **The metadata extension**: `initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri)`.
|
|
78
|
+
- **Extension instructions**:
|
|
79
|
+
- `updateDefaultAccountState(mint, freezeAuthority, frozen)`
|
|
80
|
+
- `updateTransferHook(mint, authority, programId | null)`
|
|
81
|
+
- `enableRequiredMemoTransfers` / `disableRequiredMemoTransfers(account, owner)`
|
|
82
|
+
- `updateInterestRate(mint, rateAuthority, rate)`
|
|
83
|
+
- `transferCheckedWithFee(from, mint, to, authority, amount, fee)`
|
|
84
|
+
- `harvestWithheldTokensToMint(mint, remainingAccounts())`
|
|
85
|
+
- `withdrawWithheldTokensFromMint(mint, destination, authority)`
|
|
86
|
+
- `setTransferFee(mint, authority, basisPoints, maximumFee)`
|
|
87
|
+
- **The Token Metadata interface**:
|
|
88
|
+
- `updateMetadataField(mint, updateAuthority, field, value)`: "name", "symbol", "uri" or any other key
|
|
89
|
+
- `removeMetadataKey(mint, updateAuthority, key, idempotent)`
|
|
90
|
+
- `updateMetadataAuthority(mint, updateAuthority, next | null)`
|
|
91
|
+
- `emitMetadata(mint)`
|
|
92
|
+
- **The Token Group interface**, on a collection mint with a GroupPointer to itself (fund the rent for the group, which
|
|
93
|
+
Token-2022 adds to the account):
|
|
94
|
+
- `initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize)`
|
|
95
|
+
- `initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority)`
|
|
96
|
+
- `updateGroupMaxSize(group, authority, maxSize)`
|
|
97
|
+
- `updateGroupAuthority(group, authority, next | null)`
|
|
98
|
+
|
|
99
|
+
Each takes optional signer seeds.
|
|
100
|
+
|
|
101
|
+
### Token accounts and mints as parameters
|
|
102
|
+
|
|
103
|
+
| Parameter | Checked before the body |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| `TokenAccount` / `Mut<TokenAccount>` | an initialized token account of SPL Token or Token-2022 (extensions allowed, multisig accounts refused): 3012 for an empty system account (never created, or closed), 3007 for an account of another program, 3003 for a token program's account that is not an initialized token account (or mint) of its length. Fields: `mint`, `owner`, `amount`, `delegate`, `delegatedAmount`, `isFrozen`, `isNative`, `closeAuthority`, `tokenProgram` |
|
|
106
|
+
| `Mint` / `Mut<Mint>` | an initialized mint of SPL Token or Token-2022: the same codes as a token account. Fields: `decimals`, `supply`, `mintAuthority`, `freezeAuthority`, `tokenProgram` |
|
|
107
|
+
| `HasOne<TokenAccount, "mint" \| "owner">`, `HasOne<Mint, "mintAuthority" \| "freezeAuthority">` | against the parameter with that name (2014 / 2015 / 2016 / 2017) |
|
|
108
|
+
| `TokenOf<TokenAccount, "mintParam", "authorityParam", "tokenProgramParam">` | Anchor's `token::mint = …`, `token::authority = …`, `token::token_program = …`: the token account's mint (2014), owner (2015), and owner program (2021). `never` leaves one out |
|
|
109
|
+
| `MintOf<Mint, "authorityParam", "freezeParam", "tokenProgramParam">` | Anchor's `mint::authority = …` etc.: mint authority (2016), freeze authority (2017), owner program (2022) |
|
|
110
|
+
| `Ata<TokenAccount, "owner", "mint">` | the associated token account of those parameters (2009; the ATA's `pda` in the IDL). The owner may be a `Pubkey` field of a struct account parameter, `"@config.wallet"` (Anchor's `associated_token::authority = config.load()?.wallet`; the IDL names the account, as Anchor's does) |
|
|
111
|
+
|
|
112
|
+
### Creating mints and token accounts
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { type AccountInfo, type Ata, type Init, type InitIfNeeded, type Mint, type Mut, type Signer, type SystemProgram, type TokenAccount, type TokenInterface, type AssociatedTokenProgram, type u8 } from "typesol";
|
|
116
|
+
|
|
117
|
+
export function makeMint(payer: Mut<Signer>, mint: Init<Mint>, authority: AccountInfo, tokenProgram: TokenInterface, systemProgram: SystemProgram, decimals: u8): u8 {
|
|
118
|
+
const bump = mint.create(payer, ["mint", payer.key], decimals, authority.key, null);
|
|
119
|
+
return bump;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function makeVault(payer: Mut<Signer>, mint: Mint, vault: Init<TokenAccount>, tokenProgram: TokenInterface, systemProgram: SystemProgram): void {
|
|
123
|
+
vault.create(payer, ["vault", payer.key, mint.key], mint, vault.key);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function openWallet(
|
|
127
|
+
payer: Mut<Signer>,
|
|
128
|
+
owner: AccountInfo,
|
|
129
|
+
mint: Mint,
|
|
130
|
+
wallet: Ata<InitIfNeeded<TokenAccount>, "owner", "mint">,
|
|
131
|
+
tokenProgram: TokenInterface,
|
|
132
|
+
associatedTokenProgram: AssociatedTokenProgram,
|
|
133
|
+
systemProgram: SystemProgram,
|
|
134
|
+
): boolean {
|
|
135
|
+
const created = wallet.createIfNeeded(payer);
|
|
136
|
+
return created;
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- **`Init<Mint>`, `InitIfNeeded<Mint>`** (Anchor's `init` / `init_if_needed` with `mint::decimals`, `mint::authority`,
|
|
141
|
+
`mint::freeze_authority`): `const bump = mint.create(payer, ["mint", payer.key], 6n, authority, freezeAuthority |
|
|
142
|
+
null)` creates the mint at that PDA of this program, or with `null` seeds as a new keypair account that signs (3010
|
|
143
|
+
if it did not). It uses the instruction's token program (its only token program parameter, or one passed as the last
|
|
144
|
+
argument of `create` / `createIfNeeded`) and needs `SystemProgram`. `createIfNeeded(…)` returns whether it created
|
|
145
|
+
the mint; an existing one must be that PDA and have those decimals and authorities (2018 / 2016 / 2017).
|
|
146
|
+
- **Token-2022 extensions** (Anchor's `extensions::…`) go after the freeze authority: `mint.create(payer, null, 6n,
|
|
147
|
+
authority, null, { metadataPointer: { authority, metadataAddress: mint.key }, transferHook: { authority, programId },
|
|
148
|
+
closeAuthority, permanentDelegate, nonTransferable: true, defaultAccountState: true, interestBearing: { rateAuthority,
|
|
149
|
+
rate }, transferFee: { configAuthority, withdrawAuthority, basisPoints, maximumFee }, groupPointer,
|
|
150
|
+
groupMemberPointer })`. The mint is sized for them as Token-2022 does (extensions adding up to a Multisig's 355 bytes
|
|
151
|
+
give a 357-byte mint), and each is initialized before InitializeMint2. A `null` authority is sent as Token-2022's
|
|
152
|
+
empty COption. Extensions under SPL Token are refused (`mint extensions are Token-2022's`).
|
|
153
|
+
- With `createIfNeeded`, an existing mint must carry groupPointer / groupMemberPointer / metadataPointer /
|
|
154
|
+
closeAuthority / permanentDelegate / transferHook with those keys (Anchor's 2024–2039). Extensions not listed are
|
|
155
|
+
not looked at, so an existing mint may carry others (a permanent delegate, say). Extensions that cannot be checked on
|
|
156
|
+
an existing mint (`nonTransferable`, …) are refused on `createIfNeeded`.
|
|
157
|
+
- **`Init<TokenAccount>`, `InitIfNeeded<TokenAccount>`** without `Ata<…>` (Anchor's `token::mint` / `token::authority`):
|
|
158
|
+
`vault.create(payer, ["vault", payer.key, mint.key], mint, authority)` (the authority may be `vault.key` itself)
|
|
159
|
+
creates a token account at that PDA (or a keypair account with `null`), sized for the mint's extensions under
|
|
160
|
+
Token-2022. `makeVault` above makes the vault [`payOut`](#tokens) pays from: the same seeds, with the payer's key
|
|
161
|
+
as the `owner` seed; the token account's owner (its authority) is the vault itself.
|
|
162
|
+
`createIfNeeded` checks that an existing one has that mint and owner (2014 / 2015), not its delegate or close
|
|
163
|
+
authority (as Anchor).
|
|
164
|
+
- **`Ata<Init<TokenAccount>, "owner", "mint">`, `Ata<InitIfNeeded<TokenAccount>, "owner", "mint">`** (Anchor's `init` /
|
|
165
|
+
`init_if_needed` with `associated_token::…`): `acct.create(payer)` creates the ATA (fails if it exists);
|
|
166
|
+
`const created = acct.createIfNeeded(payer)` creates it only when missing, otherwise checks it is that ATA (2009).
|
|
167
|
+
Then it is a `TokenAccount` of that mint and owner (2014 / 2015). Needs `AssociatedTokenProgram`, `SystemProgram`
|
|
168
|
+
and a token program parameter; call it at the top level before using the account.
|
|
169
|
+
|
|
170
|
+
### Token-2022 extension reads
|
|
171
|
+
|
|
172
|
+
| Function | Reads |
|
|
173
|
+
| --- | --- |
|
|
174
|
+
| `transferFee(mint, amount)` | the current epoch's TransferFeeConfig fee for `amount` (ceiling and cap, as spl-token-2022) |
|
|
175
|
+
| `transferFeeInverse(mint, amountReceived)` | the fee when the recipient is to get that much (spl-token-2022's `calculate_inverse_epoch_fee`) |
|
|
176
|
+
| `transferFeeBasisPoints(mint)`, `transferFeeMaximum(mint)` | this epoch's; 0 without the extension |
|
|
177
|
+
| `extensionsWithin(account, [1n, 18n, …])` | whether every extension is one of those types |
|
|
178
|
+
| `hasExtension(account, type)` | whether the account has that extension |
|
|
179
|
+
| `transferHookProgram(mint)`, `transferHookAuthority(mint)`, `permanentDelegate(mint)`, `mintCloseAuthority(mint)` | `Option<Pubkey>` |
|
|
180
|
+
| `isTransferring(tokenAccount)` | inside a transfer hook: whether Token-2022 is transferring from it |
|
|
181
|
+
|
|
182
|
+
## Associated Token, Memo, Metadata and Stake
|
|
183
|
+
|
|
184
|
+
- **`AssociatedTokenProgram`**: `create` and `createIdempotent` CPIs; `associatedTokenAddress(owner, mint,
|
|
185
|
+
tokenProgram)` derives the address.
|
|
186
|
+
- **`MemoProgram`** (SPL Memo v2): `memoProgram.memo(text, [signers], signerSeeds?)`; each listed account signs (a PDA
|
|
187
|
+
of this program with its seeds).
|
|
188
|
+
- **`TokenMetadataProgram`** (Metaplex Token Metadata):
|
|
189
|
+
- `createV3(…)` (CreateMetadataAccountV3), optionally with `{ creators: [{ address, verified, share }], collection:
|
|
190
|
+
mint }` after `isMutable` (1–5 creators, shares adding up to 100; only the update authority, signing, can be
|
|
191
|
+
`verified: true`; the collection is written unverified; `isCollection: true` makes the NFT a sized collection);
|
|
192
|
+
- `createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram,
|
|
193
|
+
maxSupply | null)`;
|
|
194
|
+
- `verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram,
|
|
195
|
+
instructionsSysvar)` (Verify with CollectionV1);
|
|
196
|
+
- `updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened |
|
|
197
|
+
null, isMutable | null)` (`data` replaces the whole DataV2: `{ name, symbol, uri, sellerFeeBasisPoints, creators?,
|
|
198
|
+
collection? }`; each null leaves that part);
|
|
199
|
+
- `burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram,
|
|
200
|
+
instructionsSysvar, tokenProgram, amount)` (Burn: the holder signs and gets the rent back; the token account and
|
|
201
|
+
edition close, the metadata is cleared to one byte);
|
|
202
|
+
- `metadataAddress(mint)`, `masterEditionAddress(mint)`.
|
|
203
|
+
- **`StakeProgram`**:
|
|
204
|
+
- `initialize(stake, rentSysvar, staker, withdrawer, lockup?)` (`lockup`: `{ unixTimestamp, epoch, custodian }`,
|
|
205
|
+
none when left out);
|
|
206
|
+
- `authorize(stake, clockSysvar, authority, newAuthority, "staker" | "withdrawer", custodian?)`;
|
|
207
|
+
- `delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker)`;
|
|
208
|
+
- `split(stake, splitStake, staker, lamports)`;
|
|
209
|
+
- `deactivate(stake, clockSysvar, staker)`;
|
|
210
|
+
- `withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, custodian?)`;
|
|
211
|
+
- `merge(destination, source, clockSysvar, stakeHistorySysvar, staker)`;
|
|
212
|
+
- `getMinimumDelegation()`: a CPI, then the u64 the Stake program returns; fails as solana_program's
|
|
213
|
+
`get_minimum_delegation` does.
|
|
214
|
+
- Instruction tags and account lists are solana-stake-interface's builders'.
|
|
215
|
+
- The sysvar and config accounts are parameters, as in anchor-spl's stake module, or `named(account, address)` (a
|
|
216
|
+
native port): the instruction names `address` (`SysvarC1ock…`), as solana_program's builders do, and `account`,
|
|
217
|
+
the slot's account, is what the runtime gets, as Rust's `invoke_signed(&ix, &[stake, clock_info, …])` passes it.
|
|
218
|
+
The runtime looks the address up among the CPI's accounts only, so a slot holding another account fails the call
|
|
219
|
+
(MissingAccount), as the original does, even when the sysvar is elsewhere in the transaction (`named` is valid only
|
|
220
|
+
there).
|
|
221
|
+
- Authorities and the lockup custodian sign (PDAs with signer seeds, given last).
|
|
222
|
+
|
|
223
|
+
## Metaplex Core
|
|
224
|
+
|
|
225
|
+
`core: MplCoreProgram`:
|
|
226
|
+
|
|
227
|
+
- `createCollection`, `createAsset` (in a collection, PDA authorities via signer seeds), `transferAsset`, `burnAsset`
|
|
228
|
+
(`null` leaves an optional account out).
|
|
229
|
+
- Plugins as a literal list after the uri: `[{ kind: "Royalties", basisPoints: 500n, creators: [{ address, percentage:
|
|
230
|
+
100n }] }, { kind: "PermanentFreezeDelegate", frozen: false, authority: studio.key }]`, and `addPlugin` /
|
|
231
|
+
`updatePlugin` / `removePlugin(…, "FreezeDelegate")` with their `…CollectionPlugin` forms.
|
|
232
|
+
- Plugins: Royalties (with an optional `ruleSet: { programAllowList | programDenyList: [...] }`), FreezeDelegate,
|
|
233
|
+
BurnDelegate, TransferDelegate, UpdateDelegate, PermanentFreezeDelegate, Attributes, PermanentTransferDelegate,
|
|
234
|
+
PermanentBurnDelegate, Edition, MasterEdition (collections: `maxSupply?`, `name?`, `uri?`), AddBlocker,
|
|
235
|
+
ImmutableMetadata, VerifiedCreators, Autograph, BubblegumV2, FreezeExecute, PermanentFreezeExecute (Groups is kept by
|
|
236
|
+
Core's group instructions). `authority` is `"owner"`, `"updateAuthority"`, `"none"` or a Pubkey.
|
|
237
|
+
- `coreAssetOwner(asset)`, `coreAssetCollection(asset)` read an asset.
|
|
238
|
+
- External plugin adapters: `addExternalPlugin` / `removeExternalPlugin` / `writeExternalPluginData` (and the
|
|
239
|
+
Collection forms) with `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle", baseAddress, checks: [{
|
|
240
|
+
event: "transfer", canReject: true }], resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram,
|
|
241
|
+
checks, extraAccounts?, dataAuthority?, schema? }` and the Linked forms. A key names one (`{ kind: "AppData",
|
|
242
|
+
dataAuthority }`, `{ kind: "Oracle", address }`); data is a string, a `Vec<u8>` argument or `null` (Core currently
|
|
243
|
+
answers lifecycle hooks with NotAvailable, 23).
|
|
244
|
+
|
|
245
|
+
## Compressed NFTs (Bubblegum)
|
|
246
|
+
|
|
247
|
+
`bubblegum: BubblegumProgram`:
|
|
248
|
+
|
|
249
|
+
- **V1** (trees on SPL Account Compression): `createTree`, `mint` (MintV1, no collection or creators),
|
|
250
|
+
`mintToCollection` (MintToCollectionV1: into a verified Token Metadata collection), `transfer`, `burn`, `delegate`
|
|
251
|
+
(the leaf owner or delegate signs; a PDA owner signs with the seeds).
|
|
252
|
+
- **V2** (trees on mpl-account-compression with mpl-noop): `createTreeV2`, `mintV2(…, { name, symbol, uri,
|
|
253
|
+
sellerFeeBasisPoints, creators?, isMutable? }, { collection, authority, cpiSigner }?)` (into a Core collection that
|
|
254
|
+
has the `BubblegumV2` plugin), `transferV2`, `burnV2`, `delegateV2`, `freezeV2` / `thawV2`, `setNonTransferableV2`,
|
|
255
|
+
`updateMetadataV2(…, currentMetadata, { name?, symbol?, uri?, creators?, … })`, `verifyCreatorV2` /
|
|
256
|
+
`unverifyCreatorV2`, `setCollectionV2`.
|
|
257
|
+
- Each takes the leaf (`{ root, dataHash, creatorHash, assetDataHash?, flags?, nonce, index }`, or `{ root,
|
|
258
|
+
assetDataHash?, flags?, nonce, index }` with the leaf's current metadata for the metadata instructions) and its proof
|
|
259
|
+
as `remainingAccounts()` / `rest.slice(a)`.
|
|
260
|
+
|
|
261
|
+
## Typed calls from an IDL
|
|
262
|
+
|
|
263
|
+
`typesol cpi other.json --out other_cpi.ts` writes one helper per instruction of another program
|
|
264
|
+
(`vaultDeposit(program, owner, vault, systemProgram, amount, seeds)`), with the account flags, discriminator and
|
|
265
|
+
argument encoding taken from the IDL (Anchor 0.30+ / 1.x, or TypeSOL's own). Import the file and call a helper with
|
|
266
|
+
`signer([...seeds, bump])` when a PDA of your program signs, or `signer([])`. Instructions whose arguments have no
|
|
267
|
+
Borsh-identical TypeSOL type (strings or Options inside structs, data-carrying enums) are listed and left out.
|
|
268
|
+
|
|
269
|
+
## invoke
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { type AccountInfo, type Mut, type Program, type Signer, type SystemAccount, type SystemProgram, type u64, type u8, invoke, readonlySigner, sighash, u32, writable, writableSigner } from "typesol";
|
|
273
|
+
|
|
274
|
+
export function relayIncrement(authority: Signer, counter: Mut<AccountInfo>, counterProgram: Program<"JD2vDBgLPPLbLDghjzLMp5zCLvBWuZBkgFDCqCQv99Y2">, by: u64): void {
|
|
275
|
+
invoke(counterProgram, [readonlySigner(authority), writable(counter)], [sighash("increment"), by]);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function payOut(admin: Signer, treasury: Mut<SystemAccount>, recipient: Mut<SystemAccount>, systemProgram: SystemProgram, amount: u64, bump: u8): void {
|
|
279
|
+
invoke(systemProgram, [writableSigner(treasury), writable(recipient)], [u32(2n), amount], ["treasury", admin.key, bump]);
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
`invoke(program, accounts, data, signerSeeds?)` calls any program. The second call above is a raw System transfer
|
|
284
|
+
(u32 tag 2, u64 lamports) out of a treasury PDA. Its bump comes from the arguments to keep the example short: the
|
|
285
|
+
seeds hold the signer's key, so a caller can only reach a treasury of its own, but a program normally stores the bump
|
|
286
|
+
when it creates the PDA and signs with that one ([PDAs](language-pdas.md#checking-a-pda-in-the-body)).
|
|
287
|
+
|
|
288
|
+
### Program
|
|
289
|
+
|
|
290
|
+
A `Program<"address">` (key and executable checked on entry), an `UncheckedProgram`, an `Address<AccountInfo,
|
|
291
|
+
"address">` (Anchor's `#[account(address = ID)]` on an `UncheckedAccount`: only the key is checked, 2012), the system
|
|
292
|
+
or a token program, or a remaining account.
|
|
293
|
+
|
|
294
|
+
### Accounts
|
|
295
|
+
|
|
296
|
+
- `readonly(x)`, `writable(x)`, `readonlySigner(x)`, `writableSigner(x)`, written inside the list (`only valid inside
|
|
297
|
+
the accounts list`).
|
|
298
|
+
- The compiler refuses `writable` on a parameter that is not `Mut<…>` (`not writable here`), and a signer flag on an
|
|
299
|
+
account that neither signed nor is covered by signer seeds (`did not sign`).
|
|
300
|
+
- An optional account passed as it is (`readonly(x)` / `writable(x)` with `x: A | null`, no `!`) is left out of the
|
|
301
|
+
list when it was not passed, as Rust's `if let Some(x) = &self.x { accounts.push(…) }` does.
|
|
302
|
+
- Remaining accounts: one at a time, or spread (`...remainingAccounts()`, `...readonly(rest)`, `...writable(rest)`,
|
|
303
|
+
`rest.slice(a, b)`; [remaining accounts](language-accounts.md#remaining-accounts)).
|
|
304
|
+
- At most 32 accounts in one call (`invoke takes at most 32 accounts`), or the program's `MAX_ACCOUNTS`; at run time
|
|
305
|
+
5113.
|
|
306
|
+
|
|
307
|
+
### Data
|
|
308
|
+
|
|
309
|
+
Borsh: integers little-endian at their declared width (`u32(2n)` is 4 bytes, a bare `5n` is a u64), booleans,
|
|
310
|
+
Pubkeys, strings, Options, structs and FixedArrays (their fixed layout), data enums, `Vec` arguments,
|
|
311
|
+
`sighash("name")` (an Anchor instruction discriminator) and `hex("0a0b")`. Up to 1024 bytes.
|
|
312
|
+
|
|
313
|
+
### Return data
|
|
314
|
+
|
|
315
|
+
After the call, `returnData<u64>(program)` reads what the callee returned, checking the size and that it came from
|
|
316
|
+
`program`. A struct is bound to a local, `const quote = returnData<Quote>(amm)`: a fixed layout of integers, booleans,
|
|
317
|
+
Pubkeys, unit enums and arrays is read as its bytes (booleans and enums checked); a struct with Options, strings or
|
|
318
|
+
Vecs is declared `/** @layout borsh */` and Borsh-decoded. Bytes that are not exactly the struct fail with 5106. The
|
|
319
|
+
type argument is required.
|
|
320
|
+
|
|
321
|
+
## invokeInstruction
|
|
322
|
+
|
|
323
|
+
A call decided at run time, such as one a multisig stored in account data, is `invokeInstruction` (Rust's
|
|
324
|
+
`invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`):
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
import { type Account, type Pubkey, type u8, type Vec, invokeInstruction, remainingAccounts } from "typesol";
|
|
328
|
+
|
|
329
|
+
export interface TransactionAccount {
|
|
330
|
+
pubkey: Pubkey;
|
|
331
|
+
isSigner: boolean;
|
|
332
|
+
isWritable: boolean;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export interface Multisig {
|
|
336
|
+
nonce: u8;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export interface Transaction {
|
|
340
|
+
programId: Pubkey;
|
|
341
|
+
accounts: Vec<TransactionAccount>;
|
|
342
|
+
data: Vec<u8>;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export function execute(multisig: Account<Multisig>, transaction: Account<Transaction>): void {
|
|
346
|
+
invokeInstruction(transaction.programId, transaction.accounts, transaction.data, remainingAccounts(), [multisig.key, multisig.nonce]);
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
`execute` above shows the call only: as written, anyone can make the multisig's PDA sign any stored instruction. The
|
|
351
|
+
showcase's `executeTransaction` first requires that the transaction belongs to the multisig (`HasOne`), has not run
|
|
352
|
+
yet and has enough owners' approvals, and then marks it executed.
|
|
353
|
+
|
|
354
|
+
- The accounts are a list of structs with `pubkey`, `isSigner` and `isWritable` (a Vec or FixedVec in account data, a
|
|
355
|
+
Vec argument, a stored `map` result, or a local list built on the stack); the data a list of u8 (the same, the
|
|
356
|
+
instruction data or a slice of it).
|
|
357
|
+
- Every account in the fourth argument (`remainingAccounts()` or a slice; in a helper, its `RemainingAccounts`
|
|
358
|
+
parameter or a slice of it) is handed to the runtime, which finds each meta's account there by key: one that is
|
|
359
|
+
missing fails the call, as under Rust (MissingAccount, "Instruction references an unknown account").
|
|
360
|
+
- So a native port builds the instruction as Rust's instruction builders do, in a helper too, with metas naming
|
|
361
|
+
accounts by key:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
import { type FixedVec, type InstructionBytes, type Pubkey, type RemainingAccounts, type u8, fixedVec, instructionData, invokeInstruction, remainingAccounts } from "typesol";
|
|
365
|
+
|
|
366
|
+
interface Meta {
|
|
367
|
+
pubkey: Pubkey;
|
|
368
|
+
isSigner: boolean;
|
|
369
|
+
isWritable: boolean;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function transfer(rest: RemainingAccounts, data: InstructionBytes, to: Pubkey): void {
|
|
373
|
+
const metas: FixedVec<Meta, 2> = fixedVec([{ pubkey: rest.get(0n).key, isSigner: true, isWritable: true }]);
|
|
374
|
+
metas.push({ pubkey: to, isSigner: false, isWritable: true });
|
|
375
|
+
const ix: FixedVec<u8, 12> = fixedVec([2n, 0n, 0n, 0n]); // system_instruction::transfer
|
|
376
|
+
ix.pushAll(data.slice(1n, 9n)); // the lamports, as sent
|
|
377
|
+
invokeInstruction(rest.get(2n).key, metas, ix, rest);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** @fallback */
|
|
381
|
+
export function entry(): void {
|
|
382
|
+
const rest = remainingAccounts();
|
|
383
|
+
const data = instructionData();
|
|
384
|
+
transfer(rest, data, rest.get(1n).key);
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
- The runtime checks the privileges: a meta may be a signer or writable only as the transaction passed that account,
|
|
389
|
+
or as a PDA of this program the seeds (fifth argument) sign for. The multisig port in the showcase
|
|
390
|
+
([`showcase/mainnet/multisig/multisig.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/mainnet/multisig/multisig.ts)) uses it.
|
|
391
|
+
|
|
392
|
+
## Programs and sysvars passed as remaining accounts
|
|
393
|
+
|
|
394
|
+
A native program takes its programs and sysvars by position too. `programAt<P>(account)` checks that a remaining
|
|
395
|
+
account (or an `AccountInfo` parameter) is that program, once, by its key, and gives it P's typed methods:
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
import { type StakeProgram, type TokenInterface, instructionData, programAt, remainingAccounts } from "typesol";
|
|
399
|
+
|
|
400
|
+
/** @fallback */
|
|
401
|
+
export function entry(): void {
|
|
402
|
+
const data = instructionData();
|
|
403
|
+
const lamports = data.readU64(1n);
|
|
404
|
+
const bump = data.readU8(9n);
|
|
405
|
+
const rest = remainingAccounts();
|
|
406
|
+
const stake = programAt<StakeProgram>(rest.get(12n)); // ProgramError.IncorrectProgramId if it is another account
|
|
407
|
+
stake.split(rest.get(3n), rest.get(4n), rest.get(1n), lamports, [rest.get(0n).key, "withdraw", bump]);
|
|
408
|
+
const minimum = stake.getMinimumDelegation();
|
|
409
|
+
programAt<TokenInterface>(rest.get(10n)).mintTo(rest.get(7n), rest.get(8n), rest.get(1n), minimum, [rest.get(0n).key, "withdraw", bump]);
|
|
410
|
+
}
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
- The example shows the calls only: a real instruction checks its accounts before it signs as the pool's `withdraw`
|
|
414
|
+
PDA, as the SPL Stake Pool port in [`showcase/mainnet/spl-stake-pool`](https://github.com/typesol-lang/typesol/tree/main/showcase/mainnet/spl-stake-pool) checks the pool's owner, its manager or staker
|
|
415
|
+
and the withdraw authority's address first.
|
|
416
|
+
- P is `StakeProgram`, `SystemProgram`, `TokenProgram`, `Token2022Program`, `TokenInterface` (either token program),
|
|
417
|
+
`AssociatedTokenProgram` or `MemoProgram`. Bind it with `const`, or call a method on it directly; pass it to a helper
|
|
418
|
+
that takes that program type.
|
|
419
|
+
- `sysvarAt<StakeHistorySysvar>(account)` does the same for the StakeHistory sysvar (ProgramError.InvalidArgument for
|
|
420
|
+
another account): `count`, `latestEpoch`, `has(epoch)`, `effective(epoch)` … as on a parameter (read its fields
|
|
421
|
+
through a `const` bound to it; methods also work on the call itself).
|
|
422
|
+
- Every typed CPI (System, SPL Token and Token-2022, ATA, Memo, Stake) takes, for each account, a declared parameter, a
|
|
423
|
+
remaining account (`rest.get(i)`, a local bound to one, a `RemainingAccount` helper parameter), a struct loaded from
|
|
424
|
+
one, or an `AccountInfo` parameter where a `TokenAccount` or `Mint` goes. Declared parameters keep their compile-time
|
|
425
|
+
checks (writable slots need `Mut<…>`, an authority without signer seeds a `Signer`). A remaining account is not
|
|
426
|
+
checked by the compiler, and unlike `invoke` the typed calls add no run-time check of their own: the runtime refuses
|
|
427
|
+
a CPI that makes an account writable or a signer when the transaction did not (and no seeds sign for it), and the
|
|
428
|
+
called program checks the rest (a token account's mint and owner, a stake account's authorities).
|
|
429
|
+
- The cost is the key check (four 8-byte compares) and the call itself: within a few compute units of the same call
|
|
430
|
+
written with `invoke`, which checks only the executable flag ([`test/integrations/native-cpi.test.ts`](https://github.com/typesol-lang/typesol/blob/main/test/integrations/native-cpi.test.ts) measures it).
|
|
431
|
+
|
|
432
|
+
## Order of evaluation
|
|
433
|
+
|
|
434
|
+
A call's arguments are evaluated left to right, as in JavaScript, and its seeds are read where they are written: a seed
|
|
435
|
+
list written in the call holds the seeds as they were when the list was read, even when a later argument changes one,
|
|
436
|
+
while a named `signer([…])` list holds them as they were when it was declared ([signing as a
|
|
437
|
+
PDA](language-pdas.md#signing-as-a-pda)).
|
|
438
|
+
|
|
439
|
+
## Implementing another program's interface (transfer hooks)
|
|
440
|
+
|
|
441
|
+
```ts
|
|
442
|
+
import { type AccountInfo, type Mint, type Mut, type Signer, type SystemProgram, type TokenAccount, type u64, initExtraAccountMetas, require } from "typesol";
|
|
443
|
+
|
|
444
|
+
/** @discriminator spl-transfer-hook-interface:initialize-extra-account-metas */
|
|
445
|
+
export function initializeExtraAccountMetaList(payer: Mut<Signer>, extraMetas: Mut<AccountInfo>, mint: Mint, systemProgram: SystemProgram): void {
|
|
446
|
+
initExtraAccountMetas(payer, extraMetas, mint, systemProgram);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** @discriminator spl-transfer-hook-interface:execute */
|
|
450
|
+
export function execute(source: TokenAccount, mint: Mint, destination: TokenAccount, owner: AccountInfo, extraMetas: AccountInfo, amount: u64): void {
|
|
451
|
+
require(amount <= 1000n, "transfers above 1000 are blocked by the hook");
|
|
452
|
+
}
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
`/** @discriminator spl-transfer-hook-interface:execute */` above an instruction replaces its Anchor discriminator with
|
|
456
|
+
sha256(preimage)[..8] (or `@discriminator 0x…` for raw bytes), so a TypeSOL program can be a Token-2022 transfer hook:
|
|
457
|
+
`execute(source, mint, destination, owner, extraMetas, ...extraAccounts, amount)` plus
|
|
458
|
+
`initExtraAccountMetas(payer, account, mint, systemProgram, extraAccounts?)` for the validation account (an
|
|
459
|
+
ExtraAccountMetaList).
|
|
460
|
+
|
|
461
|
+
- Extra accounts are listed as `{ address, isSigner?, isWritable? }` (a fixed address) or `{ seeds: [...], program?,
|
|
462
|
+
isSigner?, isWritable? }` (a PDA of this program, or with `program: i` of the program at account index i), with
|
|
463
|
+
seeds from string literals, `seedAccountKey(i)`, `seedAccountData(i, offset, length)` and
|
|
464
|
+
`seedInstructionData(offset, length)`. Token-2022 resolves and checks them on every transfer. The first extra account
|
|
465
|
+
has index 5.
|
|
466
|
+
- `updateExtraAccountMetas(...)` rewrites and resizes an existing list.
|
|
467
|
+
- Inside the hook, `isTransferring(source)` says whether Token-2022 is transferring from it.
|
|
468
|
+
- See [`test/fixtures/hook.ts`](https://github.com/typesol-lang/typesol/blob/main/test/fixtures/hook.ts) and the transfer-hook ports.
|
|
469
|
+
|
|
470
|
+
**Next:** [Sysvars, hashes, signatures and oracles](language-chain.md).
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Errors, logs, events and return values
|
|
2
|
+
|
|
3
|
+
How a TypeSOL program fails, what it writes to the transaction's logs, the events it emits and the values it returns.
|
|
4
|
+
Part of the [language guide](language.md). The full list of error codes is in [errors.md](errors.md).
|
|
5
|
+
|
|
6
|
+
## require
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { type Account, type Mut, type Pubkey, type Signer, type u64, AnchorError, require } from "typesol";
|
|
10
|
+
|
|
11
|
+
export enum VaultError {
|
|
12
|
+
NotOwner = "Only the owner can withdraw",
|
|
13
|
+
/** @code 6100 */
|
|
14
|
+
TooLarge = "Amount above the balance",
|
|
15
|
+
Empty = "",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Vault {
|
|
19
|
+
owner: Pubkey;
|
|
20
|
+
balance: u64;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function withdraw(owner: Signer, vault: Mut<Vault>, amount: u64): void {
|
|
24
|
+
require(vault.owner === owner.key, VaultError.NotOwner);
|
|
25
|
+
require(amount <= vault.balance, VaultError.TooLarge);
|
|
26
|
+
require(amount > 0n, "amount must be positive");
|
|
27
|
+
require(vault.owner === owner.key, AnchorError.RequireKeysEqViolated);
|
|
28
|
+
vault.balance -= amount;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function audit(vault: Account<Vault>): void {
|
|
32
|
+
require(vault.balance > 0n, VaultError.Empty);
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`require(condition, error)` fails the instruction with `error` when the condition is false. There are no exceptions:
|
|
37
|
+
unlike JavaScript's `throw`, a failure cannot be caught. On Solana a failed instruction fails the whole transaction:
|
|
38
|
+
the runtime discards every change the transaction made, in this instruction, in the programs it called and in the
|
|
39
|
+
transaction's other instructions (only the fee is charged).
|
|
40
|
+
|
|
41
|
+
The error may be:
|
|
42
|
+
|
|
43
|
+
| Error | Code |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| a member of one of your error enums, `MyError.Name` | 6000 + its position, or its `@code` |
|
|
46
|
+
| a string, `require(cond, "message")` | an error of its own, `RequireFailed<N>`, numbered after the enums' errors; one per distinct message, listed in the IDL |
|
|
47
|
+
| `AnchorError.X`, any of anchor-lang's `ErrorCode`s | Anchor's own code: `AnchorError.RequireKeysEqViolated` is 2502, as `require_keys_eq!` |
|
|
48
|
+
| `ProgramError.X` | a built-in Solana error (`ProgramError.InvalidInstructionData`), as a native program returns it |
|
|
49
|
+
| a `u32` value | that code, computed at run time |
|
|
50
|
+
|
|
51
|
+
A code computed at run time is how a helper passes an error on as Rust's `?` does, when it returns the error as a
|
|
52
|
+
value instead of failing (a price read whose error the caller may record or ignore): `const r = price(feed);
|
|
53
|
+
require(r.err === 0n, r.err);`. The code is reported as it is (use one of your errors' codes, so clients can decode
|
|
54
|
+
it); a zero code fails with 5100.
|
|
55
|
+
|
|
56
|
+
## Error enums
|
|
57
|
+
|
|
58
|
+
- `export enum MyError { Name = "message" }`: an enum whose members are strings is an error enum, Anchor's
|
|
59
|
+
`#[error_code]`. Each member is an error; its string is the message (the IDL's `msg`).
|
|
60
|
+
- Codes start at 6000 and follow declaration order. Error enums of imported files are numbered first.
|
|
61
|
+
- `/** @code 6200 */` before a member gives it that code (Anchor's `Name = 200`), and the members after it continue
|
|
62
|
+
from there. Codes only go up (`@code must be a number from … up`). The tag goes on its own line above the member, or
|
|
63
|
+
first on the member's line; after other code on a line (`A = "a", /** @code 6200 */ B = "b"`) it would belong to no
|
|
64
|
+
member, so it is refused.
|
|
65
|
+
- `Name = ""` has no message in the IDL, as an Anchor variant without `#[msg]`.
|
|
66
|
+
- An error enum may start at code 0 (`/** @code 0 */`, Rust's `ProgramError::Custom(0)`, returned as Solana's
|
|
67
|
+
CUSTOM_ZERO), for ports of native programs ([native
|
|
68
|
+
programs](language-native.md#errors-and-panics-as-the-original-reports-them)).
|
|
69
|
+
- `require(cond, "message")` errors come after the highest code.
|
|
70
|
+
|
|
71
|
+
When the program fails, the logs show the error and the source line, `Error 6000 NotOwner (vault.ts:21)`, and
|
|
72
|
+
TypeSOL's own failures say what failed, `TypeSOL: arithmetic overflow (vault.ts:42)`. Native ports can change or drop
|
|
73
|
+
that line ([log lines](language-native.md#log-lines-as-the-original-writes-them)).
|
|
74
|
+
|
|
75
|
+
## log
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { type Pubkey, type u64, log } from "typesol";
|
|
79
|
+
|
|
80
|
+
export function show(owner: Pubkey, amount: u64, ok: boolean): void {
|
|
81
|
+
log("deposit");
|
|
82
|
+
log(amount);
|
|
83
|
+
log(owner);
|
|
84
|
+
log(`owner ${owner} deposited ${amount}: ${ok}`);
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`log(text)`, `log(value)` (an integer) and `log(key)` (a `Pubkey` or `Hash`, as base58) write a `Program log:`
|
|
89
|
+
line. A boolean is logged through a template string (`` log(`ok: ${ok}`) ``); `log(flag)` alone is a type error.
|
|
90
|
+
`console.log` is not available. Template strings and `+` build the text on the heap
|
|
91
|
+
([strings built at run time](language-types.md#strings-built-at-run-time)). `logBase64` and `logComputeUnits` are for
|
|
92
|
+
native ports ([log lines](language-native.md#log-lines-as-the-original-writes-them)).
|
|
93
|
+
|
|
94
|
+
## Events
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import { type Mut, type Option, type Pubkey, type Signer, type u64, type Vec, emit } from "typesol";
|
|
98
|
+
|
|
99
|
+
export interface Deposited {
|
|
100
|
+
owner: Pubkey;
|
|
101
|
+
amount: u64;
|
|
102
|
+
memo: string;
|
|
103
|
+
referrer: Option<Pubkey>;
|
|
104
|
+
tags: Vec<u64>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface Pool {
|
|
108
|
+
total: u64;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function deposit(owner: Signer, pool: Mut<Pool>, amount: u64, tags: Vec<u64>): void {
|
|
112
|
+
pool.total += amount;
|
|
113
|
+
emit<Deposited>({ owner: owner.key, amount, memo: "thanks", referrer: null, tags });
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- `emit<T>({ … })` writes an Anchor-format event: a `Program data:` log line holding the event's discriminator
|
|
118
|
+
(sha256("event:<Name>")[..8]) and its Borsh bytes. The IDL lists `T` under `events`, and Anchor's event parsers and
|
|
119
|
+
the generated client decode it.
|
|
120
|
+
- The type argument is required (`emit<T>(…)`), and the literal names every field.
|
|
121
|
+
- Event structs may hold `string`, `Option`, `FixedVec<T, N>` (its fixed layout, as in account data), `Vec<T>` (Borsh:
|
|
122
|
+
from a Vec argument or a list in account data) and `Option<Vec<T>>` (given `null`, such an argument or a list). A
|
|
123
|
+
nested struct given as a literal (`header: { signer: who.key, … }`) goes out as Borsh too, its Options one byte
|
|
124
|
+
when empty.
|
|
125
|
+
- An event is at most 1024 bytes (5107).
|
|
126
|
+
|
|
127
|
+
### Events through CPI
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import { type EventAuthority, type Mut, type SelfProgram, type u64, emitCpi } from "typesol";
|
|
131
|
+
|
|
132
|
+
export interface Paid {
|
|
133
|
+
amount: u64;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface Ledger {
|
|
137
|
+
total: u64;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function pay(ledger: Mut<Ledger>, eventAuthority: EventAuthority, self: SelfProgram, amount: u64): void {
|
|
141
|
+
ledger.total += amount;
|
|
142
|
+
emitCpi<Paid>({ amount }, eventAuthority, self);
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
`emitCpi<T>({ … }, eventAuthority, self)` is Anchor's `emit_cpi!`: the event rides in a self-CPI (an inner
|
|
147
|
+
instruction) instead of the logs. The instruction takes `eventAuthority:
|
|
148
|
+
EventAuthority` (Anchor's `["__event_authority"]` PDA) and `self: SelfProgram` parameters, and the program accepts
|
|
149
|
+
Anchor's event instruction (2002 when the event authority did not sign it, 2006 when it is not that PDA).
|
|
150
|
+
|
|
151
|
+
## Return values
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { type Account, type Pubkey, type u64 } from "typesol";
|
|
155
|
+
|
|
156
|
+
export interface Quote {
|
|
157
|
+
price: u64;
|
|
158
|
+
maker: Pubkey;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface Market {
|
|
162
|
+
price: u64;
|
|
163
|
+
maker: Pubkey;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function price(market: Account<Market>): u64 {
|
|
167
|
+
return market.price;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function quote(market: Account<Market>): Quote {
|
|
171
|
+
return { price: market.price, maker: market.maker };
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
An instruction that returns a value sends it as return data: one integer, `boolean`, `Pubkey`, `string` (a Borsh
|
|
176
|
+
String) or fixed-size struct, at most 1024 bytes. The IDL lists it as `returns`, and the generated client decodes it.
|
|
177
|
+
|
|
178
|
+
- Another program reads it after a CPI with `returnData<T>(program)` ([calling other
|
|
179
|
+
programs](language-cpi.md#return-data)).
|
|
180
|
+
- `setReturnData(bytes)` sets the raw bytes, as Rust's `set_return_data` (a native port's); an instruction that returns
|
|
181
|
+
a value cannot call it ([return data as the original sets
|
|
182
|
+
it](language-native.md#return-data-as-the-original-sets-it)).
|
|
183
|
+
|
|
184
|
+
**Next:** [Calling other programs](language-cpi.md).
|