Skip to content

Commit

Permalink
Code updated with the latest modifications, and with the new keypair
Browse files Browse the repository at this point in the history
  • Loading branch information
smhussainpk committed Nov 13, 2024
1 parent 33f0e1a commit 39bdc50
Show file tree
Hide file tree
Showing 15 changed files with 289 additions and 7 deletions.
4 changes: 2 additions & 2 deletions Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ resolution = true
skip-lint = false

[programs.devnet]
pda_vesting = "aaUSJAx9C6W8nQqdX1H4YibzBh17tXA8JZnuRqj8ukZ"
pda_vesting = "abcxGrLevAiSMXHnzaasyrKwU4D58w8Ab5KBA9fcrWj"

[registry]
url = "https://api.apr.dev"

[provider]
cluster = "devnet"
cluster = "Devnet"
wallet = "~/.config/solana/id.json"

[scripts]
Expand Down
96 changes: 96 additions & 0 deletions client/emergency_withdraw/emergency_withdraw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import idl from "../../target/idl/pda_vesting.json";
import { PdaVesting } from "../../target/types/pda_vesting";
import { Program, Idl, AnchorProvider, setProvider, web3, Wallet } from "@coral-xyz/anchor";
import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import fs from 'fs';

// Helper function to load wallet keypair from file system
export function loadWalletKey(keypairFile: string): web3.Keypair {
const loaded = web3.Keypair.fromSecretKey(
new Uint8Array(JSON.parse(fs.readFileSync(keypairFile).toString())),
);
return loaded;
}

// Initialize Solana connection to devnet
const connection = new web3.Connection("https://api.devnet.solana.com");

// Load owner's keypair from wallet file
const ownerKeypair = loadWalletKey("owner_signer_wallet.json");

// Create wallet instance from keypair
const ownerWallet = new Wallet(ownerKeypair);

// Create Anchor provider with connection and wallet
const provider = new AnchorProvider(connection, ownerWallet, {});
setProvider(provider);

// Parse IDL and create program instance
const idlString = JSON.parse(JSON.stringify(idl));
const program = new Program<PdaVesting>(idlString, provider);

async function main() {
// BTB token mint address on devnet
const btbMint = new web3.PublicKey("btbVv5dmAjutpRRSr6DKwBPyPyfKiJw4eXU11BPuTCK");

// Derive PDA for BTB sale account
const [btbSaleAccount] = await web3.PublicKey.findProgramAddress(
[Buffer.from("btb-sale-account"), ownerKeypair.publicKey.toBuffer()],
program.programId
);

// Get BTB token account for sale account (PDA)
const btbSaleTokenAccount = await getAssociatedTokenAddress(
btbMint,
btbSaleAccount,
true
);

// Get owner's BTB token account
const ownerBtbAccount = await getAssociatedTokenAddress(
btbMint,
ownerKeypair.publicKey
);

console.log("BTB Sale Account (PDA):", btbSaleAccount.toString());
console.log("BTB Sale Token Account:", btbSaleTokenAccount.toString());
console.log("Owner BTB Account:", ownerBtbAccount.toString());

try {
// Get current balance before withdrawal
const saleTokenAccount = await connection.getTokenAccountBalance(btbSaleTokenAccount);
console.log("Current BTB balance in sale account:", saleTokenAccount.value.uiAmount);

// Execute emergency_withdraw instruction
const tx = await program.methods.emergencyWithdraw()
.accounts({
btbSaleAccount: btbSaleAccount,
btbSaleTokenAccount: btbSaleTokenAccount,
ownerBtbAccount: ownerBtbAccount,
btbMintAccount: btbMint,
signer: ownerWallet.publicKey,
systemProgram: web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID
})
.signers([ownerKeypair])
.rpc();

console.log("Emergency withdrawal successful. Transaction signature:", tx);

// Get new balance after withdrawal
const newSaleBalance = await connection.getTokenAccountBalance(btbSaleTokenAccount);
const ownerBalance = await connection.getTokenAccountBalance(ownerBtbAccount);

console.log("New BTB balance in sale account:", newSaleBalance.value.uiAmount);
console.log("Owner BTB balance:", ownerBalance.value.uiAmount);

} catch (error) {
console.error("Error during emergency withdrawal:", error);
}
}

