Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Disallow omitting a return value for init methods #617

Merged
merged 3 commits into from
Dec 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ impl ImplItemMethodInfo {
quote! {}
};
let body = if matches!(method_type, &MethodType::Init) {
if matches!(returns, ReturnType::Default) {
return syn::Error::new(
ident.span(),
"Init methods must return the contract state",
)
.to_compile_error();
}
quote! {
if near_sdk::env::state_exists() {
near_sdk::env::panic_str("The contract has already been initialized");
Expand All @@ -86,6 +93,13 @@ impl ImplItemMethodInfo {
near_sdk::env::state_write(&contract);
}
} else if matches!(method_type, &MethodType::InitIgnoreState) {
if matches!(returns, ReturnType::Default) {
return syn::Error::new(
ident.span(),
"Init methods must return the contract state",
)
.to_compile_error();
}
quote! {
let contract = #struct_type::#ident(#arg_list);
near_sdk::env::state_write(&contract);
Expand Down
15 changes: 15 additions & 0 deletions near-sdk-macros/src/core_impl/code_generator/item_impl_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,21 @@ mod tests {
assert_eq!(expected.to_string(), actual.to_string());
}

#[test]
fn init_no_return() {
let impl_type: Type = syn::parse_str("Hello").unwrap();
let mut method: ImplItemMethod = parse_quote! {
#[init]
pub fn method(k: &mut u64) { }
};
let method_info = ImplItemMethodInfo::new(&mut method, impl_type).unwrap();
let actual = method_info.method_wrapper();
let expected = quote!(
compile_error! { "Init methods must return the contract state" }
);
assert_eq!(expected.to_string(), actual.to_string());
}

#[test]
fn init_ignore_state() {
let impl_type: Type = syn::parse_str("Hello").unwrap();
Expand Down