local.mdx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. ---
  2. title: Local Development
  3. description:
  4. Learn how to build Solana programs using the Anchor framework on your local
  5. machine.
  6. ---
  7. The Anchor framework is a tool that simplifies the process of building Solana
  8. programs. Whether you're new to blockchain development or an experienced
  9. programmer, Anchor simplifies the process of writing, testing, and deploying
  10. Solana programs.
  11. In this section, we'll walk through:
  12. - Creating a new Anchor project
  13. - Building and testing your program
  14. - Deploying to Solana clusters
  15. - Understanding the project file structure
  16. ## Prerequisites
  17. For detailed installation instructions, visit the
  18. [installation](/docs/installation) page.
  19. Before you begin, ensure you have the following installed:
  20. - Rust: The programming language for building Solana programs.
  21. - Solana CLI: Command-line tool for Solana development.
  22. - Anchor CLI: Command-line tool for the Anchor framework.
  23. To verify Anchor CLI installation, open your terminal and run:
  24. ```shell filename="Terminal"
  25. anchor --version
  26. ```
  27. Expected output:
  28. ```shell filename="Terminal"
  29. anchor-cli 0.31.1
  30. ```
  31. ## Getting Started
  32. This section covers the basic steps to create, build, and test your first local
  33. Anchor program.
  34. <Steps>
  35. <Step>
  36. ### Create a new Project
  37. To start a new project, use the `anchor init` command followed by your project's
  38. name. This command creates a new directory with the specified name and sets up a
  39. default program and test file.
  40. ```shell filename="Terminal"
  41. anchor init my-project
  42. ```
  43. Navigate to the new project directory and open it in your code editor.
  44. ```shell filename="Terminal" copy
  45. cd my-project
  46. ```
  47. The default Anchor program is located at `/programs/my-project/src/lib.rs`.
  48. <Accordions>
  49. <Accordion title="Default Program">
  50. The value in the `declare_id!` macro is the program ID, a unique identifier for
  51. your program.
  52. By default, it is the public key of the keypair generated in
  53. `/target/deploy/my_project-keypair.json`.
  54. ```rust filename="lib.rs"
  55. use anchor_lang::prelude::*;
  56. declare_id!("3ynNB373Q3VAzKp7m4x238po36hjAGFXFJB4ybN2iTyg");
  57. #[program]
  58. pub mod my_project {
  59. use super::*;
  60. pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
  61. msg!("Greetings from: {:?}", ctx.program_id);
  62. Ok(())
  63. }
  64. }
  65. #[derive(Accounts)]
  66. pub struct Initialize {}
  67. ```
  68. </Accordion>
  69. </Accordions>
  70. The default Typescript test file is located at `/tests/my-project.ts`.
  71. <Accordions>
  72. <Accordion title="Default Test File">
  73. This file demonstrates how to invoke the default program's `initialize`
  74. instruction in Typescript.
  75. ```ts filename="my-project.ts"
  76. import * as anchor from "@coral-xyz/anchor";
  77. import { Program } from "@coral-xyz/anchor";
  78. import { MyProject } from "../target/types/my_project";
  79. describe("my-project", () => {
  80. // Configure the client to use the local cluster.
  81. anchor.setProvider(anchor.AnchorProvider.env());
  82. const program = anchor.workspace.MyProject as Program<MyProject>;
  83. it("Is initialized!", async () => {
  84. // Add your test here.
  85. const tx = await program.methods.initialize().rpc();
  86. console.log("Your transaction signature", tx);
  87. });
  88. });
  89. ```
  90. </Accordion>
  91. </Accordions>
  92. If you prefer Rust for testing, initialize your project with the
  93. `--test-template rust` ([Anchor Rust client](/docs/clients/rust)) or
  94. `--test-template mollusk` ([Mollusk test library](/docs/testing/mollusk)) flag.
  95. ```shell
  96. anchor init --test-template rust my-program
  97. ```
  98. The Rust test file will be at `/tests/src/test_initialize.rs`.
  99. <Accordions>
  100. <Accordion title="Rust Test File">
  101. ```rust filename="test_initialize.rs"
  102. use std::str::FromStr;
  103. use anchor_client::{
  104. solana_sdk::{
  105. commitment_config::CommitmentConfig, pubkey::Pubkey, signature::read_keypair_file,
  106. },
  107. Client, Cluster,
  108. };
  109. #[test]
  110. fn test_initialize() {
  111. let program_id = "3ynNB373Q3VAzKp7m4x238po36hjAGFXFJB4ybN2iTyg";
  112. let anchor_wallet = std::env::var("ANCHOR_WALLET").unwrap();
  113. let payer = read_keypair_file(&anchor_wallet).unwrap();
  114. let client = Client::new_with_options(Cluster::Localnet, &payer, CommitmentConfig::confirmed());
  115. let program_id = Pubkey::from_str(program_id).unwrap();
  116. let program = client.program(program_id).unwrap();
  117. let tx = program
  118. .request()
  119. .accounts(my_program::accounts::Initialize {})
  120. .args(my_program::instruction::Initialize {})
  121. .send()
  122. .expect("");
  123. println!("Your transaction signature {}", tx);
  124. }
  125. ```
  126. </Accordion>
  127. </Accordions>
  128. </Step>
  129. <Step>
  130. ### Build the Program
  131. Build the program by running `anchor build`.
  132. ```shell filename="Terminal" copy
  133. anchor build
  134. ```
  135. The compiled program will be at `/target/deploy/my_project.so`. The content of
  136. this file is what gets stored on the Solana network (as an executable account)
  137. when you deploy your program.
  138. </Step>
  139. <Step>
  140. ### Test the Program
  141. To test the program, run `anchor test`.
  142. ```shell filename="Terminal" copy
  143. anchor test
  144. ```
  145. By default, the `Anchor.toml` config file specifies the `localnet` cluster. When
  146. developing on `localnet`, `anchor test` will automatically:
  147. 1. Start a local Solana validator
  148. 2. Build and deploy your program to the local cluster
  149. 3. Run the tests in the `tests` folder
  150. 4. Stop the local Solana validator
  151. Alternatively, you can manually start a local Solana validator and run tests
  152. against it. This is useful if you want to keep the validator running while you
  153. iterate on your program. It allows you to inspect accounts and transaction logs
  154. on the [Solana Explorer](https://explorer.solana.com/?cluster=custom) while
  155. developing locally.
  156. Open a new terminal and start a local Solana validator by running the
  157. `solana-test-validator` command.
  158. ```shell filename="Terminal" copy
  159. solana-test-validator
  160. ```
  161. In a separate terminal, run the tests against the local cluster. Use the
  162. `--skip-local-validator` flag to skip starting the local validator since it's
  163. already running.
  164. ```shell filename="Terminal" copy
  165. anchor test --skip-local-validator
  166. ```
  167. </Step>
  168. <Step>
  169. ### Deploy to Devnet
  170. By default, the `Anchor.toml` config file in an Anchor project specifies the
  171. localnet cluster.
  172. ```toml filename="Anchor.toml" {14}
  173. [toolchain]
  174. [features]
  175. resolution = true
  176. skip-lint = false
  177. [programs.localnet]
  178. my_program = "3ynNB373Q3VAzKp7m4x238po36hjAGFXFJB4ybN2iTyg"
  179. [registry]
  180. url = "https://api.apr.dev"
  181. [provider]
  182. cluster = "Localnet"
  183. wallet = "~/.config/solana/id.json"
  184. [scripts]
  185. test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
  186. ```
  187. To deploy your program to devnet, change the `cluster` value to `Devnet`.
  188. <Callout type="info">
  189. Note that deploying to devnet requires your wallet to have enough SOL to cover
  190. deployment cost. You can get devnet SOL using the
  191. [Web Faucet](https://faucet.solana.com/).
  192. </Callout>
  193. ```diff
  194. -cluster = "Localnet"
  195. +cluster = "Devnet"
  196. ```
  197. ```toml filename="Anchor.toml"
  198. [provider]
  199. cluster = "Devnet"
  200. wallet = "~/.config/solana/id.json"
  201. ```
  202. Now when you run `anchor deploy`, your program will be deployed to the devnet
  203. cluster. The `anchor test` command will also use the cluster specified in the
  204. `Anchor.toml` file.
  205. ```shell
  206. anchor deploy
  207. ```
  208. To deploy to mainnet, simply update the `Anchor.toml` file to specify the
  209. mainnet cluster.
  210. ```toml filename="Anchor.toml"
  211. [provider]
  212. cluster = "Mainnet"
  213. wallet = "~/.config/solana/id.json"
  214. ```
  215. </Step>
  216. <Step>
  217. ### Update the Program
  218. Solana programs can be updated by redeploying the program to the same program
  219. ID.
  220. To update a program, simply make changes to your program's code and run the
  221. `anchor build` command to generated an updated `.so` file.
  222. ```shell
  223. anchor build
  224. ```
  225. Then run the `anchor deploy` command to redeploy the updated program.
  226. ```shell
  227. anchor deploy
  228. ```
  229. </Step>
  230. <Step>
  231. ### Close the Program
  232. To reclaim the SOL allocated to a program account, you can close your Solana
  233. program.
  234. To close a program, use the `solana program close <PROGRAM_ID>` command. For
  235. example:
  236. ```shell
  237. solana program close 3ynNB373Q3VAzKp7m4x238po36hjAGFXFJB4ybN2iTyg --bypass-warning
  238. ```
  239. Note that once a program is closed, the program ID cannot be reused to deploy a
  240. new program.
  241. </Step>
  242. </Steps>
  243. ## Project File Structure
  244. Below is an overview of default file structure in an Anchor workspace:
  245. <Files>
  246. <Folder name=".anchor">
  247. <File name="program-logs" />
  248. </Folder>
  249. <Folder name="app" />
  250. <Folder name="migrations" />
  251. <Folder name="programs" defaultOpen={true}>
  252. <Folder name="[project-name]" defaultOpen={true}>
  253. <Folder name="src" defaultOpen={true}>
  254. <File name="lib.rs" />
  255. <File name="Cargo.toml" />
  256. <File name="Xargo.toml" />
  257. </Folder>
  258. </Folder>
  259. </Folder>
  260. <Folder name="target" defaultOpen={true}>
  261. <Folder name="deploy">
  262. <File name="[project-name]-keypair.json" />
  263. </Folder>
  264. <Folder name="idl">
  265. <File name="[project-name].json" />
  266. </Folder>
  267. <Folder name="types">
  268. <File name="[project-name].ts" />
  269. </Folder>
  270. </Folder>
  271. <Folder name="tests" defaultOpen={true}>
  272. <File name="[project-name].ts" />
  273. </Folder>
  274. <File name="Anchor.toml" />
  275. <File name="Cargo.toml" />
  276. <File name="package.json" />
  277. </Files>
  278. ### Programs Folder
  279. The `/programs` directory contains your project's Anchor programs. A single
  280. workspace can contain multiple programs.
  281. ### Tests Folder
  282. The `/tests` directory contains test files for your project. A default test file
  283. is created for you when you create your project.
  284. ### Target Folder
  285. The `/target` directory contains build outputs. The main subfolders include:
  286. - `/deploy`: Contains the keypair and program binary for your programs.
  287. - `/idl`: Contains the JSON IDL for your programs.
  288. - `/types`: Contains the TypeScript type for the IDL.
  289. ### Anchor.toml File
  290. The `Anchor.toml` file configures workspace settings for your project.
  291. ### .anchor Folder
  292. Includes a `program-logs` file that contains transaction logs from the last run
  293. of test files.
  294. ### App Folder
  295. The `/app` folder is an empty folder that can be optionally used for your
  296. frontend code.