From de757166142f293fde3d5deeecac60779fe8dbee Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 20 Dec 2024 12:12:34 -0500 Subject: [PATCH 01/25] add toolkit content --- docs/toolkit/index.md | 870 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 870 insertions(+) create mode 100644 docs/toolkit/index.md diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md new file mode 100644 index 000000000..8b0eeba6f --- /dev/null +++ b/docs/toolkit/index.md @@ -0,0 +1,870 @@ +--- +title: The Solana Toolkit +--- + +The Solana Toolkit consists of all open sourced tools for smart contract development on the Solana Blockchain. + +You can contribute to this book on [GitHub](). + +## Installation + +To get started, install The Solana toolkit: + +```shell +npx solana install +``` + +This will install the latest versions of the following: + +- [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line tool that allows developers to interact with the Solana blockchain, manage accounts, send transactions, and deploy programs. +- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana Smart Contracts are written in. +- [Anchor](https://www.anchor-lang.com/): A framework for writing Solana programs that abstracts many complexities to speed up smart contract development. +- [Trident](https://ackee.xyz/trident/docs/latest/): A fuzz tester +- [Zest](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage tool + +## Getting Started + +This section will cover all the toolkit basics to help you get started. + +### Keypair generation + +For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're required to generate a new keypair. + +```shell +solana-keygen new +``` + +The above command will both: + +- print the pubkey generated +- store the your new keypair at the Solana CLI's default path (`~/.config/solana/id.json`) unless you already have a keypair saved there + +Check the pubkey of your machine's newly generated keypair: + +```shell +solana address +``` + +### Configuration + +Check your current configuration: + +```shell +solana config get +``` + +You can configure your RPC to connect to either mainnet, testnet, devnet, or your localhost. + +When using this toolkit, most of the time you'll want to be connected to a local node. + +Update your Solana configuration to connect to localhost: + +```shell +solana config set --url localhost +``` + +To test locally, you must also spin up a local node to run on your localhost: + +```shell +solana-test-validator +``` + +To log the network run: + +```shell +solana logs +``` + +For a more information, read this [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). + +## Creating a New Project + +To start a new project with the Solana toolkit, pick which scaffold you want to use. There are scaffolds for: + +- [Anchor framework workspaces](#anchor-smart-contract-scaffold) +- [general scaffolds using `create-solana-program`](#general-smart-contract-scaffold) +- [web app workspaces](#web-app-scaffold) +- [mobile app workspaces](#mobile-app-templates) + +### Anchor Smart Contract Scaffold + +```shell +anchor init +``` + +This initializes a simplistic workspace set up for Anchor smart contract development, with the following structure: + +- `Anchor.toml`: Anchor configuration file. +- `Cargo.toml`: Rust workspace configuration file. +- `package.json`: JavaScript dependencies file. +- `programs/`: Directory for Solana program crates. +- `app/`: Directory for your application frontend. +- `tests/`: Directory for JavaScript integration tests. +- `migrations/deploy.js`: Deploy script. + +The Anchor framework abstracts away many complexities enabling fast program development. + +To test out this project before making any modifications, just build and test: + +```shell +anchor build +``` + +```shell +anchor test +``` + +To start writing your own anchor smart contract, navigate to `programs/src/lib.rs`. + +For more complex programs, using a more structured project template would be best practice. This can be generated with: + +```shell +anchor init --template multiple +``` + +which creates the following layout inside of `programs/src`: + +```shell +├── constants.rs +├── error.rs +├── instructions +│ ├── initialize.rs +│ └── mod.rs +├── lib.rs +└── state + └── mod.rs +``` + +For more information on the Anchor framework, check out the [Anchor book](https://www.anchor-lang.com/). + +### General Smart Contract Scaffold - Create Solana Program + +```shell +pnpm create solana-program +``` + +This initializes a more complex workspace with everything you need for general Solana smart contract development. This Scaffold allows you to write either native rust smart contracts or anchor smart contracts. + +After running this command, you'll have the option to choose between Shank and Anchor for the program framework: + +- **Shank** creates a vanilla Solana smart contract with Shank macros to generate IDLs. For more information on Shank, read the [README](https://github.com/metaplex-foundation/shank). + +- **Anchor** creates a smart contract using the Anchor framework, which abstracts away many complexities enabling fast program development. For more information on the Anchor framework, read the [Anchor book](https://www.anchor-lang.com/). + +Next, you'll have the option to choose between a JavaScript client, a Rust Client, or both. + +- **JavaScript Client** creates a typescript library compatible with [web3.js](https://solana-labs.github.io/solana-web3.js/). + +- **Rust Client** creates a rust crate allowing consumers to interact with the smart contract. + +For further workspace customization and additional information, check out the `create-solana-program` [README](https://github.com/solana-program/create-solana-program/tree/main). + +After answering the above questions, the workspace will be generated. To get started, build your program and clients by running: + +```shell +cd +pnpm install +pnpm generate +``` + +#### Native Rust Smart Contract Development with Create Solana Program + +To use `create-solana-program` for native rust development, make sure you chose Shank when asked which program framework to use. This will create a basic counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +#### Anchor Smart Contract Development with Create Solana Program + +To use `create-solana-program` for native rust development, make sure you chose Anchor when asked which program framework to use. This will create a basic counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── lib.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +### Web App Scaffold + +```shell +npx create-solana-dapp +``` + +This command generates a new project that connects a Solana smart contract to a frontend with a wallet connector. + +For additional information, check out its [README](https://github.com/solana-developers/create-solana-dapp). + +To test out this project before making any modifications, follow these steps: + +1. Build the smart contract: + +```shell +npm run anchor-build +``` + +2. Start the local validator: + +```shell +npm run anchor-localnet +``` + +3. Run tests: + +```shell +npm run anchor-test +``` + +4. Deploy to the local validator: + +```shell +npm run anchor deploy --provider.cluster localnet +``` + +5. Build the web app: + +```shell +npm run build +``` + +6. Run the web app: + +```shell +npm run dev +``` + +### Mobile App Templates + +```shell +yarn create expo-app --template @solana-mobile/solana-mobile-expo-template +``` + +This is initializing a new project using the Expo framework that is specifically designed for creating mobile applications that interact with the Solana blockchain. + +Follow their [Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) guide to launch the template as a custom development build and get it running on your Android emulator. Once you have built the program and are running a dev client with Expo, the emulator will automatically update every time you save your code. + +To use this template, you will also need to set up the following: + +- [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) +- [React Native](https://reactnative.dev/docs/environment-setup?platform=android) +- [EAS CLI and Account](https://docs.expo.dev/build/setup/) + +For additional information on Solana Mobile Development: https://docs.solanamobile.com/getting-started/intro + +## Smart Contract File Structure Best Practices + +Typically Solana smart contract (aka [programs](/docs/core/programs.md)) workspaces will be have the following file structure: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs +├── target +└── tests +``` + +The main smart contract is the `lib.rs` file, which lives insides the `programs` directory, as shown below: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs + ├── src + ├── lib.rs +├── target +└── tests +``` + +As the smart contract gets more cumbersome, you'll typically want to separate the logic into multiple files, as shown below: + +```shell +├── programs + ├── src + ├── state.rs + ├── instructions + ├── instruction_1.rs + ├── instruction_2.rs + ├── instruction_3.rs + ├── lib.rs + ├── constants.rs + ├── error.rs + ├── mod.rs +``` + +For native rust smart contract development, you need to explicitly write out the entrypoint and processor for the program, so you'll need a few more files: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├──assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +## Working on an Existing Project + +If you have an existing anchor program and want to use the [create solana program tool](#general-smart-contract-scaffold), you can easily replace the generated program with your existing one: + +1. Ensure the installed Solana and Anchor versions are the same as the ones your existing program requires. + +2. Scaffold a new Solana program using Anchor. `pnpm create solana-program --anchor`. + +3. Replace the `program` folder with your existing program directory (not the workspace directory). If you have more than one program, add more folders to the root directory and update the `members` attribute of the top-level `Cargo.toml` accordingly. + +4. Ensure your program’s `Cargo.toml` contains the following metadata: + +``` +[package.metadata.solana] +program-id = "YOUR_PROGRAM_ADDRESS" +program-dependencies = [] +``` + +5. Build your program and clients. + +``` +pnpm install +pnpm programs:build +pnpm generate +``` + +6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` file so the `ID` alias points to the correct generated constant. + +7. If you have any generated clients, update the scaffolded tests so they work with your existing program. + +## Dependencies?? + +/// FIXME: Can we do anything similar to: https://book.getfoundry.sh/projects/dependencies ?? + +## Solana Test Suite Overview + +Within the Solana toolkit, there are several resources for testing Solana Smart Contracts, including: + +- Zest - A fuzzer +- A code coverage tool +- A framework for testing Solana programs in NodeJS that spins up a lightweight `BanksServer` that's like an RPC node but much faster and creates a `BanksClient` to talk to the server. +- A fast and lightweight library for testing Solana programs in Rust, which works by creating an in-process Solana VM optimized for program developers. +- A tool to scan your repo for common security vulnerabilities and provide suggestions for fixes. +- A reference guide of important cheat codes to simplify writing tests. + +### Testing Basics + +Sync all the program's key. If you're using an Anchor program: + +```shell +anchor keys sync +``` + +Build the smart contract: + +```shell +npx solana build +``` + +Test the smart contract: + +```shell +npx solana test +``` + +Deploy the smart contract: + +```shell +npx solana deploy +``` + +If deploying to localnet, you must first start your local validator: + +```shell +solana-test-validator +``` + +For more information on local validator customization and commands, read the [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). + +### Fuzz Tester + +Generate fuzz tests: + +```shell +npx solana fuzz +``` + +This command will initialize a Trident workspace and generate a new Fuzz Test Template: + +```shell +project-root +├── trident-tests +│ ├── fuzz_tests # fuzz tests folder +│ │ ├── fuzz_0 # particular fuzz test +│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test +│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test +│ │ ├── fuzz_1 +│ │ ├── fuzz_X # possible multiple fuzz tests +│ │ ├── fuzzing # compilations and crashes folder +│ │ └── Cargo.toml +├── Trident.toml +└── ... +``` + +Run fuzz tests: + +```shell +npx solana fuzz run +``` + +The output of the fuzz tests is as follows: + +1. Number of Fuzzing Iterations. +2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. feedback based on Coverage progress). +3. Average Iterations per second. +4. Number of crashes it found (panics or failed invariant checks). + +```shell +------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- + Iterations : 688 (out of: 1000 [68%]) # -- 1. -- + Mode [3/3] : Feedback Driven Mode # -- 2. -- + Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 + Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] + Speed : 680/sec [avg: 688] # -- 3. -- + Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- + Timeouts : 0 [10 sec] + Corpus Size : 98, max: 1048576 bytes, init: 0 files + Cov Update : 0 days 00 hrs 00 mins 00 secs ago + Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 +---------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- +``` + +View the source code [here](https://github.com/Ackee-Blockchain/trident). + +### Code Coverage Tool + +```shell +npx solana coverage +``` + +This command will run a code coverage test on all of your Rust tests and then generate report in an HTML page with in depth metrics on where additional code may be needed to improve your current code coverage. + +Note: So far, this tool only works on tests written in Rust and is not compatible with a JavaScript test suite. + +View the source code [here](https://github.com/LimeChain/zest?tab=readme-ov-file). + +### JavaScript Testing Framework + +```shell +npm install solana-bankrun +``` + +[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and lightweight framework for testing solana programs in NodeJS. + +It uses [solana-program-test](https://crates.io/crates/solana-program-test) under the hood and allows you to do things that are not possible with `solana-test-validator`, such as jumping back and forth in time or dynamically setting account data. + +Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node but much faster, and creating a `BanksClient` to talk to the server. This runs the Solana [Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). + +Here is a minimal example of this framework: + +```javascript +import { start } from "solana-bankrun"; +import { PublicKey, Transaction, SystemProgram } from "@solana/web3.js"; + +test("one transfer", async () => { + const context = await start([], []); + const client = context.banksClient; + const payer = context.payer; + const receiver = PublicKey.unique(); + const blockhash = context.lastBlockhash; + const transferLamports = 1_000_000n; + const ixs = [ + SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: receiver, + lamports: transferLamports, + }), + ]; + const tx = new Transaction(); + tx.recentBlockhash = blockhash; + tx.add(...ixs); + tx.sign(payer); + await client.processTransaction(tx); + const balanceAfter = await client.getBalance(receiver); + expect(balanceAfter).toEqual(transferLamports); +}); +``` + +For more complex examples, please refer to the [Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) + +### Rust Testing Library + +```shell +cargo add --dev litesvm +``` + +[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library for testing Solana programs. It works by creating an in-process Solana VM optimized for program developers. This makes it much faster to run and compile than alternatives like solana-program-test and solana-test-validator. In a further break from tradition, it has an ergonomic API with sane defaults and extensive configurability for those who want it. + +Here is a minimal example: + +```rust +use litesvm::LiteSVM; +use solana_program::{message::Message, pubkey::Pubkey, system_instruction::transfer}; +use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction}; + +let from_keypair = Keypair::new(); +let from = from_keypair.pubkey(); +let to = Pubkey::new_unique(); + +let mut svm = LiteSVM::new(); +svm.airdrop(&from, 10_000).unwrap(); + +let instruction = transfer(&from, &to, 64); +let tx = Transaction::new( + &[&from_keypair], + Message::new(&[instruction], Some(&from)), + svm.latest_blockhash(), +); +let tx_res = svm.send_transaction(tx).unwrap(); + +let from_account = svm.get_account(&from); +let to_account = svm.get_account(&to); +assert_eq!(from_account.unwrap().lamports, 4936); +assert_eq!(to_account.unwrap().lamports, 64); + +``` + +### Security Vulnerability Scanner + +[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static analysis tool for anchor rust programs. It allows you to write, share, and utilize templates to identify security issues in rust-based smart contracts using a powerful python based rule engine that enables automating detection of vulnerable code patterns through logical expressions. + +[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform command-line interface (CLI) tool designed for static analysis of Solana programs and smart contracts written in Rust. + +## Running a local network + +The Solana test validator is a local emulator for the Solana blockchain, designed to provide developers with a private and controlled environment for building and testing Solana programs without the need to connect to a public testnet or mainnet. If you have the Solana CLI tool suite already installed, you can run the test validator with the following command: + +```shell +solana-test-validator +``` + +Advantages # + +- Ability to reset the blockchain state at any moment +- Ability to simulate different network conditions +- No RPC rate-limits +- No airdrop limits +- Direct on-chain program deployment +- Ability to clone accounts from a public cluster +- Ability to load accounts from files +- Configurable transaction history retention +- Configurable epoch length +- Installation # + +Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure you have Solana's command-line tools installed. You can install the entire Solana toolkit (which includes the Solana CLI) using the following command: + +```shell +npx solana install +``` + +Or install just the Solana CLI with: + +```shell +sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)" +``` + +You can replace `stable` with the release tag matching the software version of your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel names: `stable`, `beta`, or `edge`. + +### Starting the Test Validator + +To start your local validator, simply run: + +```shell +solana-test-validator +``` + +This command initializes a new ledger and starts the validator. + +### Interacting with a Running Test Validator + +Once you have the `solana-test-validator` up and running, you can interact with it using various Solana CLI commands. These commands let you deploy programs, manage accounts, send transactions, and much more. Below is a detailed guide on the key commands you will use. + +Check your current CLI configuration to see which network you are selected too: + +```shell +solana config get +``` + +If needed update your Solana configuration to connect to your test validator running on localhost: + +```shell +solana config set --url localhost +``` + +### Checking the Status of the Test Validator + +Before interacting with the test validator, it's useful to confirm its status and ensure it is running correctly. + +```shell +solana ping +``` + +This command pings the local test validator and returns the current blockhash and latency, verifying that it is active. + +### Account Management + +View the pubkey of your configured CLI keypair: + +```shell +solana address +``` + +View the current balance of your keypair: + +```shell +solana balance +``` + +To add SOL to your CLI keypair, request an airdrop: + +```shell +solana airdrop 10 +``` + +To retrieve details about any account, such as its balance and owner: + +```shell +solana account +``` + +You must first add SOL to an account for it to exist. This airdrop command requests 2 SOL to the specified account address: + +```shell +solana airdrop 2 +``` + +Aside from "wallet accounts" that only hold SOL, accounts are normally created by smart contracts (aka programs) so they can store the `data` desired by that program. + +### Deploying and Managing Programs + +To deploy a compiled program (BPF) to the test validator: + +```shell +solana program deploy +``` + +This uploads and deploys a program to the blockchain. + +To check the details of a deployed program: + +```shell +solana program show +``` + +### Sending Transactions + +To transfer SOL from one account to another: + +```shell +solana transfer --from /path/to/keypair.json +``` + +This sends `AMOUNT` of SOL from the source account to the `RECIPIENT_ADDRESS`. + +### Simulating and Confirming Transactions + +Before actually sending a transaction, you can simulate it to see if it would likely succeed: + +```shell +solana transfer --from /path/to/keypair.json --simulate +``` + +To confirm the details and status of a transaction: + +```shell +solana confirm +``` + +### Viewing Recent Block Production + +To see information about recent block production, which can be useful for debugging performance issues: + +```shell +solana block-production +``` + +### Creating Token Accounts + +### Adjusting Logs + +For debugging, you might want more detailed logs: + +```shell +solana logs +``` + +This streams log messages from the validator. + +### Tips for Logging + +- Increase log verbosity with the `-v` flag if you need more detailed output for debugging. +- Use the `--rpc-port` and `--rpc-bind-address` options to customize the RPC server settings. +- Adjust the number of CPU cores used by the validator with the `--gossip-host` option to simulate network conditions more realistically. + +### Configuration + +Check CLI Tool Suite configuration: + +```shell +solana genesis-hash +``` + +View all the configuration options available for the Solana test validator: + +```shell +solana-test-validator --help +``` + +### Local Ledger + +By default, the ledger data is stored in a directory named `test-ledger` in your current working directory. + +### Specifying Ledger Location + +When starting the test validator, you can specify a different directory for the ledger data using the `--ledger` option: + +```shell +solana-test-validator --ledger /path/to/custom/ledger +``` + +### Resetting the Ledger + +By default the validator will resume an existing ledger, if one is found. To reset the ledger, you can either manually delete the ledger directory or restart the validator with the `--reset` flag: + +```shell +solana-test-validator --reset +``` + +If the ledger exists, this command will reset the ledger to genesis, which resets the state by deleting all existing accounts and starting fresh. + +### Cloning Programs + +To add existing onchain programs to your local environment, you can clone the program with a new ledger. This is useful for testing interactions with other programs that already exist on any other cluster. + +To clone an account from another cluster: + +```shell +solana-test-validator --clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +``` + +To clone an upgradeable program and its executable data from another cluster: + +```shell +solana-test-validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +``` + +> If a ledger already exists in your working directory, you must reset the ledger to be able to clone a program. + +### Cloning Accounts + +To add existing onchain accounts to your local environment, you can clone the account with a new ledger from any other network cluster. + +To clone an account from the cluster when a ledger already exists: + +```shell +solana-test-validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset +``` + +### Reset to Specific Account Data + +To reset the state of specific accounts every time you start the validator, you can use a combination of account snapshots and the `--account` flag. + +First, save the desired state of an account as a JSON file: + +```shell +solana account ACCOUNT_ADDRESS --output json > account_state.json +``` + +Then load this state each time you reset the validator: + +```shell +solana-test-validator --reset --account ACCOUNT_ADDRESS account_state.json +``` + +### Runtime Features + +Solana has a feature set mechanism that allows you to enable or disable certain blockchain features when running the test validator. By default, the test validator runs with all runtime features activated. + +To see all the runtime features available and their statuses: + +```shell +solana feature status +``` + +To query a specific runtime feature's status: + +```shell +solana feature status
+``` + +To activate a specific feature: + +```shell +solana feature activate +``` + +- `FEATURE_KEYPAIR` is the signer for the feature to activate +- `CLUSTER` is the cluster to activate the feature on + +To deactivate specific features in genesis: + +```shell +solana-test-validator --deactivate-feature --reset +``` + +This must be done on a fresh ledger, so if a ledger already exists in your working directory you must add the `--reset` flag to reset to genesis. + +### Changing Versions + +To check your current `solana-test-validator` version: + +```shell +solana-test-validator --version +``` + +Your test validator runs on the same version as the Solana CLI installed and configured for use. + +To test your programs against different versions of the Solana runtime, you can install multiple versions of the Solana CLI and switch between them using the following command: + +```shell +solana-install init +``` + +Make sure to reset your Solana test validator's ledger after changing versions to ensure it runs a valid ledger without corruption. + +## Compute and Fees Section + +In Solana program development, you don't need to track gas but it is best practice to optimize for compute. For more information on how to optimize compute, read the this [guide](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). + +To understand more about fees on Solana, read this [document](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). From 8d35de25d9af1d70dddb97326b4fe072032065cf Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 20 Dec 2024 12:15:11 -0500 Subject: [PATCH 02/25] prettier:fix --- content/cookbook/wallets/sign-message.md | 3 +- .../getstarted/local-rust-hello-world.md | 4 +- docs/toolkit/index.md | 312 +++++++++++++----- 3 files changed, 227 insertions(+), 92 deletions(-) diff --git a/content/cookbook/wallets/sign-message.md b/content/cookbook/wallets/sign-message.md index fe6488b23..42a07f1fd 100644 --- a/content/cookbook/wallets/sign-message.md +++ b/content/cookbook/wallets/sign-message.md @@ -8,7 +8,8 @@ The primary function of a keypair is to sign messages, transactions and enable verification of the signature. Verification of a signature allows the recipient to be sure that the data was signed by the owner of a specific private key. - + + ```typescript import { diff --git a/content/guides/getstarted/local-rust-hello-world.md b/content/guides/getstarted/local-rust-hello-world.md index a8ea90c83..83ba94e73 100644 --- a/content/guides/getstarted/local-rust-hello-world.md +++ b/content/guides/getstarted/local-rust-hello-world.md @@ -228,8 +228,8 @@ library. ### Install Node.js To use node in WSL2 on Windows, please follow this -[guide to installing node in WSL2](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) to -install node. +[guide to installing node in WSL2](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) +to install node. ```shell sudo apt-get install curl diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 8b0eeba6f..08b7e32fc 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -2,7 +2,8 @@ title: The Solana Toolkit --- -The Solana Toolkit consists of all open sourced tools for smart contract development on the Solana Blockchain. +The Solana Toolkit consists of all open sourced tools for smart contract +development on the Solana Blockchain. You can contribute to this book on [GitHub](). @@ -16,11 +17,17 @@ npx solana install This will install the latest versions of the following: -- [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line tool that allows developers to interact with the Solana blockchain, manage accounts, send transactions, and deploy programs. -- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana Smart Contracts are written in. -- [Anchor](https://www.anchor-lang.com/): A framework for writing Solana programs that abstracts many complexities to speed up smart contract development. +- [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line + tool that allows developers to interact with the Solana blockchain, manage + accounts, send transactions, and deploy programs. +- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana + Smart Contracts are written in. +- [Anchor](https://www.anchor-lang.com/): A framework for writing Solana + programs that abstracts many complexities to speed up smart contract + development. - [Trident](https://ackee.xyz/trident/docs/latest/): A fuzz tester -- [Zest](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage tool +- [Zest](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage + tool ## Getting Started @@ -28,7 +35,8 @@ This section will cover all the toolkit basics to help you get started. ### Keypair generation -For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're required to generate a new keypair. +For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're +required to generate a new keypair. ```shell solana-keygen new @@ -37,7 +45,8 @@ solana-keygen new The above command will both: - print the pubkey generated -- store the your new keypair at the Solana CLI's default path (`~/.config/solana/id.json`) unless you already have a keypair saved there +- store the your new keypair at the Solana CLI's default path + (`~/.config/solana/id.json`) unless you already have a keypair saved there Check the pubkey of your machine's newly generated keypair: @@ -53,9 +62,11 @@ Check your current configuration: solana config get ``` -You can configure your RPC to connect to either mainnet, testnet, devnet, or your localhost. +You can configure your RPC to connect to either mainnet, testnet, devnet, or +your localhost. -When using this toolkit, most of the time you'll want to be connected to a local node. +When using this toolkit, most of the time you'll want to be connected to a local +node. Update your Solana configuration to connect to localhost: @@ -75,11 +86,13 @@ To log the network run: solana logs ``` -For a more information, read this [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). +For a more information, read this +[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). ## Creating a New Project -To start a new project with the Solana toolkit, pick which scaffold you want to use. There are scaffolds for: +To start a new project with the Solana toolkit, pick which scaffold you want to +use. There are scaffolds for: - [Anchor framework workspaces](#anchor-smart-contract-scaffold) - [general scaffolds using `create-solana-program`](#general-smart-contract-scaffold) @@ -92,7 +105,8 @@ To start a new project with the Solana toolkit, pick which scaffold you want to anchor init ``` -This initializes a simplistic workspace set up for Anchor smart contract development, with the following structure: +This initializes a simplistic workspace set up for Anchor smart contract +development, with the following structure: - `Anchor.toml`: Anchor configuration file. - `Cargo.toml`: Rust workspace configuration file. @@ -102,7 +116,8 @@ This initializes a simplistic workspace set up for Anchor smart contract develop - `tests/`: Directory for JavaScript integration tests. - `migrations/deploy.js`: Deploy script. -The Anchor framework abstracts away many complexities enabling fast program development. +The Anchor framework abstracts away many complexities enabling fast program +development. To test out this project before making any modifications, just build and test: @@ -114,9 +129,11 @@ anchor build anchor test ``` -To start writing your own anchor smart contract, navigate to `programs/src/lib.rs`. +To start writing your own anchor smart contract, navigate to +`programs/src/lib.rs`. -For more complex programs, using a more structured project template would be best practice. This can be generated with: +For more complex programs, using a more structured project template would be +best practice. This can be generated with: ```shell anchor init --template multiple @@ -135,7 +152,8 @@ which creates the following layout inside of `programs/src`: └── mod.rs ``` -For more information on the Anchor framework, check out the [Anchor book](https://www.anchor-lang.com/). +For more information on the Anchor framework, check out the +[Anchor book](https://www.anchor-lang.com/). ### General Smart Contract Scaffold - Create Solana Program @@ -143,23 +161,37 @@ For more information on the Anchor framework, check out the [Anchor book](https: pnpm create solana-program ``` -This initializes a more complex workspace with everything you need for general Solana smart contract development. This Scaffold allows you to write either native rust smart contracts or anchor smart contracts. +This initializes a more complex workspace with everything you need for general +Solana smart contract development. This Scaffold allows you to write either +native rust smart contracts or anchor smart contracts. -After running this command, you'll have the option to choose between Shank and Anchor for the program framework: +After running this command, you'll have the option to choose between Shank and +Anchor for the program framework: -- **Shank** creates a vanilla Solana smart contract with Shank macros to generate IDLs. For more information on Shank, read the [README](https://github.com/metaplex-foundation/shank). +- **Shank** creates a vanilla Solana smart contract with Shank macros to + generate IDLs. For more information on Shank, read the + [README](https://github.com/metaplex-foundation/shank). -- **Anchor** creates a smart contract using the Anchor framework, which abstracts away many complexities enabling fast program development. For more information on the Anchor framework, read the [Anchor book](https://www.anchor-lang.com/). +- **Anchor** creates a smart contract using the Anchor framework, which + abstracts away many complexities enabling fast program development. For more + information on the Anchor framework, read the + [Anchor book](https://www.anchor-lang.com/). -Next, you'll have the option to choose between a JavaScript client, a Rust Client, or both. +Next, you'll have the option to choose between a JavaScript client, a Rust +Client, or both. -- **JavaScript Client** creates a typescript library compatible with [web3.js](https://solana-labs.github.io/solana-web3.js/). +- **JavaScript Client** creates a typescript library compatible with + [web3.js](https://solana-labs.github.io/solana-web3.js/). -- **Rust Client** creates a rust crate allowing consumers to interact with the smart contract. +- **Rust Client** creates a rust crate allowing consumers to interact with the + smart contract. -For further workspace customization and additional information, check out the `create-solana-program` [README](https://github.com/solana-program/create-solana-program/tree/main). +For further workspace customization and additional information, check out the +`create-solana-program` +[README](https://github.com/solana-program/create-solana-program/tree/main). -After answering the above questions, the workspace will be generated. To get started, build your program and clients by running: +After answering the above questions, the workspace will be generated. To get +started, build your program and clients by running: ```shell cd @@ -169,7 +201,9 @@ pnpm generate #### Native Rust Smart Contract Development with Create Solana Program -To use `create-solana-program` for native rust development, make sure you chose Shank when asked which program framework to use. This will create a basic counter program with the following project structure for your program: +To use `create-solana-program` for native rust development, make sure you chose +Shank when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: ```shell ├── program.rs @@ -189,7 +223,9 @@ To use `create-solana-program` for native rust development, make sure you chose #### Anchor Smart Contract Development with Create Solana Program -To use `create-solana-program` for native rust development, make sure you chose Anchor when asked which program framework to use. This will create a basic counter program with the following project structure for your program: +To use `create-solana-program` for native rust development, make sure you chose +Anchor when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: ```shell ├── program.rs @@ -206,9 +242,11 @@ To use `create-solana-program` for native rust development, make sure you chose npx create-solana-dapp ``` -This command generates a new project that connects a Solana smart contract to a frontend with a wallet connector. +This command generates a new project that connects a Solana smart contract to a +frontend with a wallet connector. -For additional information, check out its [README](https://github.com/solana-developers/create-solana-dapp). +For additional information, check out its +[README](https://github.com/solana-developers/create-solana-dapp). To test out this project before making any modifications, follow these steps: @@ -254,9 +292,16 @@ npm run dev yarn create expo-app --template @solana-mobile/solana-mobile-expo-template ``` -This is initializing a new project using the Expo framework that is specifically designed for creating mobile applications that interact with the Solana blockchain. +This is initializing a new project using the Expo framework that is specifically +designed for creating mobile applications that interact with the Solana +blockchain. -Follow their [Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) guide to launch the template as a custom development build and get it running on your Android emulator. Once you have built the program and are running a dev client with Expo, the emulator will automatically update every time you save your code. +Follow their +[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) +guide to launch the template as a custom development build and get it running on +your Android emulator. Once you have built the program and are running a dev +client with Expo, the emulator will automatically update every time you save +your code. To use this template, you will also need to set up the following: @@ -264,11 +309,13 @@ To use this template, you will also need to set up the following: - [React Native](https://reactnative.dev/docs/environment-setup?platform=android) - [EAS CLI and Account](https://docs.expo.dev/build/setup/) -For additional information on Solana Mobile Development: https://docs.solanamobile.com/getting-started/intro +For additional information on Solana Mobile Development: +https://docs.solanamobile.com/getting-started/intro ## Smart Contract File Structure Best Practices -Typically Solana smart contract (aka [programs](/docs/core/programs.md)) workspaces will be have the following file structure: +Typically Solana smart contract (aka [programs](/docs/core/programs.md)) +workspaces will be have the following file structure: ```shell . @@ -280,7 +327,8 @@ Typically Solana smart contract (aka [programs](/docs/core/programs.md)) workspa └── tests ``` -The main smart contract is the `lib.rs` file, which lives insides the `programs` directory, as shown below: +The main smart contract is the `lib.rs` file, which lives insides the `programs` +directory, as shown below: ```shell . @@ -294,7 +342,8 @@ The main smart contract is the `lib.rs` file, which lives insides the `programs` └── tests ``` -As the smart contract gets more cumbersome, you'll typically want to separate the logic into multiple files, as shown below: +As the smart contract gets more cumbersome, you'll typically want to separate +the logic into multiple files, as shown below: ```shell ├── programs @@ -310,7 +359,8 @@ As the smart contract gets more cumbersome, you'll typically want to separate th ├── mod.rs ``` -For native rust smart contract development, you need to explicitly write out the entrypoint and processor for the program, so you'll need a few more files: +For native rust smart contract development, you need to explicitly write out the +entrypoint and processor for the program, so you'll need a few more files: ```shell ├── program.rs @@ -330,13 +380,20 @@ For native rust smart contract development, you need to explicitly write out the ## Working on an Existing Project -If you have an existing anchor program and want to use the [create solana program tool](#general-smart-contract-scaffold), you can easily replace the generated program with your existing one: +If you have an existing anchor program and want to use the +[create solana program tool](#general-smart-contract-scaffold), you can easily +replace the generated program with your existing one: -1. Ensure the installed Solana and Anchor versions are the same as the ones your existing program requires. +1. Ensure the installed Solana and Anchor versions are the same as the ones your + existing program requires. -2. Scaffold a new Solana program using Anchor. `pnpm create solana-program --anchor`. +2. Scaffold a new Solana program using Anchor. + `pnpm create solana-program --anchor`. -3. Replace the `program` folder with your existing program directory (not the workspace directory). If you have more than one program, add more folders to the root directory and update the `members` attribute of the top-level `Cargo.toml` accordingly. +3. Replace the `program` folder with your existing program directory (not the + workspace directory). If you have more than one program, add more folders to + the root directory and update the `members` attribute of the top-level + `Cargo.toml` accordingly. 4. Ensure your program’s `Cargo.toml` contains the following metadata: @@ -354,23 +411,31 @@ pnpm programs:build pnpm generate ``` -6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` file so the `ID` alias points to the correct generated constant. +6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` + file so the `ID` alias points to the correct generated constant. -7. If you have any generated clients, update the scaffolded tests so they work with your existing program. +7. If you have any generated clients, update the scaffolded tests so they work + with your existing program. ## Dependencies?? -/// FIXME: Can we do anything similar to: https://book.getfoundry.sh/projects/dependencies ?? +/// FIXME: Can we do anything similar to: +https://book.getfoundry.sh/projects/dependencies ?? ## Solana Test Suite Overview -Within the Solana toolkit, there are several resources for testing Solana Smart Contracts, including: +Within the Solana toolkit, there are several resources for testing Solana Smart +Contracts, including: - Zest - A fuzzer - A code coverage tool -- A framework for testing Solana programs in NodeJS that spins up a lightweight `BanksServer` that's like an RPC node but much faster and creates a `BanksClient` to talk to the server. -- A fast and lightweight library for testing Solana programs in Rust, which works by creating an in-process Solana VM optimized for program developers. -- A tool to scan your repo for common security vulnerabilities and provide suggestions for fixes. +- A framework for testing Solana programs in NodeJS that spins up a lightweight + `BanksServer` that's like an RPC node but much faster and creates a + `BanksClient` to talk to the server. +- A fast and lightweight library for testing Solana programs in Rust, which + works by creating an in-process Solana VM optimized for program developers. +- A tool to scan your repo for common security vulnerabilities and provide + suggestions for fixes. - A reference guide of important cheat codes to simplify writing tests. ### Testing Basics @@ -405,7 +470,8 @@ If deploying to localnet, you must first start your local validator: solana-test-validator ``` -For more information on local validator customization and commands, read the [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). +For more information on local validator customization and commands, read the +[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). ### Fuzz Tester @@ -415,7 +481,8 @@ Generate fuzz tests: npx solana fuzz ``` -This command will initialize a Trident workspace and generate a new Fuzz Test Template: +This command will initialize a Trident workspace and generate a new Fuzz Test +Template: ```shell project-root @@ -441,7 +508,8 @@ npx solana fuzz run The output of the fuzz tests is as follows: 1. Number of Fuzzing Iterations. -2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. feedback based on Coverage progress). +2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. + feedback based on Coverage progress). 3. Average Iterations per second. 4. Number of crashes it found (panics or failed invariant checks). @@ -468,11 +536,15 @@ View the source code [here](https://github.com/Ackee-Blockchain/trident). npx solana coverage ``` -This command will run a code coverage test on all of your Rust tests and then generate report in an HTML page with in depth metrics on where additional code may be needed to improve your current code coverage. +This command will run a code coverage test on all of your Rust tests and then +generate report in an HTML page with in depth metrics on where additional code +may be needed to improve your current code coverage. -Note: So far, this tool only works on tests written in Rust and is not compatible with a JavaScript test suite. +Note: So far, this tool only works on tests written in Rust and is not +compatible with a JavaScript test suite. -View the source code [here](https://github.com/LimeChain/zest?tab=readme-ov-file). +View the source code +[here](https://github.com/LimeChain/zest?tab=readme-ov-file). ### JavaScript Testing Framework @@ -480,11 +552,18 @@ View the source code [here](https://github.com/LimeChain/zest?tab=readme-ov-file npm install solana-bankrun ``` -[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and lightweight framework for testing solana programs in NodeJS. +[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and +lightweight framework for testing solana programs in NodeJS. -It uses [solana-program-test](https://crates.io/crates/solana-program-test) under the hood and allows you to do things that are not possible with `solana-test-validator`, such as jumping back and forth in time or dynamically setting account data. +It uses [solana-program-test](https://crates.io/crates/solana-program-test) +under the hood and allows you to do things that are not possible with +`solana-test-validator`, such as jumping back and forth in time or dynamically +setting account data. -Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node but much faster, and creating a `BanksClient` to talk to the server. This runs the Solana [Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). +Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node +but much faster, and creating a `BanksClient` to talk to the server. This runs +the Solana +[Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). Here is a minimal example of this framework: @@ -516,7 +595,8 @@ test("one transfer", async () => { }); ``` -For more complex examples, please refer to the [Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) +For more complex examples, please refer to the +[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) ### Rust Testing Library @@ -524,7 +604,12 @@ For more complex examples, please refer to the [Solana Developers Bootcamp](http cargo add --dev litesvm ``` -[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library for testing Solana programs. It works by creating an in-process Solana VM optimized for program developers. This makes it much faster to run and compile than alternatives like solana-program-test and solana-test-validator. In a further break from tradition, it has an ergonomic API with sane defaults and extensive configurability for those who want it. +[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library +for testing Solana programs. It works by creating an in-process Solana VM +optimized for program developers. This makes it much faster to run and compile +than alternatives like solana-program-test and solana-test-validator. In a +further break from tradition, it has an ergonomic API with sane defaults and +extensive configurability for those who want it. Here is a minimal example: @@ -557,13 +642,23 @@ assert_eq!(to_account.unwrap().lamports, 64); ### Security Vulnerability Scanner -[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static analysis tool for anchor rust programs. It allows you to write, share, and utilize templates to identify security issues in rust-based smart contracts using a powerful python based rule engine that enables automating detection of vulnerable code patterns through logical expressions. +[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static +analysis tool for anchor rust programs. It allows you to write, share, and +utilize templates to identify security issues in rust-based smart contracts +using a powerful python based rule engine that enables automating detection of +vulnerable code patterns through logical expressions. -[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform command-line interface (CLI) tool designed for static analysis of Solana programs and smart contracts written in Rust. +[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform +command-line interface (CLI) tool designed for static analysis of Solana +programs and smart contracts written in Rust. ## Running a local network -The Solana test validator is a local emulator for the Solana blockchain, designed to provide developers with a private and controlled environment for building and testing Solana programs without the need to connect to a public testnet or mainnet. If you have the Solana CLI tool suite already installed, you can run the test validator with the following command: +The Solana test validator is a local emulator for the Solana blockchain, +designed to provide developers with a private and controlled environment for +building and testing Solana programs without the need to connect to a public +testnet or mainnet. If you have the Solana CLI tool suite already installed, you +can run the test validator with the following command: ```shell solana-test-validator @@ -582,7 +677,9 @@ Advantages # - Configurable epoch length - Installation # -Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure you have Solana's command-line tools installed. You can install the entire Solana toolkit (which includes the Solana CLI) using the following command: +Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure +you have Solana's command-line tools installed. You can install the entire +Solana toolkit (which includes the Solana CLI) using the following command: ```shell npx solana install @@ -594,7 +691,9 @@ Or install just the Solana CLI with: sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)" ``` -You can replace `stable` with the release tag matching the software version of your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel names: `stable`, `beta`, or `edge`. +You can replace `stable` with the release tag matching the software version of +your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel +names: `stable`, `beta`, or `edge`. ### Starting the Test Validator @@ -608,7 +707,10 @@ This command initializes a new ledger and starts the validator. ### Interacting with a Running Test Validator -Once you have the `solana-test-validator` up and running, you can interact with it using various Solana CLI commands. These commands let you deploy programs, manage accounts, send transactions, and much more. Below is a detailed guide on the key commands you will use. +Once you have the `solana-test-validator` up and running, you can interact with +it using various Solana CLI commands. These commands let you deploy programs, +manage accounts, send transactions, and much more. Below is a detailed guide on +the key commands you will use. Check your current CLI configuration to see which network you are selected too: @@ -616,7 +718,8 @@ Check your current CLI configuration to see which network you are selected too: solana config get ``` -If needed update your Solana configuration to connect to your test validator running on localhost: +If needed update your Solana configuration to connect to your test validator +running on localhost: ```shell solana config set --url localhost @@ -624,13 +727,15 @@ solana config set --url localhost ### Checking the Status of the Test Validator -Before interacting with the test validator, it's useful to confirm its status and ensure it is running correctly. +Before interacting with the test validator, it's useful to confirm its status +and ensure it is running correctly. ```shell solana ping ``` -This command pings the local test validator and returns the current blockhash and latency, verifying that it is active. +This command pings the local test validator and returns the current blockhash +and latency, verifying that it is active. ### Account Management @@ -658,13 +763,16 @@ To retrieve details about any account, such as its balance and owner: solana account ``` -You must first add SOL to an account for it to exist. This airdrop command requests 2 SOL to the specified account address: +You must first add SOL to an account for it to exist. This airdrop command +requests 2 SOL to the specified account address: ```shell solana airdrop 2 ``` -Aside from "wallet accounts" that only hold SOL, accounts are normally created by smart contracts (aka programs) so they can store the `data` desired by that program. +Aside from "wallet accounts" that only hold SOL, accounts are normally created +by smart contracts (aka programs) so they can store the `data` desired by that +program. ### Deploying and Managing Programs @@ -694,7 +802,8 @@ This sends `AMOUNT` of SOL from the source account to the `RECIPIENT_ADDRESS`. ### Simulating and Confirming Transactions -Before actually sending a transaction, you can simulate it to see if it would likely succeed: +Before actually sending a transaction, you can simulate it to see if it would +likely succeed: ```shell solana transfer --from /path/to/keypair.json --simulate @@ -708,7 +817,8 @@ solana confirm ### Viewing Recent Block Production -To see information about recent block production, which can be useful for debugging performance issues: +To see information about recent block production, which can be useful for +debugging performance issues: ```shell solana block-production @@ -728,9 +838,12 @@ This streams log messages from the validator. ### Tips for Logging -- Increase log verbosity with the `-v` flag if you need more detailed output for debugging. -- Use the `--rpc-port` and `--rpc-bind-address` options to customize the RPC server settings. -- Adjust the number of CPU cores used by the validator with the `--gossip-host` option to simulate network conditions more realistically. +- Increase log verbosity with the `-v` flag if you need more detailed output for + debugging. +- Use the `--rpc-port` and `--rpc-bind-address` options to customize the RPC + server settings. +- Adjust the number of CPU cores used by the validator with the `--gossip-host` + option to simulate network conditions more realistically. ### Configuration @@ -748,11 +861,13 @@ solana-test-validator --help ### Local Ledger -By default, the ledger data is stored in a directory named `test-ledger` in your current working directory. +By default, the ledger data is stored in a directory named `test-ledger` in your +current working directory. ### Specifying Ledger Location -When starting the test validator, you can specify a different directory for the ledger data using the `--ledger` option: +When starting the test validator, you can specify a different directory for the +ledger data using the `--ledger` option: ```shell solana-test-validator --ledger /path/to/custom/ledger @@ -760,17 +875,22 @@ solana-test-validator --ledger /path/to/custom/ledger ### Resetting the Ledger -By default the validator will resume an existing ledger, if one is found. To reset the ledger, you can either manually delete the ledger directory or restart the validator with the `--reset` flag: +By default the validator will resume an existing ledger, if one is found. To +reset the ledger, you can either manually delete the ledger directory or restart +the validator with the `--reset` flag: ```shell solana-test-validator --reset ``` -If the ledger exists, this command will reset the ledger to genesis, which resets the state by deleting all existing accounts and starting fresh. +If the ledger exists, this command will reset the ledger to genesis, which +resets the state by deleting all existing accounts and starting fresh. ### Cloning Programs -To add existing onchain programs to your local environment, you can clone the program with a new ledger. This is useful for testing interactions with other programs that already exist on any other cluster. +To add existing onchain programs to your local environment, you can clone the +program with a new ledger. This is useful for testing interactions with other +programs that already exist on any other cluster. To clone an account from another cluster: @@ -784,11 +904,13 @@ To clone an upgradeable program and its executable data from another cluster: solana-test-validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO ``` -> If a ledger already exists in your working directory, you must reset the ledger to be able to clone a program. +> If a ledger already exists in your working directory, you must reset the +> ledger to be able to clone a program. ### Cloning Accounts -To add existing onchain accounts to your local environment, you can clone the account with a new ledger from any other network cluster. +To add existing onchain accounts to your local environment, you can clone the +account with a new ledger from any other network cluster. To clone an account from the cluster when a ledger already exists: @@ -798,7 +920,8 @@ solana-test-validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_ ### Reset to Specific Account Data -To reset the state of specific accounts every time you start the validator, you can use a combination of account snapshots and the `--account` flag. +To reset the state of specific accounts every time you start the validator, you +can use a combination of account snapshots and the `--account` flag. First, save the desired state of an account as a JSON file: @@ -814,7 +937,9 @@ solana-test-validator --reset --account ACCOUNT_ADDRESS account_state.json ### Runtime Features -Solana has a feature set mechanism that allows you to enable or disable certain blockchain features when running the test validator. By default, the test validator runs with all runtime features activated. +Solana has a feature set mechanism that allows you to enable or disable certain +blockchain features when running the test validator. By default, the test +validator runs with all runtime features activated. To see all the runtime features available and their statuses: @@ -843,7 +968,8 @@ To deactivate specific features in genesis: solana-test-validator --deactivate-feature --reset ``` -This must be done on a fresh ledger, so if a ledger already exists in your working directory you must add the `--reset` flag to reset to genesis. +This must be done on a fresh ledger, so if a ledger already exists in your +working directory you must add the `--reset` flag to reset to genesis. ### Changing Versions @@ -853,18 +979,26 @@ To check your current `solana-test-validator` version: solana-test-validator --version ``` -Your test validator runs on the same version as the Solana CLI installed and configured for use. +Your test validator runs on the same version as the Solana CLI installed and +configured for use. -To test your programs against different versions of the Solana runtime, you can install multiple versions of the Solana CLI and switch between them using the following command: +To test your programs against different versions of the Solana runtime, you can +install multiple versions of the Solana CLI and switch between them using the +following command: ```shell solana-install init ``` -Make sure to reset your Solana test validator's ledger after changing versions to ensure it runs a valid ledger without corruption. +Make sure to reset your Solana test validator's ledger after changing versions +to ensure it runs a valid ledger without corruption. ## Compute and Fees Section -In Solana program development, you don't need to track gas but it is best practice to optimize for compute. For more information on how to optimize compute, read the this [guide](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). +In Solana program development, you don't need to track gas but it is best +practice to optimize for compute. For more information on how to optimize +compute, read the this +[guide](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). -To understand more about fees on Solana, read this [document](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). +To understand more about fees on Solana, read this +[document](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). From 0560e948f018d4376c25c23f26e6bc8461e0a716 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:24:42 -0500 Subject: [PATCH 03/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 08b7e32fc..acfc5d20b 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -5,7 +5,8 @@ title: The Solana Toolkit The Solana Toolkit consists of all open sourced tools for smart contract development on the Solana Blockchain. -You can contribute to this book on [GitHub](). +You can contribute to this book on +[GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). ## Installation From 2be5e7d280bd2e7e8b6a62f3f390c18d60b121af Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:24:54 -0500 Subject: [PATCH 04/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index acfc5d20b..810db0613 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -159,7 +159,7 @@ For more information on the Anchor framework, check out the ### General Smart Contract Scaffold - Create Solana Program ```shell -pnpm create solana-program +npx create-solana-program ``` This initializes a more complex workspace with everything you need for general From 004021a793d82090bce51d8c972b18154d962a74 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:24 -0500 Subject: [PATCH 05/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 810db0613..770575314 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -196,8 +196,8 @@ started, build your program and clients by running: ```shell cd -pnpm install -pnpm generate +npm install +npm dev generate ``` #### Native Rust Smart Contract Development with Create Solana Program From e450d14592ae148672843be5cd66fd25f83a819c Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:31 -0500 Subject: [PATCH 06/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 770575314..016950d8e 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -398,7 +398,7 @@ replace the generated program with your existing one: 4. Ensure your program’s `Cargo.toml` contains the following metadata: -``` +```toml filename="Cargo.toml" [package.metadata.solana] program-id = "YOUR_PROGRAM_ADDRESS" program-dependencies = [] From ba9168b665ea19ac716a311eb0c9674ec3419683 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:37 -0500 Subject: [PATCH 07/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 016950d8e..bcde5f1df 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -406,11 +406,10 @@ program-dependencies = [] 5. Build your program and clients. -``` -pnpm install -pnpm programs:build -pnpm generate -``` +```shell +npm install +npm run programs:build +npm run generate 6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` file so the `ID` alias points to the correct generated constant. From 6a9e75db80ffcb8b6ad60d69ed59578d4adb46e4 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:42 -0500 Subject: [PATCH 08/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index bcde5f1df..aa225f77c 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -533,7 +533,7 @@ View the source code [here](https://github.com/Ackee-Blockchain/trident). ### Code Coverage Tool ```shell -npx solana coverage +mucho coverage ``` This command will run a code coverage test on all of your Rust tests and then From 92b6ffd0f3b83feb0f48ca28d754b959a593f61d Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:48 -0500 Subject: [PATCH 09/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index aa225f77c..4055585a5 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -664,7 +664,7 @@ can run the test validator with the following command: solana-test-validator ``` -Advantages # +### Advantages - Ability to reset the blockchain state at any moment - Ability to simulate different network conditions From 792118b35e764c45324cc51e470a4244ec6b7256 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:52 -0500 Subject: [PATCH 10/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 4055585a5..18d02cb5a 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -662,7 +662,6 @@ can run the test validator with the following command: ```shell solana-test-validator -``` ### Advantages From 6d66d2ceafa098c001b2498ffd4c4bb136d00b67 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Fri, 3 Jan 2025 11:25:59 -0500 Subject: [PATCH 11/25] Update docs/toolkit/index.md Co-authored-by: Nick Frostbutter <75431177+nickfrosty@users.noreply.github.com> --- docs/toolkit/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 18d02cb5a..25ddf0747 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -549,7 +549,7 @@ View the source code ### JavaScript Testing Framework ```shell -npm install solana-bankrun +npm install solana-bankrun ``` [Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and From 72555519ce2f100a6d7974f1457b07dbd9cb5604 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:53:44 -0500 Subject: [PATCH 12/25] update docs --- docs/toolkit/best-practices.md | 90 +++ docs/toolkit/getting-started.md | 88 +++ docs/toolkit/index.md | 1003 +------------------------------ docs/toolkit/local-testing.md | 342 +++++++++++ docs/toolkit/projects.md | 263 ++++++++ docs/toolkit/test-suite.md | 230 +++++++ 6 files changed, 1036 insertions(+), 980 deletions(-) create mode 100644 docs/toolkit/best-practices.md create mode 100644 docs/toolkit/getting-started.md create mode 100644 docs/toolkit/local-testing.md create mode 100644 docs/toolkit/projects.md create mode 100644 docs/toolkit/test-suite.md diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md new file mode 100644 index 000000000..676817871 --- /dev/null +++ b/docs/toolkit/best-practices.md @@ -0,0 +1,90 @@ +--- +title: Solana Smart Contract Best Practices +--- + +## Smart Contract File Structure + +Typically Solana smart contract (aka [programs](/docs/core/programs.md)) +workspaces will be have the following file structure: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs +├── target +└── tests +``` + +The main smart contract is the `lib.rs` file, which lives insides the `programs` +directory, as shown below: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs + ├── src + ├── lib.rs +├── target +└── tests +``` + +As the smart contract gets more cumbersome, you'll typically want to separate +the logic into multiple files, as shown below: + +```shell +├── programs + ├── src + ├── state.rs + ├── instructions + ├── instruction_1.rs + ├── instruction_2.rs + ├── instruction_3.rs + ├── lib.rs + ├── constants.rs + ├── error.rs + ├── mod.rs +``` + +For native rust smart contract development, you need to explicitly write out the +entrypoint and processor for the program, so you'll need a few more files: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├──assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +## Optimize Compute Usage + +To prevent abuse of computational resources, each transaction is allocated a "compute budget". This budget specifies details about [compute units](https://solana.com/docs/core/fees#compute-units) and includes: + +- the compute costs associated with different types of operations the transaction may perform (compute units consumed per operation), +- the maximum number of compute units that a transaction can consume (compute unit limit), +- and the operational bounds the transaction must adhere to (like account data size limits) + +When the transaction consumes its entire compute budget (compute budget exhaustion), or exceeds a bound such as attempting to exceed the [max call stack depth](https://github.com/anza-xyz/agave/blob/b7bbe36918f23d98e2e73502e3c4cba78d395ba9/program-runtime/src/compute_budget.rs#L138) or [max loaded account](https://solana.com/docs/core/fees#accounts-data-size-limit) data size limit, the runtime halts the transaction processing and returns an error. Resulting in a failed transaction and no state changes (aside from the transaction fee being [collected](https://solana.com/docs/core/fees#fee-collection)). + +### Solana Developer Guides +- [How to Optimize Compute](https://solana.com/developers/guides/advanced/how-to-optimize-compute). +- [How to Request Optimal Compute](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute) + +## Saving Bumps + +Saving the bump to your Solana smart contract account state enables deterministic address generation, efficiency in address reconstruction, reduced transaction failure, and consistency across invocations. + +### Solana Developer Guides +- [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization#challenge) \ No newline at end of file diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md new file mode 100644 index 000000000..0175f50fe --- /dev/null +++ b/docs/toolkit/getting-started.md @@ -0,0 +1,88 @@ +--- +title: Getting Started +--- + +## Installation + +To get started, install The Solana toolkit: + +```shell +npx solana install +``` + +This will install the latest versions of the following: + +- [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line + tool that allows developers to interact with the Solana blockchain, manage + accounts, send transactions, and deploy programs. +- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana + Smart Contracts are written in. +- [Anchor](https://www.anchor-lang.com/): A framework for writing Solana + programs that abstracts many complexities to speed up smart contract + development. +- [Fuzz Tester](https://ackee.xyz/trident/docs/latest/): Rust-based Fuzzing + framework for Solana programs to help you ship secure code. +- [Code Coverage Tool](https://github.com/LimeChain/zest?tab=readme-ov-file): A + code coverage CLI tool for Solana programs. + +## Keypair generation + +For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're +required to generate a new keypair. + +```shell +solana-keygen new +``` + +The above command will both: + +- print the pubkey generated +- store the your new keypair at the Solana CLI's default path + (`~/.config/solana/id.json`) unless you already have a keypair saved there + +Get the pubkey of your machine's newly generated keypair: + +```shell +solana address +``` + +## Fund the CLI keypair + +```shell +solana airdrop 10 +``` + +## Network Configuration + +Check your current configuration: + +```shell +solana config get +``` + +You can configure your RPC to connect to either mainnet, testnet, devnet, or +your localhost. + +When using this toolkit, most of the time you'll want to be connected to a local +node. + +Update your Solana configuration to connect to localhost: + +```shell +solana config set --url localhost +``` + +To test locally, you must also spin up a local node to run on your localhost: + +```shell +solana-test-validator +``` + +To log the network run: + +```shell +solana logs +``` + +For a more information, read this +[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 25ddf0747..807a35fef 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -2,1002 +2,45 @@ title: The Solana Toolkit --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + The Solana Toolkit consists of all open sourced tools for smart contract development on the Solana Blockchain. You can contribute to this book on [GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). -## Installation - -To get started, install The Solana toolkit: - -```shell -npx solana install -``` - -This will install the latest versions of the following: - -- [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line - tool that allows developers to interact with the Solana blockchain, manage - accounts, send transactions, and deploy programs. -- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana - Smart Contracts are written in. -- [Anchor](https://www.anchor-lang.com/): A framework for writing Solana - programs that abstracts many complexities to speed up smart contract - development. -- [Trident](https://ackee.xyz/trident/docs/latest/): A fuzz tester -- [Zest](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage - tool - -## Getting Started - -This section will cover all the toolkit basics to help you get started. - -### Keypair generation - -For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're -required to generate a new keypair. - -```shell -solana-keygen new -``` - -The above command will both: - -- print the pubkey generated -- store the your new keypair at the Solana CLI's default path - (`~/.config/solana/id.json`) unless you already have a keypair saved there - -Check the pubkey of your machine's newly generated keypair: - -```shell -solana address -``` - -### Configuration - -Check your current configuration: - -```shell -solana config get -``` - -You can configure your RPC to connect to either mainnet, testnet, devnet, or -your localhost. - -When using this toolkit, most of the time you'll want to be connected to a local -node. - -Update your Solana configuration to connect to localhost: - -```shell -solana config set --url localhost -``` - -To test locally, you must also spin up a local node to run on your localhost: - -```shell -solana-test-validator -``` - -To log the network run: - -```shell -solana logs -``` - -For a more information, read this -[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). - -## Creating a New Project - -To start a new project with the Solana toolkit, pick which scaffold you want to -use. There are scaffolds for: - -- [Anchor framework workspaces](#anchor-smart-contract-scaffold) -- [general scaffolds using `create-solana-program`](#general-smart-contract-scaffold) -- [web app workspaces](#web-app-scaffold) -- [mobile app workspaces](#mobile-app-templates) - -### Anchor Smart Contract Scaffold - -```shell -anchor init -``` - -This initializes a simplistic workspace set up for Anchor smart contract -development, with the following structure: - -- `Anchor.toml`: Anchor configuration file. -- `Cargo.toml`: Rust workspace configuration file. -- `package.json`: JavaScript dependencies file. -- `programs/`: Directory for Solana program crates. -- `app/`: Directory for your application frontend. -- `tests/`: Directory for JavaScript integration tests. -- `migrations/deploy.js`: Deploy script. - -The Anchor framework abstracts away many complexities enabling fast program -development. - -To test out this project before making any modifications, just build and test: - -```shell -anchor build -``` - -```shell -anchor test -``` - -To start writing your own anchor smart contract, navigate to -`programs/src/lib.rs`. - -For more complex programs, using a more structured project template would be -best practice. This can be generated with: - -```shell -anchor init --template multiple -``` - -which creates the following layout inside of `programs/src`: - -```shell -├── constants.rs -├── error.rs -├── instructions -│ ├── initialize.rs -│ └── mod.rs -├── lib.rs -└── state - └── mod.rs -``` - -For more information on the Anchor framework, check out the -[Anchor book](https://www.anchor-lang.com/). - -### General Smart Contract Scaffold - Create Solana Program - -```shell -npx create-solana-program -``` - -This initializes a more complex workspace with everything you need for general -Solana smart contract development. This Scaffold allows you to write either -native rust smart contracts or anchor smart contracts. - -After running this command, you'll have the option to choose between Shank and -Anchor for the program framework: - -- **Shank** creates a vanilla Solana smart contract with Shank macros to - generate IDLs. For more information on Shank, read the - [README](https://github.com/metaplex-foundation/shank). - -- **Anchor** creates a smart contract using the Anchor framework, which - abstracts away many complexities enabling fast program development. For more - information on the Anchor framework, read the - [Anchor book](https://www.anchor-lang.com/). - -Next, you'll have the option to choose between a JavaScript client, a Rust -Client, or both. - -- **JavaScript Client** creates a typescript library compatible with - [web3.js](https://solana-labs.github.io/solana-web3.js/). - -- **Rust Client** creates a rust crate allowing consumers to interact with the - smart contract. - -For further workspace customization and additional information, check out the -`create-solana-program` -[README](https://github.com/solana-program/create-solana-program/tree/main). - -After answering the above questions, the workspace will be generated. To get -started, build your program and clients by running: - -```shell -cd -npm install -npm dev generate -``` - -#### Native Rust Smart Contract Development with Create Solana Program - -To use `create-solana-program` for native rust development, make sure you chose -Shank when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├── assertions.rs -│ │ ├──entrypoint.rs -│ │ ├──error.rs -│ │ ├──instruction.rs -│ │ ├──lib.rs -│ │ ├──processor.rs -│ │ ├──state.rs -│ │ ├──utils.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -#### Anchor Smart Contract Development with Create Solana Program - -To use `create-solana-program` for native rust development, make sure you chose -Anchor when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├── lib.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -### Web App Scaffold - -```shell -npx create-solana-dapp -``` - -This command generates a new project that connects a Solana smart contract to a -frontend with a wallet connector. - -For additional information, check out its -[README](https://github.com/solana-developers/create-solana-dapp). - -To test out this project before making any modifications, follow these steps: - -1. Build the smart contract: - -```shell -npm run anchor-build -``` - -2. Start the local validator: - -```shell -npm run anchor-localnet -``` - -3. Run tests: - -```shell -npm run anchor-test -``` - -4. Deploy to the local validator: - -```shell -npm run anchor deploy --provider.cluster localnet -``` - -5. Build the web app: - -```shell -npm run build -``` - -6. Run the web app: - -```shell -npm run dev -``` - -### Mobile App Templates - -```shell -yarn create expo-app --template @solana-mobile/solana-mobile-expo-template -``` - -This is initializing a new project using the Expo framework that is specifically -designed for creating mobile applications that interact with the Solana -blockchain. - -Follow their -[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) -guide to launch the template as a custom development build and get it running on -your Android emulator. Once you have built the program and are running a dev -client with Expo, the emulator will automatically update every time you save -your code. - -To use this template, you will also need to set up the following: - -- [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) -- [React Native](https://reactnative.dev/docs/environment-setup?platform=android) -- [EAS CLI and Account](https://docs.expo.dev/build/setup/) - -For additional information on Solana Mobile Development: -https://docs.solanamobile.com/getting-started/intro - -## Smart Contract File Structure Best Practices - -Typically Solana smart contract (aka [programs](/docs/core/programs.md)) -workspaces will be have the following file structure: - -```shell -. -├── app -├── migrations -├── node_modules -├── programs -├── target -└── tests -``` - -The main smart contract is the `lib.rs` file, which lives insides the `programs` -directory, as shown below: - -```shell -. -├── app -├── migrations -├── node_modules -├── programs - ├── src - ├── lib.rs -├── target -└── tests -``` - -As the smart contract gets more cumbersome, you'll typically want to separate -the logic into multiple files, as shown below: - -```shell -├── programs - ├── src - ├── state.rs - ├── instructions - ├── instruction_1.rs - ├── instruction_2.rs - ├── instruction_3.rs - ├── lib.rs - ├── constants.rs - ├── error.rs - ├── mod.rs -``` - -For native rust smart contract development, you need to explicitly write out the -entrypoint and processor for the program, so you'll need a few more files: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├──assertions.rs -│ │ ├──entrypoint.rs -│ │ ├──error.rs -│ │ ├──instruction.rs -│ │ ├──lib.rs -│ │ ├──processor.rs -│ │ ├──state.rs -│ │ ├──utils.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -## Working on an Existing Project - -If you have an existing anchor program and want to use the -[create solana program tool](#general-smart-contract-scaffold), you can easily -replace the generated program with your existing one: - -1. Ensure the installed Solana and Anchor versions are the same as the ones your - existing program requires. - -2. Scaffold a new Solana program using Anchor. - `pnpm create solana-program --anchor`. - -3. Replace the `program` folder with your existing program directory (not the - workspace directory). If you have more than one program, add more folders to - the root directory and update the `members` attribute of the top-level - `Cargo.toml` accordingly. - -4. Ensure your program’s `Cargo.toml` contains the following metadata: - -```toml filename="Cargo.toml" -[package.metadata.solana] -program-id = "YOUR_PROGRAM_ADDRESS" -program-dependencies = [] -``` - -5. Build your program and clients. - -```shell -npm install -npm run programs:build -npm run generate - -6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` - file so the `ID` alias points to the correct generated constant. - -7. If you have any generated clients, update the scaffolded tests so they work - with your existing program. - -## Dependencies?? - -/// FIXME: Can we do anything similar to: -https://book.getfoundry.sh/projects/dependencies ?? - -## Solana Test Suite Overview - -Within the Solana toolkit, there are several resources for testing Solana Smart -Contracts, including: - -- Zest - A fuzzer -- A code coverage tool -- A framework for testing Solana programs in NodeJS that spins up a lightweight - `BanksServer` that's like an RPC node but much faster and creates a - `BanksClient` to talk to the server. -- A fast and lightweight library for testing Solana programs in Rust, which - works by creating an in-process Solana VM optimized for program developers. -- A tool to scan your repo for common security vulnerabilities and provide - suggestions for fixes. -- A reference guide of important cheat codes to simplify writing tests. - -### Testing Basics - -Sync all the program's key. If you're using an Anchor program: - -```shell -anchor keys sync -``` - -Build the smart contract: - -```shell -npx solana build -``` - -Test the smart contract: - -```shell -npx solana test -``` - -Deploy the smart contract: - -```shell -npx solana deploy -``` - -If deploying to localnet, you must first start your local validator: - -```shell -solana-test-validator -``` - -For more information on local validator customization and commands, read the -[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). - -### Fuzz Tester - -Generate fuzz tests: - -```shell -npx solana fuzz -``` - -This command will initialize a Trident workspace and generate a new Fuzz Test -Template: - -```shell -project-root -├── trident-tests -│ ├── fuzz_tests # fuzz tests folder -│ │ ├── fuzz_0 # particular fuzz test -│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test -│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test -│ │ ├── fuzz_1 -│ │ ├── fuzz_X # possible multiple fuzz tests -│ │ ├── fuzzing # compilations and crashes folder -│ │ └── Cargo.toml -├── Trident.toml -└── ... -``` - -Run fuzz tests: - -```shell -npx solana fuzz run -``` - -The output of the fuzz tests is as follows: - -1. Number of Fuzzing Iterations. -2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. - feedback based on Coverage progress). -3. Average Iterations per second. -4. Number of crashes it found (panics or failed invariant checks). - -```shell -------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- - Iterations : 688 (out of: 1000 [68%]) # -- 1. -- - Mode [3/3] : Feedback Driven Mode # -- 2. -- - Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 - Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] - Speed : 680/sec [avg: 688] # -- 3. -- - Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- - Timeouts : 0 [10 sec] - Corpus Size : 98, max: 1048576 bytes, init: 0 files - Cov Update : 0 days 00 hrs 00 mins 00 secs ago - Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 ----------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- -``` - -View the source code [here](https://github.com/Ackee-Blockchain/trident). - -### Code Coverage Tool - -```shell -mucho coverage -``` - -This command will run a code coverage test on all of your Rust tests and then -generate report in an HTML page with in depth metrics on where additional code -may be needed to improve your current code coverage. - -Note: So far, this tool only works on tests written in Rust and is not -compatible with a JavaScript test suite. - -View the source code -[here](https://github.com/LimeChain/zest?tab=readme-ov-file). - -### JavaScript Testing Framework - -```shell -npm install solana-bankrun -``` - -[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and -lightweight framework for testing solana programs in NodeJS. - -It uses [solana-program-test](https://crates.io/crates/solana-program-test) -under the hood and allows you to do things that are not possible with -`solana-test-validator`, such as jumping back and forth in time or dynamically -setting account data. - -Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node -but much faster, and creating a `BanksClient` to talk to the server. This runs -the Solana -[Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). - -Here is a minimal example of this framework: - -```javascript -import { start } from "solana-bankrun"; -import { PublicKey, Transaction, SystemProgram } from "@solana/web3.js"; - -test("one transfer", async () => { - const context = await start([], []); - const client = context.banksClient; - const payer = context.payer; - const receiver = PublicKey.unique(); - const blockhash = context.lastBlockhash; - const transferLamports = 1_000_000n; - const ixs = [ - SystemProgram.transfer({ - fromPubkey: payer.publicKey, - toPubkey: receiver, - lamports: transferLamports, - }), - ]; - const tx = new Transaction(); - tx.recentBlockhash = blockhash; - tx.add(...ixs); - tx.sign(payer); - await client.processTransaction(tx); - const balanceAfter = await client.getBalance(receiver); - expect(balanceAfter).toEqual(transferLamports); -}); -``` - -For more complex examples, please refer to the -[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) - -### Rust Testing Library - -```shell -cargo add --dev litesvm -``` - -[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library -for testing Solana programs. It works by creating an in-process Solana VM -optimized for program developers. This makes it much faster to run and compile -than alternatives like solana-program-test and solana-test-validator. In a -further break from tradition, it has an ergonomic API with sane defaults and -extensive configurability for those who want it. - -Here is a minimal example: - -```rust -use litesvm::LiteSVM; -use solana_program::{message::Message, pubkey::Pubkey, system_instruction::transfer}; -use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction}; - -let from_keypair = Keypair::new(); -let from = from_keypair.pubkey(); -let to = Pubkey::new_unique(); - -let mut svm = LiteSVM::new(); -svm.airdrop(&from, 10_000).unwrap(); - -let instruction = transfer(&from, &to, 64); -let tx = Transaction::new( - &[&from_keypair], - Message::new(&[instruction], Some(&from)), - svm.latest_blockhash(), -); -let tx_res = svm.send_transaction(tx).unwrap(); - -let from_account = svm.get_account(&from); -let to_account = svm.get_account(&to); -assert_eq!(from_account.unwrap().lamports, 4936); -assert_eq!(to_account.unwrap().lamports, 64); - -``` - -### Security Vulnerability Scanner - -[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static -analysis tool for anchor rust programs. It allows you to write, share, and -utilize templates to identify security issues in rust-based smart contracts -using a powerful python based rule engine that enables automating detection of -vulnerable code patterns through logical expressions. - -[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform -command-line interface (CLI) tool designed for static analysis of Solana -programs and smart contracts written in Rust. - -## Running a local network - -The Solana test validator is a local emulator for the Solana blockchain, -designed to provide developers with a private and controlled environment for -building and testing Solana programs without the need to connect to a public -testnet or mainnet. If you have the Solana CLI tool suite already installed, you -can run the test validator with the following command: - -```shell -solana-test-validator - -### Advantages - -- Ability to reset the blockchain state at any moment -- Ability to simulate different network conditions -- No RPC rate-limits -- No airdrop limits -- Direct on-chain program deployment -- Ability to clone accounts from a public cluster -- Ability to load accounts from files -- Configurable transaction history retention -- Configurable epoch length -- Installation # - -Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure -you have Solana's command-line tools installed. You can install the entire -Solana toolkit (which includes the Solana CLI) using the following command: - -```shell -npx solana install -``` - -Or install just the Solana CLI with: - -```shell -sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)" -``` - -You can replace `stable` with the release tag matching the software version of -your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel -names: `stable`, `beta`, or `edge`. - -### Starting the Test Validator - -To start your local validator, simply run: - -```shell -solana-test-validator -``` - -This command initializes a new ledger and starts the validator. - -### Interacting with a Running Test Validator - -Once you have the `solana-test-validator` up and running, you can interact with -it using various Solana CLI commands. These commands let you deploy programs, -manage accounts, send transactions, and much more. Below is a detailed guide on -the key commands you will use. - -Check your current CLI configuration to see which network you are selected too: - -```shell -solana config get -``` - -If needed update your Solana configuration to connect to your test validator -running on localhost: - -```shell -solana config set --url localhost -``` - -### Checking the Status of the Test Validator - -Before interacting with the test validator, it's useful to confirm its status -and ensure it is running correctly. - -```shell -solana ping -``` - -This command pings the local test validator and returns the current blockhash -and latency, verifying that it is active. - -### Account Management - -View the pubkey of your configured CLI keypair: - -```shell -solana address -``` - -View the current balance of your keypair: - -```shell -solana balance -``` - -To add SOL to your CLI keypair, request an airdrop: - -```shell -solana airdrop 10 -``` - -To retrieve details about any account, such as its balance and owner: - -```shell -solana account -``` - -You must first add SOL to an account for it to exist. This airdrop command -requests 2 SOL to the specified account address: - -```shell -solana airdrop 2 -``` - -Aside from "wallet accounts" that only hold SOL, accounts are normally created -by smart contracts (aka programs) so they can store the `data` desired by that -program. - -### Deploying and Managing Programs - -To deploy a compiled program (BPF) to the test validator: - -```shell -solana program deploy -``` - -This uploads and deploys a program to the blockchain. - -To check the details of a deployed program: - -```shell -solana program show -``` - -### Sending Transactions - -To transfer SOL from one account to another: - -```shell -solana transfer --from /path/to/keypair.json -``` - -This sends `AMOUNT` of SOL from the source account to the `RECIPIENT_ADDRESS`. - -### Simulating and Confirming Transactions - -Before actually sending a transaction, you can simulate it to see if it would -likely succeed: - -```shell -solana transfer --from /path/to/keypair.json --simulate -``` - -To confirm the details and status of a transaction: - -```shell -solana confirm -``` - -### Viewing Recent Block Production - -To see information about recent block production, which can be useful for -debugging performance issues: - -```shell -solana block-production -``` - -### Creating Token Accounts - -### Adjusting Logs - -For debugging, you might want more detailed logs: - -```shell -solana logs -``` - -This streams log messages from the validator. - -### Tips for Logging - -- Increase log verbosity with the `-v` flag if you need more detailed output for - debugging. -- Use the `--rpc-port` and `--rpc-bind-address` options to customize the RPC - server settings. -- Adjust the number of CPU cores used by the validator with the `--gossip-host` - option to simulate network conditions more realistically. - -### Configuration - -Check CLI Tool Suite configuration: - -```shell -solana genesis-hash -``` - -View all the configuration options available for the Solana test validator: - -```shell -solana-test-validator --help -``` - -### Local Ledger - -By default, the ledger data is stored in a directory named `test-ledger` in your -current working directory. - -### Specifying Ledger Location - -When starting the test validator, you can specify a different directory for the -ledger data using the `--ledger` option: - -```shell -solana-test-validator --ledger /path/to/custom/ledger -``` - -### Resetting the Ledger - -By default the validator will resume an existing ledger, if one is found. To -reset the ledger, you can either manually delete the ledger directory or restart -the validator with the `--reset` flag: - -```shell -solana-test-validator --reset -``` - -If the ledger exists, this command will reset the ledger to genesis, which -resets the state by deleting all existing accounts and starting fresh. - -### Cloning Programs - -To add existing onchain programs to your local environment, you can clone the -program with a new ledger. This is useful for testing interactions with other -programs that already exist on any other cluster. - -To clone an account from another cluster: - -```shell -solana-test-validator --clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO -``` - -To clone an upgradeable program and its executable data from another cluster: - -```shell -solana-test-validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO -``` - -> If a ledger already exists in your working directory, you must reset the -> ledger to be able to clone a program. - -### Cloning Accounts - -To add existing onchain accounts to your local environment, you can clone the -account with a new ledger from any other network cluster. - -To clone an account from the cluster when a ledger already exists: - -```shell -solana-test-validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset -``` - -### Reset to Specific Account Data - -To reset the state of specific accounts every time you start the validator, you -can use a combination of account snapshots and the `--account` flag. - -First, save the desired state of an account as a JSON file: - -```shell -solana account ACCOUNT_ADDRESS --output json > account_state.json -``` - -Then load this state each time you reset the validator: - -```shell -solana-test-validator --reset --account ACCOUNT_ADDRESS account_state.json -``` - -### Runtime Features - -Solana has a feature set mechanism that allows you to enable or disable certain -blockchain features when running the test validator. By default, the test -validator runs with all runtime features activated. - -To see all the runtime features available and their statuses: - -```shell -solana feature status -``` - -To query a specific runtime feature's status: - -```shell -solana feature status
-``` - -To activate a specific feature: - -```shell -solana feature activate -``` - -- `FEATURE_KEYPAIR` is the signer for the feature to activate -- `CLUSTER` is the cluster to activate the feature on +This toolkit includes tool CLIs: -To deactivate specific features in genesis: +- [The Solana CLI](https://www.npmjs.com/package/solana) is meant to be a generic utilitarian helper CLI to accomplish some basic setup and troubleshooting for Solana development. -```shell -solana-test-validator --deactivate-feature --reset -``` +- [The Mucho CLI](https://www.npmjs.com/package/mucho) is encapsulates all additional tools for Solana Program development. - *Mucho Tools, One CLI*. -This must be done on a fresh ledger, so if a ledger already exists in your -working directory you must add the `--reset` flag to reset to genesis. +## Sections -### Changing Versions +### [Getting Started](getting-started.md) -To check your current `solana-test-validator` version: +To get started with The Solana Toolkit, install the toolkit, configure your +Solana CLI, fund your local keypair. -```shell -solana-test-validator --version -``` +### [Creating a Project](projects.md) -Your test validator runs on the same version as the Solana CLI installed and -configured for use. +Set up your project with one of the open source scaffolds and templates +available. Each scaffold/template has a different purpose, so be sure to review +all the options explained in this section to pick the most optimal one for your +project. -To test your programs against different versions of the Solana runtime, you can -install multiple versions of the Solana CLI and switch between them using the -following command: +### [Smart Contract Best Practices](best-practices.md) -```shell -solana-install init -``` +Make sure you're developing Solana smart contracts with best practices like optimizing compute units, saving bumps, the payer-authority pattern, etc. -Make sure to reset your Solana test validator's ledger after changing versions -to ensure it runs a valid ledger without corruption. +### [Test Suite](test-suite.md) -## Compute and Fees Section +Use the Solana Test Suite with the `mucho` CLI to have access to tools like a fuzz tester, code coverage tool, security vulnerability scanner, etc. -In Solana program development, you don't need to track gas but it is best -practice to optimize for compute. For more information on how to optimize -compute, read the this -[guide](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). +### [Running a Local Network](local-testing.md) -To understand more about fees on Solana, read this -[document](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute). +Run a local network to be able to build and test with a private and controlled environment for Solana programs without the need to connect to a public +testnet or mainnet. \ No newline at end of file diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md new file mode 100644 index 000000000..749bbfd4d --- /dev/null +++ b/docs/toolkit/local-testing.md @@ -0,0 +1,342 @@ +--- +title: Running a Local Network +--- + +The Solana test validator is a local emulator for the Solana blockchain, +designed to provide developers with a private and controlled environment for +building and testing Solana programs without the need to connect to a public +testnet or mainnet. If you have the Solana CLI tool suite already installed, you +can run the test validator with the following command: + +```shell +solana-test-validator +``` + +### Advantages + +- Ability to reset the blockchain state at any moment +- Ability to simulate different network conditions +- No RPC rate-limits +- No airdrop limits +- Direct on-chain program deployment +- Ability to clone accounts from a public cluster +- Ability to load accounts from files +- Configurable transaction history retention +- Configurable epoch length +- Installation # + +Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure +you have Solana's command-line tools installed. You can install the entire +Solana toolkit (which includes the Solana CLI) using the following command: + +```shell +npx solana install +``` + +Or install just the Solana CLI with: + +```shell +sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)" +``` + +You can replace `stable` with the release tag matching the software version of +your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel +names: `stable`, `beta`, or `edge`. + +### Starting the Test Validator + +To start your local validator, simply run: + +```shell +solana-test-validator +``` + +This command initializes a new ledger and starts the validator. + +### Interacting with a Running Test Validator + +Once you have the `solana-test-validator` up and running, you can interact with +it using various Solana CLI commands. These commands let you deploy programs, +manage accounts, send transactions, and much more. Below is a detailed guide on +the key commands you will use. + +Check your current CLI configuration to see which network you are selected too: + +```shell +solana config get +``` + +If needed update your Solana configuration to connect to your test validator +running on localhost: + +```shell +solana config set --url localhost +``` + +### Checking the Status of the Test Validator + +Before interacting with the test validator, it's useful to confirm its status +and ensure it is running correctly. + +```shell +solana ping +``` + +This command pings the local test validator and returns the current blockhash +and latency, verifying that it is active. + +### Account Management + +View the pubkey of your configured CLI keypair: + +```shell +solana address +``` + +View the current balance of your keypair: + +```shell +solana balance +``` + +To add SOL to your CLI keypair, request an airdrop: + +```shell +solana airdrop 10 +``` + +To retrieve details about any account, such as its balance and owner: + +```shell +solana account +``` + +You must first add SOL to an account for it to exist. This airdrop command +requests 2 SOL to the specified account address: + +```shell +solana airdrop 2 +``` + +Aside from "wallet accounts" that only hold SOL, accounts are normally created +by smart contracts (aka programs) so they can store the `data` desired by that +program. + +### Deploying and Managing Programs + +To deploy a compiled program (BPF) to the test validator: + +```shell +solana program deploy +``` + +This uploads and deploys a program to the blockchain. + +To check the details of a deployed program: + +```shell +solana program show +``` + +### Sending Transactions + +To transfer SOL from one account to another: + +```shell +solana transfer --from /path/to/keypair.json +``` + +This sends `AMOUNT` of SOL from the source account to the `RECIPIENT_ADDRESS`. + +### Simulating and Confirming Transactions + +Before actually sending a transaction, you can simulate it to see if it would +likely succeed: + +```shell +solana transfer --from /path/to/keypair.json --simulate +``` + +To confirm the details and status of a transaction: + +```shell +solana confirm +``` + +### Viewing Recent Block Production + +To see information about recent block production, which can be useful for +debugging performance issues: + +```shell +solana block-production +``` + +### Creating Token Accounts + +### Adjusting Logs + +For debugging, you might want more detailed logs: + +```shell +solana logs +``` + +This streams log messages from the validator. + +### Tips for Logging + +- Increase log verbosity with the `-v` flag if you need more detailed output for + debugging. +- Use the `--rpc-port` and `--rpc-bind-address` options to customize the RPC + server settings. +- Adjust the number of CPU cores used by the validator with the `--gossip-host` + option to simulate network conditions more realistically. + +### Configuration + +Check CLI Tool Suite configuration: + +```shell +solana genesis-hash +``` + +View all the configuration options available for the Solana test validator: + +```shell +solana-test-validator --help +``` + +### Local Ledger + +By default, the ledger data is stored in a directory named `test-ledger` in your +current working directory. + +### Specifying Ledger Location + +When starting the test validator, you can specify a different directory for the +ledger data using the `--ledger` option: + +```shell +solana-test-validator --ledger /path/to/custom/ledger +``` + +### Resetting the Ledger + +By default the validator will resume an existing ledger, if one is found. To +reset the ledger, you can either manually delete the ledger directory or restart +the validator with the `--reset` flag: + +```shell +solana-test-validator --reset +``` + +If the ledger exists, this command will reset the ledger to genesis, which +resets the state by deleting all existing accounts and starting fresh. + +### Cloning Programs + +To add existing onchain programs to your local environment, you can clone the +program with a new ledger. This is useful for testing interactions with other +programs that already exist on any other cluster. + +To clone an account from another cluster: + +```shell +solana-test-validator --clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +``` + +To clone an upgradeable program and its executable data from another cluster: + +```shell +solana-test-validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +``` + +> If a ledger already exists in your working directory, you must reset the +> ledger to be able to clone a program. + +### Cloning Accounts + +To add existing onchain accounts to your local environment, you can clone the +account with a new ledger from any other network cluster. + +To clone an account from the cluster when a ledger already exists: + +```shell +solana-test-validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset +``` + +### Reset to Specific Account Data + +To reset the state of specific accounts every time you start the validator, you +can use a combination of account snapshots and the `--account` flag. + +First, save the desired state of an account as a JSON file: + +```shell +solana account ACCOUNT_ADDRESS --output json > account_state.json +``` + +Then load this state each time you reset the validator: + +```shell +solana-test-validator --reset --account ACCOUNT_ADDRESS account_state.json +``` + +### Runtime Features + +Solana has a feature set mechanism that allows you to enable or disable certain +blockchain features when running the test validator. By default, the test +validator runs with all runtime features activated. + +To see all the runtime features available and their statuses: + +```shell +solana feature status +``` + +To query a specific runtime feature's status: + +```shell +solana feature status
+``` + +To activate a specific feature: + +```shell +solana feature activate +``` + +- `FEATURE_KEYPAIR` is the signer for the feature to activate +- `CLUSTER` is the cluster to activate the feature on + +To deactivate specific features in genesis: + +```shell +solana-test-validator --deactivate-feature --reset +``` + +This must be done on a fresh ledger, so if a ledger already exists in your +working directory you must add the `--reset` flag to reset to genesis. + +### Changing Versions + +To check your current `solana-test-validator` version: + +```shell +solana-test-validator --version +``` + +Your test validator runs on the same version as the Solana CLI installed and +configured for use. + +To test your programs against different versions of the Solana runtime, you can +install multiple versions of the Solana CLI and switch between them using the +following command: + +```shell +solana-install init +``` + +Make sure to reset your Solana test validator's ledger after changing versions +to ensure it runs a valid ledger without corruption. \ No newline at end of file diff --git a/docs/toolkit/projects.md b/docs/toolkit/projects.md new file mode 100644 index 000000000..4431148fb --- /dev/null +++ b/docs/toolkit/projects.md @@ -0,0 +1,263 @@ +--- +title: Creating A Project on Solana +--- + +To start a new project with the Solana toolkit, pick which scaffold you want to +use. There are scaffolds for: + +- [Anchor framework workspaces](#anchor-smart-contract-scaffold) +- [general scaffolds using `create-solana-program`](#general-smart-contract-scaffold) +- [web app workspaces](#web-app-scaffold) +- [mobile app workspaces](#mobile-app-templates) + +## Anchor Smart Contract Scaffold + +```shell +anchor init +``` + +This initializes a simplistic workspace set up for Anchor smart contract +development, with the following structure: + +- `Anchor.toml`: Anchor configuration file. +- `Cargo.toml`: Rust workspace configuration file. +- `package.json`: JavaScript dependencies file. +- `programs/`: Directory for Solana program crates. +- `app/`: Directory for your application frontend. +- `tests/`: Directory for JavaScript integration tests. +- `migrations/deploy.js`: Deploy script. + +The Anchor framework abstracts away many complexities enabling fast program +development. + +To test out this project before making any modifications, just build and test: + +```shell +anchor build +``` + +```shell +anchor test +``` + +To start writing your own anchor smart contract, navigate to +`programs/src/lib.rs`. + +For more complex programs, using a more structured project template would be +best practice. This can be generated with: + +```shell +anchor init --template multiple +``` + +which creates the following layout inside of `programs/src`: + +```shell +├── constants.rs +├── error.rs +├── instructions +│ ├── initialize.rs +│ └── mod.rs +├── lib.rs +└── state + └── mod.rs +``` + +For more information on the Anchor framework, check out the +[Anchor book](https://www.anchor-lang.com/). + +## General Smart Contract Scaffold - Create Solana Program + +```shell +npx create-solana-program +``` + +This initializes a more complex workspace with everything you need for general +Solana smart contract development. This Scaffold allows you to write either +native rust smart contracts or anchor smart contracts. + +After running this command, you'll have the option to choose between Shank and +Anchor for the program framework: + +- **Shank** creates a vanilla Solana smart contract with Shank macros to + generate IDLs. For more information on Shank, read the + [README](https://github.com/metaplex-foundation/shank). + +- **Anchor** creates a smart contract using the Anchor framework, which + abstracts away many complexities enabling fast program development. For more + information on the Anchor framework, read the + [Anchor book](https://www.anchor-lang.com/). + +Next, you'll have the option to choose between a JavaScript client, a Rust +Client, or both. + +- **JavaScript Client** creates a typescript library compatible with + [web3.js](https://solana-labs.github.io/solana-web3.js/). + +- **Rust Client** creates a rust crate allowing consumers to interact with the + smart contract. + +For further workspace customization and additional information, check out the +`create-solana-program` +[README](https://github.com/solana-program/create-solana-program/tree/main). + +After answering the above questions, the workspace will be generated. To get +started, build your program and clients by running: + +```shell +cd +npm install +npm dev generate +``` + +### Native Rust Smart Contract Development with Create Solana Program + +To use `create-solana-program` for native rust development, make sure you chose +Shank when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +### Anchor Smart Contract Development with Create Solana Program + +To use `create-solana-program` for native rust development, make sure you chose +Anchor when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── lib.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +## Web App Scaffold + +```shell +npx create-solana-dapp +``` + +This command generates a new project that connects a Solana smart contract to a +frontend with a wallet connector. + +For additional information, check out its +[README](https://github.com/solana-developers/create-solana-dapp). + +To test out this project before making any modifications, follow these steps: + +1. Build the smart contract: + +```shell +npm run anchor-build +``` + +2. Start the local validator: + +```shell +npm run anchor-localnet +``` + +3. Run tests: + +```shell +npm run anchor-test +``` + +4. Deploy to the local validator: + +```shell +npm run anchor deploy --provider.cluster localnet +``` + +5. Build the web app: + +```shell +npm run build +``` + +6. Run the web app: + +```shell +npm run dev +``` + +## Mobile App Templates + +```shell +yarn create expo-app --template @solana-mobile/solana-mobile-expo-template +``` + +This is initializing a new project using the Expo framework that is specifically +designed for creating mobile applications that interact with the Solana +blockchain. + +Follow their +[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) +guide to launch the template as a custom development build and get it running on +your Android emulator. Once you have built the program and are running a dev +client with Expo, the emulator will automatically update every time you save +your code. + +To use this template, you will also need to set up the following: + +- [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) +- [React Native](https://reactnative.dev/docs/environment-setup?platform=android) +- [EAS CLI and Account](https://docs.expo.dev/build/setup/) + +For additional information on Solana Mobile Development: +https://docs.solanamobile.com/getting-started/intro + +## Working on an Existing Project + +If you have an existing anchor program and want to use the +[create solana program tool](#general-smart-contract-scaffold), you can easily +replace the generated program with your existing one: + +1. Ensure the installed Solana and Anchor versions are the same as the ones your + existing program requires. + +2. Scaffold a new Solana program using Anchor. + `pnpm create solana-program --anchor`. + +3. Replace the `program` folder with your existing program directory (not the + workspace directory). If you have more than one program, add more folders to + the root directory and update the `members` attribute of the top-level + `Cargo.toml` accordingly. + +4. Ensure your program’s `Cargo.toml` contains the following metadata: + +```toml filename="Cargo.toml" +[package.metadata.solana] +program-id = "YOUR_PROGRAM_ADDRESS" +program-dependencies = [] +``` + +5. Build your program and clients. + +```shell +npm install +npm run programs:build +npm run generate +``` + +6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` + file so the `ID` alias points to the correct generated constant. + +7. If you have any generated clients, update the scaffolded tests so they work + with your existing program. diff --git a/docs/toolkit/test-suite.md b/docs/toolkit/test-suite.md new file mode 100644 index 000000000..d24e9d52d --- /dev/null +++ b/docs/toolkit/test-suite.md @@ -0,0 +1,230 @@ +--- +title: Test Suite +--- + +Within the Solana toolkit, there are several resources for testing Solana Smart +Contracts, including: + +- A fuzz tester +- A code coverage tool +- A framework for testing Solana programs in NodeJS that spins up a lightweight + `BanksServer` that's like an RPC node but much faster and creates a + `BanksClient` to talk to the server. +- A fast and lightweight library for testing Solana programs in Rust, which + works by creating an in-process Solana VM optimized for program developers. +- A tool to scan your repo for common security vulnerabilities and provide + suggestions for fixes. + +### Testing Basics + +Sync all the program's key. If you're using an Anchor program: + +```shell +anchor keys sync +``` + +Build the smart contract: + +```shell +npx solana build +``` + +Test the smart contract: + +```shell +npx solana test +``` + +Deploy the smart contract: + +```shell +npx solana deploy +``` + +If deploying to localnet, you must first start your local validator: + +```shell +solana-test-validator +``` + +For more information on local validator customization and commands, read the +[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). + +### Fuzz Tester + +Generate fuzz tests: + +```shell +npx solana fuzz +``` + +This command will initialize a Trident workspace and generate a new Fuzz Test +Template: + +```shell +project-root +├── trident-tests +│ ├── fuzz_tests # fuzz tests folder +│ │ ├── fuzz_0 # particular fuzz test +│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test +│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test +│ │ ├── fuzz_1 +│ │ ├── fuzz_X # possible multiple fuzz tests +│ │ ├── fuzzing # compilations and crashes folder +│ │ └── Cargo.toml +├── Trident.toml +└── ... +``` + +Run fuzz tests: + +```shell +npx solana fuzz run +``` + +The output of the fuzz tests is as follows: + +1. Number of Fuzzing Iterations. +2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. + feedback based on Coverage progress). +3. Average Iterations per second. +4. Number of crashes it found (panics or failed invariant checks). + +```shell +------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- + Iterations : 688 (out of: 1000 [68%]) # -- 1. -- + Mode [3/3] : Feedback Driven Mode # -- 2. -- + Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 + Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] + Speed : 680/sec [avg: 688] # -- 3. -- + Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- + Timeouts : 0 [10 sec] + Corpus Size : 98, max: 1048576 bytes, init: 0 files + Cov Update : 0 days 00 hrs 00 mins 00 secs ago + Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 +---------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- +``` + +View the source code [here](https://github.com/Ackee-Blockchain/trident). + +### Code Coverage Tool + +```shell +mucho coverage +``` + +This command will run a code coverage test on all of your Rust tests and then +generate report in an HTML page with in depth metrics on where additional code +may be needed to improve your current code coverage. + +Note: So far, this tool only works on tests written in Rust and is not +compatible with a JavaScript test suite. + +View the source code +[here](https://github.com/LimeChain/zest?tab=readme-ov-file). + +### JavaScript Testing Framework + +```shell +npm install solana-bankrun +``` + +[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and +lightweight framework for testing solana programs in NodeJS. + +It uses [solana-program-test](https://crates.io/crates/solana-program-test) +under the hood and allows you to do things that are not possible with +`solana-test-validator`, such as jumping back and forth in time or dynamically +setting account data. + +Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node +but much faster, and creating a `BanksClient` to talk to the server. This runs +the Solana +[Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). + +Here is a minimal example of this framework: + +```javascript +import { start } from "solana-bankrun"; +import { PublicKey, Transaction, SystemProgram } from "@solana/web3.js"; + +test("one transfer", async () => { + const context = await start([], []); + const client = context.banksClient; + const payer = context.payer; + const receiver = PublicKey.unique(); + const blockhash = context.lastBlockhash; + const transferLamports = 1_000_000n; + const ixs = [ + SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: receiver, + lamports: transferLamports, + }), + ]; + const tx = new Transaction(); + tx.recentBlockhash = blockhash; + tx.add(...ixs); + tx.sign(payer); + await client.processTransaction(tx); + const balanceAfter = await client.getBalance(receiver); + expect(balanceAfter).toEqual(transferLamports); +}); +``` + +For more complex examples, please refer to the +[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) + +### Rust Testing Library + +```shell +cargo add --dev litesvm +``` + +[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library +for testing Solana programs. It works by creating an in-process Solana VM +optimized for program developers. This makes it much faster to run and compile +than alternatives like solana-program-test and solana-test-validator. In a +further break from tradition, it has an ergonomic API with sane defaults and +extensive configurability for those who want it. + +Here is a minimal example: + +```rust +use litesvm::LiteSVM; +use solana_program::{message::Message, pubkey::Pubkey, system_instruction::transfer}; +use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction}; + +let from_keypair = Keypair::new(); +let from = from_keypair.pubkey(); +let to = Pubkey::new_unique(); + +let mut svm = LiteSVM::new(); +svm.airdrop(&from, 10_000).unwrap(); + +let instruction = transfer(&from, &to, 64); +let tx = Transaction::new( + &[&from_keypair], + Message::new(&[instruction], Some(&from)), + svm.latest_blockhash(), +); +let tx_res = svm.send_transaction(tx).unwrap(); + +let from_account = svm.get_account(&from); +let to_account = svm.get_account(&to); +assert_eq!(from_account.unwrap().lamports, 4936); +assert_eq!(to_account.unwrap().lamports, 64); + +``` + +### Security Vulnerability Scanner + +[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static +analysis tool for anchor rust programs. It allows you to write, share, and +utilize templates to identify security issues in rust-based smart contracts +using a powerful python based rule engine that enables automating detection of +vulnerable code patterns through logical expressions. + +[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform +command-line interface (CLI) tool designed for static analysis of Solana +programs and smart contracts written in Rust. From 9f4940b3123b38e0ef7eefa0a5feb58735a624bb Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:54:05 -0500 Subject: [PATCH 13/25] update docs --- docs/toolkit/best-practices.md | 45 +++++++++++++++++++++++----------- docs/toolkit/index.md | 20 +++++++++------ docs/toolkit/local-testing.md | 2 +- docs/toolkit/projects.md | 2 +- 4 files changed, 46 insertions(+), 23 deletions(-) diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index 676817871..905550a60 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -2,7 +2,7 @@ title: Solana Smart Contract Best Practices --- -## Smart Contract File Structure +## Smart Contract File Structure Typically Solana smart contract (aka [programs](/docs/core/programs.md)) workspaces will be have the following file structure: @@ -68,23 +68,40 @@ entrypoint and processor for the program, so you'll need a few more files: │ ├── README.md ``` -## Optimize Compute Usage +## Optimize Compute Usage + +To prevent abuse of computational resources, each transaction is allocated a +"compute budget". This budget specifies details about +[compute units](https://solana.com/docs/core/fees#compute-units) and includes: + +- the compute costs associated with different types of operations the + transaction may perform (compute units consumed per operation), +- the maximum number of compute units that a transaction can consume (compute + unit limit), +- and the operational bounds the transaction must adhere to (like account data + size limits) + +When the transaction consumes its entire compute budget (compute budget +exhaustion), or exceeds a bound such as attempting to exceed the +[max call stack depth](https://github.com/anza-xyz/agave/blob/b7bbe36918f23d98e2e73502e3c4cba78d395ba9/program-runtime/src/compute_budget.rs#L138) +or +[max loaded account](https://solana.com/docs/core/fees#accounts-data-size-limit) +data size limit, the runtime halts the transaction processing and returns an +error. Resulting in a failed transaction and no state changes (aside from the +transaction fee being +[collected](https://solana.com/docs/core/fees#fee-collection)). -To prevent abuse of computational resources, each transaction is allocated a "compute budget". This budget specifies details about [compute units](https://solana.com/docs/core/fees#compute-units) and includes: - -- the compute costs associated with different types of operations the transaction may perform (compute units consumed per operation), -- the maximum number of compute units that a transaction can consume (compute unit limit), -- and the operational bounds the transaction must adhere to (like account data size limits) - -When the transaction consumes its entire compute budget (compute budget exhaustion), or exceeds a bound such as attempting to exceed the [max call stack depth](https://github.com/anza-xyz/agave/blob/b7bbe36918f23d98e2e73502e3c4cba78d395ba9/program-runtime/src/compute_budget.rs#L138) or [max loaded account](https://solana.com/docs/core/fees#accounts-data-size-limit) data size limit, the runtime halts the transaction processing and returns an error. Resulting in a failed transaction and no state changes (aside from the transaction fee being [collected](https://solana.com/docs/core/fees#fee-collection)). +### Solana Developer Guides -### Solana Developer Guides -- [How to Optimize Compute](https://solana.com/developers/guides/advanced/how-to-optimize-compute). +- [How to Optimize Compute](https://solana.com/developers/guides/advanced/how-to-optimize-compute). - [How to Request Optimal Compute](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute) ## Saving Bumps -Saving the bump to your Solana smart contract account state enables deterministic address generation, efficiency in address reconstruction, reduced transaction failure, and consistency across invocations. - +Saving the bump to your Solana smart contract account state enables +deterministic address generation, efficiency in address reconstruction, reduced +transaction failure, and consistency across invocations. + ### Solana Developer Guides -- [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization#challenge) \ No newline at end of file + +- [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization#challenge) diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 807a35fef..5b4b29938 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -12,11 +12,14 @@ development on the Solana Blockchain. You can contribute to this book on [GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). -This toolkit includes tool CLIs: +This toolkit includes tool CLIs: -- [The Solana CLI](https://www.npmjs.com/package/solana) is meant to be a generic utilitarian helper CLI to accomplish some basic setup and troubleshooting for Solana development. +- [The Solana CLI](https://www.npmjs.com/package/solana) is meant to be a + generic utilitarian helper CLI to accomplish some basic setup and + troubleshooting for Solana development. -- [The Mucho CLI](https://www.npmjs.com/package/mucho) is encapsulates all additional tools for Solana Program development. - *Mucho Tools, One CLI*. +- [The Mucho CLI](https://www.npmjs.com/package/mucho) is encapsulates all + additional tools for Solana Program development. - _Mucho Tools, One CLI_. ## Sections @@ -34,13 +37,16 @@ project. ### [Smart Contract Best Practices](best-practices.md) -Make sure you're developing Solana smart contracts with best practices like optimizing compute units, saving bumps, the payer-authority pattern, etc. +Make sure you're developing Solana smart contracts with best practices like +optimizing compute units, saving bumps, the payer-authority pattern, etc. ### [Test Suite](test-suite.md) -Use the Solana Test Suite with the `mucho` CLI to have access to tools like a fuzz tester, code coverage tool, security vulnerability scanner, etc. +Use the Solana Test Suite with the `mucho` CLI to have access to tools like a +fuzz tester, code coverage tool, security vulnerability scanner, etc. ### [Running a Local Network](local-testing.md) -Run a local network to be able to build and test with a private and controlled environment for Solana programs without the need to connect to a public -testnet or mainnet. \ No newline at end of file +Run a local network to be able to build and test with a private and controlled +environment for Solana programs without the need to connect to a public testnet +or mainnet. diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md index 749bbfd4d..702b1b1dd 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-testing.md @@ -339,4 +339,4 @@ solana-install init ``` Make sure to reset your Solana test validator's ledger after changing versions -to ensure it runs a valid ledger without corruption. \ No newline at end of file +to ensure it runs a valid ledger without corruption. diff --git a/docs/toolkit/projects.md b/docs/toolkit/projects.md index 4431148fb..9058f5476 100644 --- a/docs/toolkit/projects.md +++ b/docs/toolkit/projects.md @@ -1,5 +1,5 @@ --- -title: Creating A Project on Solana +title: Creating A Project on Solana --- To start a new project with the Solana toolkit, pick which scaffold you want to From fae227dbf0426776666cf3974eaf9c97b0887d45 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Mon, 6 Jan 2025 11:07:15 -0500 Subject: [PATCH 14/25] prettier:fix --- docs/toolkit/getting-started.md | 37 +++++++++++++++ docs/toolkit/local-testing.md | 80 +-------------------------------- 2 files changed, 39 insertions(+), 78 deletions(-) diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index 0175f50fe..4182e8cfc 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -86,3 +86,40 @@ solana logs For a more information, read this [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). + +### Account Management + +View the pubkey of your configured CLI keypair: + +```shell +solana address +``` + +View the current balance of your keypair: + +```shell +solana balance +``` + +To add SOL to your CLI keypair, request an airdrop: + +```shell +solana airdrop 10 +``` + +To retrieve details about any account, such as its balance and owner: + +```shell +solana account +``` + +You must first add SOL to an account for it to exist. This airdrop command +requests 2 SOL to the specified account address: + +```shell +solana airdrop 2 +``` + +Aside from "wallet accounts" that only hold SOL, accounts are normally created +by smart contracts (aka programs) so they can store the `data` desired by that +program. diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md index 702b1b1dd..f4dfc66d5 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-testing.md @@ -9,7 +9,7 @@ testnet or mainnet. If you have the Solana CLI tool suite already installed, you can run the test validator with the following command: ```shell -solana-test-validator +mucho test-validator ``` ### Advantages @@ -23,56 +23,17 @@ solana-test-validator - Ability to load accounts from files - Configurable transaction history retention - Configurable epoch length -- Installation # - -Since the `solana-test-validator` is part of the Solana CLI tool suite, ensure -you have Solana's command-line tools installed. You can install the entire -Solana toolkit (which includes the Solana CLI) using the following command: - -```shell -npx solana install -``` - -Or install just the Solana CLI with: - -```shell -sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)" -``` - -You can replace `stable` with the release tag matching the software version of -your desired release (i.e. `v1.18.12`), or use one of the three symbolic channel -names: `stable`, `beta`, or `edge`. ### Starting the Test Validator To start your local validator, simply run: ```shell -solana-test-validator +mucho test-validator ``` This command initializes a new ledger and starts the validator. -### Interacting with a Running Test Validator - -Once you have the `solana-test-validator` up and running, you can interact with -it using various Solana CLI commands. These commands let you deploy programs, -manage accounts, send transactions, and much more. Below is a detailed guide on -the key commands you will use. - -Check your current CLI configuration to see which network you are selected too: - -```shell -solana config get -``` - -If needed update your Solana configuration to connect to your test validator -running on localhost: - -```shell -solana config set --url localhost -``` - ### Checking the Status of the Test Validator Before interacting with the test validator, it's useful to confirm its status @@ -85,43 +46,6 @@ solana ping This command pings the local test validator and returns the current blockhash and latency, verifying that it is active. -### Account Management - -View the pubkey of your configured CLI keypair: - -```shell -solana address -``` - -View the current balance of your keypair: - -```shell -solana balance -``` - -To add SOL to your CLI keypair, request an airdrop: - -```shell -solana airdrop 10 -``` - -To retrieve details about any account, such as its balance and owner: - -```shell -solana account -``` - -You must first add SOL to an account for it to exist. This airdrop command -requests 2 SOL to the specified account address: - -```shell -solana airdrop 2 -``` - -Aside from "wallet accounts" that only hold SOL, accounts are normally created -by smart contracts (aka programs) so they can store the `data` desired by that -program. - ### Deploying and Managing Programs To deploy a compiled program (BPF) to the test validator: From ca036d5290d68e5e59635efd8c7ca30809af56d1 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Mon, 6 Jan 2025 15:54:16 -0500 Subject: [PATCH 15/25] update projects --- .../getstarted/local-rust-hello-world.md | 4 +- docs/toolkit/best-practices.md | 68 +---- docs/toolkit/getting-started.md | 83 ++---- docs/toolkit/index.md | 12 +- docs/toolkit/projects.md | 263 ------------------ docs/toolkit/projects/advanced-native.md | 68 +++++ docs/toolkit/projects/advanded-anchor.md | 61 ++++ docs/toolkit/projects/anchor-init.md | 59 ++++ docs/toolkit/projects/existing-project.md | 42 +++ docs/toolkit/projects/index.md | 6 + docs/toolkit/projects/mobile-app.md | 29 ++ docs/toolkit/projects/overview.md | 26 ++ docs/toolkit/projects/project-layout.md | 69 +++++ docs/toolkit/projects/web-app.md | 55 ++++ docs/toolkit/test-suite.md | 2 + 15 files changed, 447 insertions(+), 400 deletions(-) delete mode 100644 docs/toolkit/projects.md create mode 100644 docs/toolkit/projects/advanced-native.md create mode 100644 docs/toolkit/projects/advanded-anchor.md create mode 100644 docs/toolkit/projects/anchor-init.md create mode 100644 docs/toolkit/projects/existing-project.md create mode 100644 docs/toolkit/projects/index.md create mode 100644 docs/toolkit/projects/mobile-app.md create mode 100644 docs/toolkit/projects/overview.md create mode 100644 docs/toolkit/projects/project-layout.md create mode 100644 docs/toolkit/projects/web-app.md diff --git a/content/guides/getstarted/local-rust-hello-world.md b/content/guides/getstarted/local-rust-hello-world.md index 83ba94e73..a8ea90c83 100644 --- a/content/guides/getstarted/local-rust-hello-world.md +++ b/content/guides/getstarted/local-rust-hello-world.md @@ -228,8 +228,8 @@ library. ### Install Node.js To use node in WSL2 on Windows, please follow this -[guide to installing node in WSL2](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) -to install node. +[guide to installing node in WSL2](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) to +install node. ```shell sudo apt-get install curl diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index 905550a60..bf61f0838 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -1,73 +1,9 @@ --- title: Solana Smart Contract Best Practices +sidebarSortOrder: 3 +sidebarLabel: Best Practices --- -## Smart Contract File Structure - -Typically Solana smart contract (aka [programs](/docs/core/programs.md)) -workspaces will be have the following file structure: - -```shell -. -├── app -├── migrations -├── node_modules -├── programs -├── target -└── tests -``` - -The main smart contract is the `lib.rs` file, which lives insides the `programs` -directory, as shown below: - -```shell -. -├── app -├── migrations -├── node_modules -├── programs - ├── src - ├── lib.rs -├── target -└── tests -``` - -As the smart contract gets more cumbersome, you'll typically want to separate -the logic into multiple files, as shown below: - -```shell -├── programs - ├── src - ├── state.rs - ├── instructions - ├── instruction_1.rs - ├── instruction_2.rs - ├── instruction_3.rs - ├── lib.rs - ├── constants.rs - ├── error.rs - ├── mod.rs -``` - -For native rust smart contract development, you need to explicitly write out the -entrypoint and processor for the program, so you'll need a few more files: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├──assertions.rs -│ │ ├──entrypoint.rs -│ │ ├──error.rs -│ │ ├──instruction.rs -│ │ ├──lib.rs -│ │ ├──processor.rs -│ │ ├──state.rs -│ │ ├──utils.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - ## Optimize Compute Usage To prevent abuse of computational resources, each transaction is allocated a diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index 4182e8cfc..4e591ea1d 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -1,13 +1,20 @@ --- title: Getting Started +sidebarSortOrder: 1 +sidebarLabel: Getting Started --- +The Solana Program development toolkit is publish as the +[mucho npm package](https://www.npmjs.com/package/mucho). The `mucho` command +will be used to run all the solana program development tools - _mucho tools, one +cli_. + ## Installation To get started, install The Solana toolkit: ```shell -npx solana install +npx mucho install ``` This will install the latest versions of the following: @@ -25,7 +32,7 @@ This will install the latest versions of the following: - [Code Coverage Tool](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage CLI tool for Solana programs. -## Keypair generation +### Generate a keypair For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're required to generate a new keypair. @@ -34,39 +41,30 @@ required to generate a new keypair. solana-keygen new ``` -The above command will both: - -- print the pubkey generated -- store the your new keypair at the Solana CLI's default path - (`~/.config/solana/id.json`) unless you already have a keypair saved there +_This will store the your new keypair at the Solana CLI's default path +(`~/.config/solana/id.json`) and print the pubkey that was generated._ -Get the pubkey of your machine's newly generated keypair: +### Query your keypair's public key ```shell solana address ``` -## Fund the CLI keypair +### Fund your keypair ```shell -solana airdrop 10 +solana airdrop 10 --url localhost ``` -## Network Configuration +### Set your network configuration -Check your current configuration: +Check your current config: ```shell solana config get ``` -You can configure your RPC to connect to either mainnet, testnet, devnet, or -your localhost. - -When using this toolkit, most of the time you'll want to be connected to a local -node. - -Update your Solana configuration to connect to localhost: +To use this toolkit, update your config to connect to localhost: ```shell solana config set --url localhost @@ -75,51 +73,8 @@ solana config set --url localhost To test locally, you must also spin up a local node to run on your localhost: ```shell -solana-test-validator -``` - -To log the network run: - -```shell -solana logs +mucho validator ``` -For a more information, read this +For a more information, read the [Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). - -### Account Management - -View the pubkey of your configured CLI keypair: - -```shell -solana address -``` - -View the current balance of your keypair: - -```shell -solana balance -``` - -To add SOL to your CLI keypair, request an airdrop: - -```shell -solana airdrop 10 -``` - -To retrieve details about any account, such as its balance and owner: - -```shell -solana account -``` - -You must first add SOL to an account for it to exist. This airdrop command -requests 2 SOL to the specified account address: - -```shell -solana airdrop 2 -``` - -Aside from "wallet accounts" that only hold SOL, accounts are normally created -by smart contracts (aka programs) so they can store the `data` desired by that -program. diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 5b4b29938..eb1151133 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -1,5 +1,7 @@ --- title: The Solana Toolkit +sidebarSortOrder: +sidebarLabel: --- > This is a beta version of The Solana Toolkit, and is still a WIP. Please post @@ -23,29 +25,29 @@ This toolkit includes tool CLIs: ## Sections -### [Getting Started](getting-started.md) +### Getting Started To get started with The Solana Toolkit, install the toolkit, configure your Solana CLI, fund your local keypair. -### [Creating a Project](projects.md) +### Creating a Project Set up your project with one of the open source scaffolds and templates available. Each scaffold/template has a different purpose, so be sure to review all the options explained in this section to pick the most optimal one for your project. -### [Smart Contract Best Practices](best-practices.md) +### Best Practices Make sure you're developing Solana smart contracts with best practices like optimizing compute units, saving bumps, the payer-authority pattern, etc. -### [Test Suite](test-suite.md) +### Test Suite Use the Solana Test Suite with the `mucho` CLI to have access to tools like a fuzz tester, code coverage tool, security vulnerability scanner, etc. -### [Running a Local Network](local-testing.md) +### Running a Local Network Run a local network to be able to build and test with a private and controlled environment for Solana programs without the need to connect to a public testnet diff --git a/docs/toolkit/projects.md b/docs/toolkit/projects.md deleted file mode 100644 index 9058f5476..000000000 --- a/docs/toolkit/projects.md +++ /dev/null @@ -1,263 +0,0 @@ ---- -title: Creating A Project on Solana ---- - -To start a new project with the Solana toolkit, pick which scaffold you want to -use. There are scaffolds for: - -- [Anchor framework workspaces](#anchor-smart-contract-scaffold) -- [general scaffolds using `create-solana-program`](#general-smart-contract-scaffold) -- [web app workspaces](#web-app-scaffold) -- [mobile app workspaces](#mobile-app-templates) - -## Anchor Smart Contract Scaffold - -```shell -anchor init -``` - -This initializes a simplistic workspace set up for Anchor smart contract -development, with the following structure: - -- `Anchor.toml`: Anchor configuration file. -- `Cargo.toml`: Rust workspace configuration file. -- `package.json`: JavaScript dependencies file. -- `programs/`: Directory for Solana program crates. -- `app/`: Directory for your application frontend. -- `tests/`: Directory for JavaScript integration tests. -- `migrations/deploy.js`: Deploy script. - -The Anchor framework abstracts away many complexities enabling fast program -development. - -To test out this project before making any modifications, just build and test: - -```shell -anchor build -``` - -```shell -anchor test -``` - -To start writing your own anchor smart contract, navigate to -`programs/src/lib.rs`. - -For more complex programs, using a more structured project template would be -best practice. This can be generated with: - -```shell -anchor init --template multiple -``` - -which creates the following layout inside of `programs/src`: - -```shell -├── constants.rs -├── error.rs -├── instructions -│ ├── initialize.rs -│ └── mod.rs -├── lib.rs -└── state - └── mod.rs -``` - -For more information on the Anchor framework, check out the -[Anchor book](https://www.anchor-lang.com/). - -## General Smart Contract Scaffold - Create Solana Program - -```shell -npx create-solana-program -``` - -This initializes a more complex workspace with everything you need for general -Solana smart contract development. This Scaffold allows you to write either -native rust smart contracts or anchor smart contracts. - -After running this command, you'll have the option to choose between Shank and -Anchor for the program framework: - -- **Shank** creates a vanilla Solana smart contract with Shank macros to - generate IDLs. For more information on Shank, read the - [README](https://github.com/metaplex-foundation/shank). - -- **Anchor** creates a smart contract using the Anchor framework, which - abstracts away many complexities enabling fast program development. For more - information on the Anchor framework, read the - [Anchor book](https://www.anchor-lang.com/). - -Next, you'll have the option to choose between a JavaScript client, a Rust -Client, or both. - -- **JavaScript Client** creates a typescript library compatible with - [web3.js](https://solana-labs.github.io/solana-web3.js/). - -- **Rust Client** creates a rust crate allowing consumers to interact with the - smart contract. - -For further workspace customization and additional information, check out the -`create-solana-program` -[README](https://github.com/solana-program/create-solana-program/tree/main). - -After answering the above questions, the workspace will be generated. To get -started, build your program and clients by running: - -```shell -cd -npm install -npm dev generate -``` - -### Native Rust Smart Contract Development with Create Solana Program - -To use `create-solana-program` for native rust development, make sure you chose -Shank when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├── assertions.rs -│ │ ├──entrypoint.rs -│ │ ├──error.rs -│ │ ├──instruction.rs -│ │ ├──lib.rs -│ │ ├──processor.rs -│ │ ├──state.rs -│ │ ├──utils.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -### Anchor Smart Contract Development with Create Solana Program - -To use `create-solana-program` for native rust development, make sure you chose -Anchor when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├── lib.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -## Web App Scaffold - -```shell -npx create-solana-dapp -``` - -This command generates a new project that connects a Solana smart contract to a -frontend with a wallet connector. - -For additional information, check out its -[README](https://github.com/solana-developers/create-solana-dapp). - -To test out this project before making any modifications, follow these steps: - -1. Build the smart contract: - -```shell -npm run anchor-build -``` - -2. Start the local validator: - -```shell -npm run anchor-localnet -``` - -3. Run tests: - -```shell -npm run anchor-test -``` - -4. Deploy to the local validator: - -```shell -npm run anchor deploy --provider.cluster localnet -``` - -5. Build the web app: - -```shell -npm run build -``` - -6. Run the web app: - -```shell -npm run dev -``` - -## Mobile App Templates - -```shell -yarn create expo-app --template @solana-mobile/solana-mobile-expo-template -``` - -This is initializing a new project using the Expo framework that is specifically -designed for creating mobile applications that interact with the Solana -blockchain. - -Follow their -[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) -guide to launch the template as a custom development build and get it running on -your Android emulator. Once you have built the program and are running a dev -client with Expo, the emulator will automatically update every time you save -your code. - -To use this template, you will also need to set up the following: - -- [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) -- [React Native](https://reactnative.dev/docs/environment-setup?platform=android) -- [EAS CLI and Account](https://docs.expo.dev/build/setup/) - -For additional information on Solana Mobile Development: -https://docs.solanamobile.com/getting-started/intro - -## Working on an Existing Project - -If you have an existing anchor program and want to use the -[create solana program tool](#general-smart-contract-scaffold), you can easily -replace the generated program with your existing one: - -1. Ensure the installed Solana and Anchor versions are the same as the ones your - existing program requires. - -2. Scaffold a new Solana program using Anchor. - `pnpm create solana-program --anchor`. - -3. Replace the `program` folder with your existing program directory (not the - workspace directory). If you have more than one program, add more folders to - the root directory and update the `members` attribute of the top-level - `Cargo.toml` accordingly. - -4. Ensure your program’s `Cargo.toml` contains the following metadata: - -```toml filename="Cargo.toml" -[package.metadata.solana] -program-id = "YOUR_PROGRAM_ADDRESS" -program-dependencies = [] -``` - -5. Build your program and clients. - -```shell -npm install -npm run programs:build -npm run generate -``` - -6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` - file so the `ID` alias points to the correct generated constant. - -7. If you have any generated clients, update the scaffolded tests so they work - with your existing program. diff --git a/docs/toolkit/projects/advanced-native.md b/docs/toolkit/projects/advanced-native.md new file mode 100644 index 000000000..9e61e4997 --- /dev/null +++ b/docs/toolkit/projects/advanced-native.md @@ -0,0 +1,68 @@ +--- +title: Advanced Native Smart Contracts +sidebarSortOrder: 4 +sidebarLabel: Advanced Native +--- + +```shell +npx create-solana-program +``` + +[Create solana program](https://github.com/solana-program/create-solana-program) +initializes a more complex workspace with everything you need for general Solana +smart contract development. This Scaffold allows you to write either native rust +smart contracts or anchor smart contracts. + +After running this command, you'll have the option to choose between Shank and +Anchor for the program framework: + +- **Shank** creates a vanilla Solana smart contract with Shank macros to + generate IDLs. For more information on Shank, read the + [README](https://github.com/metaplex-foundation/shank). + +- **Anchor** creates a smart contract using the Anchor framework, which + abstracts away many complexities enabling fast program development. For more + information on the Anchor framework, read the + [Anchor book](https://www.anchor-lang.com/). + +To use `create-solana-program` for native rust development, make sure you chose +Shank when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +Next, you'll have the option to choose between a JavaScript client, a Rust +Client, or both. + +- **JavaScript Client** creates a typescript library compatible with + [web3.js](https://solana-labs.github.io/solana-web3.js/). + +- **Rust Client** creates a rust crate allowing consumers to interact with the + smart contract. + +For further workspace customization and additional information, check out the +`create-solana-program` +[README](https://github.com/solana-program/create-solana-program/tree/main). + +After answering the above questions, the workspace will be generated. To get +started, build your program and clients by running: + +```shell +cd +npm install +npm dev generate +``` diff --git a/docs/toolkit/projects/advanded-anchor.md b/docs/toolkit/projects/advanded-anchor.md new file mode 100644 index 000000000..f1f0036ac --- /dev/null +++ b/docs/toolkit/projects/advanded-anchor.md @@ -0,0 +1,61 @@ +--- +title: Advanced Anchor Smart Contracts +sidebarSortOrder: 3 +sidebarLabel: Advanced Anchor +--- + +```shell +npx create-solana-program +``` + +[Create solana program](https://github.com/solana-program/create-solana-program) +initializes a more complex workspace with everything you need for general Solana +smart contract development. This Scaffold allows you to write either native rust +smart contracts or anchor smart contracts. + +After running this command, you'll have the option to choose between Shank and +Anchor for the program framework: + +- **Shank** creates a vanilla Solana smart contract with Shank macros to + generate IDLs. For more information on Shank, read the + [README](https://github.com/metaplex-foundation/shank). + +- **Anchor** creates a smart contract using the Anchor framework, which + abstracts away many complexities enabling fast program development. For more + information on the Anchor framework, read the + [Anchor book](https://www.anchor-lang.com/). + +To use `create-solana-program` for native rust development, make sure you chose +Anchor when asked which program framework to use. This will create a basic +counter program with the following project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── lib.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +Next, you'll have the option to choose between a JavaScript client, a Rust +Client, or both. + +- **JavaScript Client** creates a typescript library compatible with + [web3.js](https://solana-labs.github.io/solana-web3.js/). + +- **Rust Client** creates a rust crate allowing consumers to interact with the + smart contract. + +For further workspace customization and additional information, check out the +`create-solana-program` +[README](https://github.com/solana-program/create-solana-program/tree/main). + +After answering the above questions, the workspace will be generated. To get +started, build your program and clients by running: + +```shell +cd +npm install +npm dev generate +``` diff --git a/docs/toolkit/projects/anchor-init.md b/docs/toolkit/projects/anchor-init.md new file mode 100644 index 000000000..e6f7fa165 --- /dev/null +++ b/docs/toolkit/projects/anchor-init.md @@ -0,0 +1,59 @@ +--- +title: Basic Anchor Smart Contracts +sidebarSortOrder: 2 +sidebarLabel: Basic Anchor +--- + +```shell +anchor init +``` + +This initializes a simplistic workspace set up for Anchor smart contract +development, with the following structure: + +- `Anchor.toml`: Anchor configuration file. +- `Cargo.toml`: Rust workspace configuration file. +- `package.json`: JavaScript dependencies file. +- `programs/`: Directory for Solana program crates. +- `app/`: Directory for your application frontend. +- `tests/`: Directory for JavaScript integration tests. +- `migrations/deploy.js`: Deploy script. + +The Anchor framework abstracts away many complexities enabling fast program +development. + +To test out this project before making any modifications, just build and test: + +```shell +anchor build +``` + +```shell +anchor test +``` + +To start writing your own anchor smart contract, navigate to +`programs/src/lib.rs`. + +For more complex programs, using a more structured project template would be +best practice. This can be generated with: + +```shell +anchor init --template multiple +``` + +which creates the following layout inside of `programs/src`: + +```shell +├── constants.rs +├── error.rs +├── instructions +│ ├── initialize.rs +│ └── mod.rs +├── lib.rs +└── state + └── mod.rs +``` + +For more information on the Anchor framework, check out the +[Anchor book](https://www.anchor-lang.com/). diff --git a/docs/toolkit/projects/existing-project.md b/docs/toolkit/projects/existing-project.md new file mode 100644 index 000000000..18bd2a740 --- /dev/null +++ b/docs/toolkit/projects/existing-project.md @@ -0,0 +1,42 @@ +--- +title: Update an Existing Project +sidebarSortOrder: 7 +sidebarLabel: Existing Project +--- + +If you have an existing anchor program and want to use the +[Create solana program](https://github.com/solana-program/create-solana-program) +tool, you can easily replace the generated program with your existing one: + +1. Ensure the installed Solana and Anchor versions are the same as the ones your + existing program requires. + +2. Scaffold a new Solana program using Anchor. + `pnpm create solana-program --anchor`. + +3. Replace the `program` folder with your existing program directory (not the + workspace directory). If you have more than one program, add more folders to + the root directory and update the `members` attribute of the top-level + `Cargo.toml` accordingly. + +4. Ensure your program’s `Cargo.toml` contains the following metadata: + +```toml filename="Cargo.toml" +[package.metadata.solana] +program-id = "YOUR_PROGRAM_ADDRESS" +program-dependencies = [] +``` + +5. Build your program and clients. + +```shell +npm install +npm run programs:build +npm run generate +``` + +6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` + file so the `ID` alias points to the correct generated constant. + +7. If you have any generated clients, update the scaffolded tests so they work + with your existing program. diff --git a/docs/toolkit/projects/index.md b/docs/toolkit/projects/index.md new file mode 100644 index 000000000..678a8ba0f --- /dev/null +++ b/docs/toolkit/projects/index.md @@ -0,0 +1,6 @@ +--- +title: Creating a Project +sidebarSortOrder: 2 +sidebarLabel: Creating a Project +metaOnly: true +--- diff --git a/docs/toolkit/projects/mobile-app.md b/docs/toolkit/projects/mobile-app.md new file mode 100644 index 000000000..12d33a1d5 --- /dev/null +++ b/docs/toolkit/projects/mobile-app.md @@ -0,0 +1,29 @@ +--- +title: Mobile App with a Smart Contract Connection +sidebarSortOrder: 6 +sidebarLabel: Mobile App +--- + +```shell +yarn create expo-app --template @solana-mobile/solana-mobile-expo-template +``` + +This is initializing a new project using the Expo framework that is specifically +designed for creating mobile applications that interact with the Solana +blockchain. + +Follow their +[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) +guide to launch the template as a custom development build and get it running on +your Android emulator. Once you have built the program and are running a dev +client with Expo, the emulator will automatically update every time you save +your code. + +To use this template, you will also need to set up the following: + +- [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) +- [React Native](https://reactnative.dev/docs/environment-setup?platform=android) +- [EAS CLI and Account](https://docs.expo.dev/build/setup/) + +For additional information on Solana Mobile Development: +https://docs.solanamobile.com/getting-started/intro diff --git a/docs/toolkit/projects/overview.md b/docs/toolkit/projects/overview.md new file mode 100644 index 000000000..03d3806db --- /dev/null +++ b/docs/toolkit/projects/overview.md @@ -0,0 +1,26 @@ +--- +title: Available Project Templates +sidebarSortOrder: 1 +sidebarLabel: Overview +--- + +There are several project scaffolds available for various use cases. Here is a +high level overview: + +- [Basic Anchor Smart Contracts](anchor-init.md): Generates a basic workspace to + be able to write an anchor rust smart contracts, build, test, and deploy. +- [Advanced Anchor Smart Contracts](advanced-anchor.md): Generates an in-depth + workspace for Anchor smart contract development with a Javascript Client and a + Rust Client. +- [Advanced Native Smart Contracts](advanced-native.md): Generates an in-depth + workspace for Native smart contract development with a Shank IDL, a Javascript + Client, and a Rust Client. +- [Web App with a Smart Contract Connection](web-app.md): Initializes a new + project that connects a Solana smart contract to a typescript frontend with a + wallet connector. +- [Mobile App with a Smart Contract Connection](mobile-app.md): Initializes a + new project using the Expo framework that is specifically designed for + creating mobile applications that interact with the Solana blockchain. +- [Update an Existing Project to Use a Solana Scaffold](existing-project.md): + Scaffolds a new program repository and replaces the generated program with + your existing one. diff --git a/docs/toolkit/projects/project-layout.md b/docs/toolkit/projects/project-layout.md new file mode 100644 index 000000000..8c480becb --- /dev/null +++ b/docs/toolkit/projects/project-layout.md @@ -0,0 +1,69 @@ +--- +title: Smart Contract File Structure +sidebarSortOrder: 8 +sidebarLabel: Project layout +--- + +Typically Solana smart contracts (aka [programs](/docs/core/programs.md)) +workspaces will be have the following file structure: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs +├── target +└── tests +``` + +The main smart contract is the `lib.rs` file, which lives insides the `programs` +directory, as shown below: + +```shell +. +├── app +├── migrations +├── node_modules +├── programs + ├── src + ├── lib.rs +├── target +└── tests +``` + +As the smart contract gets more cumbersome, you'll typically want to separate +the logic into multiple files, as shown below: + +```shell +├── programs + ├── src + ├── state.rs + ├── instructions + ├── instruction_1.rs + ├── instruction_2.rs + ├── instruction_3.rs + ├── lib.rs + ├── constants.rs + ├── error.rs + ├── mod.rs +``` + +For native rust smart contract development, you need to explicitly write out the +entrypoint and processor for the program, so you'll need a few more files: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├──assertions.rs +│ │ ├──entrypoint.rs +│ │ ├──error.rs +│ │ ├──instruction.rs +│ │ ├──lib.rs +│ │ ├──processor.rs +│ │ ├──state.rs +│ │ ├──utils.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` diff --git a/docs/toolkit/projects/web-app.md b/docs/toolkit/projects/web-app.md new file mode 100644 index 000000000..cb437559d --- /dev/null +++ b/docs/toolkit/projects/web-app.md @@ -0,0 +1,55 @@ +--- +title: Web App with a Smart Contract Connection +sidebarSortOrder: 5 +sidebarLabel: Web App +--- + +## Web App Scaffold + +```shell +npx create-solana-dapp +``` + +This command generates a new project that connects a Solana smart contract to a +frontend with a wallet connector. + +For additional information, check out its +[README](https://github.com/solana-developers/create-solana-dapp). + +To test out this project before making any modifications, follow these steps: + +1. Build the smart contract: + +```shell +npm run anchor-build +``` + +2. Start the local validator: + +```shell +npm run anchor-localnet +``` + +3. Run tests: + +```shell +npm run anchor-test +``` + +4. Deploy to the local validator: + +```shell +npm run anchor deploy --provider.cluster localnet +``` + +5. Build the web app: + +```shell +npm run build +``` + +6. Run the web app: + +```shell +npm run dev +``` diff --git a/docs/toolkit/test-suite.md b/docs/toolkit/test-suite.md index d24e9d52d..ba034174f 100644 --- a/docs/toolkit/test-suite.md +++ b/docs/toolkit/test-suite.md @@ -1,5 +1,7 @@ --- title: Test Suite +sidebarSortOrder: 4 +sidebarLabel: Test Suite --- Within the Solana toolkit, there are several resources for testing Solana Smart From c1cb328c4639caf9a6cbd6c5552135e36a11cb2b Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Tue, 7 Jan 2025 09:51:51 -0500 Subject: [PATCH 16/25] add test docs --- docs/toolkit/getting-started.md | 3 +- docs/toolkit/local-testing.md | 2 + docs/toolkit/test-suite.md | 232 -------------------- docs/toolkit/test-suite/code-coverage.md | 19 ++ docs/toolkit/test-suite/fuzz-tester.md | 60 +++++ docs/toolkit/test-suite/index.md | 17 ++ docs/toolkit/test-suite/js-test.md | 58 +++++ docs/toolkit/test-suite/rust-tests.md | 48 ++++ docs/toolkit/test-suite/security-scanner.md | 15 ++ docs/toolkit/test-suite/testing-basics.md | 38 ++++ 10 files changed, 258 insertions(+), 234 deletions(-) delete mode 100644 docs/toolkit/test-suite.md create mode 100644 docs/toolkit/test-suite/code-coverage.md create mode 100644 docs/toolkit/test-suite/fuzz-tester.md create mode 100644 docs/toolkit/test-suite/index.md create mode 100644 docs/toolkit/test-suite/js-test.md create mode 100644 docs/toolkit/test-suite/rust-tests.md create mode 100644 docs/toolkit/test-suite/security-scanner.md create mode 100644 docs/toolkit/test-suite/testing-basics.md diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index 4e591ea1d..81499c82f 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -76,5 +76,4 @@ To test locally, you must also spin up a local node to run on your localhost: mucho validator ``` -For a more information, read the -[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). +For a more information, read the [Local Testing Guide](local-testing.md). diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md index f4dfc66d5..0d428e1bb 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-testing.md @@ -1,5 +1,7 @@ --- title: Running a Local Network +sidebarSortOrder: 5 +sidebarLabel: Local Testing --- The Solana test validator is a local emulator for the Solana blockchain, diff --git a/docs/toolkit/test-suite.md b/docs/toolkit/test-suite.md deleted file mode 100644 index ba034174f..000000000 --- a/docs/toolkit/test-suite.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Test Suite -sidebarSortOrder: 4 -sidebarLabel: Test Suite ---- - -Within the Solana toolkit, there are several resources for testing Solana Smart -Contracts, including: - -- A fuzz tester -- A code coverage tool -- A framework for testing Solana programs in NodeJS that spins up a lightweight - `BanksServer` that's like an RPC node but much faster and creates a - `BanksClient` to talk to the server. -- A fast and lightweight library for testing Solana programs in Rust, which - works by creating an in-process Solana VM optimized for program developers. -- A tool to scan your repo for common security vulnerabilities and provide - suggestions for fixes. - -### Testing Basics - -Sync all the program's key. If you're using an Anchor program: - -```shell -anchor keys sync -``` - -Build the smart contract: - -```shell -npx solana build -``` - -Test the smart contract: - -```shell -npx solana test -``` - -Deploy the smart contract: - -```shell -npx solana deploy -``` - -If deploying to localnet, you must first start your local validator: - -```shell -solana-test-validator -``` - -For more information on local validator customization and commands, read the -[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). - -### Fuzz Tester - -Generate fuzz tests: - -```shell -npx solana fuzz -``` - -This command will initialize a Trident workspace and generate a new Fuzz Test -Template: - -```shell -project-root -├── trident-tests -│ ├── fuzz_tests # fuzz tests folder -│ │ ├── fuzz_0 # particular fuzz test -│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test -│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test -│ │ ├── fuzz_1 -│ │ ├── fuzz_X # possible multiple fuzz tests -│ │ ├── fuzzing # compilations and crashes folder -│ │ └── Cargo.toml -├── Trident.toml -└── ... -``` - -Run fuzz tests: - -```shell -npx solana fuzz run -``` - -The output of the fuzz tests is as follows: - -1. Number of Fuzzing Iterations. -2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. - feedback based on Coverage progress). -3. Average Iterations per second. -4. Number of crashes it found (panics or failed invariant checks). - -```shell -------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- - Iterations : 688 (out of: 1000 [68%]) # -- 1. -- - Mode [3/3] : Feedback Driven Mode # -- 2. -- - Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 - Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] - Speed : 680/sec [avg: 688] # -- 3. -- - Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- - Timeouts : 0 [10 sec] - Corpus Size : 98, max: 1048576 bytes, init: 0 files - Cov Update : 0 days 00 hrs 00 mins 00 secs ago - Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 ----------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- -``` - -View the source code [here](https://github.com/Ackee-Blockchain/trident). - -### Code Coverage Tool - -```shell -mucho coverage -``` - -This command will run a code coverage test on all of your Rust tests and then -generate report in an HTML page with in depth metrics on where additional code -may be needed to improve your current code coverage. - -Note: So far, this tool only works on tests written in Rust and is not -compatible with a JavaScript test suite. - -View the source code -[here](https://github.com/LimeChain/zest?tab=readme-ov-file). - -### JavaScript Testing Framework - -```shell -npm install solana-bankrun -``` - -[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and -lightweight framework for testing solana programs in NodeJS. - -It uses [solana-program-test](https://crates.io/crates/solana-program-test) -under the hood and allows you to do things that are not possible with -`solana-test-validator`, such as jumping back and forth in time or dynamically -setting account data. - -Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node -but much faster, and creating a `BanksClient` to talk to the server. This runs -the Solana -[Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). - -Here is a minimal example of this framework: - -```javascript -import { start } from "solana-bankrun"; -import { PublicKey, Transaction, SystemProgram } from "@solana/web3.js"; - -test("one transfer", async () => { - const context = await start([], []); - const client = context.banksClient; - const payer = context.payer; - const receiver = PublicKey.unique(); - const blockhash = context.lastBlockhash; - const transferLamports = 1_000_000n; - const ixs = [ - SystemProgram.transfer({ - fromPubkey: payer.publicKey, - toPubkey: receiver, - lamports: transferLamports, - }), - ]; - const tx = new Transaction(); - tx.recentBlockhash = blockhash; - tx.add(...ixs); - tx.sign(payer); - await client.processTransaction(tx); - const balanceAfter = await client.getBalance(receiver); - expect(balanceAfter).toEqual(transferLamports); -}); -``` - -For more complex examples, please refer to the -[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) - -### Rust Testing Library - -```shell -cargo add --dev litesvm -``` - -[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library -for testing Solana programs. It works by creating an in-process Solana VM -optimized for program developers. This makes it much faster to run and compile -than alternatives like solana-program-test and solana-test-validator. In a -further break from tradition, it has an ergonomic API with sane defaults and -extensive configurability for those who want it. - -Here is a minimal example: - -```rust -use litesvm::LiteSVM; -use solana_program::{message::Message, pubkey::Pubkey, system_instruction::transfer}; -use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction}; - -let from_keypair = Keypair::new(); -let from = from_keypair.pubkey(); -let to = Pubkey::new_unique(); - -let mut svm = LiteSVM::new(); -svm.airdrop(&from, 10_000).unwrap(); - -let instruction = transfer(&from, &to, 64); -let tx = Transaction::new( - &[&from_keypair], - Message::new(&[instruction], Some(&from)), - svm.latest_blockhash(), -); -let tx_res = svm.send_transaction(tx).unwrap(); - -let from_account = svm.get_account(&from); -let to_account = svm.get_account(&to); -assert_eq!(from_account.unwrap().lamports, 4936); -assert_eq!(to_account.unwrap().lamports, 64); - -``` - -### Security Vulnerability Scanner - -[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static -analysis tool for anchor rust programs. It allows you to write, share, and -utilize templates to identify security issues in rust-based smart contracts -using a powerful python based rule engine that enables automating detection of -vulnerable code patterns through logical expressions. - -[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform -command-line interface (CLI) tool designed for static analysis of Solana -programs and smart contracts written in Rust. diff --git a/docs/toolkit/test-suite/code-coverage.md b/docs/toolkit/test-suite/code-coverage.md new file mode 100644 index 000000000..a924dd9cf --- /dev/null +++ b/docs/toolkit/test-suite/code-coverage.md @@ -0,0 +1,19 @@ +--- +title: Solana Code Coverage Tool +sidebarSortOrder: 2 +sidebarLabel: Code Coverage +--- + +```shell +mucho coverage +``` + +This command will run a code coverage test on all of your Rust tests and then +generate report in an HTML page with in depth metrics on where additional code +may be needed to improve your current code coverage. + +Note: So far, this tool only works on tests written in Rust and is not +compatible with a JavaScript test suite. + +View the source code +[here](https://github.com/LimeChain/zest?tab=readme-ov-file). diff --git a/docs/toolkit/test-suite/fuzz-tester.md b/docs/toolkit/test-suite/fuzz-tester.md new file mode 100644 index 000000000..b13bed056 --- /dev/null +++ b/docs/toolkit/test-suite/fuzz-tester.md @@ -0,0 +1,60 @@ +--- +title: Solana Fuzz Tester +sidebarSortOrder: 1 +sidebarLabel: Fuzz Tester +--- + +Generate fuzz tests: + +```shell +npx solana fuzz +``` + +This command will initialize a Trident workspace and generate a new Fuzz Test +Template: + +```shell +project-root +├── trident-tests +│ ├── fuzz_tests # fuzz tests folder +│ │ ├── fuzz_0 # particular fuzz test +│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test +│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test +│ │ ├── fuzz_1 +│ │ ├── fuzz_X # possible multiple fuzz tests +│ │ ├── fuzzing # compilations and crashes folder +│ │ └── Cargo.toml +├── Trident.toml +└── ... +``` + +Run fuzz tests: + +```shell +npx solana fuzz run +``` + +The output of the fuzz tests is as follows: + +1. Number of Fuzzing Iterations. +2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. + feedback based on Coverage progress). +3. Average Iterations per second. +4. Number of crashes it found (panics or failed invariant checks). + +```shell +------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- + Iterations : 688 (out of: 1000 [68%]) # -- 1. -- + Mode [3/3] : Feedback Driven Mode # -- 2. -- + Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 + Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] + Speed : 680/sec [avg: 688] # -- 3. -- + Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- + Timeouts : 0 [10 sec] + Corpus Size : 98, max: 1048576 bytes, init: 0 files + Cov Update : 0 days 00 hrs 00 mins 00 secs ago + Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 +---------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- +``` + +View the source code [here](https://github.com/Ackee-Blockchain/trident). diff --git a/docs/toolkit/test-suite/index.md b/docs/toolkit/test-suite/index.md new file mode 100644 index 000000000..e551d2201 --- /dev/null +++ b/docs/toolkit/test-suite/index.md @@ -0,0 +1,17 @@ +--- +title: Test Suite Overview +sidebarSortOrder: 4 +--- + +Within the Solana toolkit, there are several resources for testing Solana Smart +Contracts, including: + +- A fuzz tester +- A code coverage tool +- A framework for testing Solana programs in NodeJS that spins up a lightweight + `BanksServer` that's like an RPC node but much faster and creates a + `BanksClient` to talk to the server. +- A fast and lightweight library for testing Solana programs in Rust, which + works by creating an in-process Solana VM optimized for program developers. +- A tool to scan your repo for common security vulnerabilities and provide + suggestions for fixes. diff --git a/docs/toolkit/test-suite/js-test.md b/docs/toolkit/test-suite/js-test.md new file mode 100644 index 000000000..aedb6ec67 --- /dev/null +++ b/docs/toolkit/test-suite/js-test.md @@ -0,0 +1,58 @@ +--- +title: JavaScript Testing Framework +sidebarSortOrder: 3 +sidebarLabel: JS Tests +--- + +> This is a dev dependency, you must `cd` into the directory you want to create +> JavaScript tests in before running the below command. + +```shell +npm install solana-bankrun +``` + +[Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and +lightweight framework for testing solana programs in NodeJS. + +It uses [solana-program-test](https://crates.io/crates/solana-program-test) +under the hood and allows you to do things that are not possible with +`solana-test-validator`, such as jumping back and forth in time or dynamically +setting account data. + +Bankrun works by spinning up a lightweight `BanksServer` that's like an RPC node +but much faster, and creating a `BanksClient` to talk to the server. This runs +the Solana +[Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). + +Here is a minimal example of this framework: + +```javascript +import { start } from "solana-bankrun"; +import { PublicKey, Transaction, SystemProgram } from "@solana/web3.js"; + +test("one transfer", async () => { + const context = await start([], []); + const client = context.banksClient; + const payer = context.payer; + const receiver = PublicKey.unique(); + const blockhash = context.lastBlockhash; + const transferLamports = 1_000_000n; + const ixs = [ + SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: receiver, + lamports: transferLamports, + }), + ]; + const tx = new Transaction(); + tx.recentBlockhash = blockhash; + tx.add(...ixs); + tx.sign(payer); + await client.processTransaction(tx); + const balanceAfter = await client.getBalance(receiver); + expect(balanceAfter).toEqual(transferLamports); +}); +``` + +For more complex examples, please refer to the +[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) diff --git a/docs/toolkit/test-suite/rust-tests.md b/docs/toolkit/test-suite/rust-tests.md new file mode 100644 index 000000000..e80125f44 --- /dev/null +++ b/docs/toolkit/test-suite/rust-tests.md @@ -0,0 +1,48 @@ +--- +title: Rust Testing Framework +sidebarSortOrder: 4 +sidebarLabel: Rust Tests +--- + +> This is a dev dependency, you must `cd` into the directory you want to create +> Rust tests in before running the below command. + +```shell +cargo add --dev litesvm +``` + +[LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library +for testing Solana programs. It works by creating an in-process Solana VM +optimized for program developers. This makes it much faster to run and compile +than alternatives like solana-program-test and solana-test-validator. In a +further break from tradition, it has an ergonomic API with sane defaults and +extensive configurability for those who want it. + +Here is a minimal example: + +```rust +use litesvm::LiteSVM; +use solana_program::{message::Message, pubkey::Pubkey, system_instruction::transfer}; +use solana_sdk::{signature::Keypair, signer::Signer, transaction::Transaction}; + +let from_keypair = Keypair::new(); +let from = from_keypair.pubkey(); +let to = Pubkey::new_unique(); + +let mut svm = LiteSVM::new(); +svm.airdrop(&from, 10_000).unwrap(); + +let instruction = transfer(&from, &to, 64); +let tx = Transaction::new( + &[&from_keypair], + Message::new(&[instruction], Some(&from)), + svm.latest_blockhash(), +); +let tx_res = svm.send_transaction(tx).unwrap(); + +let from_account = svm.get_account(&from); +let to_account = svm.get_account(&to); +assert_eq!(from_account.unwrap().lamports, 4936); +assert_eq!(to_account.unwrap().lamports, 64); + +``` diff --git a/docs/toolkit/test-suite/security-scanner.md b/docs/toolkit/test-suite/security-scanner.md new file mode 100644 index 000000000..7b988529f --- /dev/null +++ b/docs/toolkit/test-suite/security-scanner.md @@ -0,0 +1,15 @@ +--- +title: Security Vulnerability Scanner +sidebarSortOrder: 5 +sidebarLabel: Security Scanner +--- + +[Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static +analysis tool for anchor rust programs. It allows you to write, share, and +utilize templates to identify security issues in rust-based smart contracts +using a powerful python based rule engine that enables automating detection of +vulnerable code patterns through logical expressions. + +[Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform +command-line interface (CLI) tool designed for static analysis of Solana +programs and smart contracts written in Rust. diff --git a/docs/toolkit/test-suite/testing-basics.md b/docs/toolkit/test-suite/testing-basics.md new file mode 100644 index 000000000..8211c5e76 --- /dev/null +++ b/docs/toolkit/test-suite/testing-basics.md @@ -0,0 +1,38 @@ +--- +title: Testing Basics +sidebarSortOrder: 0 +sidebarLabel: Testing Basics +--- + +Sync all the program's key. If you're using an Anchor program: + +```shell +anchor keys sync +``` + +Build the smart contract: + +```shell +npx solana build +``` + +Test the smart contract: + +```shell +npx solana test +``` + +Deploy the smart contract: + +```shell +npx solana deploy +``` + +If deploying to localnet, you must first start your local validator: + +```shell +solana-test-validator +``` + +For more information on local validator customization and commands, read the +[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). From 132f61b5cdab4674d7edef257e5f58a4974a9491 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Tue, 7 Jan 2025 14:54:24 -0500 Subject: [PATCH 17/25] update --- docs/advanced/index.md | 2 +- docs/programs/index.md | 2 +- docs/toolkit/best-practices.md | 4 + docs/toolkit/getting-started.md | 10 +- docs/toolkit/index.md | 48 ++-------- docs/toolkit/local-testing.md | 20 ++-- docs/toolkit/projects/advanded-anchor.md | 61 ------------ docs/toolkit/projects/anchor-init.md | 19 +++- docs/toolkit/projects/existing-project.md | 6 +- docs/toolkit/projects/index.md | 62 +++++++++++- docs/toolkit/projects/mobile-app.md | 17 +++- docs/toolkit/projects/overview.md | 82 ++++++++++++---- docs/toolkit/projects/project-layout.md | 4 + .../{advanced-native.md => solana-program.md} | 51 ++++++++-- docs/toolkit/projects/web-app.md | 15 ++- docs/toolkit/test-suite/code-coverage.md | 23 +++-- docs/toolkit/test-suite/fuzz-tester.md | 96 +++++++++++-------- docs/toolkit/test-suite/index.md | 4 + docs/toolkit/test-suite/js-test.md | 19 +++- docs/toolkit/test-suite/rust-tests.md | 17 +++- docs/toolkit/test-suite/security-scanner.md | 4 + docs/toolkit/test-suite/testing-basics.md | 26 +++-- 22 files changed, 370 insertions(+), 222 deletions(-) delete mode 100644 docs/toolkit/projects/advanded-anchor.md rename docs/toolkit/projects/{advanced-native.md => solana-program.md} (57%) diff --git a/docs/advanced/index.md b/docs/advanced/index.md index 11ae9d7f4..82a978635 100644 --- a/docs/advanced/index.md +++ b/docs/advanced/index.md @@ -1,5 +1,5 @@ --- metaOnly: true title: Advanced Topics -sidebarSortOrder: 3 +sidebarSortOrder: 5 --- diff --git a/docs/programs/index.md b/docs/programs/index.md index 4189752bd..2fe2648e0 100644 --- a/docs/programs/index.md +++ b/docs/programs/index.md @@ -1,5 +1,5 @@ --- title: Developing Programs -sidebarSortOrder: 2 +sidebarSortOrder: 4 metaOnly: true --- diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index bf61f0838..0cb503cb7 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -4,6 +4,10 @@ sidebarSortOrder: 3 sidebarLabel: Best Practices --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + ## Optimize Compute Usage To prevent abuse of computational resources, each transaction is allocated a diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index 81499c82f..b73361de5 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -4,6 +4,10 @@ sidebarSortOrder: 1 sidebarLabel: Getting Started --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + The Solana Program development toolkit is publish as the [mucho npm package](https://www.npmjs.com/package/mucho). The `mucho` command will be used to run all the solana program development tools - _mucho tools, one @@ -73,7 +77,11 @@ solana config set --url localhost To test locally, you must also spin up a local node to run on your localhost: ```shell -mucho validator +npx mucho validator ``` For a more information, read the [Local Testing Guide](local-testing.md). + +### Next Steps + +Now let's [Create a Solana Project](projects/overview.md)! diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index eb1151133..58b72c3ac 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -1,54 +1,18 @@ --- title: The Solana Toolkit -sidebarSortOrder: -sidebarLabel: +sidebarSortOrder: 3 --- > This is a beta version of The Solana Toolkit, and is still a WIP. Please post > all feedback as a github issue > [here](https://github.com/solana-foundation/developer-content/issues). -The Solana Toolkit consists of all open sourced tools for smart contract -development on the Solana Blockchain. +The Solana Program development toolkit is publish as the +[mucho npm package](https://www.npmjs.com/package/mucho). The `mucho` command +will be used to run all the solana program development tools - _mucho tools, one +cli_. You can contribute to this book on [GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). -This toolkit includes tool CLIs: - -- [The Solana CLI](https://www.npmjs.com/package/solana) is meant to be a - generic utilitarian helper CLI to accomplish some basic setup and - troubleshooting for Solana development. - -- [The Mucho CLI](https://www.npmjs.com/package/mucho) is encapsulates all - additional tools for Solana Program development. - _Mucho Tools, One CLI_. - -## Sections - -### Getting Started - -To get started with The Solana Toolkit, install the toolkit, configure your -Solana CLI, fund your local keypair. - -### Creating a Project - -Set up your project with one of the open source scaffolds and templates -available. Each scaffold/template has a different purpose, so be sure to review -all the options explained in this section to pick the most optimal one for your -project. - -### Best Practices - -Make sure you're developing Solana smart contracts with best practices like -optimizing compute units, saving bumps, the payer-authority pattern, etc. - -### Test Suite - -Use the Solana Test Suite with the `mucho` CLI to have access to tools like a -fuzz tester, code coverage tool, security vulnerability scanner, etc. - -### Running a Local Network - -Run a local network to be able to build and test with a private and controlled -environment for Solana programs without the need to connect to a public testnet -or mainnet. +Now let's [Get Started](getting-started.md)! diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md index 0d428e1bb..b992b9897 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-testing.md @@ -48,7 +48,7 @@ solana ping This command pings the local test validator and returns the current blockhash and latency, verifying that it is active. -### Deploying and Managing Programs +### Deploying and Managing Programs Locally To deploy a compiled program (BPF) to the test validator: @@ -130,7 +130,7 @@ solana genesis-hash View all the configuration options available for the Solana test validator: ```shell -solana-test-validator --help +mucho validator --help ``` ### Local Ledger @@ -144,7 +144,7 @@ When starting the test validator, you can specify a different directory for the ledger data using the `--ledger` option: ```shell -solana-test-validator --ledger /path/to/custom/ledger +mucho validator --ledger /path/to/custom/ledger ``` ### Resetting the Ledger @@ -154,7 +154,7 @@ reset the ledger, you can either manually delete the ledger directory or restart the validator with the `--reset` flag: ```shell -solana-test-validator --reset +mucho validator --reset ``` If the ledger exists, this command will reset the ledger to genesis, which @@ -169,13 +169,13 @@ programs that already exist on any other cluster. To clone an account from another cluster: ```shell -solana-test-validator --clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +mucho validator--clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO ``` To clone an upgradeable program and its executable data from another cluster: ```shell -solana-test-validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +mucho validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO ``` > If a ledger already exists in your working directory, you must reset the @@ -189,7 +189,7 @@ account with a new ledger from any other network cluster. To clone an account from the cluster when a ledger already exists: ```shell -solana-test-validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset +mucho validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset ``` ### Reset to Specific Account Data @@ -206,7 +206,7 @@ solana account ACCOUNT_ADDRESS --output json > account_state.json Then load this state each time you reset the validator: ```shell -solana-test-validator --reset --account ACCOUNT_ADDRESS account_state.json +mucho validator --reset --account ACCOUNT_ADDRESS account_state.json ``` ### Runtime Features @@ -239,7 +239,7 @@ solana feature activate To deactivate specific features in genesis: ```shell -solana-test-validator --deactivate-feature --reset +mucho validator --deactivate-feature --reset ``` This must be done on a fresh ledger, so if a ledger already exists in your @@ -250,7 +250,7 @@ working directory you must add the `--reset` flag to reset to genesis. To check your current `solana-test-validator` version: ```shell -solana-test-validator --version +mucho validator --version ``` Your test validator runs on the same version as the Solana CLI installed and diff --git a/docs/toolkit/projects/advanded-anchor.md b/docs/toolkit/projects/advanded-anchor.md deleted file mode 100644 index f1f0036ac..000000000 --- a/docs/toolkit/projects/advanded-anchor.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Advanced Anchor Smart Contracts -sidebarSortOrder: 3 -sidebarLabel: Advanced Anchor ---- - -```shell -npx create-solana-program -``` - -[Create solana program](https://github.com/solana-program/create-solana-program) -initializes a more complex workspace with everything you need for general Solana -smart contract development. This Scaffold allows you to write either native rust -smart contracts or anchor smart contracts. - -After running this command, you'll have the option to choose between Shank and -Anchor for the program framework: - -- **Shank** creates a vanilla Solana smart contract with Shank macros to - generate IDLs. For more information on Shank, read the - [README](https://github.com/metaplex-foundation/shank). - -- **Anchor** creates a smart contract using the Anchor framework, which - abstracts away many complexities enabling fast program development. For more - information on the Anchor framework, read the - [Anchor book](https://www.anchor-lang.com/). - -To use `create-solana-program` for native rust development, make sure you chose -Anchor when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: - -```shell -├── program.rs -│ ├── src.rs -│ │ ├── lib.rs -│ ├── Cargo.toml -│ ├── keypair.json -│ ├── README.md -``` - -Next, you'll have the option to choose between a JavaScript client, a Rust -Client, or both. - -- **JavaScript Client** creates a typescript library compatible with - [web3.js](https://solana-labs.github.io/solana-web3.js/). - -- **Rust Client** creates a rust crate allowing consumers to interact with the - smart contract. - -For further workspace customization and additional information, check out the -`create-solana-program` -[README](https://github.com/solana-program/create-solana-program/tree/main). - -After answering the above questions, the workspace will be generated. To get -started, build your program and clients by running: - -```shell -cd -npm install -npm dev generate -``` diff --git a/docs/toolkit/projects/anchor-init.md b/docs/toolkit/projects/anchor-init.md index e6f7fa165..a85be389b 100644 --- a/docs/toolkit/projects/anchor-init.md +++ b/docs/toolkit/projects/anchor-init.md @@ -4,10 +4,16 @@ sidebarSortOrder: 2 sidebarLabel: Basic Anchor --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + ```shell anchor init ``` +## Overview + This initializes a simplistic workspace set up for Anchor smart contract development, with the following structure: @@ -22,6 +28,8 @@ development, with the following structure: The Anchor framework abstracts away many complexities enabling fast program development. +## Build and Test + To test out this project before making any modifications, just build and test: ```shell @@ -35,6 +43,8 @@ anchor test To start writing your own anchor smart contract, navigate to `programs/src/lib.rs`. +## File Structure Template + For more complex programs, using a more structured project template would be best practice. This can be generated with: @@ -55,5 +65,10 @@ which creates the following layout inside of `programs/src`: └── mod.rs ``` -For more information on the Anchor framework, check out the -[Anchor book](https://www.anchor-lang.com/). +For file structure best practices, review this [document](project-layout.md) + +## Additional Resources + +- [Anchor book](https://www.anchor-lang.com/) +- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/existing-project.md b/docs/toolkit/projects/existing-project.md index 18bd2a740..0624fbc36 100644 --- a/docs/toolkit/projects/existing-project.md +++ b/docs/toolkit/projects/existing-project.md @@ -1,9 +1,13 @@ --- title: Update an Existing Project sidebarSortOrder: 7 -sidebarLabel: Existing Project +sidebarLabel: Existing Projects --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + If you have an existing anchor program and want to use the [Create solana program](https://github.com/solana-program/create-solana-program) tool, you can easily replace the generated program with your existing one: diff --git a/docs/toolkit/projects/index.md b/docs/toolkit/projects/index.md index 678a8ba0f..4d77b6fd9 100644 --- a/docs/toolkit/projects/index.md +++ b/docs/toolkit/projects/index.md @@ -2,5 +2,65 @@ title: Creating a Project sidebarSortOrder: 2 sidebarLabel: Creating a Project -metaOnly: true --- + +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +Choose from one of the below scaffolds to generate a new project workspace: + +### Anchor + +```shell +anchor init +``` + +This generates a basic workspace to be able to write an anchor rust smart +contracts, build, test, and deploy. For more information, read the +[anchor init doc](anchor-init.md). + +### Create Solana Program + +```shell +pnpm create-solana-program +``` + +This generates an in-depth workspace for either Anchor smart contract +development or Native smart contract development with either a Javascript +Client, a Rust Client, or both. For more information, read the +[create-solana-program doc](solana-program.md). + +### Web App Template + +```shell +npx create-solana-dapp +``` + +This initializes a new project that connects a Solana smart contract to a +typescript frontend with a wallet connector. For more information, read the +[web app template doc](web-app.md) + +### Mobile App Template + +```shell +yarn create expo-app --template @solana-mobile/solana-mobile-expo-template +``` + +This is initializing a new project using the Expo framework that is specifically +designed for creating mobile applications that interact with the Solana +blockchain. + +### Update an Existing Project + +```shell +pnpm create-solana-program +``` + +You can add the solana program scaffold to an existing project by following this +[guide](existing-project.md). + +### Standard Project Layouts + +For best practices on smart contract file structure, read this +[guide](project-layout.md) diff --git a/docs/toolkit/projects/mobile-app.md b/docs/toolkit/projects/mobile-app.md index 12d33a1d5..98e23852f 100644 --- a/docs/toolkit/projects/mobile-app.md +++ b/docs/toolkit/projects/mobile-app.md @@ -4,10 +4,16 @@ sidebarSortOrder: 6 sidebarLabel: Mobile App --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + ```shell yarn create expo-app --template @solana-mobile/solana-mobile-expo-template ``` +## Overview + This is initializing a new project using the Expo framework that is specifically designed for creating mobile applications that interact with the Solana blockchain. @@ -19,11 +25,18 @@ your Android emulator. Once you have built the program and are running a dev client with Expo, the emulator will automatically update every time you save your code. +## Prerequisites + To use this template, you will also need to set up the following: - [Android Studio and Emulator](https://docs.solanamobile.com/getting-started/development-setup) - [React Native](https://reactnative.dev/docs/environment-setup?platform=android) - [EAS CLI and Account](https://docs.expo.dev/build/setup/) -For additional information on Solana Mobile Development: -https://docs.solanamobile.com/getting-started/intro +## Additional Resources + +- [Solana Mobile Development](https://docs.solanamobile.com/getting-started/intro) +- [Mobile App Example - Cash App Clone](../../../content/guides/dapps/cash-app.md) +- [Anchor book](https://www.anchor-lang.com/) +- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/overview.md b/docs/toolkit/projects/overview.md index 03d3806db..47e0c5662 100644 --- a/docs/toolkit/projects/overview.md +++ b/docs/toolkit/projects/overview.md @@ -1,26 +1,66 @@ --- -title: Available Project Templates +title: Smart Contract Project Templates sidebarSortOrder: 1 sidebarLabel: Overview --- -There are several project scaffolds available for various use cases. Here is a -high level overview: - -- [Basic Anchor Smart Contracts](anchor-init.md): Generates a basic workspace to - be able to write an anchor rust smart contracts, build, test, and deploy. -- [Advanced Anchor Smart Contracts](advanced-anchor.md): Generates an in-depth - workspace for Anchor smart contract development with a Javascript Client and a - Rust Client. -- [Advanced Native Smart Contracts](advanced-native.md): Generates an in-depth - workspace for Native smart contract development with a Shank IDL, a Javascript - Client, and a Rust Client. -- [Web App with a Smart Contract Connection](web-app.md): Initializes a new - project that connects a Solana smart contract to a typescript frontend with a - wallet connector. -- [Mobile App with a Smart Contract Connection](mobile-app.md): Initializes a - new project using the Expo framework that is specifically designed for - creating mobile applications that interact with the Solana blockchain. -- [Update an Existing Project to Use a Solana Scaffold](existing-project.md): - Scaffolds a new program repository and replaces the generated program with - your existing one. +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +Choose from one of the below scaffolds to generate a new project workspace: + +## Anchor + +```shell +anchor init +``` + +This generates a basic workspace to be able to write an anchor rust smart +contracts, build, test, and deploy. For more information, read the +[anchor init doc](anchor-init.md). + +## Create Solana Program + +```shell +pnpm create-solana-program +``` + +This generates an in-depth workspace for either Anchor smart contract +development or Native smart contract development with either a Javascript +Client, a Rust Client, or both. For more information, read the +[create-solana-program doc](solana-program.md). + +## Web App Template + +```shell +npx create-solana-dapp +``` + +This initializes a new project that connects a Solana smart contract to a +typescript frontend with a wallet connector. For more information, read the +[web app template doc](web-app.md) + +## Mobile App Template + +```shell +yarn create expo-app --template @solana-mobile/solana-mobile-expo-template +``` + +This is initializing a new project using the Expo framework that is specifically +designed for creating mobile applications that interact with the Solana +blockchain. + +## Update an Existing Project + +```shell +pnpm create-solana-program +``` + +You can add the solana program scaffold to an existing project by following this +[guide](existing-project.md). + +## Standard Project Layouts + +For best practices on smart contract file structure, read this +[guide](project-layout.md) diff --git a/docs/toolkit/projects/project-layout.md b/docs/toolkit/projects/project-layout.md index 8c480becb..ebe27b8c4 100644 --- a/docs/toolkit/projects/project-layout.md +++ b/docs/toolkit/projects/project-layout.md @@ -4,6 +4,10 @@ sidebarSortOrder: 8 sidebarLabel: Project layout --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + Typically Solana smart contracts (aka [programs](/docs/core/programs.md)) workspaces will be have the following file structure: diff --git a/docs/toolkit/projects/advanced-native.md b/docs/toolkit/projects/solana-program.md similarity index 57% rename from docs/toolkit/projects/advanced-native.md rename to docs/toolkit/projects/solana-program.md index 9e61e4997..5bd65f3fa 100644 --- a/docs/toolkit/projects/advanced-native.md +++ b/docs/toolkit/projects/solana-program.md @@ -1,18 +1,24 @@ --- -title: Advanced Native Smart Contracts -sidebarSortOrder: 4 -sidebarLabel: Advanced Native +title: Solana Program Scaffold +sidebarSortOrder: 3 +sidebarLabel: Solana Programs --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + ```shell npx create-solana-program ``` [Create solana program](https://github.com/solana-program/create-solana-program) -initializes a more complex workspace with everything you need for general Solana +initializes an in-depth workspace with everything you need for general Solana smart contract development. This Scaffold allows you to write either native rust smart contracts or anchor smart contracts. +## Program Frameworks + After running this command, you'll have the option to choose between Shank and Anchor for the program framework: @@ -25,9 +31,22 @@ Anchor for the program framework: information on the Anchor framework, read the [Anchor book](https://www.anchor-lang.com/). -To use `create-solana-program` for native rust development, make sure you chose -Shank when asked which program framework to use. This will create a basic -counter program with the following project structure for your program: +For **anchor rust development**, chose Anchor when asked which program framework +to use. This will create a basic anchor counter program with the following +project structure for your program: + +```shell +├── program.rs +│ ├── src.rs +│ │ ├── lib.rs +│ ├── Cargo.toml +│ ├── keypair.json +│ ├── README.md +``` + +For **native rust development**, make sure you chose Shank when asked which +program framework to use. This will create a basic counter program with the +following project structure for your program: ```shell ├── program.rs @@ -45,6 +64,8 @@ counter program with the following project structure for your program: │ ├── README.md ``` +## Generated Clients + Next, you'll have the option to choose between a JavaScript client, a Rust Client, or both. @@ -58,11 +79,21 @@ For further workspace customization and additional information, check out the `create-solana-program` [README](https://github.com/solana-program/create-solana-program/tree/main). -After answering the above questions, the workspace will be generated. To get +## Build + +After answering the above prompts, the workspace will be generated. To get started, build your program and clients by running: ```shell cd -npm install -npm dev generate +pnpm install +pnpm generate ``` + +To update an existing anchor project to have this scaffold, read this +[guide](existing-projects.md). + +## Additional Resources + +- [Rust Programs](../../programs/rust/index.md) +- [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/web-app.md b/docs/toolkit/projects/web-app.md index cb437559d..82dab064e 100644 --- a/docs/toolkit/projects/web-app.md +++ b/docs/toolkit/projects/web-app.md @@ -4,7 +4,9 @@ sidebarSortOrder: 5 sidebarLabel: Web App --- -## Web App Scaffold +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). ```shell npx create-solana-dapp @@ -13,8 +15,7 @@ npx create-solana-dapp This command generates a new project that connects a Solana smart contract to a frontend with a wallet connector. -For additional information, check out its -[README](https://github.com/solana-developers/create-solana-dapp). +## Build and Test To test out this project before making any modifications, follow these steps: @@ -53,3 +54,11 @@ npm run build ```shell npm run dev ``` + +## Additional Resources + +- [Create-solana-dapp README](https://github.com/solana-developers/create-solana-dapp) +- [CRUD App Example](../../../content/guides/dapps/journal.md) +- [Anchor book](https://www.anchor-lang.com/) +- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/test-suite/code-coverage.md b/docs/toolkit/test-suite/code-coverage.md index a924dd9cf..bda127cdb 100644 --- a/docs/toolkit/test-suite/code-coverage.md +++ b/docs/toolkit/test-suite/code-coverage.md @@ -1,19 +1,26 @@ --- title: Solana Code Coverage Tool -sidebarSortOrder: 2 +sidebarSortOrder: 1 sidebarLabel: Code Coverage --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + ```shell -mucho coverage +npx mucho coverage ``` +## Overview + This command will run a code coverage test on all of your Rust tests and then -generate report in an HTML page with in depth metrics on where additional code -may be needed to improve your current code coverage. +generate a report in an HTML page providing metrics on where additional code may +be needed to improve your current code coverage. + +> Currently, this tool only works on tests written in Rust and is not compatible +> with a JavaScript test suite. -Note: So far, this tool only works on tests written in Rust and is not -compatible with a JavaScript test suite. +## Additional Resources -View the source code -[here](https://github.com/LimeChain/zest?tab=readme-ov-file). +- [Source Code](https://github.com/LimeChain/zest?tab=readme-ov-file). diff --git a/docs/toolkit/test-suite/fuzz-tester.md b/docs/toolkit/test-suite/fuzz-tester.md index b13bed056..e47534654 100644 --- a/docs/toolkit/test-suite/fuzz-tester.md +++ b/docs/toolkit/test-suite/fuzz-tester.md @@ -1,60 +1,76 @@ --- title: Solana Fuzz Tester -sidebarSortOrder: 1 +sidebarSortOrder: 2 sidebarLabel: Fuzz Tester --- -Generate fuzz tests: +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +> The Fuzz tester is still a WIP. It currently is only anchor compatible and +> needs some manual work to complete tests + +## Initialize Fuzz Tests + +Navigate to an Anchor based workspace and run: ```shell -npx solana fuzz +trident init ``` -This command will initialize a Trident workspace and generate a new Fuzz Test -Template: +This command does the following: -```shell -project-root -├── trident-tests -│ ├── fuzz_tests # fuzz tests folder -│ │ ├── fuzz_0 # particular fuzz test -│ │ │ ├── test_fuzz.rs # the binary target of your fuzz test -│ │ │ └── fuzz_instructions.rs # the definition of your fuzz test -│ │ ├── fuzz_1 -│ │ ├── fuzz_X # possible multiple fuzz tests -│ │ ├── fuzzing # compilations and crashes folder -│ │ └── Cargo.toml -├── Trident.toml -└── ... +- Builds the Anchor-based project. +- Reads the generated IDL. +- Based on the IDL creates the fuzzing template. + +## Define Fuzz Accounts + +Define `AccountsStorage` type for each `Account` you would like to use + +```rust +#[doc = r" Use AccountsStorage where T can be one of:"] +#[doc = r" Keypair, PdaStore, TokenStore, MintStore, ProgramStore"] +#[derive(Default)] +pub struct FuzzAccounts { + author: AccountsStorage, + hello_world_account: AccountsStorage, + // No need to fuzz system_program + // system_program: AccountsStorage, +} ``` -Run fuzz tests: +## Implement Fuzz Instructions + +Each Instruction in the Fuzz Test has to have defined the following functions: + +- `get_program_id()` specifies to which program the Instruction belongs. This + function is automatically defined and should not need any updates. The + importance is such that if you have multiple programs in your workspace, + Trident can generate Instruction Sequences of Instruction corresponding to + different programs. +- `get_data()` specifies what Instruction inputs are send to the Program + Instructions. +- `get_accounts()` specifies what Accounts are send to the Program Instructions. + +## Execute Fuzz Tests ```shell -npx solana fuzz run +# Replace with the name of the +# fuzz test (for example: "fuzz_0") +trident fuzz run-hfuzz ``` -The output of the fuzz tests is as follows: - -1. Number of Fuzzing Iterations. -2. Feedback Driven Mode = Honggfuzz generates data based on the feedback (i.e. - feedback based on Coverage progress). -3. Average Iterations per second. -4. Number of crashes it found (panics or failed invariant checks). +## Debug Fuzz Tests ```shell -------------------------[ 0 days 00 hrs 00 mins 01 secs ]---------------------- - Iterations : 688 (out of: 1000 [68%]) # -- 1. -- - Mode [3/3] : Feedback Driven Mode # -- 2. -- - Target : trident-tests/fuzz_tests/fuzzing.....wn-linux-gnu/release/fuzz_0 - Threads : 16, CPUs: 32, CPU%: 1262% [39%/CPU] - Speed : 680/sec [avg: 688] # -- 3. -- - Crashes : 1 [unique: 1, blocklist: 0, verified: 0] # -- 4. -- - Timeouts : 0 [10 sec] - Corpus Size : 98, max: 1048576 bytes, init: 0 files - Cov Update : 0 days 00 hrs 00 mins 00 secs ago - Coverage : edge: 10345/882951 [1%] pc: 163 cmp: 622547 ----------------------------------- [ LOGS ] ------------------/ honggfuzz 2.6 /- +# fuzzer will run the with the specified +trident fuzz debug-hfuzz ``` -View the source code [here](https://github.com/Ackee-Blockchain/trident). +For additional documentation go [here](https://ackee.xyz/trident/docs/latest/). + +## Additional Resources + +- [Fuzz Tester Source Code](https://github.com/Ackee-Blockchain/trident). diff --git a/docs/toolkit/test-suite/index.md b/docs/toolkit/test-suite/index.md index e551d2201..0efe57ef3 100644 --- a/docs/toolkit/test-suite/index.md +++ b/docs/toolkit/test-suite/index.md @@ -3,6 +3,10 @@ title: Test Suite Overview sidebarSortOrder: 4 --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + Within the Solana toolkit, there are several resources for testing Solana Smart Contracts, including: diff --git a/docs/toolkit/test-suite/js-test.md b/docs/toolkit/test-suite/js-test.md index aedb6ec67..813b8a36b 100644 --- a/docs/toolkit/test-suite/js-test.md +++ b/docs/toolkit/test-suite/js-test.md @@ -4,13 +4,20 @@ sidebarSortOrder: 3 sidebarLabel: JS Tests --- -> This is a dev dependency, you must `cd` into the directory you want to create -> JavaScript tests in before running the below command. +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +## Add Dependency + +Navigate to your smart contract directory and run: ```shell npm install solana-bankrun ``` +## Overview + [Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and lightweight framework for testing solana programs in NodeJS. @@ -24,7 +31,7 @@ but much faster, and creating a `BanksClient` to talk to the server. This runs the Solana [Banks](https://github.com/solana-labs/solana/blob/master/runtime/src/bank.rs). -Here is a minimal example of this framework: +## Minimal Example ```javascript import { start } from "solana-bankrun"; @@ -54,5 +61,7 @@ test("one transfer", async () => { }); ``` -For more complex examples, please refer to the -[Solana Developers Bootcamp](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) +## Additional Resources + +- [Source Code]() +- [Complete Project Example](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) diff --git a/docs/toolkit/test-suite/rust-tests.md b/docs/toolkit/test-suite/rust-tests.md index e80125f44..f99032df2 100644 --- a/docs/toolkit/test-suite/rust-tests.md +++ b/docs/toolkit/test-suite/rust-tests.md @@ -4,13 +4,20 @@ sidebarSortOrder: 4 sidebarLabel: Rust Tests --- -> This is a dev dependency, you must `cd` into the directory you want to create -> Rust tests in before running the below command. +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +## Add Dependency + +Navigate to your smart contract directory and run: ```shell cargo add --dev litesvm ``` +## Overview + [LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library for testing Solana programs. It works by creating an in-process Solana VM optimized for program developers. This makes it much faster to run and compile @@ -18,7 +25,7 @@ than alternatives like solana-program-test and solana-test-validator. In a further break from tradition, it has an ergonomic API with sane defaults and extensive configurability for those who want it. -Here is a minimal example: +## Minimal Example ```rust use litesvm::LiteSVM; @@ -46,3 +53,7 @@ assert_eq!(from_account.unwrap().lamports, 4936); assert_eq!(to_account.unwrap().lamports, 64); ``` + +## Additional Resources + +- [Source Code](https://github.com/LiteSVM/litesvm) diff --git a/docs/toolkit/test-suite/security-scanner.md b/docs/toolkit/test-suite/security-scanner.md index 7b988529f..f34c52d38 100644 --- a/docs/toolkit/test-suite/security-scanner.md +++ b/docs/toolkit/test-suite/security-scanner.md @@ -4,6 +4,10 @@ sidebarSortOrder: 5 sidebarLabel: Security Scanner --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + [Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static analysis tool for anchor rust programs. It allows you to write, share, and utilize templates to identify security issues in rust-based smart contracts diff --git a/docs/toolkit/test-suite/testing-basics.md b/docs/toolkit/test-suite/testing-basics.md index 8211c5e76..fab3dbf91 100644 --- a/docs/toolkit/test-suite/testing-basics.md +++ b/docs/toolkit/test-suite/testing-basics.md @@ -4,34 +4,40 @@ sidebarSortOrder: 0 sidebarLabel: Testing Basics --- -Sync all the program's key. If you're using an Anchor program: +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + +## Build ```shell -anchor keys sync +npx mucho build ``` -Build the smart contract: +## Start Localnet ```shell -npx solana build +npx mucho validator ``` -Test the smart contract: +## Run Tests + +Anchor Programs: ```shell -npx solana test +anchor test ``` -Deploy the smart contract: +Native Programs: ```shell -npx solana deploy +cargo test ``` -If deploying to localnet, you must first start your local validator: +## Deploy ```shell -solana-test-validator +npx solana deploy ``` For more information on local validator customization and commands, read the From 41063caa867b5069c5803eb7583746691b9d6d3a Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Tue, 7 Jan 2025 17:30:28 -0500 Subject: [PATCH 18/25] fixes --- docs/toolkit/best-practices.md | 75 ++++++++++++++++++++- docs/toolkit/local-testing.md | 4 ++ docs/toolkit/test-suite/rust-tests.md | 2 + docs/toolkit/test-suite/security-scanner.md | 8 +++ docs/toolkit/troubleshooting.md | 11 +++ 5 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 docs/toolkit/troubleshooting.md diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index 0cb503cb7..8c097f8d5 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -31,7 +31,7 @@ error. Resulting in a failed transaction and no state changes (aside from the transaction fee being [collected](https://solana.com/docs/core/fees#fee-collection)). -### Solana Developer Guides +### Additional References - [How to Optimize Compute](https://solana.com/developers/guides/advanced/how-to-optimize-compute). - [How to Request Optimal Compute](https://solana.com/developers/guides/advanced/how-to-request-optimal-compute) @@ -42,6 +42,77 @@ Saving the bump to your Solana smart contract account state enables deterministic address generation, efficiency in address reconstruction, reduced transaction failure, and consistency across invocations. -### Solana Developer Guides +### Additional References - [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization#challenge) +- [PDA Bumps Core Concepts](https://solana.com/docs/core/pda#canonical-bump) + +## Payer-Authority Pattern + +The Payer-Authority pattern is an elegant way to handle situations where the +account’s funder (payer) differs from the account’s owner or manager +(authority). By requiring separate signers and validating them in your on-chain +logic, you can maintain clear, robust, and flexible ownership semantics in your +progra + +### Shank Example + +```rust +// Create a new account. +#[account(0, writable, signer, name="account", desc = "The address of the new account")] +#[account(1, writable, signer, name="payer", desc = "The account paying for the storage fees")] +#[account(2, optional, signer, name="authority", desc = "The authority signing for the account creation")] +#[account(3, name="system_program", desc = "The system program")] +CreateAccountV1(CreateAccountV1Args), +``` + +### Anchor Example + +```rust +#[derive(Accounts)] +pub struct CreateAccount<'info> { + /// The address of the new account + #[account(init, payer = payer_one, space = 8 + NewAccount::MAXIMUM_SIZE)] + pub account: Account<'info, NewAccount>, + + /// The account paying for the storage fees + #[account(mut)] + pub payer: Signer<'info>, + + /// The authority signing for the account creation + pub authority: Option>, + + // The system program + pub system_program: Program<'info, System> +} +``` + +### Additional References + +- [Metaplex Guide on Payer-Authority Pattern](https://developers.metaplex.com/guides/general/payer-authority-pattern) +- [Helium Program Library using the Payer-Authority Pattern](https://github.com/helium/helium-program-library/blob/master/programs/data-credits/src/instructions/change_delegated_sub_dao_v0.rs#L18) + +## Invariants + +Implement invariants, which are functions that you can call at the end of your +instruction to assert specific properties because they help ensure the +correctness and reliability of programs. + +```rust +require!(amount > 0, ErrorCode::InvalidAmount); +``` + +### Additional References + +- [Complete Project Code Example](https://github.com/solana-developers/developer-bootcamp-2024/blob/main/project-9-token-lottery/programs/token-lottery/src/lib.rs#L291) + +## Optimize Indexing + +You can make indexing easier by placing static size fields at the beginning and +variable size fields at the end of your on-chain structures. + +## Account Constraints + +## Noop/Self CPI + +## Safe Math diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-testing.md index b992b9897..f7b0d3219 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-testing.md @@ -4,6 +4,10 @@ sidebarSortOrder: 5 sidebarLabel: Local Testing --- +> This is a beta version of The Solana Toolkit, and is still a WIP. Please post +> all feedback as a github issue +> [here](https://github.com/solana-foundation/developer-content/issues). + The Solana test validator is a local emulator for the Solana blockchain, designed to provide developers with a private and controlled environment for building and testing Solana programs without the need to connect to a public diff --git a/docs/toolkit/test-suite/rust-tests.md b/docs/toolkit/test-suite/rust-tests.md index f99032df2..e18fca0ff 100644 --- a/docs/toolkit/test-suite/rust-tests.md +++ b/docs/toolkit/test-suite/rust-tests.md @@ -57,3 +57,5 @@ assert_eq!(to_account.unwrap().lamports, 64); ## Additional Resources - [Source Code](https://github.com/LiteSVM/litesvm) +- [Complete Project Example](https://github.com/cavemanloverboy/nawnce/blob/main/src/lib.rs) +- [More Complex Project Example](https://github.com/pyth-network/per) diff --git a/docs/toolkit/test-suite/security-scanner.md b/docs/toolkit/test-suite/security-scanner.md index f34c52d38..eb260f612 100644 --- a/docs/toolkit/test-suite/security-scanner.md +++ b/docs/toolkit/test-suite/security-scanner.md @@ -8,6 +8,8 @@ sidebarLabel: Security Scanner > all feedback as a github issue > [here](https://github.com/solana-foundation/developer-content/issues). +## Static Analysis tools + [Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static analysis tool for anchor rust programs. It allows you to write, share, and utilize templates to identify security issues in rust-based smart contracts @@ -17,3 +19,9 @@ vulnerable code patterns through logical expressions. [Xray](https://github.com/sec3-product/x-ray) is an open-source, cross-platform command-line interface (CLI) tool designed for static analysis of Solana programs and smart contracts written in Rust. + +## Common Security Exploits and Protections + +Read [Sealevel Attacks](https://github.com/coral-xyz/sealevel-attacks) for +examples of common exploits unique to the Solana programming model and +recommended idioms for avoiding these attacks using the Anchor framework. diff --git a/docs/toolkit/troubleshooting.md b/docs/toolkit/troubleshooting.md new file mode 100644 index 000000000..7994a36b7 --- /dev/null +++ b/docs/toolkit/troubleshooting.md @@ -0,0 +1,11 @@ +--- +title: Troubleshooting Solana Programs +sidebarSortOrder: 6 +sidebarLabel: Troubleshooting +--- + +## Solana Stack Exchange + +The [Solana stack exchange](https://solana.stackexchange.com/) is the best place +for conversations around Solana development. If you ever get stuck, ask your +question [here](https://solana.stackexchange.com/questions/ask). From 8b9ef2c3a3df459d072a90da3cb66d38324de174 Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 10:09:43 -0500 Subject: [PATCH 19/25] refactor: adjustments --- content/cookbook/wallets/sign-message.md | 1 + docs/advanced/confirmation.md | 2 +- docs/toolkit/best-practices.md | 31 ++-- docs/toolkit/getting-started.md | 35 ++--- docs/toolkit/index.md | 20 +-- .../{local-testing.md => local-validator.md} | 133 ++++++++++-------- docs/toolkit/projects/anchor-init.md | 17 +-- docs/toolkit/projects/existing-project.md | 59 +++++--- docs/toolkit/projects/index.md | 63 +-------- docs/toolkit/projects/mobile-app.md | 24 ++-- docs/toolkit/projects/overview.md | 37 +++-- docs/toolkit/projects/project-layout.md | 13 +- docs/toolkit/projects/solana-program.md | 34 +++-- docs/toolkit/projects/web-app.md | 31 ++-- .../{testing-basics.md => basics.md} | 12 +- docs/toolkit/test-suite/code-coverage.md | 14 +- docs/toolkit/test-suite/fuzz-tester.md | 32 ++--- docs/toolkit/test-suite/index.md | 20 +-- docs/toolkit/test-suite/js-test.md | 23 +-- docs/toolkit/test-suite/overview.md | 24 ++++ docs/toolkit/test-suite/rust-tests.md | 20 +-- docs/toolkit/test-suite/security-scanner.md | 10 +- docs/toolkit/troubleshooting.md | 7 + 23 files changed, 341 insertions(+), 321 deletions(-) rename docs/toolkit/{local-testing.md => local-validator.md} (64%) rename docs/toolkit/test-suite/{testing-basics.md => basics.md} (57%) create mode 100644 docs/toolkit/test-suite/overview.md diff --git a/content/cookbook/wallets/sign-message.md b/content/cookbook/wallets/sign-message.md index 42a07f1fd..06ae8819f 100644 --- a/content/cookbook/wallets/sign-message.md +++ b/content/cookbook/wallets/sign-message.md @@ -9,6 +9,7 @@ verification of the signature. Verification of a signature allows the recipient to be sure that the data was signed by the owner of a specific private key. + ```typescript diff --git a/docs/advanced/confirmation.md b/docs/advanced/confirmation.md index a4d1ae3bc..3d11b4975 100644 --- a/docs/advanced/confirmation.md +++ b/docs/advanced/confirmation.md @@ -194,7 +194,7 @@ decreased, users don't have enough time to submit their transaction. Currently, Solana clusters require that transactions use blockhashes that are no more than 151 blocks old. -> This [Github issue](https://github.com/solana-labs/solana/issues/23582) +> This [GitHub issue](https://github.com/solana-labs/solana/issues/23582) > contains some calculations that estimate that mainnet-beta validators need > about 150MB of memory to track transactions. This could be slimmed down in the > future if necessary without decreasing expiration time as are detailed in that diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index 8c097f8d5..28c16507a 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -4,9 +4,9 @@ sidebarSortOrder: 3 sidebarLabel: Best Practices --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ## Optimize Compute Usage @@ -38,22 +38,29 @@ transaction fee being ## Saving Bumps -Saving the bump to your Solana smart contract account state enables +> Program Derived Address (PDAs) are addresses that PDAs are addresses that are +> deterministically derived and look like standard public keys, but have no +> associated private keys. These PDAs are derived using a numerical value, +> called a "bump", to guarantee that the PDA is off-curve and cannot have an +> associated private key. It "bumps" the address off the cryptographic curve. + +Saving the bump to your Solana smart contract account state ensures deterministic address generation, efficiency in address reconstruction, reduced transaction failure, and consistency across invocations. ### Additional References -- [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization#challenge) -- [PDA Bumps Core Concepts](https://solana.com/docs/core/pda#canonical-bump) +- [How to derive a PDA](/docs/core/pda.md#how-to-derive-a-pda) +- [PDA Bumps Core Concepts](/docs/core/pda.md#canonical-bump) +- [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization) ## Payer-Authority Pattern The Payer-Authority pattern is an elegant way to handle situations where the account’s funder (payer) differs from the account’s owner or manager -(authority). By requiring separate signers and validating them in your on-chain +(authority). By requiring separate signers and validating them in your onchain logic, you can maintain clear, robust, and flexible ownership semantics in your -progra +program. ### Shank Example @@ -109,10 +116,4 @@ require!(amount > 0, ErrorCode::InvalidAmount); ## Optimize Indexing You can make indexing easier by placing static size fields at the beginning and -variable size fields at the end of your on-chain structures. - -## Account Constraints - -## Noop/Self CPI - -## Safe Math +variable size fields at the end of your onchain structures. diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index b73361de5..f8885ebdc 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -1,21 +1,21 @@ --- -title: Getting Started sidebarSortOrder: 1 sidebarLabel: Getting Started +title: Getting Started with the Solana Toolkit --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). The Solana Program development toolkit is publish as the -[mucho npm package](https://www.npmjs.com/package/mucho). The `mucho` command -will be used to run all the solana program development tools - _mucho tools, one -cli_. +[`mucho` npm package](https://www.npmjs.com/package/mucho). The `mucho` command +will be used to run most of the Solana program development tools within the +toolkit - _mucho tools, one cli_. ## Installation -To get started, install The Solana toolkit: +To get started, install The Solana Toolkit: ```shell npx mucho install @@ -26,17 +26,17 @@ This will install the latest versions of the following: - [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line tool that allows developers to interact with the Solana blockchain, manage accounts, send transactions, and deploy programs. -- [Rust](https://doc.rust-lang.org/book/): The Programming language that Solana +- [Rust](https://doc.rust-lang.org/book/): The programming language that Solana Smart Contracts are written in. - [Anchor](https://www.anchor-lang.com/): A framework for writing Solana programs that abstracts many complexities to speed up smart contract development. -- [Fuzz Tester](https://ackee.xyz/trident/docs/latest/): Rust-based Fuzzing +- [Fuzz Tester](https://ackee.xyz/trident/docs/latest/): Rust-based fuzzing framework for Solana programs to help you ship secure code. - [Code Coverage Tool](https://github.com/LimeChain/zest?tab=readme-ov-file): A code coverage CLI tool for Solana programs. -### Generate a keypair +## Generate a keypair For a fresh installation of the [Solana CLI](https://docs.anza.xyz/cli/), you're required to generate a new keypair. @@ -48,19 +48,19 @@ solana-keygen new _This will store the your new keypair at the Solana CLI's default path (`~/.config/solana/id.json`) and print the pubkey that was generated._ -### Query your keypair's public key +## Get your keypair's public key ```shell solana address ``` -### Fund your keypair +## Fund your keypair ```shell solana airdrop 10 --url localhost ``` -### Set your network configuration +## Set your network configuration Check your current config: @@ -80,8 +80,9 @@ To test locally, you must also spin up a local node to run on your localhost: npx mucho validator ``` -For a more information, read the [Local Testing Guide](local-testing.md). +For a more information, read the +[Local Testing Guide](/docs/toolkit/local-validator.md). -### Next Steps +## Next Steps -Now let's [Create a Solana Project](projects/overview.md)! +Now let's [Create a Solana Project](/docs/toolkit/projects/overview.md)! diff --git a/docs/toolkit/index.md b/docs/toolkit/index.md index 58b72c3ac..44f166f22 100644 --- a/docs/toolkit/index.md +++ b/docs/toolkit/index.md @@ -3,16 +3,16 @@ title: The Solana Toolkit sidebarSortOrder: 3 --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). -The Solana Program development toolkit is publish as the -[mucho npm package](https://www.npmjs.com/package/mucho). The `mucho` command -will be used to run all the solana program development tools - _mucho tools, one -cli_. +The Solana Program development toolkit is published as the +[`mucho` npm package](https://www.npmjs.com/package/mucho). The `mucho` command +will be used to run most of the Solana program development tools - _mucho tools, +one cli_. -You can contribute to this book on -[GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). +You can contribute to this +[Toolkit book on GitHub](https://github.com/solana-foundation/developer-content/tree/main/docs/toolkit). -Now let's [Get Started](getting-started.md)! +Now let's [Get Started](/docs/toolkit/getting-started.md)! diff --git a/docs/toolkit/local-testing.md b/docs/toolkit/local-validator.md similarity index 64% rename from docs/toolkit/local-testing.md rename to docs/toolkit/local-validator.md index f7b0d3219..4513e2d2a 100644 --- a/docs/toolkit/local-testing.md +++ b/docs/toolkit/local-validator.md @@ -1,46 +1,62 @@ --- -title: Running a Local Network +title: Running a Local Solana Validator Network sidebarSortOrder: 5 -sidebarLabel: Local Testing +sidebarLabel: Local Validator --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). The Solana test validator is a local emulator for the Solana blockchain, designed to provide developers with a private and controlled environment for building and testing Solana programs without the need to connect to a public -testnet or mainnet. If you have the Solana CLI tool suite already installed, you -can run the test validator with the following command: +testnet or mainnet. It also includes full support of the standard +[Solana RPC standard](/docs/rpc/http/index.mdx). + +If you have the Solana CLI tool suite already installed, you can run the test +validator with the following command: ```shell -mucho test-validator +npx mucho validator --help ``` -### Advantages +## Advantages - Ability to reset the blockchain state at any moment - Ability to simulate different network conditions - No RPC rate-limits - No airdrop limits -- Direct on-chain program deployment -- Ability to clone accounts from a public cluster -- Ability to load accounts from files +- Direct onchain program deployment +- Ability to clone accounts and programs from a public cluster (i.e. devnet, + mainnet, etc) +- Ability to load accounts and programs from files - Configurable transaction history retention - Configurable epoch length -### Starting the Test Validator +## Starting the Test Validator To start your local validator, simply run: ```shell -mucho test-validator +npx mucho validator ``` -This command initializes a new ledger and starts the validator. +This command initializes a new ledger and starts the local validator running at +`http://localhost:8899`, which can be used as your Solana RPC connection url. + +## Connecting to the Test Validator + +To connect to the local test validator with the Solana CLI: -### Checking the Status of the Test Validator +```shell +solana config set --url localhost +``` + +This will ensure all your Solana CLI commands will be directed to your local +test validator. + +## Checking the Status of the Test Validator Before interacting with the test validator, it's useful to confirm its status and ensure it is running correctly. @@ -52,7 +68,7 @@ solana ping This command pings the local test validator and returns the current blockhash and latency, verifying that it is active. -### Deploying and Managing Programs Locally +## Deploying and Managing Programs Locally To deploy a compiled program (BPF) to the test validator: @@ -68,7 +84,7 @@ To check the details of a deployed program: solana program show ``` -### Sending Transactions +## Sending Transactions To transfer SOL from one account to another: @@ -78,13 +94,14 @@ solana transfer --from /path/to/keypair.json This sends `AMOUNT` of SOL from the source account to the `RECIPIENT_ADDRESS`. -### Simulating and Confirming Transactions +## Simulating and Confirming Transactions Before actually sending a transaction, you can simulate it to see if it would likely succeed: ```shell -solana transfer --from /path/to/keypair.json --simulate +solana transfer --from /path/to/keypair.json \ + --simulate ``` To confirm the details and status of a transaction: @@ -93,7 +110,7 @@ To confirm the details and status of a transaction: solana confirm ``` -### Viewing Recent Block Production +## Viewing Recent Block Production To see information about recent block production, which can be useful for debugging performance issues: @@ -102,9 +119,7 @@ debugging performance issues: solana block-production ``` -### Creating Token Accounts - -### Adjusting Logs +## Validator Logs For debugging, you might want more detailed logs: @@ -123,21 +138,15 @@ This streams log messages from the validator. - Adjust the number of CPU cores used by the validator with the `--gossip-host` option to simulate network conditions more realistically. -### Configuration - -Check CLI Tool Suite configuration: - -```shell -solana genesis-hash -``` +## Configuration View all the configuration options available for the Solana test validator: ```shell -mucho validator --help +npx mucho validator --help ``` -### Local Ledger +## Local Ledger By default, the ledger data is stored in a directory named `test-ledger` in your current working directory. @@ -148,23 +157,23 @@ When starting the test validator, you can specify a different directory for the ledger data using the `--ledger` option: ```shell -mucho validator --ledger /path/to/custom/ledger +npx mucho validator --ledger /path/to/custom/ledger ``` -### Resetting the Ledger +## Resetting the Ledger By default the validator will resume an existing ledger, if one is found. To reset the ledger, you can either manually delete the ledger directory or restart the validator with the `--reset` flag: ```shell -mucho validator --reset +npx mucho validator --reset ``` If the ledger exists, this command will reset the ledger to genesis, which -resets the state by deleting all existing accounts and starting fresh. +resets the state by deleting all existing accounts/programs and starting fresh. -### Cloning Programs +## Cloning Programs To add existing onchain programs to your local environment, you can clone the program with a new ledger. This is useful for testing interactions with other @@ -173,19 +182,23 @@ programs that already exist on any other cluster. To clone an account from another cluster: ```shell -mucho validator--clone PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +npx mucho validator --reset \ + --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ + --clone PROGRAM_ADDRESS ``` To clone an upgradeable program and its executable data from another cluster: ```shell -mucho validator --clone-upgradeable-program PROGRAM_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO +npx mucho validator --reset \ + --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ + --clone-upgradeable-program PROGRAM_ADDRESS ``` > If a ledger already exists in your working directory, you must reset the -> ledger to be able to clone a program. +> ledger to be able to clone a program or account. -### Cloning Accounts +## Cloning Accounts To add existing onchain accounts to your local environment, you can clone the account with a new ledger from any other network cluster. @@ -193,10 +206,12 @@ account with a new ledger from any other network cluster. To clone an account from the cluster when a ledger already exists: ```shell -mucho validator --clone ACCOUNT_ADDRESS --url CLUSTER_PROGRAM_IS_DEPLOYED_TO --reset +npx mucho validator --reset \ + --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ + --clone ACCOUNT_ADDRESS ``` -### Reset to Specific Account Data +## Reset to Specific Account Data To reset the state of specific accounts every time you start the validator, you can use a combination of account snapshots and the `--account` flag. @@ -204,16 +219,17 @@ can use a combination of account snapshots and the `--account` flag. First, save the desired state of an account as a JSON file: ```shell -solana account ACCOUNT_ADDRESS --output json > account_state.json +solana account ACCOUNT_ADDRESS --output json --output-file account_state.json ``` Then load this state each time you reset the validator: ```shell -mucho validator --reset --account ACCOUNT_ADDRESS account_state.json +npx mucho validator --reset \ + --account ACCOUNT_ADDRESS account_state.json ``` -### Runtime Features +## Runtime Features Solana has a feature set mechanism that allows you to enable or disable certain blockchain features when running the test validator. By default, the test @@ -231,30 +247,29 @@ To query a specific runtime feature's status: solana feature status
``` -To activate a specific feature: +To deactivate specific features in genesis: + +> This must be done on a fresh ledger, so if a ledger already exists in your +> working directory you must add the `--reset` flag to reset to genesis. ```shell -solana feature activate +npx mucho validator --reset \ + --deactivate-feature ``` -- `FEATURE_KEYPAIR` is the signer for the feature to activate -- `CLUSTER` is the cluster to activate the feature on - -To deactivate specific features in genesis: +To deactivate multiple features in genesis: ```shell -mucho validator --deactivate-feature --reset +npx mucho validator --reset \ + --deactivate-feature ``` -This must be done on a fresh ledger, so if a ledger already exists in your -working directory you must add the `--reset` flag to reset to genesis. - -### Changing Versions +## Changing Versions To check your current `solana-test-validator` version: ```shell -mucho validator --version +npx mucho validator --version ``` Your test validator runs on the same version as the Solana CLI installed and diff --git a/docs/toolkit/projects/anchor-init.md b/docs/toolkit/projects/anchor-init.md index a85be389b..d14d19fba 100644 --- a/docs/toolkit/projects/anchor-init.md +++ b/docs/toolkit/projects/anchor-init.md @@ -4,9 +4,9 @@ sidebarSortOrder: 2 sidebarLabel: Basic Anchor --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell anchor init @@ -40,19 +40,19 @@ anchor build anchor test ``` -To start writing your own anchor smart contract, navigate to +To start writing your own Anchor smart contract, navigate to `programs/src/lib.rs`. ## File Structure Template -For more complex programs, using a more structured project template would be +For more complex programs, using a more structured project template would be the best practice. This can be generated with: ```shell anchor init --template multiple ``` -which creates the following layout inside of `programs/src`: +Which creates the following layout inside of `programs/src`: ```shell ├── constants.rs @@ -65,10 +65,11 @@ which creates the following layout inside of `programs/src`: └── mod.rs ``` -For file structure best practices, review this [document](project-layout.md) +For project file structure best practices, review this +[document](/docs/toolkit/projects/project-layout.md). ## Additional Resources - [Anchor book](https://www.anchor-lang.com/) -- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Getting Started with Anchor](/docs/programs/anchor/index.md) - [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/existing-project.md b/docs/toolkit/projects/existing-project.md index 0624fbc36..6f7ccde8d 100644 --- a/docs/toolkit/projects/existing-project.md +++ b/docs/toolkit/projects/existing-project.md @@ -4,26 +4,39 @@ sidebarSortOrder: 7 sidebarLabel: Existing Projects --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). -If you have an existing anchor program and want to use the -[Create solana program](https://github.com/solana-program/create-solana-program) +If you have an existing Anchor program and want to use the +[`create-solana-program`](https://github.com/solana-program/create-solana-program) tool, you can easily replace the generated program with your existing one: -1. Ensure the installed Solana and Anchor versions are the same as the ones your - existing program requires. + -2. Scaffold a new Solana program using Anchor. - `pnpm create solana-program --anchor`. +### Verify correct versions -3. Replace the `program` folder with your existing program directory (not the - workspace directory). If you have more than one program, add more folders to - the root directory and update the `members` attribute of the top-level - `Cargo.toml` accordingly. +Ensure the installed Solana and Anchor versions are the same as the ones your +existing program requires. -4. Ensure your program’s `Cargo.toml` contains the following metadata: +### Run create-solana-program + +Scaffold a new Solana program using Anchor by running: + +```shell +npx create-solana-program --anchor +``` + +### Migrate your program source code + +Replace the `program` folder with your existing program directory (not the +workspace directory). If you have more than one program, add more folders to the +root directory and update the `members` attribute of the top-level `Cargo.toml` +accordingly. + +### Update each program's Cargo.toml + +Ensure your program’s `Cargo.toml` contains the following metadata: ```toml filename="Cargo.toml" [package.metadata.solana] @@ -31,7 +44,9 @@ program-id = "YOUR_PROGRAM_ADDRESS" program-dependencies = [] ``` -5. Build your program and clients. +### Build your program and clients + +Run the following commands to build your programs and generate the clients: ```shell npm install @@ -39,8 +54,14 @@ npm run programs:build npm run generate ``` -6. If you have a generated Rust client, update the `clients/rust/src/lib.rs` - file so the `ID` alias points to the correct generated constant. +### Update the ID alias + +If you have a generated Rust client, update the `clients/rust/src/lib.rs` file +so the `ID` alias points to the correct generated constant. + +### Update any client tests + +If you have any generated clients, update the scaffolded tests so they work with +your existing program. -7. If you have any generated clients, update the scaffolded tests so they work - with your existing program. + diff --git a/docs/toolkit/projects/index.md b/docs/toolkit/projects/index.md index 4d77b6fd9..a6df26408 100644 --- a/docs/toolkit/projects/index.md +++ b/docs/toolkit/projects/index.md @@ -1,66 +1,5 @@ --- title: Creating a Project sidebarSortOrder: 2 -sidebarLabel: Creating a Project +metaOnly: true --- - -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). - -Choose from one of the below scaffolds to generate a new project workspace: - -### Anchor - -```shell -anchor init -``` - -This generates a basic workspace to be able to write an anchor rust smart -contracts, build, test, and deploy. For more information, read the -[anchor init doc](anchor-init.md). - -### Create Solana Program - -```shell -pnpm create-solana-program -``` - -This generates an in-depth workspace for either Anchor smart contract -development or Native smart contract development with either a Javascript -Client, a Rust Client, or both. For more information, read the -[create-solana-program doc](solana-program.md). - -### Web App Template - -```shell -npx create-solana-dapp -``` - -This initializes a new project that connects a Solana smart contract to a -typescript frontend with a wallet connector. For more information, read the -[web app template doc](web-app.md) - -### Mobile App Template - -```shell -yarn create expo-app --template @solana-mobile/solana-mobile-expo-template -``` - -This is initializing a new project using the Expo framework that is specifically -designed for creating mobile applications that interact with the Solana -blockchain. - -### Update an Existing Project - -```shell -pnpm create-solana-program -``` - -You can add the solana program scaffold to an existing project by following this -[guide](existing-project.md). - -### Standard Project Layouts - -For best practices on smart contract file structure, read this -[guide](project-layout.md) diff --git a/docs/toolkit/projects/mobile-app.md b/docs/toolkit/projects/mobile-app.md index 98e23852f..91eaac778 100644 --- a/docs/toolkit/projects/mobile-app.md +++ b/docs/toolkit/projects/mobile-app.md @@ -4,9 +4,9 @@ sidebarSortOrder: 6 sidebarLabel: Mobile App --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell yarn create expo-app --template @solana-mobile/solana-mobile-expo-template @@ -14,14 +14,14 @@ yarn create expo-app --template @solana-mobile/solana-mobile-expo-template ## Overview -This is initializing a new project using the Expo framework that is specifically -designed for creating mobile applications that interact with the Solana -blockchain. +This will initialize a new project using the [Expo](https://expo.dev) framework +that is specifically designed for creating mobile applications that interact +with the Solana blockchain. -Follow their -[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app) -guide to launch the template as a custom development build and get it running on -your Android emulator. Once you have built the program and are running a dev +Follow this template's guide for +"[Running the app](https://docs.solanamobile.com/react-native/expo#running-the-app)" +in order to launch the template as a custom development build and get it running +on your Android emulator. Once you have built the program and are running a dev client with Expo, the emulator will automatically update every time you save your code. @@ -36,7 +36,7 @@ To use this template, you will also need to set up the following: ## Additional Resources - [Solana Mobile Development](https://docs.solanamobile.com/getting-started/intro) -- [Mobile App Example - Cash App Clone](../../../content/guides/dapps/cash-app.md) +- [Mobile App Example - Cash App Clone](/content/guides/dapps/cash-app.md) - [Anchor book](https://www.anchor-lang.com/) -- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Getting Started with Anchor](/docs/programs/anchor/index.md) - [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/overview.md b/docs/toolkit/projects/overview.md index 47e0c5662..32b5b8e14 100644 --- a/docs/toolkit/projects/overview.md +++ b/docs/toolkit/projects/overview.md @@ -2,34 +2,45 @@ title: Smart Contract Project Templates sidebarSortOrder: 1 sidebarLabel: Overview +altRoutes: + - /docs/toolkit/projects --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). Choose from one of the below scaffolds to generate a new project workspace: +- [Anchor](#anchor) - A popular Rust-based framework for creating Solana smart + contracts. +- [`create-solana-program`](#create-solana-program) - In-depth workspace + generator for either Anchor smart contract development or Native smart + contract, including JavaScript and Rust clients. +- [Web App Templates](#web-app-template) - Generator for new projects that + connects a Solana smart contract to various frontend stacks, includes wallet + connector setup. + ## Anchor ```shell anchor init ``` -This generates a basic workspace to be able to write an anchor rust smart +This generates a basic workspace to be able to write an Anchor rust smart contracts, build, test, and deploy. For more information, read the -[anchor init doc](anchor-init.md). +[`anchor init` doc](/docs/toolkit/projects/anchor-init.md). ## Create Solana Program ```shell -pnpm create-solana-program +npx create-solana-program ``` This generates an in-depth workspace for either Anchor smart contract development or Native smart contract development with either a Javascript -Client, a Rust Client, or both. For more information, read the -[create-solana-program doc](solana-program.md). +Client, Rust Client, or both. For more information, read the +[`create-solana-program` doc](/docs/toolkit/projects/solana-program.md). ## Web App Template @@ -39,7 +50,7 @@ npx create-solana-dapp This initializes a new project that connects a Solana smart contract to a typescript frontend with a wallet connector. For more information, read the -[web app template doc](web-app.md) +[web app template doc](/docs/toolkit/projects/web-app.md). ## Mobile App Template @@ -54,13 +65,13 @@ blockchain. ## Update an Existing Project ```shell -pnpm create-solana-program +npx create-solana-program ``` -You can add the solana program scaffold to an existing project by following this -[guide](existing-project.md). +You can add the Solana program scaffold to an existing project by following this +[guide](/docs/toolkit/projects/existing-project.md). ## Standard Project Layouts For best practices on smart contract file structure, read this -[guide](project-layout.md) +[guide](/docs/toolkit/projects/project-layout.md). diff --git a/docs/toolkit/projects/project-layout.md b/docs/toolkit/projects/project-layout.md index ebe27b8c4..4c6cf631f 100644 --- a/docs/toolkit/projects/project-layout.md +++ b/docs/toolkit/projects/project-layout.md @@ -1,12 +1,12 @@ --- -title: Smart Contract File Structure +title: Smart Contract Repo File Structure sidebarSortOrder: 8 sidebarLabel: Project layout --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). Typically Solana smart contracts (aka [programs](/docs/core/programs.md)) workspaces will be have the following file structure: @@ -53,8 +53,9 @@ the logic into multiple files, as shown below: ├── mod.rs ``` -For native rust smart contract development, you need to explicitly write out the -entrypoint and processor for the program, so you'll need a few more files: +For [native rust smart contract development](/docs/programs/rust/index.md), you +need to explicitly write out the entrypoint and processor for the program, so +you'll need a few more files: ```shell ├── program.rs diff --git a/docs/toolkit/projects/solana-program.md b/docs/toolkit/projects/solana-program.md index 5bd65f3fa..f31290980 100644 --- a/docs/toolkit/projects/solana-program.md +++ b/docs/toolkit/projects/solana-program.md @@ -4,18 +4,18 @@ sidebarSortOrder: 3 sidebarLabel: Solana Programs --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell npx create-solana-program ``` -[Create solana program](https://github.com/solana-program/create-solana-program) +[`create-solana-program`](https://github.com/solana-program/create-solana-program) initializes an in-depth workspace with everything you need for general Solana -smart contract development. This Scaffold allows you to write either native rust -smart contracts or anchor smart contracts. +smart contract development. This scaffold allows you to write either native rust +smart contracts or Anchor smart contracts. ## Program Frameworks @@ -23,7 +23,7 @@ After running this command, you'll have the option to choose between Shank and Anchor for the program framework: - **Shank** creates a vanilla Solana smart contract with Shank macros to - generate IDLs. For more information on Shank, read the + generate IDLs. For more information on Shank, read its [README](https://github.com/metaplex-foundation/shank). - **Anchor** creates a smart contract using the Anchor framework, which @@ -31,8 +31,10 @@ Anchor for the program framework: information on the Anchor framework, read the [Anchor book](https://www.anchor-lang.com/). -For **anchor rust development**, chose Anchor when asked which program framework -to use. This will create a basic anchor counter program with the following +### Anchor framework + +For **Anchor rust development**, chose Anchor when asked which program framework +to use. This will create a basic Anchor counter program with the following project structure for your program: ```shell @@ -44,6 +46,8 @@ project structure for your program: │ ├── README.md ``` +### Native rust + For **native rust development**, make sure you chose Shank when asked which program framework to use. This will create a basic counter program with the following project structure for your program: @@ -77,7 +81,7 @@ Client, or both. For further workspace customization and additional information, check out the `create-solana-program` -[README](https://github.com/solana-program/create-solana-program/tree/main). +[README](https://github.com/solana-program/create-solana-program?tab=readme-ov-file). ## Build @@ -86,14 +90,14 @@ started, build your program and clients by running: ```shell cd -pnpm install -pnpm generate +npm install +npm run generate ``` -To update an existing anchor project to have this scaffold, read this -[guide](existing-projects.md). +To update an existing Anchor project to have this scaffold, read this +[guide](/docs/toolkit/projects/existing-project.md). ## Additional Resources -- [Rust Programs](../../programs/rust/index.md) +- [Developing Rust Programs](/docs/programs/rust/index.md) - [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/projects/web-app.md b/docs/toolkit/projects/web-app.md index 82dab064e..8a3f5e521 100644 --- a/docs/toolkit/projects/web-app.md +++ b/docs/toolkit/projects/web-app.md @@ -4,61 +4,66 @@ sidebarSortOrder: 5 sidebarLabel: Web App --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell npx create-solana-dapp ``` This command generates a new project that connects a Solana smart contract to a -frontend with a wallet connector. +frontend with a wallet connector. It has options for multiple popular frontend +stacks and UI libraries, including: NextJS, React, Tailwind, and more. ## Build and Test To test out this project before making any modifications, follow these steps: -1. Build the smart contract: + + +### Build the smart contract ```shell npm run anchor-build ``` -2. Start the local validator: +### Start the local validator ```shell npm run anchor-localnet ``` -3. Run tests: +### Run tests ```shell npm run anchor-test ``` -4. Deploy to the local validator: +### Deploy to the local validator ```shell npm run anchor deploy --provider.cluster localnet ``` -5. Build the web app: +### Build the web app ```shell npm run build ``` -6. Run the web app: +### Run the web app ```shell npm run dev ``` + + ## Additional Resources -- [Create-solana-dapp README](https://github.com/solana-developers/create-solana-dapp) -- [CRUD App Example](../../../content/guides/dapps/journal.md) +- [`create-solana-dapp` README](https://github.com/solana-developers/create-solana-dapp) +- [CRUD App Example](/content/guides/dapps/journal.md) - [Anchor book](https://www.anchor-lang.com/) -- [Getting Started with Anchor](../../programs/anchor/index.md) +- [Getting Started with Anchor](/docs/programs/anchor/index.md) - [Program Examples](https://github.com/solana-developers/program-examples) diff --git a/docs/toolkit/test-suite/testing-basics.md b/docs/toolkit/test-suite/basics.md similarity index 57% rename from docs/toolkit/test-suite/testing-basics.md rename to docs/toolkit/test-suite/basics.md index fab3dbf91..0a5b92c9a 100644 --- a/docs/toolkit/test-suite/testing-basics.md +++ b/docs/toolkit/test-suite/basics.md @@ -1,12 +1,12 @@ --- -title: Testing Basics -sidebarSortOrder: 0 sidebarLabel: Testing Basics +title: Solana Testing Basics +sidebarSortOrder: 2 --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ## Build @@ -41,4 +41,4 @@ npx solana deploy ``` For more information on local validator customization and commands, read the -[Solana Test Validator Guide](https://solana.com/developers/guides/getstarted/solana-test-validator). +[Solana Test Validator Guide](/content/guides/getstarted/solana-test-validator.md). diff --git a/docs/toolkit/test-suite/code-coverage.md b/docs/toolkit/test-suite/code-coverage.md index bda127cdb..7a16a1aea 100644 --- a/docs/toolkit/test-suite/code-coverage.md +++ b/docs/toolkit/test-suite/code-coverage.md @@ -1,12 +1,12 @@ --- title: Solana Code Coverage Tool -sidebarSortOrder: 1 +sidebarSortOrder: 3 sidebarLabel: Code Coverage --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell npx mucho coverage @@ -15,12 +15,12 @@ npx mucho coverage ## Overview This command will run a code coverage test on all of your Rust tests and then -generate a report in an HTML page providing metrics on where additional code may -be needed to improve your current code coverage. +generates a report as an HTML page providing metrics on where additional tests +may be needed to improve your current code coverage. > Currently, this tool only works on tests written in Rust and is not compatible > with a JavaScript test suite. ## Additional Resources -- [Source Code](https://github.com/LimeChain/zest?tab=readme-ov-file). +- [Source Code](https://github.com/LimeChain/zest?tab=readme-ov-file) diff --git a/docs/toolkit/test-suite/fuzz-tester.md b/docs/toolkit/test-suite/fuzz-tester.md index e47534654..20eeba331 100644 --- a/docs/toolkit/test-suite/fuzz-tester.md +++ b/docs/toolkit/test-suite/fuzz-tester.md @@ -1,15 +1,15 @@ --- title: Solana Fuzz Tester -sidebarSortOrder: 2 +sidebarSortOrder: 4 sidebarLabel: Fuzz Tester --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). -> The Fuzz tester is still a WIP. It currently is only anchor compatible and -> needs some manual work to complete tests +> The Trident fuzz tester is still a WIP and currently only Anchor compatible +> may require some manual work to complete tests. ## Initialize Fuzz Tests @@ -27,7 +27,7 @@ This command does the following: ## Define Fuzz Accounts -Define `AccountsStorage` type for each `Account` you would like to use +Define `AccountsStorage` type for each `Account` you would like to use: ```rust #[doc = r" Use AccountsStorage where T can be one of:"] @@ -43,16 +43,16 @@ pub struct FuzzAccounts { ## Implement Fuzz Instructions -Each Instruction in the Fuzz Test has to have defined the following functions: +Each Instruction in the fuzz test has to have defined the following functions: -- `get_program_id()` specifies to which program the Instruction belongs. This - function is automatically defined and should not need any updates. The - importance is such that if you have multiple programs in your workspace, - Trident can generate Instruction Sequences of Instruction corresponding to - different programs. -- `get_data()` specifies what Instruction inputs are send to the Program - Instructions. -- `get_accounts()` specifies what Accounts are send to the Program Instructions. +- `get_program_id()` specifies which program the instruction belongs to. This + function is automatically defined and should not need any updates. Its + important to use especially if you have multiple programs in your workspace, + allowing Trident to generate instruction sequences corresponding to different + programs. +- `get_data()` specifies what instruction inputs are sent to the program + instructions. +- `get_accounts()` specifies what accounts are sent to the program instructions. ## Execute Fuzz Tests diff --git a/docs/toolkit/test-suite/index.md b/docs/toolkit/test-suite/index.md index 0efe57ef3..4a8e5715b 100644 --- a/docs/toolkit/test-suite/index.md +++ b/docs/toolkit/test-suite/index.md @@ -1,21 +1,5 @@ --- -title: Test Suite Overview +title: Test Suite sidebarSortOrder: 4 +metaOnly: true --- - -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). - -Within the Solana toolkit, there are several resources for testing Solana Smart -Contracts, including: - -- A fuzz tester -- A code coverage tool -- A framework for testing Solana programs in NodeJS that spins up a lightweight - `BanksServer` that's like an RPC node but much faster and creates a - `BanksClient` to talk to the server. -- A fast and lightweight library for testing Solana programs in Rust, which - works by creating an in-process Solana VM optimized for program developers. -- A tool to scan your repo for common security vulnerabilities and provide - suggestions for fixes. diff --git a/docs/toolkit/test-suite/js-test.md b/docs/toolkit/test-suite/js-test.md index 813b8a36b..ea341d0ff 100644 --- a/docs/toolkit/test-suite/js-test.md +++ b/docs/toolkit/test-suite/js-test.md @@ -1,12 +1,12 @@ --- -title: JavaScript Testing Framework -sidebarSortOrder: 3 -sidebarLabel: JS Tests +title: JavaScript Testing Framework for Solana +sidebarSortOrder: 6 +sidebarLabel: JavaScript Tests --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ## Add Dependency @@ -16,12 +16,13 @@ Navigate to your smart contract directory and run: npm install solana-bankrun ``` -## Overview +## Bankrun Overview [Bankrun](https://github.com/kevinheavey/solana-bankrun) is a fast and -lightweight framework for testing solana programs in NodeJS. +lightweight framework for testing Solana programs in NodeJS. -It uses [solana-program-test](https://crates.io/crates/solana-program-test) +It uses the +[`solana-program-test`](https://crates.io/crates/solana-program-test) crate under the hood and allows you to do things that are not possible with `solana-test-validator`, such as jumping back and forth in time or dynamically setting account data. @@ -63,5 +64,7 @@ test("one transfer", async () => { ## Additional Resources -- [Source Code]() +- [Bankrun Docs](https://kevinheavey.github.io/solana-bankrun/) +- [Bankrun Source Code](https://github.com/kevinheavey/solana-bankrun) +- [Official Bankrun Tutorials](https://kevinheavey.github.io/solana-bankrun/tutorial/) - [Complete Project Example](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-2-voting/anchor/tests) diff --git a/docs/toolkit/test-suite/overview.md b/docs/toolkit/test-suite/overview.md new file mode 100644 index 000000000..1063aac6c --- /dev/null +++ b/docs/toolkit/test-suite/overview.md @@ -0,0 +1,24 @@ +--- +title: Solana Test Suite Overview +sidebarLabel: Overview +sidebarSortOrder: 1 +altRoutes: + - /docs/toolkit/test-suite +--- + +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). + +Within the Solana Toolkit, there are several resources for testing Solana Smart +Contracts, including: + +- A fuzz tester. +- A code coverage tool. +- A framework for testing Solana programs in NodeJS that spins up a lightweight + `BanksServer` that's like an RPC node but much faster and creates a + `BanksClient` to talk to the server. +- A fast and lightweight library for testing Solana programs in Rust, which + works by creating an in-process Solana VM optimized for program developers. +- A tool to scan your repo for common security vulnerabilities and provide + suggestions for fixes. diff --git a/docs/toolkit/test-suite/rust-tests.md b/docs/toolkit/test-suite/rust-tests.md index e18fca0ff..670ac63a6 100644 --- a/docs/toolkit/test-suite/rust-tests.md +++ b/docs/toolkit/test-suite/rust-tests.md @@ -1,12 +1,12 @@ --- -title: Rust Testing Framework -sidebarSortOrder: 4 +title: Rust Testing Framework for Solana +sidebarSortOrder: 7 sidebarLabel: Rust Tests --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ## Add Dependency @@ -16,14 +16,16 @@ Navigate to your smart contract directory and run: cargo add --dev litesvm ``` -## Overview +## LiteSVM Overview [LiteSVM](https://github.com/LiteSVM/litesvm) is a fast and lightweight library for testing Solana programs. It works by creating an in-process Solana VM optimized for program developers. This makes it much faster to run and compile -than alternatives like solana-program-test and solana-test-validator. In a -further break from tradition, it has an ergonomic API with sane defaults and -extensive configurability for those who want it. +than alternatives like +[`solana-program-test`](/docs/toolkit/test-suite/basics.md) and +[`solana-test-validator`](/docs/toolkit/local-validator.md). In a further break +from tradition, it has an ergonomic API with sane defaults and extensive +configurability for those who want it. ## Minimal Example diff --git a/docs/toolkit/test-suite/security-scanner.md b/docs/toolkit/test-suite/security-scanner.md index eb260f612..dce86340e 100644 --- a/docs/toolkit/test-suite/security-scanner.md +++ b/docs/toolkit/test-suite/security-scanner.md @@ -4,14 +4,14 @@ sidebarSortOrder: 5 sidebarLabel: Security Scanner --- -> This is a beta version of The Solana Toolkit, and is still a WIP. Please post -> all feedback as a github issue -> [here](https://github.com/solana-foundation/developer-content/issues). +> This is a beta version of the [Solana Toolkit](/docs/toolkit/index.md), and is +> still a WIP. Please post all feedback as a GitHub issue +> [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). -## Static Analysis tools +## Static Analysis Tools [Radar](https://github.com/Auditware/radar?tab=readme-ov-file) is static -analysis tool for anchor rust programs. It allows you to write, share, and +analysis tool for Anchor rust programs. It allows you to write, share, and utilize templates to identify security issues in rust-based smart contracts using a powerful python based rule engine that enables automating detection of vulnerable code patterns through logical expressions. diff --git a/docs/toolkit/troubleshooting.md b/docs/toolkit/troubleshooting.md index 7994a36b7..d1b781c04 100644 --- a/docs/toolkit/troubleshooting.md +++ b/docs/toolkit/troubleshooting.md @@ -4,6 +4,13 @@ sidebarSortOrder: 6 sidebarLabel: Troubleshooting --- +When diagnosing problems with Solana development, you can easily gather loads of +troubleshooting information with the following command: + +```shell +npx mucho info +``` + ## Solana Stack Exchange The [Solana stack exchange](https://solana.stackexchange.com/) is the best place From 02e02481343eb5b7dcc96b475410b7f1830d60c8 Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 13:30:50 -0500 Subject: [PATCH 20/25] refactor: mucho global --- docs/toolkit/getting-started.md | 5 +++- docs/toolkit/local-validator.md | 33 ++++++++++++++---------- docs/toolkit/test-suite/basics.md | 14 +++++++--- docs/toolkit/test-suite/code-coverage.md | 2 +- docs/toolkit/test-suite/index.md | 2 +- docs/toolkit/troubleshooting.md | 2 +- 6 files changed, 38 insertions(+), 20 deletions(-) diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index f8885ebdc..b38d51217 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -26,6 +26,9 @@ This will install the latest versions of the following: - [Solana CLI / Agave Tool Suite](https://docs.anza.xyz/cli/): A command line tool that allows developers to interact with the Solana blockchain, manage accounts, send transactions, and deploy programs. +- [Mucho CLI](https://github.com/solana-developers/mucho) - a superset of + popular developer tools within the Solana ecosystem used to simplify the + development and testing of Solana blockchain programs. - [Rust](https://doc.rust-lang.org/book/): The programming language that Solana Smart Contracts are written in. - [Anchor](https://www.anchor-lang.com/): A framework for writing Solana @@ -77,7 +80,7 @@ solana config set --url localhost To test locally, you must also spin up a local node to run on your localhost: ```shell -npx mucho validator +mucho validator ``` For a more information, read the diff --git a/docs/toolkit/local-validator.md b/docs/toolkit/local-validator.md index 4513e2d2a..d84b5d013 100644 --- a/docs/toolkit/local-validator.md +++ b/docs/toolkit/local-validator.md @@ -1,6 +1,6 @@ --- title: Running a Local Solana Validator Network -sidebarSortOrder: 5 +sidebarSortOrder: 4 sidebarLabel: Local Validator --- @@ -18,9 +18,16 @@ If you have the Solana CLI tool suite already installed, you can run the test validator with the following command: ```shell -npx mucho validator --help +mucho validator --help ``` +> Install the [Solana Toolkit](/docs/toolkit/getting-started#installation) by +> running the following command: +> +> ```shell +> npx mucho install +> ``` + ## Advantages - Ability to reset the blockchain state at any moment @@ -39,7 +46,7 @@ npx mucho validator --help To start your local validator, simply run: ```shell -npx mucho validator +mucho validator ``` This command initializes a new ledger and starts the local validator running at @@ -143,7 +150,7 @@ This streams log messages from the validator. View all the configuration options available for the Solana test validator: ```shell -npx mucho validator --help +mucho validator --help ``` ## Local Ledger @@ -157,7 +164,7 @@ When starting the test validator, you can specify a different directory for the ledger data using the `--ledger` option: ```shell -npx mucho validator --ledger /path/to/custom/ledger +mucho validator --ledger /path/to/custom/ledger ``` ## Resetting the Ledger @@ -167,7 +174,7 @@ reset the ledger, you can either manually delete the ledger directory or restart the validator with the `--reset` flag: ```shell -npx mucho validator --reset +mucho validator --reset ``` If the ledger exists, this command will reset the ledger to genesis, which @@ -182,7 +189,7 @@ programs that already exist on any other cluster. To clone an account from another cluster: ```shell -npx mucho validator --reset \ +mucho validator --reset \ --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ --clone PROGRAM_ADDRESS ``` @@ -190,7 +197,7 @@ npx mucho validator --reset \ To clone an upgradeable program and its executable data from another cluster: ```shell -npx mucho validator --reset \ +mucho validator --reset \ --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ --clone-upgradeable-program PROGRAM_ADDRESS ``` @@ -206,7 +213,7 @@ account with a new ledger from any other network cluster. To clone an account from the cluster when a ledger already exists: ```shell -npx mucho validator --reset \ +mucho validator --reset \ --url CLUSTER_PROGRAM_IS_DEPLOYED_TO \ --clone ACCOUNT_ADDRESS ``` @@ -225,7 +232,7 @@ solana account ACCOUNT_ADDRESS --output json --output-file account_state.json Then load this state each time you reset the validator: ```shell -npx mucho validator --reset \ +mucho validator --reset \ --account ACCOUNT_ADDRESS account_state.json ``` @@ -253,14 +260,14 @@ To deactivate specific features in genesis: > working directory you must add the `--reset` flag to reset to genesis. ```shell -npx mucho validator --reset \ +mucho validator --reset \ --deactivate-feature ``` To deactivate multiple features in genesis: ```shell -npx mucho validator --reset \ +mucho validator --reset \ --deactivate-feature ``` @@ -269,7 +276,7 @@ npx mucho validator --reset \ To check your current `solana-test-validator` version: ```shell -npx mucho validator --version +mucho validator --version ``` Your test validator runs on the same version as the Solana CLI installed and diff --git a/docs/toolkit/test-suite/basics.md b/docs/toolkit/test-suite/basics.md index 0a5b92c9a..4c7c182aa 100644 --- a/docs/toolkit/test-suite/basics.md +++ b/docs/toolkit/test-suite/basics.md @@ -8,16 +8,24 @@ sidebarSortOrder: 2 > still a WIP. Please post all feedback as a GitHub issue > [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). +## Installation + +Install the Solana Toolkit by running the following command: + +```shell +npx mucho install +``` + ## Build ```shell -npx mucho build +mucho build ``` ## Start Localnet ```shell -npx mucho validator +mucho validator ``` ## Run Tests @@ -37,7 +45,7 @@ cargo test ## Deploy ```shell -npx solana deploy +mucho deploy ``` For more information on local validator customization and commands, read the diff --git a/docs/toolkit/test-suite/code-coverage.md b/docs/toolkit/test-suite/code-coverage.md index 7a16a1aea..c02e70a4c 100644 --- a/docs/toolkit/test-suite/code-coverage.md +++ b/docs/toolkit/test-suite/code-coverage.md @@ -9,7 +9,7 @@ sidebarLabel: Code Coverage > [here](https://github.com/solana-foundation/developer-content/issues/new?title=%5Btoolkit%5D%20). ```shell -npx mucho coverage +mucho coverage ``` ## Overview diff --git a/docs/toolkit/test-suite/index.md b/docs/toolkit/test-suite/index.md index 4a8e5715b..7b6ee1048 100644 --- a/docs/toolkit/test-suite/index.md +++ b/docs/toolkit/test-suite/index.md @@ -1,5 +1,5 @@ --- title: Test Suite -sidebarSortOrder: 4 +sidebarSortOrder: 5 metaOnly: true --- diff --git a/docs/toolkit/troubleshooting.md b/docs/toolkit/troubleshooting.md index d1b781c04..2f1c00011 100644 --- a/docs/toolkit/troubleshooting.md +++ b/docs/toolkit/troubleshooting.md @@ -8,7 +8,7 @@ When diagnosing problems with Solana development, you can easily gather loads of troubleshooting information with the following command: ```shell -npx mucho info +mucho info ``` ## Solana Stack Exchange From ef3fa4516bd1c00c9efd2f52dc70ea91e706e405 Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 13:32:18 -0500 Subject: [PATCH 21/25] fix: mucho info --- docs/toolkit/troubleshooting.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/toolkit/troubleshooting.md b/docs/toolkit/troubleshooting.md index 2f1c00011..d1b781c04 100644 --- a/docs/toolkit/troubleshooting.md +++ b/docs/toolkit/troubleshooting.md @@ -8,7 +8,7 @@ When diagnosing problems with Solana development, you can easily gather loads of troubleshooting information with the following command: ```shell -mucho info +npx mucho info ``` ## Solana Stack Exchange From 32552db11ce57d05f1b6d81a23bee023fd0da085 Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 15:22:39 -0500 Subject: [PATCH 22/25] fix: install from latest --- docs/toolkit/getting-started.md | 2 +- docs/toolkit/local-validator.md | 2 +- docs/toolkit/test-suite/basics.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index b38d51217..cadb60503 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -18,7 +18,7 @@ toolkit - _mucho tools, one cli_. To get started, install The Solana Toolkit: ```shell -npx mucho install +npx mucho@latest install ``` This will install the latest versions of the following: diff --git a/docs/toolkit/local-validator.md b/docs/toolkit/local-validator.md index d84b5d013..6a98219c4 100644 --- a/docs/toolkit/local-validator.md +++ b/docs/toolkit/local-validator.md @@ -25,7 +25,7 @@ mucho validator --help > running the following command: > > ```shell -> npx mucho install +> npx mucho@latest install > ``` ## Advantages diff --git a/docs/toolkit/test-suite/basics.md b/docs/toolkit/test-suite/basics.md index 4c7c182aa..747fb514c 100644 --- a/docs/toolkit/test-suite/basics.md +++ b/docs/toolkit/test-suite/basics.md @@ -13,7 +13,7 @@ sidebarSortOrder: 2 Install the Solana Toolkit by running the following command: ```shell -npx mucho install +npx mucho@latest install ``` ## Build From ad729248762c7ecd483ad983bbe5bcee1a13ef17 Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 15:36:36 -0500 Subject: [PATCH 23/25] fix: installing --- docs/toolkit/getting-started.md | 2 +- docs/toolkit/local-validator.md | 2 +- docs/toolkit/test-suite/basics.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/toolkit/getting-started.md b/docs/toolkit/getting-started.md index cadb60503..9d8d1275a 100644 --- a/docs/toolkit/getting-started.md +++ b/docs/toolkit/getting-started.md @@ -18,7 +18,7 @@ toolkit - _mucho tools, one cli_. To get started, install The Solana Toolkit: ```shell -npx mucho@latest install +npx -y mucho@latest install ``` This will install the latest versions of the following: diff --git a/docs/toolkit/local-validator.md b/docs/toolkit/local-validator.md index 6a98219c4..c21323f2b 100644 --- a/docs/toolkit/local-validator.md +++ b/docs/toolkit/local-validator.md @@ -25,7 +25,7 @@ mucho validator --help > running the following command: > > ```shell -> npx mucho@latest install +> npx -y mucho@latest install > ``` ## Advantages diff --git a/docs/toolkit/test-suite/basics.md b/docs/toolkit/test-suite/basics.md index 747fb514c..fab6522ab 100644 --- a/docs/toolkit/test-suite/basics.md +++ b/docs/toolkit/test-suite/basics.md @@ -13,7 +13,7 @@ sidebarSortOrder: 2 Install the Solana Toolkit by running the following command: ```shell -npx mucho@latest install +npx -y mucho@latest install ``` ## Build From 0eaa3f84eb1ad68bf2140fa397f8de8493750bda Mon Sep 17 00:00:00 2001 From: nickfrosty <75431177+nickfrosty@users.noreply.github.com> Date: Thu, 9 Jan 2025 15:39:37 -0500 Subject: [PATCH 24/25] fix: prettier --- docs/core/transactions.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/core/transactions.md b/docs/core/transactions.md index 68bcc3109..be799bdef 100644 --- a/docs/core/transactions.md +++ b/docs/core/transactions.md @@ -155,7 +155,8 @@ specifies the privileges of accounts included in the transaction's account address array. It is comprised of three bytes, each containing a u8 integer, which collectively specify: -1. The number of required signatures for the transaction and message version number. +1. The number of required signatures for the transaction and message version + number. 2. The number of read-only account addresses that require signatures. 3. The number of read-only account addresses that do not require signatures. From 1042e71840394c588c820e855ad0a2c5653cdf85 Mon Sep 17 00:00:00 2001 From: brimigs <85972460+brimigs@users.noreply.github.com> Date: Wed, 15 Jan 2025 12:45:02 -0500 Subject: [PATCH 25/25] remove pa --- docs/toolkit/best-practices.md | 45 ---------------------------------- 1 file changed, 45 deletions(-) diff --git a/docs/toolkit/best-practices.md b/docs/toolkit/best-practices.md index 28c16507a..dfce7c7e4 100644 --- a/docs/toolkit/best-practices.md +++ b/docs/toolkit/best-practices.md @@ -54,51 +54,6 @@ transaction failure, and consistency across invocations. - [PDA Bumps Core Concepts](/docs/core/pda.md#canonical-bump) - [Bump Seed Canonicalization Lesson](https://solana.com/developers/courses/program-security/bump-seed-canonicalization) -## Payer-Authority Pattern - -The Payer-Authority pattern is an elegant way to handle situations where the -account’s funder (payer) differs from the account’s owner or manager -(authority). By requiring separate signers and validating them in your onchain -logic, you can maintain clear, robust, and flexible ownership semantics in your -program. - -### Shank Example - -```rust -// Create a new account. -#[account(0, writable, signer, name="account", desc = "The address of the new account")] -#[account(1, writable, signer, name="payer", desc = "The account paying for the storage fees")] -#[account(2, optional, signer, name="authority", desc = "The authority signing for the account creation")] -#[account(3, name="system_program", desc = "The system program")] -CreateAccountV1(CreateAccountV1Args), -``` - -### Anchor Example - -```rust -#[derive(Accounts)] -pub struct CreateAccount<'info> { - /// The address of the new account - #[account(init, payer = payer_one, space = 8 + NewAccount::MAXIMUM_SIZE)] - pub account: Account<'info, NewAccount>, - - /// The account paying for the storage fees - #[account(mut)] - pub payer: Signer<'info>, - - /// The authority signing for the account creation - pub authority: Option>, - - // The system program - pub system_program: Program<'info, System> -} -``` - -### Additional References - -- [Metaplex Guide on Payer-Authority Pattern](https://developers.metaplex.com/guides/general/payer-authority-pattern) -- [Helium Program Library using the Payer-Authority Pattern](https://github.com/helium/helium-program-library/blob/master/programs/data-credits/src/instructions/change_delegated_sub_dao_v0.rs#L18) - ## Invariants Implement invariants, which are functions that you can call at the end of your