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

[WIP] Add checked operations #3

Open
wants to merge 3 commits into
base: feat/v1
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ seeds = false
[programs.localnet]
casier = "FLoc9nBwGb2ayzVzb5GC9NttuPY3CxMhd4KDnApr79Ab"

[programs.mainnet]
casier = "CAsieqooSrgVxhgWRwh21gyjq7Rmuhmo4qTW9XzXtAvW"

[registry]
url = "https://anchor.projectserum.com"

Expand Down
59 changes: 56 additions & 3 deletions migrations/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,64 @@
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.

const anchor = require("@project-serum/anchor");
import * as anchor from "@project-serum/anchor";
import { Program, AnchorProvider, Wallet } from "@project-serum/anchor";
import { Casier } from "../target/types/casier";
import {
PublicKey,
Connection,
Keypair,
SystemProgram,
SYSVAR_RENT_PUBKEY,
} from "@solana/web3.js";
import * as fs from "fs";

module.exports = async function (provider) {
function loadKeypair(keypairPath: string): any {
return <any>JSON.parse(fs.readFileSync(keypairPath).toString());
}

function loadWallet(keypair: string): Keypair {
return Keypair.fromSecretKey(new Uint8Array(loadKeypair(keypair)));
}

const fee_payer = loadWallet(process.env.FEE_PAYER_KEY_PATH);

module.exports = async function () {
// Configure client to use the provider.
anchor.setProvider(provider);
const idl = JSON.parse(
require("fs")
.readFileSync(`${process.cwd()}/../target/idl/casier.json`, "utf8")
.toString()
);
const connection = new Connection(
"https://aurory.rpcpool.com/76a89d061372798b1eab339287e7",
"recent"
);
const wallet = new Wallet(fee_payer);
const provider = new AnchorProvider(connection, wallet, {
commitment: "recent",
});
const program = new Program<Casier>(
idl,
new PublicKey("CAsieqooSrgVxhgWRwh21gyjq7Rmuhmo4qTW9XzXtAvW"),
provider
);
const tx1 = await program.methods.initialize().rpc();
console.log(tx1);
const [configPDA] = await PublicKey.findProgramAddress(
[anchor.utils.bytes.utf8.encode("config")],
program.programId
);
const tx2 = await program.methods
.initConfig()
.accounts({
config: configPDA,
feePayer: fee_payer.publicKey,
systemProgram: SystemProgram.programId,
rent: SYSVAR_RENT_PUBKEY,
})
.rpc();
console.log(tx2);

// Add your deploy script here.
};
56 changes: 17 additions & 39 deletions programs/casier/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod state;
pub mod utils;

use crate::state::CustomErrorCode;
use crate::state::*;
use crate::utils::*;
use anchor_lang::prelude::*;
Expand Down Expand Up @@ -48,14 +49,14 @@ pub mod casier {
match locker.mints.iter().position(|&lm| lm == mk) {
None => {
if before_amount > 0 {
return Err(error!(ErrorCode::InvalidBeforeState));
return Err(error!(CustomErrorCode::InvalidBeforeState));
}
locker.mints.push(mk);
locker.amounts.push(deposit_amount);
}
Some(i) => {
if before_amount != locker.amounts[i] {
return Err(error!(ErrorCode::InvalidBeforeState2));
return Err(error!(CustomErrorCode::InvalidBeforeState2));
}
locker.amounts[i] += deposit_amount;
}
Expand Down Expand Up @@ -91,7 +92,7 @@ pub mod casier {
vault_ta.owner == vault_ta.key() && vault_ta.mint == ctx.accounts.mint.key();

if !is_valid_vault {
return Err(error!(ErrorCode::InvalidVault));
return Err(error!(CustomErrorCode::InvalidVault));
}

spl_token_transfer(TokenTransferParams {
Expand Down Expand Up @@ -125,15 +126,20 @@ pub mod casier {
let mk = ctx.accounts.mint.key();
match locker.mints.iter().position(|&lm| lm == mk) {
None => {
return Err(error!(ErrorCode::WithdrawForMintNotInLocker));
return Err(error!(CustomErrorCode::WithdrawForMintNotInLocker));
}
Some(i) => {
let vault_remaining = ctx
.accounts
.vault_ta
.amount
.checked_sub(withdraw_amount)
.ok_or_else(|| CustomErrorCode::NotEnoughTokensInVault)?;

if locker.amounts[i] != before_amount {
return Err(error!(ErrorCode::InvalidBeforeState));
return Err(error!(CustomErrorCode::InvalidBeforeState));
// if final amount is lower than the amounts of tokens that will be left, we should call withdraw_and_burn
} else if (final_amount)
< ctx.accounts.vault_ta.amount - withdraw_amount
{
} else if (final_amount) < ctx.accounts.vault_ta.amount - withdraw_amount {
return Err(error!(ErrorCode::BurnRequired));
}
if final_amount > 0 {
Expand Down Expand Up @@ -209,7 +215,7 @@ pub mod casier {
with_transfer: bool,
) -> Result<()> {
if ctx.accounts.vault_ta.amount <= final_amount.into() {
return Err(error!(ErrorCode::BurnNotRequired));
return Err(error!(CustomErrorCode::BurnNotRequired));
}
let withdrawAccounts = &mut Withdraw {
config: ctx.accounts.config.clone(),
Expand All @@ -232,18 +238,12 @@ pub mod casier {
let mk = ctx.accounts.mint.key();
match locker.mints.iter().position(|&lm| lm == mk) {
None => {
return Err(error!(ErrorCode::WithdrawForMintNotInLocker));
return Err(error!(CustomErrorCode::WithdrawForMintNotInLocker));
}
Some(i) => {
if locker.amounts[i] != before_amount {
return Err(error!(ErrorCode::InvalidBeforeState));
return Err(error!(CustomErrorCode::InvalidBeforeState));
}
// if final amount is lower than the amounts of tokens that will be left, we should call withdraw_and_burn
// } else if (final_amount as u64)
// < ctx.accounts.vault_ta.amount - (withdraw_amount as u64)
// {
// return Err(error!(ErrorCode::BurnRequired));
// }
if final_amount > 0 {
locker.amounts[i] = final_amount;
} else {
Expand Down Expand Up @@ -356,25 +356,3 @@ pub mod casier {
Ok(())
}
}

#[error_code]
pub enum ErrorCode {
#[msg("Invalid vault.")]
InvalidVault,
#[msg("Invalid before state.")]
InvalidBeforeState,
#[msg("Invalid before state.")]
InvalidBeforeState2,
#[msg("Invalid before state.")]
InvalidBeforeState3,
#[msg("Invalid before state.")]
InvalidBeforeState4,
#[msg("Trying to withdraw a mint not in locker..")]
WithdrawForMintNotInLocker,
#[msg("InvalidFinalState: FinalState.")]
InvalidFinalState,
#[msg("BurnNotRequired")]
BurnNotRequired,
#[msg("BurnRequired")]
BurnRequired,
}
27 changes: 27 additions & 0 deletions programs/casier/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anchor_lang::error_code;
use anchor_lang::prelude::*;
use anchor_spl::{
associated_token::AssociatedToken,
Expand Down Expand Up @@ -182,3 +183,29 @@ pub struct Locker {
pub version: u8,
pub space: u64,
}

#[anchor_lang::error_code]
pub enum CustomErrorCode {
#[msg("Invalid vault.")]
InvalidVault,
#[msg("Invalid before state.")]
InvalidBeforeState,
#[msg("Invalid before state.")]
InvalidBeforeState2,
#[msg("Invalid before state.")]
InvalidBeforeState3,
#[msg("Invalid before state.")]
InvalidBeforeState4,
#[msg("Trying to withdraw a mint not in locker..")]
WithdrawForMintNotInLocker,
#[msg("InvalidFinalState: FinalState.")]
InvalidFinalState,
#[msg("BurnNotRequired")]
BurnNotRequired,
#[msg("BurnRequired")]
BurnRequired,
#[msg("Transfer failed2.")]
TransferFail2,
#[msg("Not enough tokens in vault")]
NotEnoughTokensInVault,
}
13 changes: 4 additions & 9 deletions programs/casier/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::state::CustomErrorCode;
use anchor_lang::prelude::*;
use anchor_lang::solana_program::{
entrypoint::ProgramResult,
Expand Down Expand Up @@ -114,7 +115,7 @@ pub fn spl_init_token_account(params: InitializeTokenAccountParams<'_, '_>) -> R
)?,
&[account, mint, owner, token_program, rent],
);
return result.map_err(|_| ErrorCode2::TransferFail2.into());
return result.map_err(|_| CustomErrorCode::TransferFail2.into());
}

pub fn spl_init_token_account2(params: InitializeTokenAccountParams<'_, '_>) -> Result<()> {
Expand All @@ -138,7 +139,7 @@ pub fn spl_init_token_account2(params: InitializeTokenAccountParams<'_, '_>) ->
)?,
&[account, mint, owner, token_program, rent],
);
return result.map_err(|_| ErrorCode2::TransferFail2.into());
return result.map_err(|_| CustomErrorCode::TransferFail2.into());
}

pub struct TokenTransferParams<'a: 'b, 'b> {
Expand Down Expand Up @@ -179,11 +180,5 @@ pub fn spl_token_transfer(params: TokenTransferParams<'_, '_>) -> Result<()> {
&[authority_signer_seeds],
);

return result.map_err(|_| ErrorCode2::TransferFail2.into());
}

#[error_code]
pub enum ErrorCode2 {
#[msg("Transfer failed2.")]
TransferFail2,
return result.map_err(|_| CustomErrorCode::TransferFail2.into());
}