template.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. use crate::config::ProgramWorkspace;
  2. use crate::VERSION;
  3. use anchor_syn::idl::Idl;
  4. use anyhow::Result;
  5. use heck::{CamelCase, MixedCase, SnakeCase};
  6. use solana_sdk::pubkey::Pubkey;
  7. pub fn default_program_id() -> Pubkey {
  8. "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"
  9. .parse()
  10. .unwrap()
  11. }
  12. pub fn virtual_manifest() -> &'static str {
  13. r#"[workspace]
  14. members = [
  15. "programs/*"
  16. ]
  17. "#
  18. }
  19. pub fn credentials(token: &str) -> String {
  20. format!(
  21. r#"[registry]
  22. token = "{}"
  23. "#,
  24. token
  25. )
  26. }
  27. pub fn idl_ts(idl: &Idl) -> Result<String> {
  28. let mut idl = idl.clone();
  29. for acc in idl.accounts.iter_mut() {
  30. acc.name = acc.name.to_mixed_case();
  31. }
  32. let idl_json = serde_json::to_string_pretty(&idl)?;
  33. Ok(format!(
  34. r#"export type {} = {};
  35. export const IDL: {} = {};
  36. "#,
  37. idl.name.to_camel_case(),
  38. idl_json,
  39. idl.name.to_camel_case(),
  40. idl_json
  41. ))
  42. }
  43. pub fn cargo_toml(name: &str) -> String {
  44. format!(
  45. r#"[package]
  46. name = "{0}"
  47. version = "0.1.0"
  48. description = "Created with Anchor"
  49. edition = "2018"
  50. [lib]
  51. crate-type = ["cdylib", "lib"]
  52. name = "{1}"
  53. [features]
  54. no-entrypoint = []
  55. no-idl = []
  56. no-log-ix-name = []
  57. cpi = ["no-entrypoint"]
  58. default = []
  59. [dependencies]
  60. anchor-lang = "{2}"
  61. "#,
  62. name,
  63. name.to_snake_case(),
  64. VERSION,
  65. )
  66. }
  67. pub fn deploy_js_script_host(cluster_url: &str, script_path: &str) -> String {
  68. format!(
  69. r#"
  70. const anchor = require('@project-serum/anchor');
  71. // Deploy script defined by the user.
  72. const userScript = require("{0}");
  73. async function main() {{
  74. const url = "{1}";
  75. const preflightCommitment = 'recent';
  76. const connection = new anchor.web3.Connection(url, preflightCommitment);
  77. const wallet = anchor.Wallet.local();
  78. const provider = new anchor.Provider(connection, wallet, {{
  79. preflightCommitment,
  80. commitment: 'recent',
  81. }});
  82. // Run the user's deploy script.
  83. userScript(provider);
  84. }}
  85. main();
  86. "#,
  87. script_path, cluster_url,
  88. )
  89. }
  90. pub fn deploy_ts_script_host(cluster_url: &str, script_path: &str) -> String {
  91. format!(
  92. r#"import * as anchor from '@project-serum/anchor';
  93. // Deploy script defined by the user.
  94. const userScript = require("{0}");
  95. async function main() {{
  96. const url = "{1}";
  97. const preflightCommitment = 'recent';
  98. const connection = new anchor.web3.Connection(url, preflightCommitment);
  99. const wallet = anchor.Wallet.local();
  100. const provider = new anchor.Provider(connection, wallet, {{
  101. preflightCommitment,
  102. commitment: 'recent',
  103. }});
  104. // Run the user's deploy script.
  105. userScript(provider);
  106. }}
  107. main();
  108. "#,
  109. script_path, cluster_url,
  110. )
  111. }
  112. pub fn deploy_script() -> &'static str {
  113. r#"// Migrations are an early feature. Currently, they're nothing more than this
  114. // single deploy script that's invoked from the CLI, injecting a provider
  115. // configured from the workspace's Anchor.toml.
  116. const anchor = require("@project-serum/anchor");
  117. module.exports = async function (provider) {
  118. // Configure client to use the provider.
  119. anchor.setProvider(provider);
  120. // Add your deploy script here.
  121. };
  122. "#
  123. }
  124. pub fn ts_deploy_script() -> &'static str {
  125. r#"// Migrations are an early feature. Currently, they're nothing more than this
  126. // single deploy script that's invoked from the CLI, injecting a provider
  127. // configured from the workspace's Anchor.toml.
  128. const anchor = require("@project-serum/anchor");
  129. module.exports = async function (provider) {
  130. // Configure client to use the provider.
  131. anchor.setProvider(provider);
  132. // Add your deploy script here.
  133. };
  134. "#
  135. }
  136. pub fn xargo_toml() -> &'static str {
  137. r#"[target.bpfel-unknown-unknown.dependencies.std]
  138. features = []
  139. "#
  140. }
  141. pub fn lib_rs(name: &str) -> String {
  142. format!(
  143. r#"use anchor_lang::prelude::*;
  144. declare_id!("{}");
  145. #[program]
  146. pub mod {} {{
  147. use super::*;
  148. pub fn initialize(ctx: Context<Initialize>) -> Result<()> {{
  149. Ok(())
  150. }}
  151. }}
  152. #[derive(Accounts)]
  153. pub struct Initialize {{}}
  154. "#,
  155. default_program_id(),
  156. name.to_snake_case(),
  157. )
  158. }
  159. pub fn mocha(name: &str) -> String {
  160. format!(
  161. r#"const anchor = require("@project-serum/anchor");
  162. describe("{}", () => {{
  163. // Configure the client to use the local cluster.
  164. anchor.setProvider(anchor.Provider.env());
  165. it("Is initialized!", async () => {{
  166. // Add your test here.
  167. const program = anchor.workspace.{};
  168. const tx = await program.rpc.initialize();
  169. console.log("Your transaction signature", tx);
  170. }});
  171. }});
  172. "#,
  173. name,
  174. name.to_camel_case(),
  175. )
  176. }
  177. pub fn package_json() -> String {
  178. format!(
  179. r#"{{
  180. "dependencies": {{
  181. "@project-serum/anchor": "^{0}"
  182. }},
  183. "devDependencies": {{
  184. "chai": "^4.3.4",
  185. "mocha": "^9.0.3"
  186. }}
  187. }}
  188. "#,
  189. VERSION
  190. )
  191. }
  192. pub fn ts_package_json() -> String {
  193. format!(
  194. r#"{{
  195. "dependencies": {{
  196. "@project-serum/anchor": "^{0}"
  197. }},
  198. "devDependencies": {{
  199. "chai": "^4.3.4",
  200. "mocha": "^9.0.3",
  201. "ts-mocha": "^8.0.0",
  202. "@types/chai": "^4.3.0",
  203. "@types/mocha": "^9.0.0",
  204. "typescript": "^4.3.5"
  205. }}
  206. }}
  207. "#,
  208. VERSION
  209. )
  210. }
  211. pub fn ts_mocha(name: &str) -> String {
  212. format!(
  213. r#"import * as anchor from "@project-serum/anchor";
  214. import {{ Program }} from "@project-serum/anchor";
  215. import {{ {} }} from "../target/types/{}";
  216. describe("{}", () => {{
  217. // Configure the client to use the local cluster.
  218. anchor.setProvider(anchor.Provider.env());
  219. const program = anchor.workspace.{} as Program<{}>;
  220. it("Is initialized!", async () => {{
  221. // Add your test here.
  222. const tx = await program.rpc.initialize({{}});
  223. console.log("Your transaction signature", tx);
  224. }});
  225. }});
  226. "#,
  227. name.to_camel_case(),
  228. name.to_snake_case(),
  229. name,
  230. name.to_camel_case(),
  231. name.to_camel_case(),
  232. )
  233. }
  234. pub fn ts_config() -> &'static str {
  235. r#"{
  236. "compilerOptions": {
  237. "types": ["mocha", "chai"],
  238. "typeRoots": ["./node_modules/@types"],
  239. "lib": ["es2015"],
  240. "module": "commonjs",
  241. "target": "es6",
  242. "esModuleInterop": true
  243. }
  244. }
  245. "#
  246. }
  247. pub fn git_ignore() -> &'static str {
  248. r#"
  249. .anchor
  250. .DS_Store
  251. target
  252. **/*.rs.bk
  253. node_modules
  254. "#
  255. }
  256. pub fn node_shell(
  257. cluster_url: &str,
  258. wallet_path: &str,
  259. programs: Vec<ProgramWorkspace>,
  260. ) -> Result<String> {
  261. let mut eval_string = format!(
  262. r#"
  263. const anchor = require('@project-serum/anchor');
  264. const web3 = anchor.web3;
  265. const PublicKey = anchor.web3.PublicKey;
  266. const Keypair = anchor.web3.Keypair;
  267. const __wallet = new anchor.Wallet(
  268. Keypair.fromSecretKey(
  269. Buffer.from(
  270. JSON.parse(
  271. require('fs').readFileSync(
  272. "{}",
  273. {{
  274. encoding: "utf-8",
  275. }},
  276. ),
  277. ),
  278. ),
  279. ),
  280. );
  281. const __connection = new web3.Connection("{}", "processed");
  282. const provider = new anchor.Provider(__connection, __wallet, {{
  283. commitment: "processed",
  284. preflightcommitment: "processed",
  285. }});
  286. anchor.setProvider(provider);
  287. "#,
  288. wallet_path, cluster_url,
  289. );
  290. for program in programs {
  291. eval_string.push_str(&format!(
  292. r#"
  293. anchor.workspace.{} = new anchor.Program({}, new PublicKey("{}"), provider);
  294. "#,
  295. program.name.to_camel_case(),
  296. serde_json::to_string(&program.idl)?,
  297. program.program_id
  298. ));
  299. }
  300. Ok(eval_string)
  301. }