Skip to content

Commit

Permalink
feat: update clarinet generated template to use the sdk (#1209)
Browse files Browse the repository at this point in the history
* feat: update clarinet generated template to use the sdk

* refactor: fix a few clippy warnings
  • Loading branch information
hugocaillard authored Oct 16, 2023
1 parent 1addb98 commit 27f9bce
Show file tree
Hide file tree
Showing 5 changed files with 269 additions and 145 deletions.
6 changes: 4 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{
"rust-analyzer.check.overrideCommand": [
"cargo",
"check",
"clippy",
"--package=clarinet-cli",
"--message-format=json"
"--message-format=json",
"--",
"--no-deps"
]
}
92 changes: 42 additions & 50 deletions components/clarinet-cli/src/frontend/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,11 +579,7 @@ pub fn main() {
}
};

let hints_enabled = if env::var("CLARINET_DISABLE_HINTS") == Ok("1".into()) {
false
} else {
true
};
let hints_enabled = env::var("CLARINET_DISABLE_HINTS") != Ok("1".into());

match opts.command {
Command::New(project_opts) => {
Expand Down Expand Up @@ -669,11 +665,11 @@ pub fn main() {
Deployments::GenerateDeployment(cmd) => {
let manifest = load_manifest_or_exit(cmd.manifest_path);

let network = if cmd.devnet == true {
let network = if cmd.devnet {
StacksNetwork::Devnet
} else if cmd.testnet == true {
} else if cmd.testnet {
StacksNetwork::Testnet
} else if cmd.mainnet == true {
} else if cmd.mainnet {
StacksNetwork::Mainnet
} else {
StacksNetwork::Simnet
Expand Down Expand Up @@ -750,11 +746,11 @@ pub fn main() {
Deployments::ApplyDeployment(cmd) => {
let manifest = load_manifest_or_exit(cmd.manifest_path);

let network = if cmd.devnet == true {
let network = if cmd.devnet {
Some(StacksNetwork::Devnet)
} else if cmd.testnet == true {
} else if cmd.testnet {
Some(StacksNetwork::Testnet)
} else if cmd.mainnet == true {
} else if cmd.mainnet {
Some(StacksNetwork::Mainnet)
} else {
None
Expand All @@ -765,7 +761,7 @@ pub fn main() {
Err(format!("{}: a flag `--devnet`, `--testnet`, `--mainnet` or `--deployment-plan-path=path/to/yaml` should be provided.", yellow!("Command usage")))
}
(Some(network), None) => {
let res = load_deployment_if_exists(&manifest, &network, cmd.use_on_disk_deployment_plan, cmd.use_computed_deployment_plan);
let res = load_deployment_if_exists(&manifest, network, cmd.use_on_disk_deployment_plan, cmd.use_computed_deployment_plan);
match res {
Some(Ok(deployment)) => {
println!(
Expand All @@ -777,8 +773,8 @@ pub fn main() {
}
Some(Err(e)) => Err(e),
None => {
let default_deployment_path = get_default_deployment_path(&manifest, &network).unwrap();
let (deployment, _) = match generate_default_deployment(&manifest, &network, false) {
let default_deployment_path = get_default_deployment_path(&manifest, network).unwrap();
let (deployment, _) = match generate_default_deployment(&manifest, network, false) {
Ok(deployment) => deployment,
Err(message) => {
println!("{}", red!(message));
Expand Down Expand Up @@ -1142,7 +1138,7 @@ pub fn main() {
}

if success {
println!("{} Syntax of contract successfully checked", green!("✔"),);
println!("{} Syntax of contract successfully checked", green!("✔"));
return;
} else {
std::process::exit(1);
Expand Down Expand Up @@ -1300,7 +1296,7 @@ pub fn main() {
}
},
Command::Completions(cmd) => {
let mut app = Opts::command();
let app = Opts::command();
let file_name = cmd.shell.file_name("clarinet");
let mut file = match File::create(file_name.clone()) {
Ok(file) => file,
Expand All @@ -1314,7 +1310,7 @@ pub fn main() {
std::process::exit(1);
}
};
cmd.shell.generate(&mut app, &mut file);
cmd.shell.generate(&app, &mut file);
println!("{} {}", green!("Created file"), file_name.clone());
println!("Check your shell's documentation for details about using this file to enable completions for clarinet");
}
Expand Down Expand Up @@ -1366,7 +1362,7 @@ fn get_manifest_location_or_warn(path: Option<String>) -> Option<FileLocation> {

fn load_manifest_or_exit(path: Option<String>) -> ProjectManifest {
let manifest_location = get_manifest_location_or_exit(path);
let manifest = match ProjectManifest::from_location(&manifest_location) {
match ProjectManifest::from_location(&manifest_location) {
Ok(manifest) => manifest,
Err(message) => {
println!(
Expand All @@ -1376,8 +1372,7 @@ fn load_manifest_or_exit(path: Option<String>) -> ProjectManifest {
);
process::exit(1);
}
};
manifest
}
}

fn load_manifest_or_warn(path: Option<String>) -> Option<ProjectManifest> {
Expand Down Expand Up @@ -1413,7 +1408,7 @@ fn load_deployment_and_artifacts_or_exit(
let result = match deployment_plan_path {
None => {
let res = load_deployment_if_exists(
&manifest,
manifest,
&StacksNetwork::Simnet,
force_on_disk,
force_computed,
Expand All @@ -1424,41 +1419,42 @@ fn load_deployment_and_artifacts_or_exit(
"{} using deployments/default.simnet-plan.yaml",
yellow!("note:")
);
let artifacts = setup_session_with_deployment(&manifest, &deployment, None);
let artifacts = setup_session_with_deployment(manifest, &deployment, None);
Ok((deployment, None, artifacts))
}
Some(Err(e)) => Err(format!(
"loading deployments/default.simnet-plan.yaml failed with error: {}",
e
)),
None => match generate_default_deployment(&manifest, &StacksNetwork::Simnet, false)
{
Ok((deployment, ast_artifacts)) if ast_artifacts.success => {
let mut artifacts = setup_session_with_deployment(
&manifest,
&deployment,
Some(&ast_artifacts.asts),
);
for (contract_id, mut parser_diags) in ast_artifacts.diags.into_iter() {
// Merge parser's diags with analysis' diags.
if let Some(ref mut diags) = artifacts.diags.remove(&contract_id) {
parser_diags.append(diags);
None => {
match generate_default_deployment(manifest, &StacksNetwork::Simnet, false) {
Ok((deployment, ast_artifacts)) if ast_artifacts.success => {
let mut artifacts = setup_session_with_deployment(
manifest,
&deployment,
Some(&ast_artifacts.asts),
);
for (contract_id, mut parser_diags) in ast_artifacts.diags.into_iter() {
// Merge parser's diags with analysis' diags.
if let Some(ref mut diags) = artifacts.diags.remove(&contract_id) {
parser_diags.append(diags);
}
artifacts.diags.insert(contract_id, parser_diags);
}
artifacts.diags.insert(contract_id, parser_diags);
Ok((deployment, None, artifacts))
}
Ok((deployment, None, artifacts))
Ok((deployment, ast_artifacts)) => Ok((deployment, None, ast_artifacts)),
Err(e) => Err(e),
}
Ok((deployment, ast_artifacts)) => Ok((deployment, None, ast_artifacts)),
Err(e) => Err(e),
},
}
}
}
Some(path) => {
let deployment_location = get_absolute_deployment_path(&manifest, &path)
let deployment_location = get_absolute_deployment_path(manifest, path)
.expect("unable to retrieve deployment");
match load_deployment(&manifest, &deployment_location) {
match load_deployment(manifest, &deployment_location) {
Ok(deployment) => {
let artifacts = setup_session_with_deployment(&manifest, &deployment, None);
let artifacts = setup_session_with_deployment(manifest, &deployment, None);
Ok((deployment, Some(deployment_location.to_string()), artifacts))
}
Err(e) => Err(format!("loading {} failed with error: {}", path, e)),
Expand Down Expand Up @@ -1510,11 +1506,7 @@ pub fn should_existing_plan_be_replaced(
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).unwrap();

if buffer.starts_with("n") {
return false;
} else {
return true;
}
!buffer.starts_with('n')
}

pub fn load_deployment_if_exists(
Expand Down Expand Up @@ -1770,7 +1762,7 @@ fn display_hint_footer() {
}

fn display_post_check_hint() {
println!("");
println!();
display_hint_header();
println!(
"{}",
Expand All @@ -1786,7 +1778,7 @@ fn display_post_check_hint() {
}

fn display_post_console_hint() {
println!("");
println!();
display_hint_header();
println!(
"{}",
Expand All @@ -1809,7 +1801,7 @@ fn display_post_console_hint() {
}

fn display_deploy_hint() {
println!("");
println!();
display_hint_header();
println!(
"{}",
Expand Down
15 changes: 6 additions & 9 deletions components/clarinet-cli/src/generate/chainhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ impl<'a> GetChangesForNewChainhook<'a> {
}

fn create_template_bitcoin_chainhook(&mut self) -> Result<(), String> {
let content = format!(
r#"
let content = r#"
---
name: "Bitcoin hook"
version: 1
Expand All @@ -52,12 +51,11 @@ networks:
p2pkh: # support hex, p2pkh, p2sh, p2wpkh, p2wsh.
equals: muYdXKmX9bByAueDe6KFfHd5Ff1gdN9ErG # support equals, starts-with, ends-with
action:
http:
http:
url: http://localhost:3000/api/v1/<path>
method: POST
authorization-header: "Bearer cn389ncoiwuencr"
"#
);
"#.into();

let name = format!("{}.chainhook.yaml", self.chainhook_name);
let mut new_file = self
Expand All @@ -80,8 +78,7 @@ networks:
}

fn create_template_stacks_chainhook(&mut self) -> Result<(), String> {
let content = format!(
r#"
let content = r#"
---
name: "Stacks hook"
version: 1
Expand All @@ -106,12 +103,12 @@ networks:
# contract-identifier: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.cbtc-token
# method: mint
action:
http:
http:
url: http://localhost:3000/api/v1/<path>
method: POST
authorization-header: "Bearer cn389ncoiwuencr"
"#
);
.into();

let name = format!("{}.chainhook.yaml", self.chainhook_name);
let mut project_path = self
Expand Down
61 changes: 27 additions & 34 deletions components/clarinet-cli/src/generate/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl GetChangesForNewContract {
) -> Self {
Self {
manifest_location,
contract_name: contract_name.replace(".", "_"),
contract_name: contract_name.replace('.', "_"),
source,
changes: vec![],
}
Expand Down Expand Up @@ -50,7 +50,7 @@ impl GetChangesForNewContract {
;;
;; token definitions
;;
;;
;; constants
;;
Expand Down Expand Up @@ -92,38 +92,31 @@ impl GetChangesForNewContract {
}

fn create_template_test(&mut self) -> Result<(), String> {
let content = format!(
r#"
import {{ Clarinet, Tx, Chain, Account, types }} from 'https://deno.land/x/clarinet@v{}/index.ts';
import {{ assertEquals }} from 'https://deno.land/std@0.170.0/testing/asserts.ts';
Clarinet.test({{
name: "Ensure that <...>",
async fn(chain: Chain, accounts: Map<string, Account>) {{
// arrange: set up the chain, state, and other required elements
let wallet_1 = accounts.get("wallet_1")!;
// act: perform actions related to the current test
let block = chain.mineBlock([
/*
* Add transactions with:
* Tx.contractCall(...)
*/
]);
// assert: review returned data, contract state, and other requirements
assertEquals(block.receipts.length, 0);
assertEquals(block.height, 2);
// TODO
assertEquals("TODO", "a complete test");
}},
}});
"#,
env!("CARGO_PKG_VERSION")
);

let name = format!("{}_test.ts", self.contract_name);
let content = r#"
import { describe, expect, it } from "vitest";
const accounts = simnet.getAccounts();
const address1 = accounts.get("wallet_1")!;
/*
The test below is an example. To learn more, read the testing documentation here:
https://docs.hiro.so/clarinet/feature-guides/test-contract-with-clarinet-sdk
*/
describe("example tests", () => {
it("ensures simnet is well initalised", () => {
expect(simnet.blockHeight).toBeDefined();
});
// it("shows an example", () => {
// const { result } = simnet.callReadOnlyFn("counter", "get-counter", [], address1);
// expect(result).toBeUint(0);
// });
});
"#
.into();

let name = format!("{}.test.ts", self.contract_name);
let mut new_file = self.manifest_location.get_project_root_location().unwrap();
new_file.append_path("tests")?;
new_file.append_path(&name)?;
Expand Down
Loading

0 comments on commit 27f9bce

Please sign in to comment.