Skip to content

Instantly share code, notes, and snippets.

@omgbbqhaxx
Last active February 1, 2023 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omgbbqhaxx/38520fb673ef612a214a3191aaf8a490 to your computer and use it in GitHub Desktop.
Save omgbbqhaxx/38520fb673ef612a214a3191aaf8a490 to your computer and use it in GitHub Desktop.
import * as anchor from "@project-serum/anchor";
import { Program } from "@project-serum/anchor";
import { Airdrop } from "../target/types/airdrop";
const assert = require("assert");
const anchor = require("@project-serum/anchor");
const { SystemProgram } = anchor.web3;
import {Connection, PublicKey, LAMPORTS_PER_SOL} from "@solana/web3.js";
import {
Program,
AnchorProvider,
web3,
utils,
BN,
} from "@project-serum/anchor";
describe("airdrop", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.Airdrop as Program<Airdrop>;
console.log("founder: ",program.provider.wallet.publicKey.toString());
console.log("222", SystemProgram.programId.toString());
let pkey = program.provider.wallet.publicKey;
it("Can send and bounce back sol", async () => {
const connection = new Connection("http://127.0.0.1:8899", "confirmed");
const myAccount = anchor.web3.Keypair.generate();
const signature = await connection.requestAirdrop(myAccount.publicKey, 5000000000);
await connection.confirmTransaction(signature);
const response = await connection.getAccountInfo(myAccount.publicKey);
//let [to, bump] = await anchor.web3.PublicKey.findProgramAddress([Buffer.from("airdrop-example")], program.programId);
//const campaign = await anchor.web3.PublicKey.findProgramAddress([Buffer.from("airdrop-example")], program.programId);
//const [campaign] = await anchor.web3.PublicKey.findProgramAddress([Buffer.from("airdrop-example"), program.provider.wallet.publicKey.toBuffer()],program.programId);
const [campaign] = await anchor.web3.PublicKey.findProgramAddress([Buffer.from("airdrop-example"), myAccount.publicKey.toBuffer()],program.programId);
//Eğer program privader wallet keyi verilmiyorsa imzaya ihtiyaç duyuyor bu 2. numaralı camp. de hesabın sahibi dışarıdan bir accout bu yüzden aşağıda ekstra imzaya ihtiyaç duyuyor.
console.log("İşlem yapan hesap", myAccount.publicKey.toString());
const ourCampaignId = campaign.toString();
console.log("ourCampaignId", ourCampaignId);
console.log("system program id", SystemProgram.programId);
const txx = await program.rpc.create({
accounts: {
campaign,
//user: program.provider.wallet.publicKey, //Önemli : eğer user program provider ise signature ihtiyaç duymaz. fakat farklı bir account tarafından sign ediliyorsa o zaman signers kısmında
//imzaya gerek duyulur!
user: myAccount.publicKey,
systemProgram: SystemProgram.programId,
}, signers: [myAccount],
});
console.log("txx", txx);
//first of all we create an campaign account right now we are createing an secondary account then this
//account will send an some solana to program then program owner can claim that money.
const newrandaccj = anchor.web3.Keypair.generate();
const reqsecadropsign = await connection.requestAirdrop(newrandaccj.publicKey, 3000000000);
console.log("Kampanyaya para gönderen hesaptir", newrandaccj.publicKey.toString());
await connection.confirmTransaction(reqsecadropsign);
let balancehh = await connection.getBalance(newrandaccj.publicKey);
console.log(`${balancehh / LAMPORTS_PER_SOL} SOL`);
const txtwo = await program.rpc.donate(new BN(2.1 * web3.LAMPORTS_PER_SOL), {
accounts: {
campaign: ourCampaignId,
user: newrandaccj.publicKey,
systemProgram: SystemProgram.programId,
}, signers: [newrandaccj],
});
console.log("txx2", txtwo);
const lasttx = await program.rpc.withdraw(new BN(2 * web3.LAMPORTS_PER_SOL), {
accounts: {
campaign: ourCampaignId,
user: myAccount.publicKey,
//systemProgram: SystemProgram.programId,
}, signers: [myAccount],
});
console.log("lasttx is bhere", lasttx);
});
//sudo solana program deploy /Users/yasinaktimur/Documents/deneme/bounce/target/deploy/airdrop.so --program-id 9VoMvYX6Xx9ZpnjBoDZxL5TQiH7DmmFGm9XMPdyLQiPH
//EUox4zLTSZ9UnafP3GvgiJ2djcixwfEWmBvL3zpnaaRj
//solana program deploy /Users/yasinaktimur/Documents/udemy/airdrop/target/deploy/airdrop.so
//it("Is initialized!", async () => { /* Add your test here. */ const tx = await program.methods.initialize().rpc(); console.log("Your transaction signature", tx); });
});
use anchor_lang::prelude::*;
use anchor_lang::solana_program::entrypoint::ProgramResult;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod airdrop {
use super::*;
pub fn create(ctx: Context<CreateGG>) -> ProgramResult {
let campaign = &mut ctx.accounts.campaign;
campaign.amount_donated = 0;
campaign.admin = *ctx.accounts.user.key;
Ok(())
}
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> ProgramResult {
let campaign = &mut ctx.accounts.campaign;
let user = &mut ctx.accounts.user;
if campaign.admin != *user.key {
return Err(ProgramError::IncorrectProgramId);
}
let rent_balance = Rent::get()?.minimum_balance(campaign.to_account_info().data_len());
if **campaign.to_account_info().lamports.borrow() - rent_balance < amount {
return Err(ProgramError::InsufficientFunds);
}
**campaign.to_account_info().try_borrow_mut_lamports()? -= amount;
**user.to_account_info().try_borrow_mut_lamports()? += amount;
Ok(())
}
pub fn donate(ctx: Context<Donate>, amount: u64) -> ProgramResult {
let ix = anchor_lang::solana_program::system_instruction::transfer(
&ctx.accounts.user.key(),
&ctx.accounts.campaign.key(),
amount,
);
anchor_lang::solana_program::program::invoke(
&ix,
&[
ctx.accounts.user.to_account_info(),
ctx.accounts.campaign.to_account_info(),
],
);
(&mut ctx.accounts.campaign).amount_donated += amount;
Ok(())
}
}
#[derive(Accounts)]
pub struct CreateGG<'info> {
#[account(init, payer=user, space=9000, seeds=[b"airdrop-example".as_ref(), user.key().as_ref()], bump)]
pub campaign: Account<'info, Campaign>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Withdraw<'info> {
#[account(mut)]
pub campaign: Account<'info, Campaign>,
#[account(mut)]
pub user: Signer<'info>,
}
#[derive(Accounts)]
pub struct Donate<'info> {
#[account(mut)]
pub campaign: Account<'info, Campaign>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Campaign {
pub admin: Pubkey,
pub amount_donated: u64,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment