Skip to content

Commit

Permalink
lang: Close account constraint
Browse files Browse the repository at this point in the history
  • Loading branch information
armaniferrante committed Jun 9, 2021
1 parent ba99c9c commit 28f88a8
Show file tree
Hide file tree
Showing 14 changed files with 256 additions and 29 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions examples/misc/programs/misc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ pub mod misc {
ctx.accounts.data.data = data;
Ok(())
}

pub fn test_close(_ctx: Context<TestClose>) -> ProgramResult {
Ok(())
}
}

#[derive(Accounts)]
Expand Down Expand Up @@ -117,6 +121,13 @@ pub struct TestStateCpi<'info> {
misc2_program: AccountInfo<'info>,
}

#[derive(Accounts)]
pub struct TestClose<'info> {
#[account(mut, close = sol_dest)]
data: ProgramAccount<'info, Data>,
sol_dest: AccountInfo<'info>,
}

// `my_account` is the associated token account being created.
// `authority` must be a `mut` and `signer` since it will pay for the creation
// of the associated token account. `state` is used as an association, i.e., one
Expand Down
55 changes: 54 additions & 1 deletion examples/misc/tests/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,60 @@ describe("misc", () => {
});

it("Can use base58 strings to fetch an account", async () => {
const dataAccount = await program.account.dataI16.fetch(dataPubkey.toString());
const dataAccount = await program.account.dataI16.fetch(
dataPubkey.toString()
);
assert.ok(dataAccount.data === -2048);
});

it("Should fail to close an account when sending lamports to itself", async () => {
try {
await program.rpc.testClose({
accounts: {
data: data.publicKey,
solDest: data.publicKey,
},
});
assert.ok(false);
} catch (err) {
const errMsg = "A close constraint was violated";
assert.equal(err.toString(), errMsg);
assert.equal(err.msg, errMsg);
assert.equal(err.code, 151);
}
});

it("Can close an account", async () => {
const openAccount = await program.provider.connection.getAccountInfo(
data.publicKey
);
assert.ok(openAccount !== null);

let beforeBalance = (
await program.provider.connection.getAccountInfo(
program.provider.wallet.publicKey
)
).lamports;

await program.rpc.testClose({
accounts: {
data: data.publicKey,
solDest: program.provider.wallet.publicKey,
},
});

let afterBalance = (
await program.provider.connection.getAccountInfo(
program.provider.wallet.publicKey
)
).lamports;

// Retrieved rent exemption sol.
assert.ok(afterBalance > beforeBalance);

const closedAccount = await program.provider.connection.getAccountInfo(
data.publicKey
);
assert.ok(closedAccount === null);
});
});
2 changes: 2 additions & 0 deletions lang/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ pub enum ErrorCode {
ConstraintAssociated,
#[msg("An associated init constraint was violated")]
ConstraintAssociatedInit,
#[msg("A close constraint was violated")]
ConstraintClose,

// Accounts.
#[msg("The account discriminator was already set on this account")]
Expand Down
10 changes: 9 additions & 1 deletion lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ extern crate self as anchor_lang;

use bytemuck::{Pod, Zeroable};
use solana_program::account_info::AccountInfo;
use solana_program::entrypoint::ProgramResult;
use solana_program::instruction::AccountMeta;
use solana_program::program_error::ProgramError;
use solana_program::pubkey::Pubkey;
Expand Down Expand Up @@ -92,7 +93,13 @@ pub trait Accounts<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
/// should be done here.
pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
/// `program_id` is the currently executing program.
fn exit(&self, program_id: &Pubkey) -> solana_program::entrypoint::ProgramResult;
fn exit(&self, program_id: &Pubkey) -> ProgramResult;
}

/// The close procedure to initiate garabage collection of an account, allowing
/// one to retrieve the rent exemption.
pub trait AccountsClose<'info>: ToAccountInfos<'info> {
fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult;
}

/// A data structure of accounts providing a one time deserialization upon
Expand Down Expand Up @@ -275,4 +282,5 @@ pub mod __private {
}

pub use crate::state::PROGRAM_STATE_SEED;
pub const CLOSED_ACCOUNT_DISCRIMINATOR: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255];
}
24 changes: 23 additions & 1 deletion lang/src/loader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::error::ErrorCode;
use crate::{
Accounts, AccountsExit, AccountsInit, ToAccountInfo, ToAccountInfos, ToAccountMetas, ZeroCopy,
Accounts, AccountsClose, AccountsExit, AccountsInit, ToAccountInfo, ToAccountInfos,
ToAccountMetas, ZeroCopy,
};
use solana_program::account_info::AccountInfo;
use solana_program::entrypoint::ProgramResult;
Expand Down Expand Up @@ -175,6 +176,27 @@ impl<'info, T: ZeroCopy> AccountsExit<'info> for Loader<'info, T> {
}
}

impl<'info, T: ZeroCopy> AccountsClose<'info> for Loader<'info, T> {
fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
let info = self.to_account_info();

// Transfer tokens from this account to the sol_destination.
let dest_starting_lamports = sol_destination.lamports();
**sol_destination.lamports.borrow_mut() =
dest_starting_lamports.checked_add(info.lamports()).unwrap();
**info.lamports.borrow_mut() = 0;

// Mark the account discriminator as closed.
let mut data = info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut cursor = std::io::Cursor::new(dst);
cursor
.write_all(&crate::__private::CLOSED_ACCOUNT_DISCRIMINATOR)
.map_err(|_| ErrorCode::AccountDidNotSerialize)?;
Ok(())
}
}

impl<'info, T: ZeroCopy> ToAccountMetas for Loader<'info, T> {
fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
let is_signer = is_signer.unwrap_or(self.acc_info.is_signer);
Expand Down
28 changes: 26 additions & 2 deletions lang/src/program_account.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use crate::error::ErrorCode;
use crate::{
AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AccountsInit, CpiAccount,
ToAccountInfo, ToAccountInfos, ToAccountMetas,
AccountDeserialize, AccountSerialize, Accounts, AccountsClose, AccountsExit, AccountsInit,
CpiAccount, ToAccountInfo, ToAccountInfos, ToAccountMetas,
};
use solana_program::account_info::AccountInfo;
use solana_program::entrypoint::ProgramResult;
use solana_program::instruction::AccountMeta;
use solana_program::program_error::ProgramError;
use solana_program::pubkey::Pubkey;
use std::io::Write;
use std::ops::{Deref, DerefMut};

/// Boxed container for a deserialized `account`. Use this to reference any
Expand Down Expand Up @@ -120,6 +121,29 @@ impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsExit<'info
}
}

impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsClose<'info>
for ProgramAccount<'info, T>
{
fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
let info = self.to_account_info();

// Transfer tokens from this account to the sol_destination.
let dest_starting_lamports = sol_destination.lamports();
**sol_destination.lamports.borrow_mut() =
dest_starting_lamports.checked_add(info.lamports()).unwrap();
**info.lamports.borrow_mut() = 0;

// Mark the account discriminator as closed.
let mut data = info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut cursor = std::io::Cursor::new(dst);
cursor
.write_all(&crate::__private::CLOSED_ACCOUNT_DISCRIMINATOR)
.map_err(|_| ErrorCode::AccountDidNotSerialize)?;
Ok(())
}
}

impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas
for ProgramAccount<'info, T>
{
Expand Down
17 changes: 16 additions & 1 deletion lang/syn/src/codegen/accounts/constraints.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
CompositeField, Constraint, ConstraintAssociatedGroup, ConstraintBelongsTo,
CompositeField, Constraint, ConstraintAssociatedGroup, ConstraintBelongsTo, ConstraintClose,
ConstraintExecutable, ConstraintGroup, ConstraintInit, ConstraintLiteral, ConstraintMut,
ConstraintOwner, ConstraintRaw, ConstraintRentExempt, ConstraintSeeds, ConstraintSigner,
ConstraintState, Field, Ty,
Expand Down Expand Up @@ -50,6 +50,7 @@ pub fn linearize(c_group: &ConstraintGroup) -> Vec<Constraint> {
executable,
state,
associated,
close,
} = c_group.clone();

let mut constraints = Vec::new();
Expand Down Expand Up @@ -94,6 +95,9 @@ pub fn linearize(c_group: &ConstraintGroup) -> Vec<Constraint> {
if let Some(c) = state {
constraints.push(Constraint::State(c));
}
if let Some(c) = close {
constraints.push(Constraint::Close(c));
}
constraints
}

Expand All @@ -111,6 +115,7 @@ fn generate_constraint(f: &Field, c: &Constraint) -> proc_macro2::TokenStream {
Constraint::Executable(c) => generate_constraint_executable(f, c),
Constraint::State(c) => generate_constraint_state(f, c),
Constraint::AssociatedGroup(c) => generate_constraint_associated(f, c),
Constraint::Close(c) => generate_constraint_close(f, c),
}
}

Expand All @@ -126,6 +131,16 @@ pub fn generate_constraint_init(_f: &Field, _c: &ConstraintInit) -> proc_macro2:
quote! {}
}

pub fn generate_constraint_close(f: &Field, c: &ConstraintClose) -> proc_macro2::TokenStream {
let field = &f.ident;
let target = &c.sol_dest;
quote! {
if #field.to_account_info().key == #target.to_account_info().key {
return Err(anchor_lang::__private::ErrorCode::ConstraintClose.into());
}
}
}

pub fn generate_constraint_mut(f: &Field, _c: &ConstraintMut) -> proc_macro2::TokenStream {
let ident = &f.ident;
quote! {
Expand Down
20 changes: 15 additions & 5 deletions lang/syn/src/codegen/accounts/exit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,21 @@ pub fn generate(accs: &AccountsStruct) -> proc_macro2::TokenStream {
}
AccountField::Field(f) => {
let ident = &f.ident;
match f.constraints.is_mutable() {
false => quote! {},
true => quote! {
anchor_lang::AccountsExit::exit(&self.#ident, program_id)?;
},
if f.constraints.is_close() {
let close_target = &f.constraints.close.as_ref().unwrap().sol_dest;
quote! {
anchor_lang::AccountsClose::close(
&self.#ident,
self.#close_target.to_account_info(),
)?;
}
} else {
match f.constraints.is_mutable() {
false => quote! {},
true => quote! {
anchor_lang::AccountsExit::exit(&self.#ident, program_id)?;
},
}
}
}
})
Expand Down
9 changes: 9 additions & 0 deletions lang/syn/src/idl/borsh_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pub enum IdlValue {
Bool,
U8,
Defined(Box<IdlTypeDefinitionValue>),
}

pub enum IdlTypeDefinitionValue {
Struct { fields: Vec<IdlValue> },
}
13 changes: 12 additions & 1 deletion lang/syn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ pub struct ConstraintGroup {
belongs_to: Vec<ConstraintBelongsTo>,
literal: Vec<ConstraintLiteral>,
raw: Vec<ConstraintRaw>,
close: Option<ConstraintClose>,
}

impl ConstraintGroup {
Expand All @@ -271,6 +272,10 @@ impl ConstraintGroup {
pub fn is_signer(&self) -> bool {
self.signer.is_some()
}

pub fn is_close(&self) -> bool {
self.close.is_some()
}
}

// A single account constraint *after* merging all tokens into a well formed
Expand All @@ -290,6 +295,7 @@ pub enum Constraint {
Executable(ConstraintExecutable),
State(ConstraintState),
AssociatedGroup(ConstraintAssociatedGroup),
Close(ConstraintClose),
}

// Constraint token is a single keyword in a `#[account(<TOKEN>)]` attribute.
Expand All @@ -306,7 +312,7 @@ pub enum ConstraintToken {
Seeds(Context<ConstraintSeeds>),
Executable(Context<ConstraintExecutable>),
State(Context<ConstraintState>),
AssociatedGroup(ConstraintAssociatedGroup),
Close(Context<ConstraintClose>),
Associated(Context<ConstraintAssociated>),
AssociatedPayer(Context<ConstraintAssociatedPayer>),
AssociatedSpace(Context<ConstraintAssociatedSpace>),
Expand Down Expand Up @@ -396,6 +402,11 @@ pub struct ConstraintAssociatedSpace {
pub space: LitInt,
}

#[derive(Debug, Clone)]
pub struct ConstraintClose {
pub sol_dest: Ident,
}

// Syntaxt context object for preserving metadata about the inner item.
#[derive(Debug, Clone)]
pub struct Context<T> {
Expand Down
Loading

0 comments on commit 28f88a8

Please sign in to comment.