This commit is contained in:
Sewmina Dilshan 2024-11-12 08:44:03 +05:30
commit 6993766862
27 changed files with 4541 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
.anchor
.DS_Store
target
**/*.rs.bk
node_modules
test-ledger
.yarn

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
.anchor
.DS_Store
target
node_modules
dist
build
test-ledger

18
Anchor.toml Normal file
View File

@ -0,0 +1,18 @@
[toolchain]
[features]
resolution = true
skip-lint = false
[programs.localnet]
tournaments = "88dRZraTvmpqMs8GqtgCc321Foo5bWtDAsXJ1kqoc6nC"
[registry]
url = "https://api.apr.dev"
[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"
[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"

2732
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

14
Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[workspace]
members = [
"programs/*"
]
resolver = "2"
[profile.release]
overflow-checks = true
lto = "fat"
codegen-units = 1
[profile.release.build-override]
opt-level = 3
incremental = false
codegen-units = 1

12
migrations/deploy.ts Normal file
View File

@ -0,0 +1,12 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
const anchor = require("@coral-xyz/anchor");
module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);
// Add your deploy script here.
};

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"license": "ISC",
"scripts": {
"lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
"lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
},
"dependencies": {
"@coral-xyz/anchor": "^0.30.1"
},
"devDependencies": {
"chai": "^4.3.4",
"mocha": "^9.0.3",
"ts-mocha": "^10.0.0",
"@types/bn.js": "^5.1.0",
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"typescript": "^4.3.5",
"prettier": "^2.6.2"
}
}

View File

@ -0,0 +1,22 @@
[package]
name = "tournaments"
version = "0.1.0"
description = "Created with Anchor"
edition = "2021"
[lib]
crate-type = ["cdylib", "lib"]
name = "tournaments"
[features]
default = []
cpi = ["no-entrypoint"]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"]
[dependencies]
anchor-lang = {version="0.30.1", features=["init-if-needed"]}
anchor-spl= "0.30.1"
solana-program = "=2.0.3"

View File

@ -0,0 +1,2 @@
[target.bpfel-unknown-unknown.dependencies.std]
features = []

View File

@ -0,0 +1,7 @@
use anchor_lang::prelude::*;
#[constant]
pub const ID: &str = "";
#[constant]
pub const DATA_REGISTRY_SEED:&[u8; 9] = b"sales_reg";

View File

@ -0,0 +1,11 @@
use anchor_lang::prelude::*;
#[error_code]
pub enum CustomErrors {
#[msg("Custom error message")]
CustomError,
#[msg("Insufficient funds to purchase a ticket, Recharge your wallet and try again")]
InsufficientFunds,
#[msg("Only the owner can perform this action")]
Unauthorized
}

View File

@ -0,0 +1,81 @@
use anchor_lang::prelude::*;
use anchor_spl::{
associated_token::AssociatedToken, token_interface::{Mint, TokenAccount, TokenInterface, close_account, transfer_checked, CloseAccount, TransferChecked}
};
use crate::{Sales, DataRegistry, DATA_REGISTRY_SEED};
use super::transfer_tokens;
#[derive(Accounts)]
pub struct AddSeller <'info>{
#[account(mut)]
pub seller: Signer<'info>,
// #[account(
// mut,
// associated_token::mint=mint,
// associated_token::authority = seller,
// associated_token::token_program= token_program,
// )]
// pub seller_token_account: InterfaceAccount<'info, TokenAccount>,
#[account(
init,
payer = seller,
space = 8 + Sales::INIT_SPACE,
seeds= [b"sales", seller.key().as_ref()],
bump
)]
pub sales: Account<'info, Sales>,
#[account(mint::token_program = token_program)]
pub mint: InterfaceAccount<'info, Mint>,
#[account(
init,
payer =seller,
associated_token::mint=mint,
associated_token::authority = sales,
associated_token::token_program= token_program,
)]
pub vault: InterfaceAccount<'info, TokenAccount>,
#[account(
mut,
seeds=[DATA_REGISTRY_SEED],
bump
)]
pub data_registry: Account<'info, DataRegistry>,
pub system_program: Program<'info, System>,
pub token_program: Interface<'info, TokenInterface>,
pub associated_token_program: Program<'info, AssociatedToken>
}
// pub fn send_tickets_to_vault(ctx: &Context<AddSeller>, tickets_count: u64) -> Result<()>{
// transfer_tokens(
// &ctx.accounts.seller_token_account,
// &ctx.accounts.vault,
// &tickets_count,
// &ctx.accounts.mint,
// &ctx.accounts.seller,
// &ctx.accounts.token_program
// )
// }
pub fn save_sales_account(ctx: Context<AddSeller>) -> Result<()> {
ctx.accounts.sales.set_inner(
Sales{
seller: ctx.accounts.seller.key(),
vault: ctx.accounts.vault.key(),
mint: ctx.accounts.mint.key(),
bump: ctx.bumps.sales
}
);
ctx.accounts.data_registry.sales_pdas.push(ctx.accounts.sales.key());
Ok(())
}

View File

@ -0,0 +1,42 @@
use anchor_lang::prelude::*;
use anchor_spl::associated_token::spl_associated_token_account::instruction;
use crate::{error::CustomErrors, DataRegistry, Tournament, DATA_REGISTRY_SEED};
pub fn handler(ctx:Context<AddTournament>, id:u64, start_time:String)->Result<()>{
require!(ctx.accounts.payer.key() == ctx.accounts.data_registry.authority, CustomErrors::Unauthorized);
let tournamentAccount = &mut ctx.accounts.tournament_account;
tournamentAccount.id = id;
tournamentAccount.start_time = start_time;
Ok(())
}
#[derive(Accounts)]
#[instruction(id:u64)]
pub struct AddTournament<'info>{
#[account(mut)]
pub payer: Signer<'info>,
#[account(
init,
payer= payer,
space = Tournament::INIT_SPACE,
seeds = [b"tournament",id.to_le_bytes().as_ref()],
bump
)]
pub tournament_account: Account<'info,Tournament>,
#[account(
mut,
seeds = [DATA_REGISTRY_SEED],
bump
)]
pub data_registry: Account<'info, DataRegistry>,
pub system_program: Program<'info, System>
}

View File

@ -0,0 +1,29 @@
use anchor_lang::prelude::*;
use anchor_spl:: token::{Mint, Token, TokenAccount};
use crate::{Sales, DataRegistry, DATA_REGISTRY_SEED};
#[derive(Accounts)]
pub struct Initialize <'info>{
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
payer=signer,
space= 8 + DataRegistry::INIT_SPACE,
seeds = [DATA_REGISTRY_SEED],
bump
)]
pub data_registry: Account<'info, DataRegistry>,
pub system_program: Program<'info, System>,
}
pub fn handler(ctx: Context<Initialize>) -> Result<()> {
let reg_acc = &mut ctx.accounts.data_registry;
reg_acc.authority = ctx.accounts.signer.key();
msg!("Initiated Ticket store");
Ok(())
}

View File

@ -0,0 +1,82 @@
use anchor_lang::prelude::*;
use crate::{DataRegistry, Sales, Tournament, DATA_REGISTRY_SEED};
use anchor_spl::{associated_token::AssociatedToken, token_interface::{transfer_checked, Mint, TokenAccount, TokenInterface, TransferChecked}};
// pub fn transfer_ticket_to_vault(ctx:&Context<JoinTorunament>, id:u64) -> Result<()>{
// let seeds = &[
// b"sales",
// ctx.accounts.seller.to_account_info().key.as_ref(),
// &[ctx.accounts.sales.bump]
// ];
// let signer_seeds = [&seeds[..]];
// let accounts = TransferChecked{
// from: ctx.accounts.vault.to_account_info(),
// to: ctx.accounts.buyer_token_account.to_account_info(),
// mint: ctx.accounts.mint.to_account_info(),
// authority: ctx.accounts.sales.to_account_info()
// };
// let cpi_context = CpiContext::new_with_signer(
// ctx.accounts.token_program.to_account_info(),
// accounts,
// &signer_seeds
// );
// transfer_checked(cpi_context, amount*LAMPORTS_PER_SOL, ctx.accounts.mint.decimals)
// }
pub fn add_to_participants_list(ctx:Context<JoinTorunament>, id:u64) -> Result<()>{
let tournament_account = &mut ctx.accounts.tournament_account;
tournament_account.participants.push(*ctx.accounts.user.key);
Ok(())
}
#[derive(Accounts)]
#[instruction(id:u64)]
pub struct JoinTorunament<'info>{
#[account(mut)]
pub user: Signer<'info>,
#[account(
mut,
seeds = [b"Tournament", id.to_le_bytes().as_ref()],
bump
)]
pub tournament_account: Account<'info, Tournament>,
#[account(
mut,
seeds = [DATA_REGISTRY_SEED],
bump
)]
pub data_registry: Account<'info, DataRegistry>,
#[account(mut)]
pub seller:SystemAccount<'info>,
#[account(mint::token_program = token_program)]
pub mint: InterfaceAccount<'info, Mint>,
#[account(
mut,
seeds= [b"sales", seller.key().as_ref()],
bump = sales.bump
)]
pub sales: Account<'info, Sales>,
#[account(
mut,
associated_token::mint= mint,
associated_token::authority = sales,
associated_token::token_program = token_program
)]
vault: InterfaceAccount<'info, TokenAccount>,
pub system_program: Program<'info, System>,
pub token_program: Interface<'info, TokenInterface>,
pub associated_token_program: Program<'info, AssociatedToken>
}

View File

@ -0,0 +1,20 @@
pub mod initialize;
pub use initialize::*;
pub mod add_seller;
pub use add_seller::*;
pub mod add_tournament;
pub use add_tournament::*;
pub mod join_tournament;
pub use join_tournament::*;
pub mod purchase;
pub use purchase::*;
pub mod shared;
pub use shared::*;
pub mod set_data;
pub use set_data::*;

View File

@ -0,0 +1,96 @@
use anchor_lang::{prelude::*, solana_program::{native_token::LAMPORTS_PER_SOL, system_instruction}};
use anchor_spl::{
associated_token::AssociatedToken, token_interface::{Mint, TokenAccount, TokenInterface, close_account, transfer_checked, CloseAccount, TransferChecked}
};
use crate::{error::CustomErrors, Sales};
use super::transfer_tokens;
pub fn pay_seller(ctx:&Context<PurchaseTickets>, amount:u64)->Result<()>{
let from_account = &ctx.accounts.buyer;
let to_account = &ctx.accounts.seller;
let transfer_instruction = system_instruction::transfer(
from_account.key,
to_account.key,
amount);
anchor_lang::solana_program::program::invoke_signed(
&transfer_instruction,
&[
from_account.to_account_info(),
to_account.to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
&[],
)?;
Ok(())
}
pub fn handover_tickets(ctx:Context<PurchaseTickets>, amount:u64)->Result<()>{
let seeds = &[
b"sales",
ctx.accounts.seller.to_account_info().key.as_ref(),
&[ctx.accounts.sales.bump]
];
let signer_seeds = [&seeds[..]];
let accounts = TransferChecked{
from: ctx.accounts.vault.to_account_info(),
to: ctx.accounts.buyer_token_account.to_account_info(),
mint: ctx.accounts.mint.to_account_info(),
authority: ctx.accounts.sales.to_account_info()
};
let cpi_context = CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
accounts,
&signer_seeds
);
transfer_checked(cpi_context, amount*LAMPORTS_PER_SOL, ctx.accounts.mint.decimals)
}
#[derive(Accounts)]
pub struct PurchaseTickets<'info>{
#[account(mut)]
pub buyer:Signer<'info>,
#[account(mut)]
pub seller:SystemAccount<'info>,
#[account(mint::token_program = token_program)]
pub mint: InterfaceAccount<'info, Mint>,
#[account(
init_if_needed,
payer= buyer,
associated_token::mint = mint,
associated_token::authority = buyer,
associated_token::token_program = token_program
)]
pub buyer_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds= [b"sales", seller.key().as_ref()],
bump = sales.bump
)]
pub sales: Account<'info, Sales>,
#[account(
mut,
associated_token::mint= mint,
associated_token::authority = sales,
associated_token::token_program = token_program
)]
vault: InterfaceAccount<'info, TokenAccount>,
pub system_program: Program<'info, System>,
pub token_program: Interface<'info, TokenInterface>,
pub associated_token_program: Program<'info, AssociatedToken>
}

View File

@ -0,0 +1,28 @@
use anchor_lang::prelude::*;
use anchor_spl:: token::{Mint, Token, TokenAccount};
use crate::{error::CustomErrors, DataRegistry, Sales, DATA_REGISTRY_SEED};
pub fn handler(ctx: Context<SetData>, new_auth:Pubkey)->Result<()>{
require!(ctx.accounts.signer.key() == ctx.accounts.data_registry.authority, CustomErrors::Unauthorized);
let reg_acc = &mut ctx.accounts.data_registry;
reg_acc.authority = new_auth;
Ok(())
}
#[derive(Accounts)]
pub struct SetData <'info>{
pub signer: Signer<'info>,
#[account(
mut,
seeds = [DATA_REGISTRY_SEED],
bump
)]
pub data_registry: Account<'info, DataRegistry>,
pub system_program: Program<'info, System>,
}

View File

@ -0,0 +1,25 @@
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{TokenAccount, TokenInterface, TransferChecked, Mint, transfer_checked};
pub fn transfer_tokens<'info> (
from: &InterfaceAccount<'info,TokenAccount>,
to: &InterfaceAccount<'info,TokenAccount>,
amount: &u64,
mint: &InterfaceAccount<'info, Mint>,
authority: &Signer<'info>,
token_program: &Interface<'info, TokenInterface>
)-> Result<()>{
let transfer_accounts_options = TransferChecked{
from: from.to_account_info(),
mint: mint.to_account_info(),
to: to.to_account_info(),
authority: authority.to_account_info(),
};
let cpi_context = CpiContext::new(token_program.to_account_info(), transfer_accounts_options);
transfer_checked(cpi_context, *amount, mint.decimals)?;
Ok(())
}

View File

@ -0,0 +1,41 @@
pub mod constants;
pub mod error;
pub mod instructions;
pub mod state;
use anchor_lang::{prelude::*, solana_program::native_token::LAMPORTS_PER_SOL};
pub use constants::*;
pub use instructions::*;
pub use state::*;
declare_id!("88dRZraTvmpqMs8GqtgCc321Foo5bWtDAsXJ1kqoc6nC");
#[program]
pub mod tournaments {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
initialize::handler(ctx)
}
pub fn add_seller(ctx: Context<AddSeller>, tickets_count:u64) -> Result<()> {
// msg!("seller ata: {}", ctx.accounts.seller_token_account.key());
// add_seller::send_tickets_to_vault(&ctx, tickets_count)?;
add_seller::save_sales_account(ctx)
}
pub fn purchase_tickets(ctx:Context<PurchaseTickets>, amount:u64)->Result<()>{
let ticket_price: u64 =( LAMPORTS_PER_SOL / 100) * 3;
purchase::pay_seller(&ctx, ticket_price)?;
purchase::handover_tickets(ctx, amount)
}
pub fn add_tournament(ctx:Context<AddTournament>, id:u64, start_time:String)->Result<()>{
add_tournament::handler(ctx, id, start_time)
}
pub fn join_tournament(ctx:Context<JoinTorunament>, id:u64)-> Result<()>{
join_tournament::transfer_ticket_to_vault(&ctx, id);
join_tournament::add_to_participants_list(ctx, id)
}
}

View File

@ -0,0 +1,9 @@
use anchor_lang::prelude::*;
#[account]
#[derive(InitSpace)]
pub struct DataRegistry{
#[max_len(100)]
pub sales_pdas: Vec<Pubkey>,
pub authority: Pubkey
}

View File

@ -0,0 +1,8 @@
pub mod sales;
pub use sales::Sales;
pub mod data_registry;
pub use data_registry::DataRegistry;
pub mod tournament;
pub use tournament::Tournament;

View File

@ -0,0 +1,10 @@
use anchor_lang::prelude::*;
#[account]
#[derive(InitSpace)]
pub struct Sales{
pub seller: Pubkey,
pub vault: Pubkey,
pub mint : Pubkey,
pub bump:u8
}

View File

@ -0,0 +1,11 @@
use anchor_lang::prelude::*;
#[account]
#[derive(InitSpace)]
pub struct Tournament{
pub id:u64,
#[max_len(20)]
pub participants:Vec<Pubkey>,
#[max_len(30)]
pub start_time:String,
}

16
tests/tournaments.ts Normal file
View File

@ -0,0 +1,16 @@
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Tournaments } from "../target/types/tournaments";
describe("tournaments", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.Tournaments as Program<Tournaments>;
it("Is initialized!", async () => {
// Add your test here.
const tx = await program.methods.initialize().rpc();
console.log("Your transaction signature", tx);
});
});

10
tsconfig.json Normal file
View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"types": ["mocha", "chai"],
"typeRoots": ["./node_modules/@types"],
"lib": ["es2015"],
"module": "commonjs",
"target": "es6",
"esModuleInterop": true
}
}

1181
yarn.lock Normal file

File diff suppressed because it is too large Load Diff