// Execute the main function
main().catch((error) => {
console.error("Program execution failed:", error);
process.exit(1);
});
1 change: 1 addition & 0 deletions client/emergency_withdraw/owner_signer_wallet.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[238,58,240,86,204,14,212,156,80,210,93,80,80,157,225,218,197,251,216,54,242,52,201,88,115,165,12,244,35,251,188,62,11,52,168,205,223,188,132,207,6,245,214,4,157,197,10,9,179,111,131,213,165,10,69,25,176,233,200,27,205,139,108,1]
3 changes: 3 additions & 0 deletions client/initialize/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ async function main() {
console.log("Vesting Price (raw):", accountInfo.vestingPrice.toString());
console.log("Vesting Price (formatted):", accountInfo.vestingPrice.toNumber() / 1_000_000, "USDT");

console.log("\nSales:");
console.log("Sales Status (raw):", accountInfo.isSaleActive.toString());


} catch (error) {
console.error("Error during initialization:", error);
Expand Down
1 change: 1 addition & 0 deletions client/toggle_sale/owner_signer_wallet.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[238,58,240,86,204,14,212,156,80,210,93,80,80,157,225,218,197,251,216,54,242,52,201,88,115,165,12,244,35,251,188,62,11,52,168,205,223,188,132,207,6,245,214,4,157,197,10,9,179,111,131,213,165,10,69,25,176,233,200,27,205,139,108,1]
71 changes: 71 additions & 0 deletions client/toggle_sale/toggle_sale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import idl from "../../target/idl/pda_vesting.json";
import { PdaVesting } from "../../target/types/pda_vesting";
import { Program, Idl, AnchorProvider, setProvider, web3, Wallet } from "@coral-xyz/anchor";
import fs from 'fs';

// Helper function to load wallet keypair from file system
export function loadWalletKey(keypairFile: string): web3.Keypair {
const loaded = web3.Keypair.fromSecretKey(
new Uint8Array(JSON.parse(fs.readFileSync(keypairFile).toString())),
);
return loaded;
}

// Initialize Solana connection to devnet
const connection = new web3.Connection("https://api.devnet.solana.com");

// Load owner's keypair from wallet file
const ownerKeypair = loadWalletKey("owner_signer_wallet.json");

// Create wallet instance from keypair
const ownerWallet = new Wallet(ownerKeypair);

// Create Anchor provider with connection and wallet
const provider = new AnchorProvider(connection, ownerWallet, {});
setProvider(provider);

// Parse IDL and create program instance
const idlString = JSON.parse(JSON.stringify(idl));
const program = new Program<PdaVesting>(idlString, provider);

async function main() {
// Derive PDA for BTB sale account
const [btbSaleAccount] = await web3.PublicKey.findProgramAddress(
[Buffer.from("btb-sale-account"), ownerKeypair.publicKey.toBuffer()],
program.programId
);

// Log btbSaleAccount address
console.log("BTB Sale Account (PDA):", btbSaleAccount.toString());

try {
// Get current sale status before toggle
const accountInfoBefore = await program.account.initializeDataAccount.fetch(btbSaleAccount);
console.log("Current sale status:", accountInfoBefore.isSaleActive);

// Execute toggle_sale instruction
const tx = await program.methods.toggleSale()
.accounts({
btbSaleAccount: btbSaleAccount,
signer: ownerWallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([ownerKeypair])
.rpc();

console.log("Sale status toggled successfully. Transaction signature:", tx);

// Get new sale status after toggle
const accountInfoAfter = await program.account.initializeDataAccount.fetch(btbSaleAccount);
console.log("New sale status:", accountInfoAfter.isSaleActive);

} catch (error) {
console.error("Error during sale toggle:", error);
}
}

// Execute the main function
main().catch((error) => {
console.error("Program execution failed:", error);
process.exit(1);
});
1 change: 1 addition & 0 deletions client/transfer_admin/owner_signer_wallet.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[238,58,240,86,204,14,212,156,80,210,93,80,80,157,225,218,197,251,216,54,242,52,201,88,115,165,12,244,35,251,188,62,11,52,168,205,223,188,132,207,6,245,214,4,157,197,10,9,179,111,131,213,165,10,69,25,176,233,200,27,205,139,108,1]
87 changes: 87 additions & 0 deletions client/transfer_admin/transfer_admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import idl from "../../target/idl/pda_vesting.json";
import { PdaVesting } from "../../target/types/pda_vesting";
import { Program, Idl, AnchorProvider, setProvider, web3, Wallet } from "@coral-xyz/anchor";
import fs from 'fs';

// Helper function to load wallet keypair from file system
export function loadWalletKey(keypairFile: string): web3.Keypair {
const loaded = web3.Keypair.fromSecretKey(
new Uint8Array(JSON.parse(fs.readFileSync(keypairFile).toString())),
);
return loaded;
}

// Initialize Solana connection to devnet
const connection = new web3.Connection("https://api.devnet.solana.com");

// Load current admin's keypair from wallet file
const currentAdminKeypair = loadWalletKey("ttZwVJp67UVCcDk7mAVzRVajEP2bozJJNUwQJ7KjEjN.json");

// Create wallet instance from keypair
const currentAdminWallet = new Wallet(currentAdminKeypair);

// Create Anchor provider with connection and wallet
const provider = new AnchorProvider(connection, currentAdminWallet, {});
setProvider(provider);

// Parse IDL and create program instance
const program = new Program<PdaVesting>(idl as Idl, provider);

async function findInitializedAccount() {
// Get all program accounts
const accounts = await program.account.initializeDataAccount.all();

// Find the account where the current wallet is the owner
const ourAccount = accounts.find(acc =>
acc.account.ownerInitializeWallet.equals(currentAdminKeypair.publicKey)
);

if (!ourAccount) {
throw new Error("No initialized account found for this wallet");
}

return ourAccount.publicKey;
}

async function main() {
try {
// Find the currently initialized account
const btbSaleAccount = await findInitializedAccount();
console.log("Found initialized BTB Sale Account:", btbSaleAccount.toString());

// New admin's public key - replace with actual public key
const newAdmin = new web3.PublicKey("kk4JSSv7f5GX3ePkB9GKvTEP1n59ZrX1oVxLtXuodC4");

// Execute transfer_admin instruction
const tx = await program.methods.transferAdmin(newAdmin)
.accounts({
btbSaleAccount: btbSaleAccount,
signer: currentAdminWallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([currentAdminKeypair])
.rpc();

console.log("Admin transferred successfully. Transaction signature:", tx);

// Wait for confirmation
await connection.confirmTransaction(tx);

// Try to fetch the updated account info
try {
const updatedAccountInfo = await program.account.initializeDataAccount.fetch(btbSaleAccount);
console.log("New admin address:", updatedAccountInfo.ownerInitializeWallet.toString());
} catch (e) {
console.log("Note: Account data fetch after transfer may fail - this is expected");
}

} catch (error) {
console.error("Error during admin transfer:", error);
}
}

// Execute the main function
main().catch((error) => {
console.error("Program execution failed:", error);
process.exit(1);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[159,131,96,78,102,251,228,196,162,146,111,73,17,86,150,50,45,156,109,197,56,47,159,103,148,12,26,85,107,121,167,56,13,74,237,230,114,140,33,24,216,93,197,187,123,28,153,123,218,42,178,236,64,50,148,94,69,91,67,170,174,148,39,157]
2 changes: 2 additions & 0 deletions client/update_initialize/update_initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ async function main() {
console.log("Vesting Price (raw):", accountInfo.vestingPrice.toString());
console.log("Vesting Price (formatted):", accountInfo.vestingPrice.toNumber() / 1_000_000, "USDT");

console.log("\nSales:");
console.log("Sales Status :", accountInfo.isSaleActive.toString());

} catch (error) {
console.error("Error during initialization:", error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn transfer_admin(ctx: Context<TransferAdmin>, new_admin: Pubkey) -> Result<
Ok(())
}

pub fn toggle_sale(ctx: Context<UpdateData>) -> Result<()> {
pub fn process_toggle_sale(ctx: Context<UpdateData>) -> Result<()> {
let sale_account = &mut ctx.accounts.btb_sale_account;

// Only owner can toggle sale status
Expand All @@ -42,7 +42,7 @@ pub fn toggle_sale(ctx: Context<UpdateData>) -> Result<()> {
Ok(())
}

pub fn emergency_withdraw(ctx: Context<EmergencyWithdraw>) -> Result<()> {
pub fn process_emergency_withdraw(ctx: Context<EmergencyWithdraw>) -> Result<()> {
let btb_sale_account = &ctx.accounts.btb_sale_account;

// Only owner can withdraw
Expand Down
11 changes: 10 additions & 1 deletion programs/pda_vesting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod instructions;
mod state;


declare_id!("aaUSJAx9C6W8nQqdX1H4YibzBh17tXA8JZnuRqj8ukZ");
declare_id!("abcxGrLevAiSMXHnzaasyrKwU4D58w8Ab5KBA9fcrWj");

#[program]
pub mod pda_vesting {
Expand Down Expand Up @@ -41,8 +41,17 @@ pub mod pda_vesting {
process_buy_token(ctx, amount, token_type)
}

/*
pub fn transfer_admin(ctx: Context<TransferAdmin>, new_admin: Pubkey) -> Result<()> {
transfer_admin(ctx, new_admin)
}*/

pub fn toggle_sale(ctx: Context<UpdateData>) -> Result<()> {
process_toggle_sale(ctx)
}

pub fn emergency_withdraw(ctx: Context<EmergencyWithdraw>) -> Result<()> {
process_emergency_withdraw(ctx)
}
}

Expand Down
8 changes: 6 additions & 2 deletions programs/pda_vesting/src/state/update_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ use crate::initialize_data_account::InitializeDataAccount;

#[derive(Accounts)]
pub struct UpdateData<'info> {
#[account(mut, seeds = [b"btb-sale-account", signer.key().as_ref()], bump)]
#[account(
mut,
seeds = [b"btb-sale-account", btb_sale_account.owner_initialize_wallet.as_ref()],
bump
)]
pub btb_sale_account: Account<'info, InitializeDataAccount>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
}
5 changes: 5 additions & 0 deletions resources/setKeyPair.md → resources/ReadMe.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@

cd BTBBackendV1/resources/

# Create a new Keypair
`solana-keygen grind --starts-with <custom starting letters like BTB>:<number of keys>`

`solana config set --keypair BTBF9x3R2nnY1cvP32KPjeyE26XQV8z7Y86xtPydxaRk.json`

`solana config set --url devnet`
Expand Down Expand Up @@ -39,3 +42,5 @@ some tokens ------
# You can transfer token with the help of below command

`spl-token transfer mnti2XLiWJ2H2YaLdCDX3Js2c6AdCxZ2FMUuhV2abEy 10 (recipient wallet address) --fund-recipient`


1 change: 1 addition & 0 deletions resources/abcxGrLevAiSMXHnzaasyrKwU4D58w8Ab5KBA9fcrWj.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[91,228,51,164,126,228,185,172,90,151,198,201,157,192,144,91,125,47,69,24,6,216,81,207,236,9,248,200,135,224,115,233,8,155,79,191,224,165,233,133,107,115,226,54,29,185,240,73,195,12,222,142,6,60,161,89,186,205,27,132,86,166,118,184]

0 comments on commit 39bdc50

Please sign in to comment.