0
# Instructions and Programs
1
2
Instruction creation, program interaction, and account metadata management for Solana blockchain operations.
3
4
## Capabilities
5
6
### Instruction Structure
7
8
Core instruction interface and components for program execution.
9
10
```typescript { .api }
11
/**
12
* Basic instruction interface for program execution
13
*/
14
interface IInstruction<TProgramAddress = Address> {
15
/** Program that will process this instruction */
16
programId: TProgramAddress;
17
/** Account metadata for accounts this instruction will access */
18
accounts?: IAccountMeta[];
19
/** Instruction data as raw bytes */
20
data?: Uint8Array;
21
}
22
23
/**
24
* Instruction with required accounts
25
*/
26
interface IInstructionWithAccounts<TAccounts> extends IInstruction {
27
/** Typed account metadata */
28
accounts: TAccounts;
29
}
30
31
/**
32
* Instruction with required data
33
*/
34
interface IInstructionWithData<TData> extends IInstruction {
35
/** Typed instruction data */
36
data: TData;
37
}
38
```
39
40
### Account Metadata
41
42
Define how instructions interact with accounts.
43
44
```typescript { .api }
45
/**
46
* Account metadata for instruction execution
47
*/
48
interface IAccountMeta<TAddress = Address> {
49
/** Account address */
50
address: TAddress;
51
/** Account role and permissions */
52
role: AccountRole;
53
}
54
55
/**
56
* Account metadata for address lookup tables
57
*/
58
interface IAccountLookupMeta<TAddress = Address> {
59
/** Lookup table address */
60
lookupTableAddress: TAddress;
61
/** Index within the lookup table */
62
addressIndex: number;
63
/** Account role and permissions */
64
role: AccountRole;
65
}
66
67
/**
68
* Account role defining permissions and signing requirements
69
*/
70
type AccountRole =
71
| { readonly __kind: "readonly" }
72
| { readonly __kind: "writable" }
73
| { readonly __kind: "readonlySigner" }
74
| { readonly __kind: "writableSigner" };
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
import { address, IInstruction, IAccountMeta } from "@solana/web3.js";
81
82
// Create basic instruction
83
const instruction: IInstruction = {
84
programId: address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
85
accounts: [
86
{
87
address: address("source-token-account"),
88
role: { __kind: "writable" }
89
},
90
{
91
address: address("destination-token-account"),
92
role: { __kind: "writable" }
93
},
94
{
95
address: address("owner-address"),
96
role: { __kind: "readonlySigner" }
97
}
98
],
99
data: new Uint8Array([3, 0, 0, 0, 100, 0, 0, 0]) // Transfer 100 tokens
100
};
101
```
102
103
### Instruction Validation
104
105
Type guards and assertions for instruction validation.
106
107
```typescript { .api }
108
/**
109
* Check if instruction is for a specific program
110
* @param instruction - Instruction to check
111
* @param programId - Expected program ID
112
* @returns True if instruction targets the program
113
*/
114
function isInstructionForProgram<TProgramAddress extends Address>(
115
instruction: IInstruction,
116
programId: TProgramAddress
117
): instruction is IInstruction<TProgramAddress>;
118
119
/**
120
* Assert instruction is for specific program
121
* @param instruction - Instruction to check
122
* @param programId - Expected program ID
123
* @throws SolanaError if instruction is not for the program
124
*/
125
function assertIsInstructionForProgram<TProgramAddress extends Address>(
126
instruction: IInstruction,
127
programId: TProgramAddress
128
): asserts instruction is IInstruction<TProgramAddress>;
129
130
/**
131
* Check if instruction has accounts
132
* @param instruction - Instruction to check
133
* @returns True if instruction has accounts
134
*/
135
function isInstructionWithAccounts<TAccounts>(
136
instruction: IInstruction
137
): instruction is IInstructionWithAccounts<TAccounts>;
138
139
/**
140
* Assert instruction has accounts
141
* @param instruction - Instruction to check
142
* @throws SolanaError if instruction lacks accounts
143
*/
144
function assertIsInstructionWithAccounts<TAccounts>(
145
instruction: IInstruction
146
): asserts instruction is IInstructionWithAccounts<TAccounts>;
147
148
/**
149
* Check if instruction has data
150
* @param instruction - Instruction to check
151
* @returns True if instruction has data
152
*/
153
function isInstructionWithData<TData>(
154
instruction: IInstruction
155
): instruction is IInstructionWithData<TData>;
156
157
/**
158
* Assert instruction has data
159
* @param instruction - Instruction to check
160
* @throws SolanaError if instruction lacks data
161
*/
162
function assertIsInstructionWithData<TData>(
163
instruction: IInstruction
164
): asserts instruction is IInstructionWithData<TData>;
165
```
166
167
### Account Role System
168
169
Utilities for working with account roles and permissions.
170
171
```typescript { .api }
172
/**
173
* Create readonly account role
174
* @returns Readonly account role
175
*/
176
function createReadonlyRole(): AccountRole;
177
178
/**
179
* Create writable account role
180
* @returns Writable account role
181
*/
182
function createWritableRole(): AccountRole;
183
184
/**
185
* Create readonly signer account role
186
* @returns Readonly signer account role
187
*/
188
function createReadonlySignerRole(): AccountRole;
189
190
/**
191
* Create writable signer account role
192
* @returns Writable signer account role
193
*/
194
function createWritableSignerRole(): AccountRole;
195
196
/**
197
* Check if account role requires signing
198
* @param role - Account role to check
199
* @returns True if role requires signing
200
*/
201
function isSignerRole(role: AccountRole): boolean;
202
203
/**
204
* Check if account role allows writing
205
* @param role - Account role to check
206
* @returns True if role allows writing
207
*/
208
function isWritableRole(role: AccountRole): boolean;
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import {
215
createWritableSignerRole,
216
createReadonlyRole,
217
isSignerRole,
218
isWritableRole
219
} from "@solana/web3.js";
220
221
// Create account metadata with specific roles
222
const signerAccount = {
223
address: myAddress,
224
role: createWritableSignerRole()
225
};
226
227
const dataAccount = {
228
address: dataAddress,
229
role: createReadonlyRole()
230
};
231
232
// Check role properties
233
console.log("Requires signing:", isSignerRole(signerAccount.role)); // true
234
console.log("Allows writing:", isWritableRole(dataAccount.role)); // false
235
```
236
237
### Program Interaction Utilities
238
239
Helper functions for common program operations.
240
241
```typescript { .api }
242
/**
243
* Create account metadata for program invocation
244
* @param config - Account configuration
245
* @returns Account metadata array
246
*/
247
function createAccountMetas(config: {
248
accounts: Array<{
249
address: Address;
250
writable?: boolean;
251
signer?: boolean;
252
}>;
253
}): IAccountMeta[];
254
255
/**
256
* Get required signers from instruction accounts
257
* @param instruction - Instruction to analyze
258
* @returns Array of addresses that must sign
259
*/
260
function getRequiredSigners(instruction: IInstruction): Address[];
261
262
/**
263
* Get writable accounts from instruction
264
* @param instruction - Instruction to analyze
265
* @returns Array of addresses that will be modified
266
*/
267
function getWritableAccounts(instruction: IInstruction): Address[];
268
269
/**
270
* Merge multiple instructions for the same program
271
* @param instructions - Instructions to merge
272
* @returns Single merged instruction
273
*/
274
function mergeInstructions(instructions: IInstruction[]): IInstruction;
275
```
276
277
### Program Error Handling
278
279
Specialized error types and handling for program execution.
280
281
```typescript { .api }
282
/**
283
* Program execution error
284
*/
285
interface ProgramError {
286
/** Program that generated the error */
287
programId: Address;
288
/** Instruction index that failed */
289
instructionIndex: number;
290
/** Custom error code from program */
291
customErrorCode?: number;
292
/** Error message */
293
message: string;
294
}
295
296
/**
297
* Parse program error from transaction error
298
* @param transactionError - Raw transaction error
299
* @returns Parsed program error or null
300
*/
301
function parseProgramError(transactionError: TransactionError): ProgramError | null;
302
303
/**
304
* Check if error is from specific program
305
* @param error - Error to check
306
* @param programId - Program ID to match
307
* @returns True if error is from the program
308
*/
309
function isProgramError(error: unknown, programId: Address): error is ProgramError;
310
```
311
312
### Cross-Program Invocation (CPI)
313
314
Utilities for programs calling other programs.
315
316
```typescript { .api }
317
/**
318
* Cross-program invocation instruction
319
*/
320
interface CPIInstruction extends IInstruction {
321
/** Invoking program ID */
322
invokingProgramId: Address;
323
/** Target program ID */
324
targetProgramId: Address;
325
/** Seeds for program-derived address signing */
326
seeds?: Uint8Array[][];
327
}
328
329
/**
330
* Create cross-program invocation
331
* @param config - CPI configuration
332
* @returns CPI instruction
333
*/
334
function createCPIInstruction(config: {
335
invokingProgramId: Address;
336
targetProgramId: Address;
337
accounts: IAccountMeta[];
338
data?: Uint8Array;
339
seeds?: Uint8Array[][];
340
}): CPIInstruction;
341
```
342
343
## Common Program Instructions
344
345
### System Program
346
347
```typescript { .api }
348
/**
349
* System program ID constant
350
*/
351
const SYSTEM_PROGRAM_ID: Address;
352
353
/**
354
* Create account instruction
355
*/
356
function createCreateAccountInstruction(config: {
357
fromPubkey: Address;
358
newAccountPubkey: Address;
359
lamports: Lamports;
360
space: number;
361
programId: Address;
362
}): IInstruction;
363
364
/**
365
* Transfer lamports instruction
366
*/
367
function createTransferInstruction(config: {
368
fromPubkey: Address;
369
toPubkey: Address;
370
lamports: Lamports;
371
}): IInstruction;
372
```
373
374
### Token Program
375
376
```typescript { .api }
377
/**
378
* Token program ID constant
379
*/
380
const TOKEN_PROGRAM_ID: Address;
381
382
/**
383
* Token transfer instruction
384
*/
385
function createTokenTransferInstruction(config: {
386
source: Address;
387
destination: Address;
388
owner: Address;
389
amount: bigint;
390
}): IInstruction;
391
392
/**
393
* Token mint instruction
394
*/
395
function createMintToInstruction(config: {
396
mint: Address;
397
destination: Address;
398
authority: Address;
399
amount: bigint;
400
}): IInstruction;
401
```
402
403
**Usage Examples:**
404
405
```typescript
406
import {
407
createTransferInstruction,
408
createTokenTransferInstruction,
409
SYSTEM_PROGRAM_ID,
410
TOKEN_PROGRAM_ID,
411
lamports
412
} from "@solana/web3.js";
413
414
// Create SOL transfer
415
const solTransfer = createTransferInstruction({
416
fromPubkey: myAddress,
417
toPubkey: recipientAddress,
418
lamports: lamports(1_000_000_000n) // 1 SOL
419
});
420
421
// Create token transfer
422
const tokenTransfer = createTokenTransferInstruction({
423
source: myTokenAccount,
424
destination: recipientTokenAccount,
425
owner: myAddress,
426
amount: 1000000n // 1 token with 6 decimals
427
});
428
429
// Combine in transaction
430
const transactionMessage = createTransactionMessage({
431
version: 0,
432
feePayer: myAddress,
433
blockhash,
434
instructions: [solTransfer, tokenTransfer]
435
});
436
```