Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .cspell-anchor-dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ programdata
projectserum
pubkeys
publickey
realizor
reallocs
repr
reqwest
Expand Down Expand Up @@ -91,9 +92,15 @@ syscalls
sysvar
Sysvar
sysvars
timelock
toolsuite
unbonding
underyling
unsized
Unsized
unstaked
unstakes
unstaking
unverify
Zeroable
Znext
2 changes: 1 addition & 1 deletion cli/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1752,7 +1752,7 @@ fn program_extend(
.send_and_confirm_transaction(&tx)
.map_err(|e| anyhow!("Failed to extend program: {}", e))?;

println!("Program extended succesfully!");
println!("Program extended successfully!");
Ok(())
}

Expand Down
9 changes: 9 additions & 0 deletions docs/content/docs/basics/idl.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,21 @@ Key Benefits of the IDL:
- Standardization: Provides a consistent format for describing the program's
instructions and accounts
- Client Generation: Used to generate client code to interact with the program
- On-chain Storage: IDLs can be stored on-chain using
[Program Metadata](https://github.com/solana-program/program-metadata),
allowing clients to fetch and use the IDL directly from the blockchain

<Callout type="info">
The `anchor build` command generates an IDL file located at
`/target/idl/<program-name>.json`.
</Callout>

<Callout type="info">
On-chain IDL storage uses the Program Metadata system. This reduces program
binary sizes and provides a standardized approach to on-chain metadata. Use
`anchor idl init` to upload your IDL to the blockchain.
</Callout>

The code snippets in the sections below highlight how the program, IDL, and
client relate to each other.

Expand Down
52 changes: 29 additions & 23 deletions docs/content/docs/clients/rust.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -170,51 +170,57 @@ Below is the `src/main.rs` file for interacting with the program:

```rust title="src/main.rs"
use anchor_client::{
solana_client::rpc_client::RpcClient,
Client,
Cluster,
solana_sdk::{
commitment_config::CommitmentConfig, native_token::LAMPORTS_PER_SOL, signature::Keypair,
commitment_config::CommitmentConfig,
native_token::LAMPORTS_PER_SOL,
signature::{Keypair, Signer},
system_program,
},
solana_signer::Signer,
Client, Cluster,
};
use anchor_lang::prelude::*;
use std::rc::Rc;
use std::sync::Arc;

declare_program!(example);
use example::{accounts::Counter, client::accounts, client::args};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let connection = RpcClient::new_with_commitment(
"http://127.0.0.1:8899", // Local validator URL
CommitmentConfig::confirmed(),
);

// Generate Keypairs and request airdrop
let payer = Keypair::new();
let counter = Keypair::new();
let payer = Arc::new(Keypair::new());
let counter = Arc::new(Keypair::new());
println!("Generated Keypairs:");
println!(" Payer: {}", payer.pubkey());
println!(" Counter: {}", counter.pubkey());

println!("\nRequesting 1 SOL airdrop to payer");
let airdrop_signature = connection.request_airdrop(&payer.pubkey(), LAMPORTS_PER_SOL)?;

// Wait for airdrop confirmation
while !connection.confirm_transaction(&airdrop_signature)? {
std::thread::sleep(std::time::Duration::from_millis(100));
}
println!(" Airdrop confirmed!");

// Create program client
let provider = Client::new_with_options(
Cluster::Localnet,
Rc::new(payer),
payer.clone(),
CommitmentConfig::confirmed(),
);
let program = provider.program(example::ID)?;

// Get RPC client from the program
let rpc = program.rpc();

println!("\nRequesting 1 SOL airdrop to payer");
let airdrop_signature = rpc.request_airdrop(&payer.pubkey(), LAMPORTS_PER_SOL).await?;

// Wait for airdrop confirmation
rpc.confirm_transaction(&airdrop_signature).await?;

// Wait for balance to be available
loop {
let balance = rpc.get_balance(&payer.pubkey()).await?;
if balance > 0 {
println!(" Airdrop confirmed! Payer balance: {} lamports", balance);
break;
}
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}

// Build and send instructions
println!("\nSend transaction with initialize and increment instructions");
let initialize_ix = program
Expand All @@ -241,7 +247,7 @@ async fn main() -> anyhow::Result<()> {
.request()
.instruction(initialize_ix)
.instruction(increment_ix)
.signer(&counter)
.signer(counter.clone())
.send()
.await?;
println!(" Transaction confirmed: {}", signature);
Expand Down
15 changes: 9 additions & 6 deletions docs/content/docs/clients/typescript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,8 @@ const provider = new AnchorProvider(connection, wallet, {});
setProvider(provider);

// [!code word:Program]
// [!code highlight:3]
export const program = new Program(idl as HelloAnchor, {
connection,
});
// [!code highlight]
export const program = new Program(idl as HelloAnchor, provider);
```

In the code snippet above:
Expand All @@ -66,10 +64,15 @@ In the code snippet above:
- `idlType.ts` is the IDL type (for use with TypeScript), found at
`/target/types/<program-name>.ts` in an Anchor project.

Alternatively, you can create an `Program` instance using only the IDL and the
The `Program` instance is created with both the IDL and the `provider`, which
enables signing and sending transactions. This allows you to call `.rpc()`
methods on program instructions.

Alternatively, you can create a `Program` instance using only the IDL and the
`Connection` to a Solana cluster. This means there is no default `Wallet`, but
allows you to use the `Program` to fetch accounts or build instructions without
a connected wallet.
a connected wallet. Note that this read-only configuration does not support
signing or sending transactions.

```ts
import { clusterApiUrl, Connection, PublicKey } from "@solana/web3.js";
Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/features/errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ scheme:
| Error Code | Description |
| ---------- | ------------------------------------- |
| >= 100 | Instruction error codes |
| >= 1000 | IDL error codes |
| >= 1500 | Event error codes |
| >= 2000 | Constraint error codes |
| >= 3000 | Account error codes |
| >= 4100 | Misc error codes |
Expand Down
89 changes: 66 additions & 23 deletions docs/content/docs/references/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,16 @@
## Idl

The `idl` subcommand provides commands for interacting with interface definition
files. It's recommended to use these commands to store an IDL on chain, at a
deterministic address, as a function of nothing but the program's ID. This
allows us to generate clients for a program using nothing but the program ID.
files. Anchor uses the [Program Metadata](https://github.com/solana-program/program-metadata)
system to store IDLs on-chain at a deterministic address derived from the
program's ID. This allows clients to be generated for a program using nothing
but the program ID.

<Callout type="info">
IDL management uses the `@solana-program/program-metadata`
package instead of legacy IDL instructions. This results in smaller program
binaries and a more standardized approach to on-chain metadata.
</Callout>

### Idl Build

Expand All @@ -163,10 +170,16 @@
anchor idl init -f <target/idl/program.json> [program-id]
```

Creates an idl account, writing the given `<target/idl/program.json>` file into
a program owned account. By default, the size of the account is double the size
of the IDL, allowing room for growth in case the idl needs to be upgraded in the
future.
Creates a metadata account containing the IDL for the given program. The IDL
file is written to an account derived from the program ID.

```shell
anchor idl init -f <target/idl/program.json> <program-id> --non-canonical
```

Use the `--non-canonical` flag to create a third-party (non-canonical) metadata
account. This is useful when you want to store metadata for a program you don't
own.

The `program-id` argument is optional — when omitted, `idl.address` is used.

Expand All @@ -183,54 +196,84 @@
anchor idl fetch GrAkKfEpTKQuVHG2Y97Y2FF4i7y7Q5AHLK94JBy7Y5yv
```

### Idl Authority
Use the `--non-canonical` flag to fetch third-party metadata:

```shell
anchor idl authority <program-id>
anchor idl fetch <program-id> --non-canonical
```

Outputs the IDL account's authority. This is the wallet that has the ability to
update the IDL.
### Idl Upgrade

### Idl Erase Authority
```shell
anchor idl upgrade -f <target/idl/program.json>
```

Upgrades the IDL file on chain to the new `target/idl/program.json` idl. The
configured wallet must be the current authority. The `program-id` argument is
optional — when omitted, `idl.address` is used.

### Idl Close

```shell
anchor idl erase-authority -p <program-id>
anchor idl close <program-id>
```

Erases the IDL account's authority so that upgrades can no longer occur. The
configured wallet must be the current authority.
Closes the metadata account and recovers the rent. By default, closes the "idl"
seed account. Use `--seed` to specify a different seed:

### Idl Upgrade
```shell
anchor idl close <program-id> --seed <custom-seed>
```

### Idl Create Buffer

```shell
anchor idl upgrade -f <target/idl/program.json>
anchor idl create-buffer -f <filepath>
```

Upgrades the IDL file on chain to the new `target/idl/program.json` idl. The
configured wallet must be the current authority. The `program-id` argument is
optional — when omitted, `idl.address` is used.
Creates a buffer account for metadata. This is useful for large IDLs that need
to be written across multiple transactions.

### Idl Set Buffer Authority

```shell
anchor idl set-buffer-authority <buffer> -n <new-authority>
```

Sets a new authority on a buffer account.

### Idl Write Buffer

```shell
anchor idl write-buffer <program-id> -b <buffer>
```

Writes metadata to the program using a pre-created buffer account. Use
`--seed` to specify the metadata seed (defaults to "idl"):

```shell
anchor idl set-authority -n <new-authority> -p <program-id>
anchor idl write-buffer <program-id> -b <buffer> --seed <seed>
```

Sets a new authority on the IDL account. Both the `new-authority` and
`program-id` must be encoded in base 58.
Use `--close-buffer` to automatically close the buffer account after writing:

```shell
anchor idl write-buffer <program-id> -b <buffer> --close-buffer
```

## Init

Check warning on line 264 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (Codama)

```shell
anchor init <project-name>

Check warning on line 267 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (codama)

Check warning on line 267 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (codama)
```

Check warning on line 268 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (codama)

Initializes a project workspace with the following structure.

Check warning on line 271 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (Codama)

Check warning on line 271 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (codama)
- `Anchor.toml`: Anchor configuration file.

Check warning on line 272 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (Codama)

Check warning on line 272 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (codama)
- `Cargo.toml`: Rust workspace configuration file.
- `package.json`: JavaScript dependencies file.
- `programs/`: Directory for Solana program crates.
- `app/`: Directory for your application frontend.

Check warning on line 276 in docs/content/docs/references/cli.mdx

View workflow job for this annotation

GitHub Actions / spellcheck

Unknown word (Codama)
- `tests/`: Directory for JavaScript integration tests.
- `migrations/deploy.js`: Deploy script.

Expand Down
2 changes: 1 addition & 1 deletion lang/src/accounts/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use {
///
/// The type has a `programdata_address` function that will return `Option::Some`
/// if the program is owned by the [`BPFUpgradeableLoader`](https://docs.rs/solana-program/latest/solana_program/bpf_loader_upgradeable/index.html)
/// which will contain the `programdata_address` property of the `Program` variant of the [`UpgradeableLoaderState`](https://docs.rs/solana-loader-v3-interface/latest/solana_loader_v3_interface/state/enum.UpgradeableLoaderState.html) enum.
/// which will contain the `programdata_address` property of the `Program` variant of the [`UpgradeableLoaderState`](https://docs.rs/solana-loader-v3-interface/6.1.0/solana_loader_v3_interface/state/enum.UpgradeableLoaderState.html) enum.
///
/// # Table of Contents
/// - [Basic Functionality](#basic-functionality)
Expand Down
2 changes: 1 addition & 1 deletion lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ pub trait DuplicateMutableAccountKeys {
fn duplicate_mutable_account_keys(&self) -> Vec<Pubkey>;
}

/// The close procedure to initiate garabage collection of an account, allowing
/// The close procedure to initiate garbage collection of an account, allowing
/// one to retrieve the rent exemption.
pub trait AccountsClose<'info>: ToAccountInfos<'info> {
fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()>;
Expand Down
2 changes: 1 addition & 1 deletion lang/syn/src/parser/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl CrateContext {
Please add a `/// CHECK:` doc comment explaining why no checks through types are necessary.
Alternatively, for reasons like quick prototyping, you may disable the safety checks
by using the `skip-lint` option.
See https://www.anchor-lang.com/docs/basics/program-structure#account-validation for more information.
See https://www.anchor-lang.com/docs/references/account-types#uncheckedaccountinfo for more information.
"#,
canonical.display(),
span.start().line,
Expand Down
22 changes: 20 additions & 2 deletions spl/src/stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,14 @@ use {
std::ops::Deref,
};

// CPI functions

// CPI Functions

/// Authorizes a new authority for a stake account.
///
/// # Parameters
/// - `ctx`: Context containing accounts required for the operation.
/// - `stake_authorize`: The type of authorization (Staker or Withdrawer).
/// - `custodian`: Optional custodian account.
pub fn authorize<'info>(
ctx: CpiContext<'_, '_, '_, 'info, Authorize<'info>>,
stake_authorize: StakeAuthorize,
Expand All @@ -39,6 +45,12 @@ pub fn authorize<'info>(
.map_err(Into::into)
}

/// Withdraws lamports from a stake account.
///
/// # Parameters
/// - `ctx`: Context containing accounts required for the operation.
/// - `amount`: The amount to withdraw in lamports.
/// - `custodian`: Optional custodian account.
pub fn withdraw<'info>(
ctx: CpiContext<'_, '_, '_, 'info, Withdraw<'info>>,
amount: u64,
Expand All @@ -65,6 +77,10 @@ pub fn withdraw<'info>(
.map_err(Into::into)
}

/// Deactivates a stake account.
///
/// # Parameters
/// - `ctx`: Context containing accounts required for the operation.
pub fn deactivate_stake<'info>(
ctx: CpiContext<'_, '_, '_, 'info, DeactivateStake<'info>>,
) -> Result<()> {
Expand Down Expand Up @@ -126,6 +142,7 @@ pub struct DeactivateStake<'info> {

// State

/// A wrapper around the Solana StakeState to enable Anchor deserialization.
#[derive(Clone)]
pub struct StakeAccount(StakeStateV2);

Expand Down Expand Up @@ -155,6 +172,7 @@ impl Deref for StakeAccount {
}
}

/// A wrapper around the Solana Stake program ID.
#[derive(Clone)]
pub struct Stake;

Expand Down
Loading
Loading