repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo/TinyAdventureTwo.tsx
|
import { Tutorial } from "../../components/Tutorial";
const TinyAdventureTwo = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
["tests/index.test.ts", require("./files/anchor.test.ts.raw")],
]}
/>
);
export default TinyAdventureTwo;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo/index.ts
|
export { default } from "./TinyAdventureTwo";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo/files/client.ts.raw
|
// The PDA adress everyone will be able to control the character if the interact with your program
const [globalLevel1GameDataAccount, bump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("level1", "utf8")],
//[pg.wallet.publicKey.toBuffer()], <- You could also add the player wallet as a seed, then you would have one instance per player. Need to also change the seed in the rust part
pg.program.programId
);
// This is where the program will save the sol reward for the chests and from which the reward will be payed out again
const [chestVaultAccount, chestBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("chestVault", "utf8")],
pg.program.programId
);
// Initialize level set the player position back to 0 and the caller needs to pay to fill up the chest with sol
let txHash = await pg.program.methods
.initializeLevelOne()
.accounts({
chestVault: chestVaultAccount,
newGameDataAccount: globalLevel1GameDataAccount,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
let balance = await pg.connection.getBalance(pg.wallet.publicKey);
console.log(
`My balance before spawning a chest: ${balance / web3.LAMPORTS_PER_SOL} SOL`
);
txHash = await pg.program.methods
.resetLevelAndSpawnChest()
.accounts({
chestVault: chestVaultAccount,
gameDataAccount: globalLevel1GameDataAccount,
payer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
console.log("Level reset and chest spawned 💎");
console.log("o........💎");
// Here we move to the right three times and collect the chest at the end of the level
for (let i = 0; i < 3; i++) {
txHash = await pg.program.methods
.moveRight()
.accounts({
chestVault: chestVaultAccount,
gameDataAccount: globalLevel1GameDataAccount,
systemProgram: web3.SystemProgram.programId,
player: pg.wallet.publicKey,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
let balance = await pg.connection.getBalance(pg.wallet.publicKey);
console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);
let gameDateAccount = await pg.program.account.gameDataAccount.fetch(
globalLevel1GameDataAccount
);
console.log("Player position is:", gameDateAccount.playerPosition.toString());
switch (gameDateAccount.playerPosition) {
case 0:
console.log("A journey begins...");
console.log("o........💎");
break;
case 1:
console.log("....o....💎");
break;
case 2:
console.log("......o..💎");
break;
case 3:
console.log(".........\\o/💎");
console.log("...........\\o/");
break;
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo/files/lib.rs
|
use anchor_lang::prelude::*;
use anchor_lang::solana_program::native_token::LAMPORTS_PER_SOL;
use anchor_lang::system_program;
// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("");
#[program]
mod tiny_adventure_two {
use super::*;
// The amount of lamports that will be put into chests and given out as rewards.
const CHEST_REWARD: u64 = LAMPORTS_PER_SOL / 10; // 0.1 SOL
pub fn initialize_level_one(_ctx: Context<InitializeLevelOne>) -> Result<()> {
// Usually in your production code you would not print lots of text because it costs compute units.
msg!("A Journey Begins!");
msg!("o.......💎");
Ok(())
}
// this will set the player position of the given level back to 0 and fill up the chest with sol
pub fn reset_level_and_spawn_chest(ctx: Context<SpawnChest>) -> Result<()> {
ctx.accounts.game_data_account.player_position = 0;
let cpi_context = CpiContext::new(
ctx.accounts.system_program.to_account_info(),
system_program::Transfer {
from: ctx.accounts.payer.to_account_info().clone(),
to: ctx.accounts.chest_vault.to_account_info().clone(),
},
);
system_program::transfer(cpi_context, CHEST_REWARD)?;
msg!("Level Reset and Chest Spawned at position 3");
Ok(())
}
pub fn move_right(ctx: Context<MoveRight>) -> Result<()> {
let game_data_account = &mut ctx.accounts.game_data_account;
if game_data_account.player_position == 3 {
msg!("You have reached the end! Super!");
} else if game_data_account.player_position == 2 {
game_data_account.player_position = game_data_account.player_position + 1;
msg!(
"You made it! Here is your reward {0} lamports",
CHEST_REWARD
);
**ctx
.accounts
.chest_vault
.to_account_info()
.try_borrow_mut_lamports()? -= CHEST_REWARD;
**ctx
.accounts
.player
.to_account_info()
.try_borrow_mut_lamports()? += CHEST_REWARD;
} else {
game_data_account.player_position = game_data_account.player_position + 1;
print_player(game_data_account.player_position);
}
Ok(())
}
}
fn print_player(player_position: u8) {
if player_position == 0 {
msg!("A Journey Begins!");
msg!("o.........💎");
} else if player_position == 1 {
msg!("..o.......💎");
} else if player_position == 2 {
msg!("....o.....💎");
} else if player_position == 3 {
msg!("........\\o/💎");
msg!("..........\\o/");
msg!("You have reached the end! Super!");
}
}
#[derive(Accounts)]
pub struct InitializeLevelOne<'info> {
// We must specify the space in order to initialize an account.
// First 8 bytes are default account discriminator,
// next 1 byte come from NewAccount.data being type u8.
// (u8 = 8 bits unsigned integer = 1 byte)
// You can also use the signer as seed [signer.key().as_ref()],
#[account(
init_if_needed,
seeds = [b"level1"],
bump,
payer = signer,
space = 8 + 1
)]
pub new_game_data_account: Account<'info, GameDataAccount>,
// This is the PDA in which we will deposit the reward SOl and
// from where we send it back to the first player reaching the chest.
#[account(
init_if_needed,
seeds = [b"chestVault"],
bump,
payer = signer,
space = 8
)]
pub chest_vault: Account<'info, ChestVaultAccount>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SpawnChest<'info> {
#[account(mut)]
pub payer: Signer<'info>,
#[account(mut, seeds = [b"chestVault"], bump)]
pub chest_vault: Account<'info, ChestVaultAccount>,
#[account(mut)]
pub game_data_account: Account<'info, GameDataAccount>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct MoveRight<'info> {
#[account(mut, seeds = [b"chestVault"], bump)]
pub chest_vault: Account<'info, ChestVaultAccount>,
#[account(mut)]
pub game_data_account: Account<'info, GameDataAccount>,
#[account(mut)]
pub player: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct GameDataAccount {
player_position: u8,
}
#[account]
pub struct ChestVaultAccount {}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventureTwo/files/anchor.test.ts.raw
|
// No imports needed: web3, anchor, pg and more are globally available
// The PDA adress everyone will be able to control the character if the interact with your program
const [globalLevel1GameDataAccount, bump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("level1", "utf8")],
//[pg.wallet.publicKey.toBuffer()], <- You could also add the player wallet as a seed, then you would have one instance per player. Need to also change the seed in the rust part
pg.program.programId
);
// This is where the program will save the sol reward for the chests and from which the reward will be payed out again
const [chestVaultAccount, chestBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("chestVault", "utf8")],
pg.program.programId
);
const CHEST_REWARD = 100000000;
const TRANSACTION_COST = 5000;
describe("Test", () => {
it("Initlialize", async () => {
// Initialize level set the player position back to 0 and the caller needs to pay to fill up the chest with sol
let txHash = await pg.program.methods
.initializeLevelOne()
.accounts({
chestVault: chestVaultAccount,
newGameDataAccount: globalLevel1GameDataAccount,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
});
it("SpawningChestCostsSol", async () => {
let balanceBefore = await pg.connection.getBalance(pg.wallet.publicKey);
console.log(`My balance before spawning a chest: ${balanceBefore} SOL`);
let txHash = await pg.program.methods
.resetLevelAndSpawnChest()
.accounts({
chestVault: chestVaultAccount,
gameDataAccount: globalLevel1GameDataAccount,
payer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
await pg.connection.confirmTransaction(txHash);
let balanceAfter = await pg.connection.getBalance(pg.wallet.publicKey);
console.log(`My balance after spawning a chest: ${balanceAfter} SOL`);
assert(balanceBefore - CHEST_REWARD - TRANSACTION_COST == balanceAfter);
});
it("Move to the right and collect chest", async () => {
let gameDateAccount;
let balanceBefore = await pg.connection.getBalance(pg.wallet.publicKey);
// Here we move to the right three times and collect the chest at the end of the level
for (let i = 0; i < 3; i++) {
let txHash = await pg.program.methods
.moveRight()
.accounts({
chestVault: chestVaultAccount,
gameDataAccount: globalLevel1GameDataAccount,
systemProgram: web3.SystemProgram.programId,
player: pg.wallet.publicKey,
})
.signers([pg.wallet.keypair])
.rpc();
await pg.connection.confirmTransaction(txHash);
gameDateAccount = await pg.program.account.gameDataAccount.fetch(
globalLevel1GameDataAccount
);
}
let balanceAfter = await pg.connection.getBalance(pg.wallet.publicKey);
console.log(
`Balance before collecting chest: ${balanceBefore} Balance after collecting chest: ${balanceAfter}`
);
assert(balanceBefore + CHEST_REWARD - 3 * TRANSACTION_COST == balanceAfter);
assert(gameDateAccount.playerPosition == 3);
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana/HelloSolana.tsx
|
import { Tutorial } from "../../components/Tutorial";
import { PgExplorer, PgView } from "../../utils/pg";
const HelloSolana = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md"), title: "Program" },
{
content: require("./pages/2.md"),
title: "Build & Deploy",
onMount: () => {
// Switch sidebar state to Build & Deploy
PgView.setSidebarPage("Build & Deploy");
},
},
{
content: require("./pages/3.md"),
title: "Client",
onMount: async () => {
// Switch sidebar state to Explorer
PgView.setSidebarPage("Explorer");
// Create client.ts file
const clientPath = "client/client.ts";
const clientExists = await PgExplorer.fs.exists(clientPath);
if (!clientExists) {
await PgExplorer.newItem(
clientPath,
require("./files/client.ts.raw")
);
}
},
},
]}
// Initial files to have at the beginning of the tutorial
files={[["src/lib.rs", require("./files/lib.rs")]]}
/>
);
export default HelloSolana;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana/index.ts
|
export { default } from "./HelloSolana";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana/files/client.ts.raw
|
// Client code...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSolana/files/lib.rs
|
// Imports we need
use solana_program::{
account_info::AccountInfo,
entrypoint,
entrypoint::ProgramResult,
msg,
pubkey::Pubkey,
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template/index.ts
|
export { default } from "./Template";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template/Template.tsx
|
import { Tutorial } from "../../components/Tutorial";
const Template = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
["tests/index.test.ts", require("./files/index.test.ts.raw")],
]}
/>
);
export default Template;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template/files/client.ts.raw
|
// Client code...
console.log(42)
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template/files/lib.rs
|
// Implement program...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Template/files/index.test.ts.raw
|
// Test(mocha)
describe("Test", () => {
it("works", () => {
console.log("wow!");
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse/TodoAppSeahorse.tsx
|
import { Tutorial } from "../../components/Tutorial";
const TodoAppSeahorse = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
{ content: require("./pages/5.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/todo_app.py", require("./files/todo_app.py")],
["tests/index.test.ts", require("./files/index.test.ts.raw")],
]}
/>
);
export default TodoAppSeahorse;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse/index.ts
|
export { default } from "./TodoAppSeahorse";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse/files/todo_app.py
|
from seahorse.prelude import *
declare_id('')
# User profile
class UserProfile(Account):
...
# Todo list item
class TodoAccount(Account):
...
# initialize user profile
@instruction
def init_user_profile():
...
# add task to user's list
@instruction
def add_task():
...
# mark task as done
@instruction
def mark_task_as_done():
...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TodoAppSeahorse/files/index.test.ts.raw
|
describe("Todo App", async () => {
const task = "ship product";
const lastTodo = new anchor.BN(0);
const lastTodoBuffer = lastTodo.toArrayLike(Buffer, "le", 1);
const [userProfile] = web3.PublicKey.findProgramAddressSync(
[Buffer.from("user_profile"), pg.wallet.publicKey.toBuffer()],
pg.PROGRAM_ID
);
const [todoAccount] = web3.PublicKey.findProgramAddressSync(
[
Buffer.from("todo_account"),
pg.wallet.publicKey.toBuffer(),
lastTodoBuffer,
],
pg.PROGRAM_ID
);
// Init user profile
it("init", async () => {
const tx = await pg.program.methods
.initUserProfile()
.accounts({
owner: pg.wallet.publicKey,
userProfile: userProfile
})
.rpc();
await pg.connection.confirmTransaction(tx);
console.log(`New user profile created at ${userProfile.toString()}`);
console.log(`Use 'solana confirm -v ${tx}' to see the logs`);
});
// Add task
it("add todo task", async () => {
const tx = await pg.program.methods
.addTask(task)
.accounts({
owner: pg.wallet.publicKey,
userProfile: userProfile,
todoAccount: todoAccount
})
.rpc();
await pg.connection.confirmTransaction(tx);
console.log(`New todo task created at ${todoAccount.toString()}`);
console.log(`Use 'solana confirm -v ${tx}' to see the logs`);
});
// Mark task as done
it("mark todo task as done", async () => {
const tx = await pg.program.methods
.markTaskAsDone()
.accounts({
owner: pg.wallet.publicKey,
todoAccount: todoAccount,
})
.rpc();
await pg.connection.confirmTransaction(tx);
console.log(`Todo task ${todoAccount.toString()} marked as done.`);
console.log(`Use 'solana confirm -v ${tx}' to see the logs`);
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/FaucetSeahorse/FaucetSeahorse.tsx
|
import { Tutorial } from "../../components/Tutorial";
const FaucetSeahorse = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
{ content: require("./pages/5.md") },
{ content: require("./pages/6.md") },
{ content: require("./pages/7.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[["src/faucet.py", require("./files/faucet.py")]]}
/>
);
export default FaucetSeahorse;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/FaucetSeahorse/index.ts
|
export { default } from "./FaucetSeahorse";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/FaucetSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/FaucetSeahorse/files/faucet.py
|
from seahorse.prelude import *
from seahorse.pyth import *
declare_id('')
# Faucet
class BitcornFaucet(Account):
...
# initialize a new faucet
@instruction
def init_faucet():
...
# drips tokens to user
@instruction
def drip_bitcorn_tokens():
...
# return unused tokens back to the faucet
@instruction
def replenish_bitcorn_tokens():
...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack/Lumberjack.tsx
|
import { Tutorial } from "../../components/Tutorial";
const Lumberjack = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
]}
/>
);
export default Lumberjack;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack/index.ts
|
export { default } from "./Lumberjack";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack/files/client.ts.raw
|
// The PDA that holds the player account data
const [playerDataPda, bump] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("player", "utf8"), pg.wallet.publicKey.toBuffer()],
pg.program.programId
);
let gameDataAccount;
try {
gameDataAccount = await pg.program.account.playerData.fetch(playerDataPda);
} catch (e) {
let txHash = await pg.program.methods
.initPlayer()
.accounts({
player: playerDataPda,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.rpc();
console.log(`New player created.`);
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
gameDataAccount = await pg.program.account.playerData.fetch(playerDataPda);
}
console.log(
"You currently have " +
gameDataAccount.wood +
" wood and " +
gameDataAccount.energy +
" energy in the on chain account."
);
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/Lumberjack/files/lib.rs
|
use anchor_lang::prelude::*;
declare_id!("4ayoaXt8odfcNneUuZPeiYQfSCDH4XyG8iEkaPK2pUHx");
const MAX_ENERGY: u64 = 5;
const TIME_TO_REFILL_ENERGY: i64 = 30;
#[program]
pub mod lumberjack {
use super::*;
pub fn init_player(ctx: Context<InitPlayer>) -> Result<()> {
ctx.accounts.player.energy = MAX_ENERGY;
ctx.accounts.player.last_login = Clock::get()?.unix_timestamp;
Ok(())
}
}
#[derive(Accounts)]
pub struct InitPlayer<'info> {
#[account(
init,
payer = signer,
space = 1000,
seeds = [b"player", signer.key().as_ref()],
bump,
)]
pub player: Account<'info, PlayerData>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct PlayerData {
pub name: String,
pub level: u8,
pub xp: u64,
pub wood: u64,
pub energy: u64,
pub last_login: i64,
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker/ExpenseTracker.tsx
|
import { Tutorial } from "../../components/Tutorial";
const ExpenseTracker = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
{ content: require("./pages/5.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["tests/index.test.ts", require("./files/index.test.ts.raw")],
]}
/>
);
export default ExpenseTracker;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker/index.ts
|
export { default } from "./ExpenseTracker";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker/files/lib.rs
|
use anchor_lang::prelude::*;
// Your program Id will be added here when you enter "build" command
declare_id!("");
#[program]
pub mod etracker {
use super::*;
pub fn initialize_expense(
ctx: Context<InitializeExpense>,
id: u64,
merchant_name: String,
amount: u64,
) -> Result<()> {
let expense_account = &mut ctx.accounts.expense_account;
expense_account.id = id;
expense_account.merchant_name = merchant_name;
expense_account.amount = amount;
expense_account.owner = *ctx.accounts.authority.key;
Ok(())
}
pub fn modify_expense(
ctx: Context<ModifyExpense>,
_id: u64,
merchant_name: String,
amount: u64,
) -> Result<()> {
let expense_account = &mut ctx.accounts.expense_account;
expense_account.merchant_name = merchant_name;
expense_account.amount = amount;
Ok(())
}
pub fn delete_expense(_ctx: Context<DeleteExpense>, _id: u64) -> Result<()> {
Ok(())
}
}
#[derive(Accounts)]
#[instruction(id : u64)]
pub struct InitializeExpense<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(
init,
payer = authority,
space = 8 + 8 + 32+ (4 + 12)+ 8 + 1,
seeds = [b"expense", authority.key().as_ref(), id.to_le_bytes().as_ref()],
bump
)]
pub expense_account: Account<'info, ExpenseAccount>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(id : u64)]
pub struct ModifyExpense<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"expense", authority.key().as_ref(), id.to_le_bytes().as_ref()],
bump
)]
pub expense_account: Account<'info, ExpenseAccount>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(id : u64)]
pub struct DeleteExpense<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(
mut,
close = authority,
seeds = [b"expense", authority.key().as_ref(), id.to_le_bytes().as_ref()],
bump
)]
pub expense_account: Account<'info, ExpenseAccount>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(Default)]
pub struct ExpenseAccount {
pub id: u64,
pub owner: Pubkey,
pub merchant_name: String,
pub amount: u64,
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ExpenseTracker/files/index.test.ts.raw
|
describe("Expense Tracker", async () => {
let merchantName = "test";
let amount = 100;
let id = 1;
let merchantName2 = "test 2";
let amount2 = 200;
let [expense_account] = anchor.web3.PublicKey.findProgramAddressSync(
[
Buffer.from("expense"),
pg.wallet.publicKey.toBuffer(),
new BN(id).toArrayLike(Buffer, "le", 8),
],
pg.program.programId
);
it("Initialize Expense", async () => {
await pg.program.methods
.initializeExpense(new anchor.BN(id), merchantName, new anchor.BN(amount))
.accounts({
expenseAccount: expense_account,
authority: pg.wallet.publicKey,
})
.rpc();
});
it("Modify Expense", async () => {
await pg.program.methods
.modifyExpense(new anchor.BN(id), merchantName2, new anchor.BN(amount2))
.accounts({
expenseAccount: expense_account,
authority: pg.wallet.publicKey,
})
.rpc();
});
it("Delete Expense", async () => {
await pg.program.methods
.deleteExpense(new anchor.BN(id))
.accounts({
expenseAccount: expense_account,
authority: pg.wallet.publicKey,
})
.rpc();
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure/TinyAdventure.tsx
|
import { Tutorial } from "../../components/Tutorial";
const TinyAdventure = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
["tests/index.test.ts", require("./files/anchor.test.ts.raw")],
]}
/>
);
export default TinyAdventure;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure/index.ts
|
export { default } from "./TinyAdventure";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure/files/client.ts.raw
|
// Client
// The PDA adress everyone will be able to control the character if the interact with your program
const [globalLevel1GameDataAccount] =
anchor.web3.PublicKey.findProgramAddressSync(
[Buffer.from("level1", "utf8")],
//[pg.wallet.publicKey.toBuffer()], <- You could also add the player wallet as a seed, then you would have one instance per player. Need to also change the seed in the rust part
pg.program.programId
);
let txHash;
let gameDateAccount;
try {
gameDateAccount = await pg.program.account.gameDataAccount.fetch(
globalLevel1GameDataAccount
);
} catch {
// Check if the account is already initialized, other wise initilalize it
txHash = await pg.program.methods
.initialize()
.accounts({
newGameDataAccount: globalLevel1GameDataAccount,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
await logTransaction(txHash);
console.log("A journey begins...");
console.log("o........");
}
// Here you can play around now, move left and right
txHash = await pg.program.methods
//.moveLeft()
.moveRight()
.accounts({
gameDataAccount: globalLevel1GameDataAccount,
})
.signers([pg.wallet.keypair])
.rpc();
await logTransaction(txHash);
gameDateAccount = await pg.program.account.gameDataAccount.fetch(
globalLevel1GameDataAccount
);
console.log("Player position is:", gameDateAccount.playerPosition.toString());
switch (gameDateAccount.playerPosition) {
case 0:
console.log("A journey begins...");
console.log("o........");
break;
case 1:
console.log("....o....");
break;
case 2:
console.log("......o..");
break;
case 3:
console.log(".........\\o/");
break;
}
async function logTransaction(txHash) {
const { blockhash, lastValidBlockHeight } =
await pg.connection.getLatestBlockhash();
await pg.connection.confirmTransaction({
blockhash,
lastValidBlockHeight,
signature: txHash,
});
console.log(
`Solana Explorer: https://explorer.solana.com/tx/${txHash}?cluster=devnet`
);
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure/files/lib.rs
|
use anchor_lang::prelude::*;
// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("");
#[program]
mod tiny_adventure {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
ctx.accounts.new_game_data_account.player_position = 0;
msg!("A Journey Begins!");
msg!("o.......");
Ok(())
}
pub fn move_left(ctx: Context<MoveLeft>) -> Result<()> {
let game_data_account = &mut ctx.accounts.game_data_account;
if game_data_account.player_position == 0 {
msg!("You are back at the start.");
} else {
game_data_account.player_position -= 1;
print_player(game_data_account.player_position);
}
Ok(())
}
pub fn move_right(ctx: Context<MoveRight>) -> Result<()> {
let game_data_account = &mut ctx.accounts.game_data_account;
if game_data_account.player_position == 3 {
msg!("You have reached the end! Super!");
} else {
game_data_account.player_position = game_data_account.player_position + 1;
print_player(game_data_account.player_position);
}
Ok(())
}
}
fn print_player(player_position: u8) {
if player_position == 0 {
msg!("A Journey Begins!");
msg!("o.......");
} else if player_position == 1 {
msg!("..o.....");
} else if player_position == 2 {
msg!("....o...");
} else if player_position == 3 {
msg!("........\\o/");
msg!("You have reached the end! Super!");
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
// We must specify the space in order to initialize an account.
// First 8 bytes are default account discriminator,
// next 1 byte come from NewAccount.data being type u8.
// (u8 = 8 bits unsigned integer = 1 byte)
// You can also use the signer as seed [signer.key().as_ref()],
#[account(
init_if_needed,
seeds = [b"level1"],
bump,
payer = signer,
space = 8 + 1
)]
pub new_game_data_account: Account<'info, GameDataAccount>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct MoveLeft<'info> {
#[account(mut)]
pub game_data_account: Account<'info, GameDataAccount>,
}
#[derive(Accounts)]
pub struct MoveRight<'info> {
#[account(mut)]
pub game_data_account: Account<'info, GameDataAccount>,
}
#[account]
pub struct GameDataAccount {
player_position: u8,
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TinyAdventure/files/anchor.test.ts.raw
|
// No imports needed: web3, anchor, pg and more are globally available
describe("Test", () => {
it("Initlialize", async () => {
const [newGameDataAccount] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("level1", "utf8")],
pg.program.programId
);
// If account is null we initialize
try {
await pg.program.account.gameDataAccount.fetch(newGameDataAccount);
} catch {
const txHash = await pg.program.methods
.initialize()
.accounts({
newGameDataAccount: newGameDataAccount,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
}
});
it("RunningRight", async () => {
const [newGameDataAccount] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("level1", "utf8")],
pg.program.programId
);
for (let i = 0; i < 3; i++) {
const txHash = await pg.program.methods
.moveRight()
.accounts({
gameDataAccount: newGameDataAccount,
})
.signers([pg.wallet.keypair])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
}
// Fetch the created account
const gameDateAccount = await pg.program.account.gameDataAccount.fetch(
newGameDataAccount
);
console.log(
"Player position is:",
gameDateAccount.playerPosition.toString()
);
// Check whether the data on-chain is equal to local 'data'
assert(3 == gameDateAccount.playerPosition);
});
it("RunningLeft", async () => {
const [newGameDataAccount] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from("level1", "utf8")],
pg.program.programId
);
for (let i = 0; i < 3; i++) {
const txHash = await pg.program.methods
.moveLeft()
.accounts({
gameDataAccount: newGameDataAccount,
})
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
await pg.connection.confirmTransaction(txHash);
}
// Fetch the created account
const gameData = await pg.program.account.gameDataAccount.fetch(
newGameDataAccount
);
console.log("Player position is:", gameData.playerPosition.toString());
// Check whether the data on-chain is equal to local 'data'
assert(0 == gameData.playerPosition);
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse/TictactoeSeahorse.tsx
|
import { Tutorial } from "../../components/Tutorial";
const TicTacToeSeahorse = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
{ content: require("./pages/5.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/tictactoe.py", require("./files/tictactoe.py")],
["tests/index.test.ts", require("./files/index.test.ts.raw")],
]}
/>
);
export default TicTacToeSeahorse;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse/index.ts
|
export { default } from "./TictactoeSeahorse";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse/files/tictactoe.py
|
from seahorse.prelude import *
declare_id('')
# Game account
class Game(Account):
...
# Winning states
class GameState(Enum):
...
# initialize game
@instruction
def init_game():
...
# check if someone has won
def win_check()-> GameState:
...
# play a turn
@instruction
def play_game():
...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/TictactoeSeahorse/files/index.test.ts.raw
|
describe("Tictactoe game", async () => {
const player1 = pg.wallet.publicKey;
const player2 = pg.wallet.publicKey;
function printgame(grid) {
console.log(`${grid[0]} ${grid[1]} ${grid[2]}`);
console.log(`${grid[3]} ${grid[4]} ${grid[5]}`);
console.log(`${grid[6]} ${grid[7]} ${grid[8]}`);
}
let [game] = anchor.web3.PublicKey.findProgramAddressSync(
[Buffer.from("ttt"), pg.wallet.publicKey.toBytes()],
pg.program.programId
);
it("Create Game!", async () => {
let tx = await pg.program.methods
.initGame(player1, player2)
.accounts({
owner: pg.wallet.publicKey,
game: game
})
.rpc();
console.log("Create game tx signature", tx);
console.log("Game address", game.toString());
});
it("Turn 1", async () => {
let person = 1;
let position = 5;
let tx = await pg.program.methods
.playGame(person, position)
.accounts({
player: player1,
gameData: game,
})
.rpc();
await pg.connection.confirmTransaction(tx);
console.log("Turn 1 signature", tx);
const gameAccount = await pg.program.account.game.fetch(game);
printgame(gameAccount.grid);
});
it("Turn 2", async () => {
let person = 2;
let position = 9;
let tx = await pg.program.methods
.playGame(person, position)
.accounts({
player: player2,
gameData: game,
})
.rpc();
await pg.connection.confirmTransaction(tx);
console.log("Turn 2 signature", tx);
const gameAccount = await pg.program.account.game.fetch(game);
printgame(gameAccount.grid);
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse/HelloSeahorse.tsx
|
import { Tutorial } from "../../components/Tutorial";
import { PgExplorer, PgView } from "../../utils/pg";
const HelloSeahorse = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md"), title: "Program" },
{
content: require("./pages/2.md"),
title: "Build & Deploy",
onMount: () => {
// Switch sidebar state to Build & Deploy
PgView.setSidebarPage("Build & Deploy");
},
},
{
content: require("./pages/3.md"),
title: "Client",
onMount: async () => {
// Switch sidebar state to Explorer
PgView.setSidebarPage("Explorer");
// Create client.ts file
const clientPath = "client/client.ts";
const clientExists = await PgExplorer.fs.exists(clientPath);
if (!clientExists) {
await PgExplorer.newItem(
clientPath,
require("./files/client.ts.raw")
);
}
},
},
{
content: require("./pages/4.md"),
title: "Test UI",
onMount: () => {
// Switch sidebar state to Test
PgView.setSidebarPage("Test");
},
},
]}
// Initial files to have at the beginning of the tutorial
files={[["src/hello.py", require("./files/hello.py")]]}
/>
);
export default HelloSeahorse;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse/index.ts
|
export { default } from "./HelloSeahorse";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse/files/hello.py
|
# Seahorse program
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloSeahorse/files/client.ts.raw
|
// Client code...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle/BossBattle.tsx
|
import { Tutorial } from "../../components/Tutorial";
const BossBattle = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md") },
{ content: require("./pages/2.md") },
{ content: require("./pages/3.md") },
{ content: require("./pages/4.md") },
{ content: require("./pages/5.md") },
]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
]}
/>
);
export default BossBattle;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle/index.ts
|
export { default } from "./BossBattle";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle/files/client.ts.raw
|
const [enemyBossPDA] = anchor.web3.PublicKey.findProgramAddressSync(
[Buffer.from("boss")],
pg.program.programId
);
async function confirmAndLogTransaction(txHash) {
const { blockhash, lastValidBlockHeight } =
await pg.connection.getLatestBlockhash();
await pg.connection.confirmTransaction(
{
blockhash,
lastValidBlockHeight,
signature: txHash,
},
"confirmed"
);
console.log(
`Solana Explorer: https://explorer.solana.com/tx/${txHash}?cluster=devnet`
);
}
async function respawnEnemyBoss() {
console.log("Respawning Enemy Boss");
const tx = await pg.program.methods
.respawn()
.accounts({
enemyBoss: enemyBossPDA,
player: pg.wallet.publicKey,
})
.rpc();
await confirmAndLogTransaction(tx);
const enemyBossData = await pg.program.account.enemyBoss.fetch(enemyBossPDA);
console.log("Enemy Health: ", enemyBossData.health.toNumber() + "\n");
}
async function attackLoop() {
let enemyBossData;
try {
do {
console.log("Attacking Enemy Boss");
const tx = await pg.program.methods
.attack()
.accounts({
enemyBoss: enemyBossPDA,
player: pg.wallet.publicKey,
})
.rpc();
await confirmAndLogTransaction(tx);
enemyBossData = await pg.program.account.enemyBoss.fetch(enemyBossPDA);
console.log("Enemy Health: ", enemyBossData.health.toNumber() + "\n");
} while (enemyBossData.health.toNumber() >= 0);
} catch (e) {
console.log(e.error.errorMessage);
}
}
await respawnEnemyBoss();
await attackLoop();
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BossBattle/files/lib.rs
|
use anchor_lang::prelude::*;
declare_id!("11111111111111111111111111111111");
const MAX_HEALTH: u64 = 1000;
const MAX_DAMAGE: u64 = 500;
#[program]
pub mod boss_battle {
use super::*;
pub fn respawn(ctx: Context<Respawn>) -> Result<()> {
// Reset enemy boss to max health
ctx.accounts.enemy_boss.health = MAX_HEALTH;
Ok(())
}
pub fn attack(ctx: Context<Attack>) -> Result<()> {
// Check if enemy boss has enough health
if ctx.accounts.enemy_boss.health == 0 {
return err!(ErrorCode::NotEnoughHealth);
}
// Get current slot
let slot = Clock::get()?.slot;
// Generate pseudo-random number using XORShift with the current slot as seed
let xorshift_output = xorshift64(slot);
// Calculate random damage
let random_damage = xorshift_output % (MAX_DAMAGE);
msg!("Random Damage: {}", random_damage);
// Subtract health from enemy boss, min health is 0
ctx.accounts.enemy_boss.health =
ctx.accounts.enemy_boss.health.saturating_sub(random_damage);
msg!("Enemy Boss Health: {}", ctx.accounts.enemy_boss.health);
Ok(())
}
}
#[derive(Accounts)]
pub struct Respawn<'info> {
#[account(mut)]
pub player: Signer<'info>,
#[account(
init_if_needed,
payer = player,
space = 8 + 8,
seeds = [b"boss"],
bump,
)]
pub enemy_boss: Account<'info, EnemyBoss>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Attack<'info> {
#[account(mut)]
pub player: Signer<'info>,
#[account(
mut,
seeds = [b"boss"],
bump,
)]
pub enemy_boss: Account<'info, EnemyBoss>,
}
#[account]
pub struct EnemyBoss {
pub health: u64,
}
#[error_code]
pub enum ErrorCode {
#[msg("Boss at 0 health; respawn to attack.")]
NotEnoughHealth,
}
pub fn xorshift64(seed: u64) -> u64 {
let mut x = seed;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor/HelloAnchor.tsx
|
import { Tutorial } from "../../components/Tutorial";
import { PgExplorer, PgView } from "../../utils/pg";
const HelloAnchor = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[
{ content: require("./pages/1.md"), title: "Program" },
{
content: require("./pages/2.md"),
title: "Build & Deploy",
onMount: () => {
// Switch sidebar state to Build & Deploy
PgView.setSidebarPage("Build & Deploy");
},
},
{
content: require("./pages/3.md"),
title: "Client",
onMount: async () => {
// Switch sidebar state to Explorer
PgView.setSidebarPage("Explorer");
// Create client.ts file
const clientPath = "client/client.ts";
const clientExists = await PgExplorer.fs.exists(clientPath);
if (!clientExists) {
await PgExplorer.newItem(
clientPath,
require("./files/client.ts.raw")
);
}
},
},
{
content: require("./pages/4.md"),
title: "Test UI",
onMount: () => {
// Switch sidebar state to Test
PgView.setSidebarPage("Test");
},
},
]}
// Initial files to have at the beginning of the tutorial
files={[["src/lib.rs", require("./files/lib.rs")]]}
/>
);
export default HelloAnchor;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor/index.ts
|
export { default } from "./HelloAnchor";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor/files/client.ts.raw
|
// Client code...
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/HelloAnchor/files/lib.rs
|
// Import anchor
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy/ZeroCopy.tsx
|
import { Tutorial } from "../../components/Tutorial";
const ZeroCopy = () => (
<Tutorial
// About section that will be shown under the description of the tutorial page
about={require("./about.md")}
// Actual tutorial pages to show next to the editor
pages={[{ content: require("./pages/1.md") }]}
// Initial files to have at the beginning of the tutorial
files={[
["src/lib.rs", require("./files/lib.rs")],
["client/client.ts", require("./files/client.ts.raw")],
["tests/index.test.ts", require("./files/anchor.test.ts.raw")],
]}
/>
);
export default ZeroCopy;
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy/index.ts
|
export { default } from "./ZeroCopy";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy/files/client.ts.raw
|
// Please run the tests for this example.
// Just type "test" in the console on the bottom
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy/files/lib.rs
|
use anchor_lang::prelude::*;
use anchor_lang::solana_program::system_program;
use std::str;
declare_id!("2MpQoKyLGXP26cGASC8pPLY3MaCGitM9XKUxziUmNN4i");
#[program]
pub mod zero_copy {
use super::*;
pub fn initialize_no_zero_copy(_ctx: Context<InitializeNoZeroCopy>) -> Result<()> {
Ok(())
}
pub fn initialize_zero_copy(_ctx: Context<InitializeZeroCopy>) -> Result<()> {
Ok(())
}
pub fn initialize_hit_stack_size(_ctx: Context<InitializeHitStackSize>) -> Result<()> {
Ok(())
}
pub fn set_data(ctx: Context<SetData>, string_to_set: String, index: u64) -> Result<()> {
let text_to_add_to_the_account = str::from_utf8(string_to_set.as_bytes()).unwrap();
msg!(text_to_add_to_the_account);
// Since the account is bigger that the heap space as soon as we access the whole account we will get a out of memory error
// let string = &ctx.accounts.data_holder.load_mut()?.long_string;
// let complete_string = str::from_utf8(string).unwrap();
// msg!("DataLength: {}", string.len());
// msg!("CompleteString: {}", complete_string);
// So the solution is use copy_from_slice and mem copy when we want to access data in the big account
ctx.accounts.data_holder.load_mut()?.long_string
[((index) as usize)..((index + 912) as usize)]
.copy_from_slice(string_to_set.as_bytes());
Ok(())
}
pub fn increase_account_data_zero_copy(
_ctx: Context<IncreaseZeroCopy>,
_len: u16,
) -> Result<()> {
Ok(())
}
pub fn increase_account_data(_ctx: Context<IncreaseAccoutSize>, _len: u16) -> Result<()> {
Ok(())
}
pub fn set_data_no_zero_copy(
ctx: Context<SetDataNoZeroCopy>,
string_to_set: String,
) -> Result<()> {
// This will work up to the limit of heap space
ctx.accounts
.data_holder
.greet_string
.push_str(&string_to_set);
//msg!(&ctx.accounts.data_holder.greet_string.len().to_string());
Ok(())
}
}
#[derive(Accounts)]
pub struct InitializeZeroCopy<'info> {
#[account(init,
seeds = [b"data_holder_zero_copy_v0",
signer.key().as_ref()],
bump,
payer=signer,
space= 10 * 1024 as usize)]
pub data_holder: AccountLoader<'info, DataHolder>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct InitializeNoZeroCopy<'info> {
#[account(init,
seeds = [b"data_holder_no_zero_copy_v0",
signer.key().as_ref()],
bump,
payer=signer,
space= 10 * 1024 as usize)]
pub data_holder_no_zero_copy: Account<'info, DataHolderNoZeroCopy>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SetData<'info> {
#[account(mut)]
pub data_holder: AccountLoader<'info, DataHolder>,
#[account(mut)]
pub signer: Signer<'info>,
}
//#[account(zero_copy)] // For Anchor 0.26.0 and before.
// See Change log: https://github.com/coral-xyz/anchor/blob/master/CHANGELOG.md
#[account(zero_copy(unsafe))]
#[repr(C)]
pub struct DataHolder {
// 40952 = 40960 - 8 (account desciminator)
pub long_string: [u8; 40952],
}
#[derive(Accounts)]
#[instruction(len: u16)]
pub struct IncreaseZeroCopy<'info> {
#[account(mut,
realloc = len as usize,
realloc::zero = true,
realloc::payer=signer)]
pub data_holder: AccountLoader<'info, DataHolder>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SetDataNoZeroCopy<'info> {
#[account(mut)]
pub data_holder: Account<'info, DataHolderNoZeroCopy>,
#[account(mut)]
pub signer: Signer<'info>,
}
#[derive(Accounts)]
#[instruction(len: u16)]
pub struct IncreaseAccoutSize<'info> {
#[account(mut,
realloc = len as usize,
realloc::zero = true,
realloc::payer=signer)]
pub data_holder: Account<'info, DataHolderNoZeroCopy>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct DataHolderNoZeroCopy {
pub greet_string: String,
}
#[derive(Accounts)]
pub struct InitializeHitStackSize<'info> {
#[account(init,
seeds = [b"hit_stack_size", signer.key().as_ref()],
bump,
payer=signer,
space= 10 * 1024 as usize)]
//pub data_holder: Box<Account<'info, HitStackSize>>,
pub data_holder: Account<'info, HitStackSize>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
// 10 * (128 + 1) = 1290 bytes -> With the way anchor deserialized the account in the init function this will already hit the stack limit
// Error will be: Stack offset of 4400 exceeded max offset of 4096 by 304 bytes.
// If you box the account int the InitilizeHitStackSize account struct.
pub struct HitStackSize {
board: [Option<BigStruct>; 12],
}
#[derive(AnchorSerialize, AnchorDeserialize, Copy, Clone, PartialEq, Eq)]
// Size of this struct is 32 bytes * 4 = 128 bytes
pub struct BigStruct {
pub public_key_1: Pubkey,
pub public_key_2: Pubkey,
pub public_key_3: Pubkey,
pub public_key_4: Pubkey,
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy
|
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/ZeroCopy/files/anchor.test.ts.raw
|
describe("Test", () => {
it("stacksize", async () => {
const signer = anchor.web3.Keypair.generate();
console.log("Local signer is: ", signer.publicKey.toBase58());
let confirmOptions = {
skipPreflight: true,
};
let [pdaHitStackSize] = await anchor.web3.PublicKey.findProgramAddress(
[
anchor.utils.bytes.utf8.encode("hit_stack_size"),
signer.publicKey.toBuffer(),
],
pg.program.programId
);
console.log(new Date(), "requesting airdrop");
const airdropTx = await pg.connection.requestAirdrop(
signer.publicKey,
5 * anchor.web3.LAMPORTS_PER_SOL
);
await pg.connection.confirmTransaction(airdropTx);
try {
const tx = await pg.program.methods
.initializeHitStackSize()
.accounts({
signer: signer.publicKey,
dataHolder: pdaHitStackSize,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Hit stack size signature", tx);
} catch (e) {
console.log("Error of hitting stack size: ", e);
}
});
it("without_zero_copy", async () => {
const signer = anchor.web3.Keypair.generate();
console.log("Local signer is: ", signer.publicKey.toBase58());
let confirmOptions = {
skipPreflight: true,
};
let [pdaNoZeroCopy] = await anchor.web3.PublicKey.findProgramAddress(
[
anchor.utils.bytes.utf8.encode("data_holder_no_zero_copy_v0"),
signer.publicKey.toBuffer(),
],
pg.program.programId
);
console.log(new Date(), "requesting airdrop");
const airdropTx = await pg.connection.requestAirdrop(
signer.publicKey,
5 * anchor.web3.LAMPORTS_PER_SOL
);
await pg.connection.confirmTransaction(airdropTx);
let tx = await pg.program.methods
.initializeNoZeroCopy()
.accounts({
signer: signer.publicKey,
dataHolderNoZeroCopy: pdaNoZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Initialize transaction", tx);
const string_length = 920;
// Max transaction size data size is 1232 Byte minus 32 bytes per account pubkey and instruction disciminator
// signature 64
// Blockhash 32
// 1024 - 32 - 32 - 32 - 8 = 920
tx = await pg.program.methods
.increaseAccountData(20480)
.accounts({
signer: signer.publicKey,
dataHolder: pdaNoZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Realloc", tx);
// Although the account is big (20480Kb) as soon as we put more data we will get an out of memory error since PDA accounts
// are limited not by the usualy heap size of 32 Kb but 10Kb per PDA. This does not apply for zero copy accounts.
// for (let counter = 0; counter < 12; counter++) {
for (let counter = 0; counter < 14; counter++) {
try {
const tx = await pg.program.methods
.setDataNoZeroCopy("A".repeat(string_length))
.accounts({
signer: signer.publicKey,
dataHolder: pdaNoZeroCopy,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Add more string " + counter, tx);
} catch (e) {
console.log("error occurred: ", e);
}
}
pg.connection.getAccountInfo(pdaNoZeroCopy).then((accountInfo) => {
let counter = 0;
for (let bytes of accountInfo.data) {
if (bytes != 0) {
counter++;
}
}
console.log("Non zero bytes in buffer: " + counter);
});
});
it("Initialize 10kb accounts", async () => {
const signer = anchor.web3.Keypair.generate();
console.log("Local signer is: ", signer.publicKey.toBase58());
let confirmOptions = {
skipPreflight: true,
};
let [pdaZeroCopy] = await anchor.web3.PublicKey.findProgramAddress(
[
anchor.utils.bytes.utf8.encode("data_holder_zero_copy_v0"),
signer.publicKey.toBuffer(),
],
pg.program.programId
);
console.log(new Date(), "requesting airdrop");
const airdropTx = await pg.connection.requestAirdrop(
signer.publicKey,
5 * anchor.web3.LAMPORTS_PER_SOL
);
await pg.connection.confirmTransaction(airdropTx);
const tx = await pg.program.methods
.initializeZeroCopy()
.accounts({
signer: signer.publicKey,
dataHolder: pdaZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Initialize transaction", tx);
// Fill big account with data above heap size using copy_from_slice in the program
// We need to increase the space in 10 * 1024 byte steps otherwise we will get an error
// This will work up to 10Mb
let reallocTransaction = await pg.program.methods
.increaseAccountDataZeroCopy(20480)
.accounts({
signer: signer.publicKey,
dataHolder: pdaZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
reallocTransaction = await pg.program.methods
.increaseAccountDataZeroCopy(30720)
.accounts({
signer: signer.publicKey,
dataHolder: pdaZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
reallocTransaction = await pg.program.methods
.increaseAccountDataZeroCopy(40960)
.accounts({
signer: signer.publicKey,
dataHolder: pdaZeroCopy,
systemProgram: anchor.web3.SystemProgram.programId,
})
.signers([signer])
.rpc(confirmOptions);
pg.connection.getAccountInfo(pdaZeroCopy).then((accountInfo) => {
console.log("Account size: ", accountInfo.data.length);
});
// 1024 - 32 - 32 - 32 - 8 - 8 = 912
const string_length = 912;
for (let counter = 0; counter < 43; counter++) {
try {
const tx = await pg.program.methods
.setData(
"A".repeat(string_length),
new anchor.BN.BN(string_length * counter)
)
.accounts({
signer: signer.publicKey,
dataHolder: pdaZeroCopy,
})
.signers([signer])
.rpc(confirmOptions);
console.log("Add more string " + counter, tx);
pg.connection.getAccountInfo(pdaZeroCopy).then((accountInfo) => {
let counter = 0;
for (let bytes of accountInfo.data) {
if (bytes != 0) {
counter++;
}
}
console.log("Non zero bytes in buffer: " + counter);
});
} catch (e) {
console.log("error occurred: ", e);
}
}
});
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/validation.ts
|
// Common command checks
import { PgCommand, PgTerminal, PgWallet } from "../utils/pg";
/** Check whether Playground Wallet is connected. */
export const isPgConnected = () => {
if (!PgWallet.current?.isPg) {
throw new Error(
`${PgTerminal.bold(
"Playground Wallet"
)} must be connected to run this command. Run '${PgTerminal.bold(
PgCommand.connect.name
)}' to connect.`
);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/commands.ts
|
// Exported commands from this file will automatically be usable in the terminal
export * from "./anchor";
export * from "./build";
export * from "./clear";
export * from "./connect";
export * from "./deploy";
export * from "./help";
export * from "./prettier";
export * from "./run-and-test";
export * from "./rustfmt";
export * from "./solana";
export * from "./spl-token";
export * from "./sugar";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/index.ts
|
export * as COMMANDS from "./commands";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/create.ts
|
import type {
Arg,
CommandImpl,
CommandInferredImpl,
Option,
} from "../utils/pg";
/**
* Create a command.
*
* NOTE: This is only a type helper function.
*
* @param cmd command to create
* @returns the command with its inferred type
*/
export const createCmd = <
N extends string,
A extends Arg[],
O extends Option[],
S,
R
>(
cmd: CommandImpl<N, A, O, S, R>
) => {
addHelpOption(cmd);
return cmd as CommandInferredImpl<N, A, O, S, R>;
};
/**
* Create subcommands.
*
* NOTE: This is only a type helper function.
*
* @param cmd command to create
* @returns the command with its inferred type
*/
export const createSubcmds = <
N extends string,
A extends Arg[],
O extends Option[],
S,
R
>(
...subcmds: CommandImpl<N, A, O, S, R>[]
) => {
for (const subcmd of subcmds) addHelpOption(subcmd);
return subcmds as CommandInferredImpl<N, A, O, S, R>[];
};
/**
* Add built-in help option to the commands options list.
*
* @param cmd command or subcommand
*/
const addHelpOption = (cmd: { options?: Option[] }) => {
cmd.options ??= [];
cmd.options.push({ name: "help", short: "h" });
};
/**
* Create command arguments.
*
* @param arg arg to create
* @returns the args with their inferred types
*/
export const createArgs = <
N extends string,
V extends string,
A extends Arg<N, V>[]
>(
args: [...A]
) => {
let isOptional;
for (const arg of args) {
if (isOptional && !arg.optional) {
throw new Error("Optional arguments must come after required arguments");
}
if (arg.multiple && arg.name !== args.at(-1)!.name) {
throw new Error("A multiple value argument must be the last argument");
}
if (arg.optional) isOptional = true;
}
return args;
};
/**
* Create command options.
*
* @param opts option to create
* @returns the options with their inferred types
*/
export const createOptions = <
N extends string,
V extends string,
O extends Option<N, V>[]
>(
opts: [...O]
) => {
const createShort = (opt: O[number]) => {
const short = typeof opt.short === "string" ? opt.short : opt.name[0];
if (short.length !== 1) {
throw new Error(`Short option must be exactly 1 letter: \`${opt.name}\``);
}
return short;
};
// Normalize shorts and verify uniqueness
for (const opt of opts) {
if (!opt.short) continue;
const short = createShort(opt);
const exists = opts
.filter((o) => o.name !== opt.name)
.some((o) => createShort(o) === short);
if (exists) throw new Error(`Duplicate short option: \`${opt.name}\``);
opt.short = short;
}
// If `values` field is specified, it implies `takeValue`
for (const opt of opts) opt.takeValue ??= !!opt.values;
return opts;
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/sugar.ts
|
import { PgPackage } from "../../utils/pg";
import { createCmd } from "../create";
import { isPgConnected } from "../validation";
export const sugar = createCmd({
name: "sugar",
description:
"Command line tool for creating and managing Metaplex Candy Machines",
run: async (input) => {
const { runSugar } = await PgPackage.import("sugar-cli", {
log: true,
});
await runSugar(input.raw);
},
preCheck: isPgConnected,
});
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/processor.ts
|
// @ts-nocheck
import { Emoji, NETWORKS } from "../../constants";
import { PgCommon, PgSettings, PgTerminal } from "../../utils/pg";
import {
processBundlr,
processCollectionSet,
processCreateConfig,
processDeploy,
processGuardAdd,
processGuardRemove,
processGuardShow,
processGuardUpdate,
processGuardWithdraw,
processHash,
processLaunch,
processMint,
processReveal,
processShow,
processSign,
processUpdate,
processUpload,
processValidate,
processVerify,
processWithdraw,
} from "./commands";
/**
* Metaplex Sugar CLI commands
*/
export class PgSugar {
static PATHS = {
METAPLEX_DIRNAME: "metaplex",
get CANDY_MACHINE_DIR_PATH() {
return PgCommon.joinPaths(this.METAPLEX_DIRNAME, "candy-machine");
},
get CANDY_MACHINE_CONFIG_FILEPATH() {
return PgCommon.joinPaths(this.CANDY_MACHINE_DIR_PATH, "config.json");
},
get CANDY_MACHINE_CACHE_FILEPATH() {
return PgCommon.joinPaths(this.CANDY_MACHINE_DIR_PATH, "cache.json");
},
get CANDY_MACHINE_ASSETS_DIR_PATH() {
return PgCommon.joinPaths(this.CANDY_MACHINE_DIR_PATH, "assets");
},
};
static async bundlr(...args) {
await this._run(() => processBundlr(...args));
}
static async collectionSet(...args) {
await this._run(() => processCollectionSet(...args));
}
static async createConfig(...args) {
await this._run(() => processCreateConfig(...args));
}
static async deploy(...args) {
await this._run(() => processDeploy(...args));
}
static async guardAdd(...args) {
await this._run(() => processGuardAdd(...args));
}
static async guardRemove(...args) {
await this._run(() => processGuardRemove(...args));
}
static async guardShow(...args) {
await this._run(() => processGuardShow(...args));
}
static async guardUpdate(...args) {
await this._run(() => processGuardUpdate(...args));
}
static async guardWithdraw(...args) {
await this._run(() => processGuardWithdraw(...args));
}
static async hash(...args) {
await this._run(() => processHash(...args));
}
static async launch(...args) {
await this._run(() => processLaunch(...args));
}
static async mint(...args) {
await this._run(() => processMint(...args));
}
static async reveal(...args) {
await this._run(() => processReveal(...args));
}
static async show(...args) {
await this._run(() => processShow(...args));
}
static async sign(...args) {
await this._run(() => processSign(...args));
}
static async update(...args) {
await this._run(() => processUpdate(...args));
}
static async upload(...args) {
await this._run(() => processUpload(...args));
}
static async validate(...args) {
await this._run(() => processValidate(...args));
}
static async verify(...args) {
await this._run(() => processVerify(...args));
}
static async withdraw(...args) {
await this._run(() => processWithdraw(...args));
}
/**
* WASM panics if any of the `PgSugar` processes throw an error.
* We are catching the errors and log them similar to Sugar's Rust implementation.
*
* @param cb callback function to run
*/
private static async _run(cb: () => Promise<void>) {
try {
await cb();
PgTerminal.log(
`\n${Emoji.CHECKMARK} ${PgTerminal.success("Command successful.")}\n`
);
} catch (e: any) {
PgTerminal.log(
`\n${Emoji.ERROR} ${PgTerminal.error(
"Error running command (re-run needed):"
)} ${e.message}`,
{ noColor: true }
);
// Show how to set a custom rpc endpoint if the current endpoint is a known endpoint
if (NETWORKS.some((n) => n.endpoint === PgSettings.connection.endpoint)) {
PgTerminal.log(
`${
e.message?.endsWith("\n") ? "" : "\n"
}NOTE: You may want to use a custom rpc endpoint. If you have one, you can set it up with ${PgTerminal.bold(
"'solana config set --url <RPC_URL>'"
)}`
);
}
} finally {
setTimeout(() => PgTerminal.setProgress(0), 1000);
}
}
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/index.ts
|
export { sugar } from "./sugar";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/types/guard-data.ts
|
import type {
CandyGuardsSettings,
DefaultCandyGuardSettings,
Option,
} from "@metaplex-foundation/js";
export interface CandyGuardData {
default: DefaultCandyGuardSettings;
groups: Option<Group[]>;
}
interface Group {
label: string;
guards: CandyGuardsSettings;
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/types/index.ts
|
export * from "./config";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/types/config.ts
|
import { BigNumber, Creator, Option } from "@metaplex-foundation/js";
import { HiddenSettings } from "@metaplex-foundation/mpl-candy-machine-core";
import type { CandyGuardData } from "./guard-data";
import type { PgWeb3 } from "../../../utils/pg";
export type ToPrimitive<T> = {
[K in keyof T]: T[K] extends PgWeb3.PublicKey
? string
: T[K] extends BigNumber
? number
: ToPrimitive<T[K]>;
};
export interface ConfigData {
/** Number of assets available */
size: BigNumber;
/** Symbol for the asset */
symbol: string;
/** Secondary sales royalty basis points (0-10000) */
royalties: number;
/** Indicates if the asset is mutable or not (default yes) */
isMutable: boolean;
/** Indicates whether the index generation is sequential or not */
isSequential: boolean;
/** List of creators */
creators: Omit<Creator, "verified">[];
/** Hidden setttings */
hiddenSettings: Option<HiddenSettings>;
/** Upload method configuration */
uploadConfig: UploadConfig;
/** Guards configuration */
guards: Option<CandyGuardData>;
}
interface UploadConfig {
/** Upload method to use */
method: UploadMethod;
/** AWS specific configuration */
awsConfig: Option<AwsConfig>;
/** NFT.Storage specific configuration */
nftStorageAuthToken: Option<string>;
/** Shadow Drive specific configuration */
shdwStorageAccount: Option<string>;
/** Pinata specific configuration */
pinataConfig: Option<PinataConfig>;
}
/** Sugar compatible upload method names */
export enum UploadMethod {
BUNDLR = "bundlr",
AWS = "aws",
NFT_STORAGE = "nft_storage",
SHDW = "shdw",
PINATA = "pinata",
}
interface AwsConfig {
bucket: string;
profile: string;
directory: string;
domain: Option<string>;
}
interface PinataConfig {
jwt: string;
apiGateway: string;
contentGateway: string;
parallelLimit: Option<number>;
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/token-metadata.ts
|
/** Prefix used for PDAs to avoid certain collision attacks */
export const TOKEN_METADATA_PREFIX = "metadata";
/** Used in seeds to make Edition model pda address */
export const EDITION = "edition";
export const RESERVATION = "reservation";
export const USER = "user";
export const BURN = "burn";
export const COLLECTION_AUTHORITY = "collection_authority";
export const MAX_NAME_LENGTH = 32;
export const MAX_SYMBOL_LENGTH = 10;
export const MAX_URI_LENGTH = 200;
export const MAX_CREATOR_LIMIT = 5;
export const MAX_CREATOR_LEN = 32 + 1 + 1;
export const MAX_DATA_SIZE =
4 +
MAX_NAME_LENGTH +
4 +
MAX_SYMBOL_LENGTH +
4 +
MAX_URI_LENGTH +
2 +
1 +
4 +
MAX_CREATOR_LIMIT * MAX_CREATOR_LEN;
export const MAX_METADATA_LEN =
1 + //key
32 + // update auth pubkey
32 + // mint pubkey
MAX_DATA_SIZE +
1 + // primary sale
1 + // mutable
9 + // nonce (pretty sure this only needs to be 2)
2 + // token standard
34 + // collection
18 + // uses
118; // Padding
export const MAX_EDITION_LEN = 1 + 32 + 8 + 200;
/**
* Large buffer because the older master editions have two pubkeys in them,
* need to keep two versions same size because the conversion process actually
* changes the same account by rewriting it.
*/
export const MAX_MASTER_EDITION_LEN = 1 + 9 + 8 + 264;
export const MAX_RESERVATIONS = 200;
/**
* Can hold up to 200 keys per reservation.
*
* NOTE: the extra 8 is for number of elements in the vec
*/
export const MAX_RESERVATION_LIST_V1_SIZE =
1 + 32 + 8 + 8 + MAX_RESERVATIONS * 34 + 100;
/**
* Can hold up to 200 keys per reservation.
*
* NOTE: the extra 8 is for number of elements in the vec
*/
export const MAX_RESERVATION_LIST_SIZE =
1 + 32 + 8 + 8 + MAX_RESERVATIONS * 48 + 8 + 8 + 84;
export const MAX_EDITION_MARKER_SIZE = 32;
export const EDITION_MARKER_BIT_SIZE = 248;
export const USE_AUTHORITY_RECORD_SIZE = 18; //8 byte padding
export const COLLECTION_AUTHORITY_RECORD_SIZE = 11; //10 byte padding
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/sugar.ts
|
export const VALID_CATEGORIES = ["image", "video", "audio", "vr", "html"];
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/bundlr.ts
|
export enum BundlrEnpoints {
DEVNET = "https://devnet.bundlr.network",
MAINNET = "https://node1.bundlr.network",
}
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/candy-machine.ts
|
import {
MAX_CREATOR_LEN,
MAX_CREATOR_LIMIT,
MAX_NAME_LENGTH,
MAX_SYMBOL_LENGTH,
MAX_URI_LENGTH,
} from "./token-metadata";
import { PgWeb3 } from "../../../utils/pg";
export const EXPIRE_OFFSET = 10 * 60;
export const CANDY_MACHINE_PREFIX = "candy_machine";
export const BOT_FEE = 10000000;
export const FREEZE_FEE = 0; //100000; // 0.0001 SOL
export const MAX_FREEZE_TIME = 60 * 60 * 24 * 31; // 1 month
export const COLLECTIONS_FEATURE_INDEX = 0;
export const FREEZE_FEATURE_INDEX = 1;
export const FREEZE_LOCK_FEATURE_INDEX = 2;
export const COLLECTION_PDA_SIZE = 8 + 32 + 32;
export const CONFIG_LINE_SIZE = 4 + MAX_NAME_LENGTH + 4 + MAX_URI_LENGTH;
export const BLOCK_HASHES = new PgWeb3.PublicKey(
"SysvarRecentB1ockHashes11111111111111111111"
);
export const GUMDROP_ID = new PgWeb3.PublicKey(
"gdrpGjVffourzkdDRrQmySw4aTHr8a3xmQzzxSwFD1a"
);
export const CUPCAKE_ID = new PgWeb3.PublicKey(
"cakeGJxEdGpZ3MJP8sM3QypwzuzZpko1ueonUQgKLPE"
);
export const A_TOKEN = new PgWeb3.PublicKey(
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
);
export const COMPUTE_BUDGET = new PgWeb3.PublicKey(
"ComputeBudget111111111111111111111111111111"
);
export const CONFIG_ARRAY_START =
8 + // key
32 + // authority
32 + //wallet
33 + // token mint
4 +
6 + // uuid
8 + // price
8 + // items available
9 + // go live
10 + // end settings
4 +
MAX_SYMBOL_LENGTH + // u32 len + symbol
2 + // seller fee basis points
4 +
MAX_CREATOR_LIMIT * MAX_CREATOR_LEN + // optional + u32 len + actual vec
8 + //max supply
1 + // is mutable
1 + // retain authority
1 + // option for hidden setting
4 +
MAX_NAME_LENGTH + // name length,
4 +
MAX_URI_LENGTH + // uri length,
32 + // hash
4 + // max number of lines;
8 + // items redeemed
1 + // whitelist option
1 + // whitelist mint mode
1 + // allow presale
9 + // discount price
32 + // mint key for whitelist
1 +
32 +
1; // gatekeeper
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/index.ts
|
export * from "./bundlr";
export * from "./candy-machine-core";
export * from "./candy-machine";
export * from "./sugar";
export * from "./token-metadata";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/constants/candy-machine-core.ts
|
import {
MAX_CREATOR_LEN,
MAX_CREATOR_LIMIT,
MAX_NAME_LENGTH,
MAX_SYMBOL_LENGTH,
MAX_URI_LENGTH,
} from "./token-metadata";
// Empty value used for string padding.
export const NULL_STRING = "\0";
// Constant to define the replacement index string.
export const REPLACEMENT_INDEX = "$ID$";
// Constant to define the replacement index increment string.
export const REPLACEMENT_INDEX_INCREMENT = "$ID+1$";
// Empty string constant.
export const EMPTY_STR = "";
// Seed used to derive the authority PDA address.
export const AUTHORITY_SEED = "candy_machine";
// Determine the start of the account hidden section.
export const HIDDEN_SECTION =
8 + // discriminator
8 + // features
32 + // authority
32 + // mint authority
32 + // collection mint
8 + // items redeemed
8 + // items available (config data)
4 +
MAX_SYMBOL_LENGTH + // u32 + max symbol length
2 + // seller fee basis points
8 + // max supply
1 + // is mutable
4 +
MAX_CREATOR_LIMIT * MAX_CREATOR_LEN + // u32 + creators vec
1 + // option (config lines settings)
4 +
MAX_NAME_LENGTH + // u32 + max name length
4 + // name length
4 +
MAX_URI_LENGTH + // u32 + max uri length
4 + // uri length
1 + // is sequential
1 + // option (hidden setting)
4 +
MAX_NAME_LENGTH + // u32 + max name length
4 +
MAX_URI_LENGTH + // u32 + max uri length
32; // hash
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/metaplex.ts
|
import {
bundlrStorage,
Metaplex,
walletAdapterIdentity,
} from "@metaplex-foundation/js";
import { BundlrEnpoints } from "../constants";
import { PgConnection, PgSettings, PgWallet } from "../../../utils/pg";
export const getMetaplex = async (
endpoint: string = PgSettings.connection.endpoint
) => {
return Metaplex.make(PgConnection.create({ endpoint }))
.use(walletAdapterIdentity(PgWallet.current!))
.use(
bundlrStorage({
address:
(await PgConnection.getCluster(endpoint)) === "mainnet-beta"
? BundlrEnpoints.MAINNET
: BundlrEnpoints.DEVNET,
providerUrl: endpoint,
})
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/print.ts
|
import { PgTerminal } from "../../../utils/pg";
export const printWithStyle = (
indent: string,
key: string | number,
value: any = ""
) => {
PgTerminal.log(
` ${PgTerminal.secondaryText(`${indent}:.. ${key}:`)} ${value}`,
{ noColor: true }
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/cache.ts
|
import {
CandyMachineItem,
Option,
findCandyMachineV2CreatorPda,
} from "@metaplex-foundation/js";
import { ConfigLine } from "@metaplex-foundation/mpl-candy-machine-core";
import { PgSugar } from "../processor";
import { PgCommon, PgExplorer, PgWeb3 } from "../../../utils/pg";
export class CandyCache {
program: CacheProgram;
items: CacheItems;
constructor(cache?: CandyCache) {
this.items = {};
if (cache) {
this.program = new CacheProgram(cache.program);
for (const i in cache.items) {
this.items[i] = new CacheItem(cache.items[i]);
}
} else {
this.program = new CacheProgram();
}
}
async syncFile(onlyRefreshIfAlreadyOpen: boolean = true) {
await PgExplorer.newItem(
PgSugar.PATHS.CANDY_MACHINE_CACHE_FILEPATH,
PgCommon.prettyJSON(this),
{
override: true,
openOptions: { dontOpen: true, onlyRefreshIfAlreadyOpen },
}
);
}
updateItemAtIndex(index: number, newValue: Partial<CacheItem>) {
this.items[index].update(newValue);
}
removeItemAtIndex(index: number) {
delete this.items[index];
}
isItemsEmpty() {
return Object.keys(this.items).length === 0;
}
getConfigLineChunks() {
const RAW_TX_LEN = 440;
const MAX_TX_LEN = 1232;
const configLineChunks = [];
let configLines: {
items: Pick<CandyMachineItem, "name" | "uri">[];
indices: number[];
} = {
items: [],
indices: [],
};
let txLen = RAW_TX_LEN;
for (const i in this.items) {
const configLine = this.items[i].toConfigLine();
if (configLine) {
const configLineLen = configLine.name.length + configLine.uri.length;
if (txLen + configLineLen > MAX_TX_LEN) {
txLen = RAW_TX_LEN + configLineLen;
configLineChunks.push(configLines);
configLines = { items: [configLine], indices: [+i] };
} else {
txLen += configLineLen;
configLines.items.push(configLine);
configLines.indices.push(+i);
}
}
}
configLineChunks.push(configLines);
return configLineChunks;
}
}
class CacheProgram {
candyMachine: string;
candyGuard: string;
candyMachineCreator: string;
collectionMint: string;
constructor(cacheProgram?: Omit<CacheProgram, "setCandyMachine">) {
if (cacheProgram) {
this.candyMachine = cacheProgram.candyMachine;
this.candyGuard = cacheProgram.candyGuard;
this.candyMachineCreator = cacheProgram.candyMachineCreator;
this.collectionMint = cacheProgram.collectionMint;
} else {
this.candyMachine = "";
this.candyGuard = "";
this.candyMachineCreator = "";
this.collectionMint = "";
}
}
setCandyMachine(candyMachinePk: PgWeb3.PublicKey) {
this.candyMachine = candyMachinePk.toBase58();
this.candyMachineCreator =
findCandyMachineV2CreatorPda(candyMachinePk).toBase58();
}
}
type CacheItems = { [key: string]: CacheItem };
// NOTE: These snake case names are standard metaplex names
export class CacheItem {
name: string;
image_hash: string;
image_link: string;
metadata_hash: string;
metadata_link: string;
onChain: boolean;
animation_hash?: string;
animation_link?: string;
constructor(cacheItem: Omit<CacheItem, "toConfigLine" | "update">) {
this.name = cacheItem.name;
this.image_hash = cacheItem.image_hash;
this.image_link = cacheItem.image_link;
this.metadata_hash = cacheItem.metadata_hash;
this.metadata_link = cacheItem.metadata_link;
this.onChain = cacheItem.onChain;
this.animation_hash = cacheItem.animation_hash;
this.animation_link = cacheItem.animation_link;
}
toConfigLine(): Option<ConfigLine> {
if (!this.onChain) {
return { name: this.name, uri: this.metadata_link };
} else {
return null;
}
}
update(newValue: Partial<CacheItem>) {
if (newValue.name !== undefined) {
this.name = newValue.name;
}
if (newValue.image_hash !== undefined) {
this.image_hash = newValue.image_hash;
}
if (newValue.image_link !== undefined) {
this.image_link = newValue.image_link;
}
if (newValue.metadata_hash !== undefined) {
this.metadata_hash = newValue.metadata_hash;
}
if (newValue.metadata_link !== undefined) {
this.metadata_link = newValue.metadata_link;
}
if (newValue.onChain !== undefined) {
this.onChain = newValue.onChain;
}
if (newValue.animation_hash !== undefined) {
this.animation_hash = newValue.animation_hash;
}
if (newValue.animation_link !== undefined) {
this.animation_link = newValue.animation_link;
}
}
}
export const loadCache = async () => {
const cacheFile = PgExplorer.getFileContent(
PgSugar.PATHS.CANDY_MACHINE_CACHE_FILEPATH
);
if (!cacheFile) {
// Cache file doesn't exist, return default
return new CandyCache();
}
return new CandyCache(JSON.parse(cacheFile));
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/candy-machine.ts
|
import type { PgWeb3 } from "../../../utils/pg";
export const assertCorrectAuthority = (
userPk: PgWeb3.PublicKey,
updateAuthorityPk: PgWeb3.PublicKey
) => {
if (!userPk.equals(updateAuthorityPk)) {
throw new Error(
"Update authority does not match that of the candy machine."
);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/accounts.ts
|
import { Metaplex } from "@metaplex-foundation/js";
import {
MAX_NAME_LENGTH,
MAX_SYMBOL_LENGTH,
MAX_URI_LENGTH,
} from "../constants";
export const getCmCreatorMetadataAccounts = async (
metaplex: Metaplex,
creator: string,
position: number = 0
) => {
if (position > 4) {
throw new Error("CM Creator position cannot be greater than 4");
}
return await metaplex
.rpc()
.getProgramAccounts(metaplex.programs().getTokenMetadata().address, {
filters: [
{
memcmp: {
offset:
1 + // key
32 + // update auth
32 + // mint
4 + // name string length
MAX_NAME_LENGTH + // name
4 + // uri string length
MAX_URI_LENGTH + // uri*
4 + // symbol string length
MAX_SYMBOL_LENGTH + // symbol
2 + // seller fee basis points
1 + // whether or not there is a creators vec
4 + // creators
position * // index for each creator
(32 + // address
1 + // verified
1), // share
bytes: creator,
},
},
],
encoding: "base64",
commitment: "confirmed",
});
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/index.ts
|
export * from "./accounts";
export * from "./cache";
export * from "./candy-machine";
export * from "./config";
export * from "./guards";
export * from "./metaplex";
export * from "./print";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/guards.ts
|
import {
Option,
sol,
toBigNumber,
toDateTime,
token,
} from "@metaplex-foundation/js";
import { PgWeb3 } from "../../../utils/pg";
import type { ConfigData, ToPrimitive } from "../types";
export const parseGuards = (
guards: ToPrimitive<Option<ConfigData["guards"]>>
) => {
if (!guards) return null;
_parseGuards(guards.default);
if (guards.groups) {
guards.groups.map((g) => _parseGuards(g.guards));
}
return guards as ConfigData["guards"];
};
const _parseGuards = (guards: { [key: string]: any }) => {
for (const key in guards) {
switch (key) {
case "addressGate":
guards[key] = {
address: new PgWeb3.PublicKey(guards[key].address),
};
break;
case "allowList":
guards[key] = {
merkleRoot: Uint8Array.from(Buffer.from(guards[key].merkleRoot)),
};
break;
case "botTax":
guards[key] = {
lamports: sol(guards[key].value),
lastInstruction: guards[key].lastInstruction,
};
break;
case "endDate":
guards[key] = {
date: toDateTime(guards[key].date),
};
break;
case "gatekeeper":
guards[key] = {
network: new PgWeb3.PublicKey(guards[key].gatekeeperNetwork),
expireOnUse: guards[key].expireOnUse,
};
break;
case "mintLimit":
guards[key] = {
id: guards[key].id,
limit: guards[key].limit,
};
break;
case "nftBurn":
guards[key] = {
requiredCollection: new PgWeb3.PublicKey(
guards[key].requiredCollection
),
};
break;
case "nftGate":
guards[key] = {
requiredCollection: new PgWeb3.PublicKey(
guards[key].requiredCollection
),
};
break;
case "nftPayment":
guards[key] = {
requiredCollection: new PgWeb3.PublicKey(
guards[key].requiredCollection
),
destination: new PgWeb3.PublicKey(guards[key].destination),
};
break;
case "redeemedAmount":
guards[key] = {
maximum: toBigNumber(guards[key].maximum),
};
break;
case "solPayment":
guards[key] = {
amount: sol(guards[key].value),
destination: new PgWeb3.PublicKey(guards[key].destination),
};
break;
case "startDate":
guards[key] = {
date: toDateTime(guards[key].date),
};
break;
case "thirdPartySigner":
guards[key] = {
signerKey: new PgWeb3.PublicKey(guards[key].signerKey),
};
break;
case "tokenBurn":
guards[key] = {
amount: token(guards[key].amount),
mint: new PgWeb3.PublicKey(guards[key].mint),
};
break;
case "tokenGate":
guards[key] = {
amount: token(guards[key].amount),
mint: new PgWeb3.PublicKey(guards[key].mint),
};
break;
case "tokenPayment":
guards[key] = {
amount: token(guards[key].amount),
tokenMint: new PgWeb3.PublicKey(guards[key].mint),
destinationAta: new PgWeb3.PublicKey(guards[key].destination),
};
break;
}
}
return guards as ConfigData["guards"];
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/utils/config.ts
|
import { Option, toBigNumber } from "@metaplex-foundation/js";
import { parseGuards } from "./guards";
import { PgSugar } from "../processor";
import { PgCommon, PgExplorer, PgTerminal, PgWeb3 } from "../../../utils/pg";
import type { ConfigData, ToPrimitive } from "../types";
export const loadConfigData = async (): Promise<ConfigData> => {
const configStr = PgExplorer.getFileContent(
PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH
);
if (!configStr)
throw new Error(
`Config file not found. Run ${PgTerminal.bold(
"'sugar create-config'"
)} to create a new config.`
);
const configData: ToPrimitive<ConfigData> = JSON.parse(configStr);
return {
size: toBigNumber(configData.size),
symbol: configData.symbol,
royalties: configData.royalties,
isMutable: configData.isMutable,
isSequential: configData.isSequential,
creators: configData.creators.map((c) => ({
...c,
address: new PgWeb3.PublicKey(c.address),
})),
hiddenSettings: configData.hiddenSettings
? {
...configData.hiddenSettings,
hash: Array.from(Buffer.from(configData.hiddenSettings.hash)),
}
: null,
uploadConfig: configData.uploadConfig,
guards: parseGuards(
configData.guards as ToPrimitive<Option<ConfigData["guards"]>> & {
[key: string]: any;
}
),
};
};
export const saveConfigData = async (configData: ConfigData) => {
await PgExplorer.newItem(
PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH,
PgCommon.prettyJSON({
...configData,
size: configData.size.toNumber(),
hiddenSettings: configData.hiddenSettings
? {
...configData.hiddenSettings,
hash: PgCommon.decodeBytes(
Uint8Array.from(configData.hiddenSettings.hash)
),
}
: null,
creators: configData.creators.map((c) => ({
...c,
address: c.address.toBase58(),
})),
}),
{
override: true,
openOptions: { onlyRefreshIfAlreadyOpen: true },
}
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/index.ts
|
export * from "./bundlr";
export * from "./collection";
export * from "./create-config";
export * from "./deploy";
export * from "./guard";
export * from "./hash";
export * from "./launch";
export * from "./mint";
export * from "./reveal";
export * from "./show";
export * from "./sign";
export * from "./update";
export * from "./upload";
export * from "./validate";
export * from "./verify";
export * from "./withdraw";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/validate/validate.ts
|
import type { JsonMetadata } from "@metaplex-foundation/js";
import {
checkCategory,
checkCreatorsAddresses,
checkCreatorsShares,
checkName,
checkSellerFeeBasisPoints,
checkSymbol,
checkUrl,
} from "./parser";
import { SugarUploadScreen } from "../upload";
import { Emoji } from "../../../../constants";
import { PgCommon, PgView, PgTerminal } from "../../../../utils/pg";
export const processValidate = async (
strict: boolean,
skipCollectionPrompt: boolean
) => {
const term = await PgTerminal.get();
term.println(`[1/1] ${Emoji.ASSETS} Loading assets`);
const files: File[] | null = await PgView.setModal(SugarUploadScreen, {
title: "Validate Assets",
});
if (!files) throw new Error("You haven't selected files.");
// Sort files based on their name
files.sort((a, b) => a.name.localeCompare(b.name));
// Get file names
const fileNames = files.map((f) => f.name);
// Collection should be one the last indices if it exists
const collectionExists =
fileNames[fileNames.length - 1] === "collection.json" ||
fileNames[fileNames.length - 2] === "collection.json";
if (!skipCollectionPrompt) {
if (!collectionExists) {
term.println(
PgTerminal.warning(
[
"+----------------------------------------------+",
`| ${Emoji.WARNING} MISSING COLLECTION FILES IN ASSETS FOLDER |`,
"+----------------------------------------------+",
].join("\n")
)
);
term.println(
PgTerminal.italic(
[
"Check https://docs.metaplex.com/developer-tools/sugar/guides/preparing-assets for",
"the collection file requirements if you want a collection to be set automatically.",
].join(" ")
)
);
if (
!(await term.waitForUserInput(
"Do you want to continue without automatically setting the candy machine collection?",
{ confirm: true, default: "yes" }
))
) {
throw new Error("Operation aborted");
}
term.println("");
}
}
// Check file names start from 0
const firstFileNumber = getNameWithoutExtension(fileNames[0]);
if (firstFileNumber !== "0") {
throw new Error(`File names must start from 0. (${fileNames[0]})`);
}
// Validate continuous assets in directory
for (const i in fileNames.slice(
0,
collectionExists ? -2 : fileNames.length - 1
)) {
const number = getNameWithoutExtension(fileNames[i]);
// Check is number
if (!PgCommon.isInt(number)) {
throw new Error(
`File names must be numbers. ${PgTerminal.secondaryText(
`(${fileNames[i]})`
)}`
);
}
// Check is sequential
if (i === "0") continue;
const lastItemNumber = getNameWithoutExtension(fileNames[+i - 1]);
if (lastItemNumber !== number && +lastItemNumber + 1 !== +number) {
throw new Error(
`File names must be sequential. Jumped from ${lastItemNumber} to ${number}.`
);
}
}
// Validate metadatas
for (const i in fileNames) {
const fileName = fileNames[i];
if (!fileName.endsWith(".json")) continue;
// To be replaced with the strict validator once JSON standard is finalized
// if (strict) {}
const metadata: JsonMetadata = JSON.parse(await files[i].text());
if (!metadata.name) throwNotSpecified(fileName, "name");
checkName(metadata.name!);
if (!metadata.image) throwNotSpecified(fileName, "image");
checkUrl(metadata.image!);
if (metadata.seller_fee_basis_points) {
checkSellerFeeBasisPoints(metadata.seller_fee_basis_points);
}
if (metadata.symbol) {
checkSymbol(metadata.symbol);
}
if (metadata.properties?.creators) {
checkCreatorsShares(metadata.properties.creators as any);
checkCreatorsAddresses(metadata.properties.creators as any);
}
if (metadata.properties?.category) {
checkCategory(metadata.properties.category as string);
}
if (metadata.external_url) {
checkUrl(metadata.external_url);
}
}
term.println("Validation complete, your metadata file(s) look good.");
};
const throwNotSpecified = (fileName: string, property: string) => {
throw new Error(
`Metadata file ${fileName} does not have property ${PgTerminal.italic(
`'${property}'`
)} specified.`
);
};
const getNameWithoutExtension = (fileName: string) => fileName.split(".")[0];
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/validate/parser.ts
|
import type { Creator } from "@metaplex-foundation/js";
import {
MAX_NAME_LENGTH,
MAX_SYMBOL_LENGTH,
MAX_URI_LENGTH,
VALID_CATEGORIES,
} from "../../constants";
import { PgCommon } from "../../../../utils/pg";
import type { ToPrimitive } from "../../types";
export const checkName = (name: string) => {
if (name.length > MAX_NAME_LENGTH) {
throw new Error("Name exceeds 32 chars.");
}
};
export const checkSymbol = (symbol: string) => {
if (symbol.length > MAX_SYMBOL_LENGTH) {
throw new Error("Symbol exceeds 10 chars.");
}
};
export const checkUrl = (url: string) => {
if (url.length > MAX_URI_LENGTH) {
throw new Error("Url exceeds 200 chars.");
}
};
export const checkSellerFeeBasisPoints = (sellerFeeBasisPoints: number) => {
if (sellerFeeBasisPoints > 10000) {
throw new Error(
`Seller fee basis points value '${sellerFeeBasisPoints}' is invalid: must be between 0 and 10,000.`
);
}
};
export const checkCreatorsShares = (creators: Creator[]) => {
let shares = 0;
for (const creator of creators) {
shares += creator.share;
}
if (shares !== 100) {
throw new Error("Combined creators' share does not equal 100%.");
}
};
export const checkCreatorsAddresses = (creators: ToPrimitive<Creator>[]) => {
for (const creator of creators) {
if (!PgCommon.isPk(creator.address)) {
throw new Error(`Creator address: '${creator.address}' is invalid.`);
}
}
};
export const checkCategory = (category: string) => {
if (!VALID_CATEGORIES.includes(category)) {
throw new Error(
`Invalid category '${category}': must be one of: ${VALID_CATEGORIES}`
);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/validate/index.ts
|
export * from "./parser";
export * from "./validate";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/collection/collection.ts
|
import { createSetCollectionInstruction } from "@metaplex-foundation/mpl-candy-machine-core";
import { hashAndUpdate } from "../hash";
import { processUpdate } from "../update";
import { assertCorrectAuthority, getMetaplex, loadCache } from "../../utils";
import { Emoji } from "../../../../constants";
import { PgTerminal, PgWeb3 } from "../../../../utils/pg";
export const processCollectionSet = async (
rpcUrl: string | undefined,
candyMachine: string | undefined,
collectionMint: string
) => {
// The candy machine id specified takes precedence over the one from the cache
const candyMachinePkStr =
candyMachine ?? (await loadCache()).program.candyMachine;
if (!candyMachinePkStr) {
throw new Error("Missing candy machine id.");
}
let candyMachinePk: PgWeb3.PublicKey;
try {
candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr);
} catch {
throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`);
}
let newCollectionMintPk: PgWeb3.PublicKey;
try {
newCollectionMintPk = new PgWeb3.PublicKey(collectionMint);
} catch {
throw new Error(`Failed to parse collection mint id: ${candyMachinePkStr}`);
}
const term = await PgTerminal.get();
term.println(`[1/2] ${Emoji.LOOKING_GLASS} Loading candy machine`);
term.println(`${PgTerminal.bold("Candy machine ID:")} ${candyMachinePkStr}`);
const metaplex = await getMetaplex(rpcUrl);
const candyState = await metaplex
.candyMachines()
.findByAddress({ address: candyMachinePk });
const payer = metaplex.identity().publicKey;
assertCorrectAuthority(payer, candyState.authorityAddress);
term.println(
`\n[2/2] ${Emoji.COLLECTION} Setting collection mint for candy machine`
);
const getCandyPdas = (collectionMintPk: PgWeb3.PublicKey) => {
const authorityPda = metaplex
.candyMachines()
.pdas()
.authority({ candyMachine: candyMachinePk });
const collectionAuthorityRecordPda = metaplex
.nfts()
.pdas()
.collectionAuthorityRecord({
collectionAuthority: authorityPda,
mint: collectionMintPk,
});
const collectionMetadataPda = metaplex
.nfts()
.pdas()
.metadata({ mint: collectionMintPk });
return [authorityPda, collectionAuthorityRecordPda, collectionMetadataPda];
};
const [authorityPda, collectionAuthorityRecordPda, collectionMetadataPda] =
getCandyPdas(candyState.collectionMintAddress);
const [, newCollectionAuthorityRecordPda, newCollectionMetadataPda] =
getCandyPdas(newCollectionMintPk);
const newCollectionMasterEditionPda = metaplex
.nfts()
.pdas()
.masterEdition({ mint: newCollectionMintPk });
const newMetadataInfo = await metaplex
.nfts()
.findByMint({ mintAddress: newCollectionMintPk });
const tx = new PgWeb3.Transaction().add(
createSetCollectionInstruction({
candyMachine: candyMachinePk,
authority: payer,
authorityPda,
payer,
collectionMint: candyState.collectionMintAddress,
collectionMetadata: collectionMetadataPda,
collectionAuthorityRecord: collectionAuthorityRecordPda,
newCollectionUpdateAuthority: newMetadataInfo.updateAuthorityAddress,
newCollectionMetadata: newCollectionMetadataPda,
newCollectionMint: newCollectionMintPk,
newCollectionMasterEdition: newCollectionMasterEditionPda,
newCollectionAuthorityRecord: newCollectionAuthorityRecordPda,
tokenMetadataProgram: metaplex.programs().getTokenMetadata().address,
})
);
const blockhashInfo = await metaplex.connection.getLatestBlockhash();
tx.feePayer = metaplex.identity().publicKey;
tx.recentBlockhash = blockhashInfo.blockhash;
await metaplex.rpc().sendAndConfirmTransaction(tx, {}, [metaplex.identity()]);
// If a candy machine id wasn't manually specified we are operating on the
// candy machine in the cache, need to update the cache file
if (!candyMachine) {
const cache = await loadCache();
cache.removeItemAtIndex(-1);
cache.program.collectionMint = newCollectionMintPk.toBase58();
await cache.syncFile();
// If hidden settings are enabled, we update the hash value in the config
// file and update the candy machine on-chain
if (candyState.itemSettings.type === "hidden") {
term.println(
`\n${PgTerminal.bold("Hidden settings hash:")} ${await hashAndUpdate()}`
);
term.println(
"\nCandy machine has hidden settings and cache file was updated. Updating hash value...\n"
);
await processUpdate(undefined, undefined, candyMachinePkStr);
}
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/collection/index.ts
|
export * from "./collection";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/create-config/create-config.ts
|
import {
MAX_NAME_LENGTH,
MAX_URI_LENGTH,
REPLACEMENT_INDEX_INCREMENT,
} from "../../constants";
import { PgSugar } from "../../processor";
import { Emoji } from "../../../../constants";
import { PgCommon, PgExplorer, PgTerminal } from "../../../../utils/pg";
import { ConfigData, ToPrimitive, UploadMethod } from "../../types";
export const processCreateConfig = async () => {
const term = await PgTerminal.get();
term.println(`[1/2] ${Emoji.CANDY} Sugar interactive config maker`);
term.println(
"\nCheck out our Candy Machine config docs to learn about the options:"
);
term.println(
` -> ${PgTerminal.underline(
"https://docs.metaplex.com/tools/sugar/configuration"
)}\n`
);
const configData: Partial<ToPrimitive<ConfigData>> = {};
// Size
configData.size = parseInt(
await term.waitForUserInput(
"How many NFTs will you have in your candy machine?",
{ validator: PgCommon.isInt }
)
);
// Symbol
configData.symbol = await term.waitForUserInput(
"What is the symbol of your collection? Hit [ENTER] for no symbol.",
{
allowEmpty: true,
validator: (input) => {
if (input.length > 10) {
throw new Error("Symbol must be 10 characters or less.");
}
},
}
);
// Royalties(seller fee basis points)
configData.royalties = parseInt(
await term.waitForUserInput("What is the seller fee basis points?", {
validator: (input) => {
if (!PgCommon.isInt(input)) {
throw new Error(`Couldn't parse input of '${input}' to a number.`);
}
if (parseInt(input) > 10_000) {
throw new Error("Seller fee basis points must be 10,000 or less.");
}
},
})
);
// Sequential
configData.isSequential = await term.waitForUserInput(
"Do you want to use a sequential mint index generation? We recommend you choose no.",
{ confirm: true, default: "no" }
);
// Creators
const numberOfCreators = parseInt(
await term.waitForUserInput(
"How many creator wallets do you have? (max limit of 4)",
{ validator: (input) => PgCommon.isInt(input) && parseInt(input) <= 4 }
)
);
let totalShare = 0;
const validateShare = (input: string, isLastCreator: boolean) => {
if (!PgCommon.isInt(input)) {
throw new Error(`Couldn't parse input of '${input}' to a number.`);
}
const newShare = parseInt(input) + totalShare;
if (newShare > 100) {
throw new Error("Royalty share total has exceeded 100 percent.");
}
if (isLastCreator && newShare !== 100) {
throw new Error("Royalty share for all creators must total 100 percent.");
}
};
configData.creators = [];
for (let i = 0; i < numberOfCreators; i++) {
const address = await term.waitForUserInput(
`Enter creator wallet address #${i + 1}`,
{
validator: PgCommon.isPk,
}
);
const share = parseInt(
await term.waitForUserInput(
`Enter royalty percentage share for creator #${
i + 1
} (e.g., 70). Total shares must add to 100.`,
{
validator: (input) =>
validateShare(input, i + 1 === numberOfCreators),
}
)
);
totalShare += share;
configData.creators.push({ address, share });
}
// Optional extra features
const choices = await term.waitForUserInput(
"Which extra features do you want to use? Leave empty for no extra features.",
{
allowEmpty: true,
choice: {
items: [
"Hidden Settings", // 0
],
allowMultiple: true,
},
}
);
// Hidden Settings
if (choices.includes(0)) {
let name = await term.waitForUserInput(
[
"What is the prefix name for your hidden settings mints? The mint index will be appended at the end of the name.",
PgTerminal.secondaryText(
"(If you put 'My NFT', NFTs will be named 'My NFT #1' 'My NFT #2'...)"
),
].join(" "),
{
validator: (input) => {
if (!input.includes(REPLACEMENT_INDEX_INCREMENT)) {
input += ` #${REPLACEMENT_INDEX_INCREMENT}`;
}
const maxNameLengthWithoutFiller =
MAX_NAME_LENGTH - (REPLACEMENT_INDEX_INCREMENT.length + 2);
if (input.length > maxNameLengthWithoutFiller) {
throw new Error(
`Your hidden settings name probably cannot be longer than ${maxNameLengthWithoutFiller} characters.`
);
}
},
}
);
if (!name.includes(REPLACEMENT_INDEX_INCREMENT)) {
name += ` #${REPLACEMENT_INDEX_INCREMENT}`;
}
const uri = await term.waitForUserInput(
"What is URI to be used for each mint?",
{
validator: (input) => {
if (input.length > MAX_URI_LENGTH) {
throw new Error(
`The URI cannot be longer than ${MAX_URI_LENGTH} characters.`
);
}
// This throws an error if url is invalid
new URL(input);
},
}
);
configData.hiddenSettings = { name, uri, hash: [] };
} else {
configData.hiddenSettings = null;
}
// Upload method
configData.uploadConfig = {
// TODO:
// method: await term.waitForUserInput(
// `"What upload method do you want to use?"`,
// {
// choice: {
// items: [
// "Bundlr", // 0
// "AWS", // 1
// "NFT Storage", // 2
// "SHDW", // 3
// "Pinata", // 4
// ],
// },
// default: "0",
// }
// ),
method: UploadMethod.BUNDLR,
awsConfig: null,
nftStorageAuthToken: null,
pinataConfig: null,
shdwStorageAccount: null,
};
switch (configData.uploadConfig.method) {
// Bundlr
case UploadMethod.BUNDLR: {
// This is the default, do nothing.
break;
}
// AWS
case UploadMethod.AWS: {
const bucket = await term.waitForUserInput(
"What is the AWS S3 bucket name?"
);
const profile = await term.waitForUserInput(
"What is the AWS profile name?",
{ default: "default" }
);
const directory = await term.waitForUserInput(
"What is the directory to upload to? Leave blank to store files at the bucket root dir.",
{ allowEmpty: true }
);
const domain = await term.waitForUserInput(
"Do you have a custom domain? Leave blank to use AWS default domain.",
{ allowEmpty: true }
);
configData.uploadConfig.awsConfig = {
bucket,
profile,
directory,
domain: domain ? domain : null,
};
break;
}
// NFT Storage
case UploadMethod.NFT_STORAGE: {
configData.uploadConfig.nftStorageAuthToken = await term.waitForUserInput(
"What is the NFT Storage authentication token?"
);
break;
}
// SHDW
case UploadMethod.SHDW: {
configData.uploadConfig.shdwStorageAccount = await term.waitForUserInput(
"What is the SHDW storage address?",
{ validator: PgCommon.isPk }
);
break;
}
// Pinata
case UploadMethod.PINATA: {
const jwt = await term.waitForUserInput(
"What is your Pinata JWT authentication?"
);
const apiGateway = await term.waitForUserInput(
"What is the Pinata API gateway for upload?",
{ default: "https://api.pinata.cloud" }
);
const contentGateway = await term.waitForUserInput(
"What is the Pinata gateway for content retrieval?",
{ default: "https://gateway.pinata.cloud" }
);
const parallelLimit = parseInt(
await term.waitForUserInput(
"How many concurrent uploads are allowed?",
{ validator: PgCommon.isInt }
)
);
configData.uploadConfig.pinataConfig = {
jwt,
apiGateway,
contentGateway,
parallelLimit,
};
}
}
// Mutability
configData.isMutable = await term.waitForUserInput(
"Do you want your NFTs to remain mutable? We HIGHLY recommend you choose yes.",
{ confirm: true, default: "yes" }
);
// Guards
configData.guards = null;
// Save the file
term.println(`\n[2/2] ${Emoji.PAPER} Saving config file\n`);
let saveFile = true;
if (await PgExplorer.fs.exists(PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH)) {
saveFile =
(await term.waitForUserInput(
[
`The file "${PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH}" already exists.`,
"Do you want to overwrite it with the new config or log the new config to the console?",
].join(" "),
{
default: "0",
choice: {
items: ["Overwrite the file", "Log to console"],
},
}
)) === 0;
}
const prettyConfigData = PgCommon.prettyJSON(configData);
if (saveFile) {
term.println(
`Saving config to file: "${PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH}"\n`
);
await PgExplorer.newItem(
PgSugar.PATHS.CANDY_MACHINE_CONFIG_FILEPATH,
prettyConfigData,
{ override: true }
);
term.println(
`${PgTerminal.secondary("Successfully generated the config file.")} ${
Emoji.CONFETTI
}`
);
} else {
term.println(PgTerminal.secondaryText("Logging config to console:\n"));
term.println(prettyConfigData);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/create-config/index.ts
|
export * from "./create-config";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/mint/mint.ts
|
import { toBigNumber } from "@metaplex-foundation/js";
import { getMetaplex, loadCache } from "../../utils";
import { Emoji } from "../../../../constants";
import { PgBlockExplorer, PgTerminal, PgWeb3 } from "../../../../utils/pg";
export const processMint = async (
rpcUrl: string | undefined,
number: bigint | undefined,
receiver: string | undefined,
candyMachine: string | undefined
) => {
const metaplex = await getMetaplex(rpcUrl);
// The candy machine id specified takes precedence over the one from the cache
const candyMachinePkStr =
candyMachine ?? (await loadCache()).program.candyMachine;
if (!candyMachinePkStr) {
throw new Error("Missing candy machine id.");
}
let candyMachinePk;
try {
candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr);
} catch {
throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`);
}
const term = await PgTerminal.get();
term.println(`[1/2] ${Emoji.LOOKING_GLASS} Loading candy machine`);
term.println(`${PgTerminal.bold("Candy machine ID:")} ${candyMachinePkStr}`);
const candyClient = metaplex.candyMachines();
const candyState = await candyClient.findByAddress({
address: candyMachinePk,
});
term.println(`\n[2/2] ${Emoji.CANDY} Minting from candy machine`);
const receiverPk = receiver
? new PgWeb3.PublicKey(receiver)
: metaplex.identity().publicKey;
term.println(`Minting to ${receiverPk.toBase58()}\n`);
const mintAmount = toBigNumber(number?.toString() ?? 1);
const available = candyState.itemsRemaining;
if (mintAmount.gt(available) || mintAmount.eqn(0)) {
throw new Error(`${available} item(s) available, requested ${mintAmount}`);
}
// Show progress bar
PgTerminal.setProgress(0.1);
let progressCount = 0;
// Check for candy guard groups
const groupLen = candyState.candyGuard?.groups.length;
let groupIndex = 0;
if (groupLen && groupLen > 1) {
groupIndex = await term.waitForUserInput(
"Candy guard has multiple groups. Which group do you belong to?",
{
choice: {
items: candyState.candyGuard.groups.map((g) => g.label),
},
}
);
}
// Need to specify the group label when we are minting if guards have groups
const group = groupLen
? candyState.candyGuard.groups[groupIndex].label
: null;
const CONCURRENT = 4;
const errors: string[] = [];
let isMintingOver = false;
const logCondition = mintAmount.ltn(100);
await Promise.all(
new Array(CONCURRENT).fill(null).map(async (_, i) => {
for (let j = 0; mintAmount.gtn(j + i); j += CONCURRENT) {
try {
const { nft } = await candyClient.mint({
candyMachine: {
address: candyState.address,
collectionMintAddress: candyState.collectionMintAddress,
candyGuard: candyState.candyGuard,
},
collectionUpdateAuthority: candyState.authorityAddress,
group,
});
if (logCondition) {
term.println(
PgTerminal.secondary(
`${Emoji.CONFETTI} Minted ${
candyState.itemSettings.type === "hidden"
? "NFT"
: `${nft.name}`
}: ${PgTerminal.underline(
// The explorer URL will be based on the current cluster
// rather than the cluster of the custom URL argument
PgBlockExplorer.current.getAddressUrl(nft.address.toBase58())
)} `
)
);
}
} catch (e: any) {
errors.push(e.message);
// Check if the mint is over
const newCandyState = await candyClient.findByAddress({
address: candyState.address,
});
if (newCandyState.itemsRemaining.eqn(0)) {
isMintingOver = true;
break;
}
} finally {
progressCount++;
PgTerminal.setProgress((progressCount / mintAmount.toNumber()) * 100);
}
}
})
);
// Hide progress bar
setTimeout(() => PgTerminal.setProgress(0), 1000);
if (isMintingOver) {
term.println(PgTerminal.info("Minting is over!"));
}
if (errors.length) {
term.println(
`${PgTerminal.error("Minted")} ${mintAmount
.subn(errors.length)
.toString()}/${mintAmount} ${PgTerminal.error("of the items.")}`
);
throw new Error(errors[0]);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/mint/index.ts
|
export * from "./mint";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/update/index.ts
|
export * from "./update";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/update/update.ts
|
import { toBigNumber } from "@metaplex-foundation/js";
import {
assertCorrectAuthority,
getMetaplex,
loadCache,
loadConfigData,
} from "../../utils";
import { Emoji } from "../../../../constants";
import { PgTerminal, PgWeb3 } from "../../../../utils/pg";
export const processUpdate = async (
rpcUrl: string | undefined,
newAuthority: string | undefined,
candyMachine: string | undefined
) => {
const metaplex = await getMetaplex(rpcUrl);
const configData = await loadConfigData();
// The candy machine id specified takes precedence over the one from the cache
const candyMachinePkStr =
candyMachine ?? (await loadCache()).program.candyMachine;
if (!candyMachinePkStr) {
throw new Error("Missing candy machine id.");
}
let candyMachinePk;
try {
candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr);
} catch {
throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`);
}
const term = await PgTerminal.get();
term.println(`[1/2] ${Emoji.LOOKING_GLASS} Loading candy machine`);
term.println(`${PgTerminal.bold("Candy machine ID:")} ${candyMachinePkStr}`);
const candyClient = metaplex.candyMachines();
const candyState = await candyClient.findByAddress({
address: candyMachinePk,
});
assertCorrectAuthority(
metaplex.identity().publicKey,
candyState.authorityAddress
);
term.println(`\n[2/2] ${Emoji.COMPUTER} Updating configuration`);
await candyClient.update({
candyMachine: candyState,
newAuthority: newAuthority ? new PgWeb3.PublicKey(newAuthority) : undefined,
creators: configData.creators,
groups: configData.guards?.groups ? configData.guards.groups : undefined,
guards: configData.guards?.default ? configData.guards.default : undefined,
isMutable: configData.isMutable,
itemsAvailable: configData.size,
sellerFeeBasisPoints: configData.royalties,
symbol: configData.symbol,
maxEditionSupply: toBigNumber(0),
itemSettings: configData.hiddenSettings
? { type: "hidden", ...configData.hiddenSettings }
: candyState.itemSettings,
});
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/hash/hash.ts
|
import { loadCache, loadConfigData, saveConfigData } from "../../utils";
import { PgBytes, PgCommon, PgTerminal } from "../../../../utils/pg";
export const processHash = async (compare: string | undefined) => {
const configData = await loadConfigData();
const term = await PgTerminal.get();
if (compare) {
const cache = await loadCache();
const hashB58 = hash(PgCommon.prettyJSON(cache));
term.println(`Cache hash: ${hashB58}`);
if (compare !== hashB58) {
throw new Error("Hashes do not match!");
}
term.println("Hashes match!");
}
if (configData.hiddenSettings) {
term.println(`Hash: ${await hashAndUpdate()}`);
} else {
throw new Error("No hidden settings found in config file.");
}
};
export const hashAndUpdate = async () => {
const configData = await loadConfigData();
const hiddenSettings = configData.hiddenSettings;
if (!hiddenSettings) {
throw new Error(
"Trying to update hidden settings when it's not specified in the config."
);
}
const cache = await loadCache();
const hashResult = hash(PgCommon.prettyJSON(cache));
hiddenSettings.hash = Array.from(Buffer.from(hashResult));
await saveConfigData(configData);
return PgCommon.decodeBytes(Buffer.from(hiddenSettings.hash));
};
// FIXME: This ends up not producing the same hash with the sugar cli
const hash = (data: string) => {
return PgBytes.toBase58(PgBytes.fromHex(PgBytes.hashSha256(data))).substring(
0,
32
);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/hash/index.ts
|
export * from "./hash";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/verify/verify.ts
|
import { CandyMachineItem } from "@metaplex-foundation/js";
import { CacheItem, getMetaplex, loadCache } from "../../utils";
import { Emoji } from "../../../../constants";
import { PgConnection, PgTerminal, PgWeb3 } from "../../../../utils/pg";
export const processVerify = async (rpcUrl: string | undefined) => {
// Load the cache file (this needs to have been created by
// the upload command)
const cache = await loadCache();
if (cache.isItemsEmpty()) {
throw new Error(
`No cache items found - run ${PgTerminal.bold(
"'sugar upload'"
)} to create the cache file first.`
);
}
const term = await PgTerminal.get();
term.println(`[1/2] ${Emoji.CANDY} Loading candy machine`);
let candyMachinePk;
try {
candyMachinePk = new PgWeb3.PublicKey(cache.program.candyMachine);
} catch {
throw new Error(
[
`Invalid candy machine address: '${cache.program.candyMachine}'.`,
"Check your cache file or run deploy to ensure your candy machine was created.",
].join(" ")
);
}
const metaplex = await getMetaplex(rpcUrl);
const candyClient = metaplex.candyMachines();
const candyState = await candyClient.findByAddress({
address: candyMachinePk,
});
term.println(`\n[2/2] ${Emoji.PAPER} Verification`);
if (candyState.itemSettings.type === "hidden") {
// Nothing else to do, there are no config lines in a candy machine
// with hidden settings
term.println("\nHidden settings enabled. No config items to verify.");
} else {
const numItems = candyState.itemsAvailable;
term.println(`Verifying ${numItems.toString()} config line(s)...`);
const errors = [];
for (const configLine of candyState.items) {
const cacheItem = cache.items[configLine.index];
try {
assertItemsMatch(cacheItem, configLine);
} catch (e: any) {
cacheItem.onChain = false;
errors.push({ index: configLine.index, message: e.message });
}
}
if (errors.length) {
term.println(PgTerminal.error("Verification failed"));
await cache.syncFile();
term.println("\nInvalid items found:");
for (const e of errors) {
term.println(`- Item ${e.index}: ${e.message}`);
}
term.println(
`\nCache updated - re-run ${PgTerminal.bold("'sugar deploy'")}.`
);
throw new Error(`${errors.length} invalid item(s) found.`);
}
}
if (candyState.itemsMinted.gtn(0)) {
term.println(
"\nAn item has already been minted. Skipping candy machine collection verification..."
);
} else {
const collectionItem = cache.items["-1"];
const collectionNeedsDeploy = collectionItem
? !collectionItem.onChain
: false;
const collectionMetadataPk = metaplex
.nfts()
.pdas()
.metadata({ mint: new PgWeb3.PublicKey(cache.program.collectionMint) });
const metadata = await metaplex
.nfts()
.findByMetadata({ metadata: collectionMetadataPk });
if (metadata.address.toBase58() !== cache.program.collectionMint) {
term.println("\nInvalid collection state found");
cache.program.collectionMint = metadata.address.toBase58();
if (collectionItem) {
collectionItem.onChain = false;
}
await cache.syncFile();
term.println(
`Cache updated - re-run ${PgTerminal.bold("'sugar deploy`")}.`
);
throw new Error(
`Collection mint in cache ${
cache.program.collectionMint
} doesn't match on chain collection mint ${metadata.address.toBase58()}!`
);
} else if (collectionNeedsDeploy) {
term.println(
`\nInvalid collection state found - re-run ${PgTerminal.bold(
"'sugar deploy`"
)}.`
);
throw new Error("Invalid cache state found.");
}
const cluster = await PgConnection.getCluster(
metaplex.connection.rpcEndpoint
);
if (cluster === "devnet" || cluster === "mainnet-beta") {
term.println(
[
`\nVerification successful. You're good to go!\n\nSee your candy machine at:\n`,
` -> ${PgTerminal.underline(
`https://www.solaneyes.com/address/${
cache.program.candyMachine
}?cluster=${cluster === "devnet" ? cluster : "mainnet"}`
)}`,
].join(""),
{ noColor: true }
);
} else {
term.println("\nVerification successful. You're good to go!");
}
}
};
const assertItemsMatch = (
cacheItem: CacheItem,
configLine: CandyMachineItem
) => {
if (cacheItem.name !== configLine.name) {
throw new Error(
`name mismatch (expected='${cacheItem.name}', found='${configLine.name}')`
);
}
if (cacheItem.metadata_link !== configLine.uri) {
throw new Error(
`uri mismatch (expected='${cacheItem.metadata_link}', found='${configLine.uri}')`
);
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/verify/index.ts
|
export * from "./verify";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/deploy/collection.ts
|
import { Creator, Metaplex } from "@metaplex-foundation/js";
import {
createCreateMetadataAccountV3Instruction,
createCreateMasterEditionV3Instruction,
} from "@metaplex-foundation/mpl-token-metadata";
import {
createAssociatedTokenAccountInstruction,
getAssociatedTokenAddress,
MINT_SIZE,
TOKEN_PROGRAM_ID,
createInitializeMintInstruction,
createMintToInstruction,
} from "@solana/spl-token";
import { CandyCache } from "../../utils";
import type { ConfigData } from "../../types";
import { PgWeb3 } from "../../../../utils/pg";
export const createCollection = async (
metaplex: Metaplex,
cache: CandyCache,
configData: ConfigData
) => {
const collectionItem = cache.items["-1"];
if (!collectionItem) {
throw new Error(
"Trying to create and set collection when collection item info isn't in cache! This shouldn't happen!"
);
}
const collectionMintKp = new PgWeb3.Keypair();
const collectionMintPk = collectionMintKp.publicKey;
const payer = metaplex.identity().publicKey;
// Create mint account
const createMintAccountIx = PgWeb3.SystemProgram.createAccount({
fromPubkey: payer,
lamports: await metaplex.connection.getMinimumBalanceForRentExemption(
MINT_SIZE
),
newAccountPubkey: collectionMintPk,
programId: TOKEN_PROGRAM_ID,
space: MINT_SIZE,
});
// Initialize mint
const initMintIx = await createInitializeMintInstruction(
collectionMintPk,
0,
payer,
payer
);
const ataPk = await getAssociatedTokenAddress(collectionMintPk, payer);
// Create associated account
const createAtaIx = await createAssociatedTokenAccountInstruction(
payer,
ataPk,
payer,
collectionMintPk
);
// Mint
const mintToIx = await createMintToInstruction(
collectionMintPk,
ataPk,
payer,
1
);
const creator: Creator = {
address: payer,
verified: true,
share: 100,
};
const collectionMetadataPk = metaplex
.nfts()
.pdas()
.metadata({ mint: collectionMintPk });
// Create metadata account
const createMetadataAccountIx = createCreateMetadataAccountV3Instruction(
{
metadata: collectionMetadataPk,
mint: collectionMintPk,
mintAuthority: payer,
payer: payer,
updateAuthority: payer,
},
{
createMetadataAccountArgsV3: {
data: {
name: collectionItem.name,
symbol: configData.symbol,
uri: collectionItem.metadata_link,
creators: [creator],
sellerFeeBasisPoints: configData.royalties,
collection: null,
uses: null,
},
collectionDetails: { __kind: "V1", size: 0 },
isMutable: configData.isMutable,
},
}
);
const collectionEditionPubkey = metaplex
.nfts()
.pdas()
.masterEdition({ mint: collectionMintPk });
// Create master edition account
const createMasterEditionIx = createCreateMasterEditionV3Instruction(
{
edition: collectionEditionPubkey,
mint: collectionMintPk,
updateAuthority: payer,
mintAuthority: payer,
metadata: collectionMetadataPk,
payer,
},
{ createMasterEditionArgs: { maxSupply: 0 } }
);
const tx = new PgWeb3.Transaction().add(
...[
createMintAccountIx,
initMintIx,
createAtaIx,
mintToIx,
createMetadataAccountIx,
createMasterEditionIx,
]
);
tx.feePayer = payer;
const blockhashInfo = await metaplex.connection.getLatestBlockhash();
tx.recentBlockhash = blockhashInfo.blockhash;
await metaplex
.rpc()
.sendAndConfirmTransaction(tx, {}, [collectionMintKp, metaplex.identity()]);
collectionItem.onChain = true;
cache.program.collectionMint = collectionMintPk.toBase58();
await cache.syncFile();
return collectionMintPk;
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/deploy/index.ts
|
export * from "./deploy";
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/deploy/deploy.ts
|
import { Emoji } from "../../../../constants";
import { PgCommon, PgTerminal, PgWeb3 } from "../../../../utils/pg";
import { loadConfigData, getMetaplex, loadCache } from "../../utils";
import { hashAndUpdate } from "../hash";
import { processUpdate } from "../update";
import { checkName, checkSellerFeeBasisPoints, checkSymbol } from "../validate";
export const processDeploy = async (rpcUrl: string | undefined) => {
const term = await PgTerminal.get();
// Load the cache file (this needs to have been created by the upload command)
const cache = await loadCache();
if (cache.isItemsEmpty()) {
throw new Error(
`No cache items found - run ${PgTerminal.bold(
"'sugar upload'"
)} to create the cache file first.`
);
}
// Check that all metadata information are present and have the correct length
for (const index in cache.items) {
const item = cache.items[index];
if (!item.name) {
throw new Error(`Missing name in metadata index ${index}`);
} else {
checkName(item.name);
}
if (!item.metadata_link) {
throw new Error(`Missing metadata link for cache item ${index}`);
}
}
const configData = await loadConfigData();
let candyMachinePkStr = cache.program.candyMachine;
// Check the candy machine data
const numItems = configData.size;
const hidden = configData.hiddenSettings ? 1 : 0;
const collectionInCache = cache.items["-1"] ? 1 : 0;
const cacheItemsSansCollection =
Object.keys(cache.items).length - collectionInCache;
if (!numItems.eqn(cacheItemsSansCollection)) {
throw new Error(
[
`Number of items (${numItems}) do not match cache items (${cacheItemsSansCollection}).`,
"Item number in the config should only include asset files, not the collection file.",
].join("")
);
} else {
checkSymbol(configData.symbol);
checkSellerFeeBasisPoints(configData.royalties);
}
const collectionStepNumber = !candyMachinePkStr ? collectionInCache : 0;
const totalSteps = 2 + collectionStepNumber - hidden;
const metaplex = await getMetaplex(rpcUrl);
const candyClient = metaplex.candyMachines();
let candyPubkey: PgWeb3.PublicKey;
if (!candyMachinePkStr) {
const candyKp = new PgWeb3.Keypair();
candyPubkey = candyKp.publicKey;
// Check collection, required in v3
const collectionItem = cache.items["-1"];
if (!collectionItem) {
throw new Error("Missing collection item in cache");
}
term.println(
`\n[1/${totalSteps}] ${Emoji.COLLECTION} Creating collection NFT for candy machine`
);
let collectionMintPk: PgWeb3.PublicKey;
if (collectionItem.onChain) {
term.println("\nCollection mint already deployed.");
collectionMintPk = new PgWeb3.PublicKey(cache.program.collectionMint);
} else {
// Create collection
// collectionMintPk = await createCollection(metaplex, cache, configData);
const { nft: collectionNft } = await metaplex.nfts().create({
isCollection: true,
name: collectionItem.name,
uri: collectionItem.metadata_link,
sellerFeeBasisPoints: configData.royalties,
isMutable: configData.isMutable,
creators: configData.creators,
symbol: configData.symbol,
});
collectionMintPk = collectionNft.address;
collectionItem.onChain = true;
cache.program.collectionMint = collectionMintPk.toBase58();
await cache.syncFile();
term.println(
`${PgTerminal.bold(
"Collection mint ID:"
)} ${collectionMintPk.toBase58()}`
);
}
// Create candy machine
term.println(`\n[2/${totalSteps}] ${Emoji.CANDY} Creating candy machine`);
// Save the candy machine pubkey to the cache before attempting to deploy
// in case the transaction doesn't confirm in time the next run should pickup
// the pubkey and check if the deploy succeeded
cache.program.setCandyMachine(candyPubkey);
await cache.syncFile();
await candyClient.create({
candyMachine: candyKp,
collection: {
address: collectionMintPk,
updateAuthority: metaplex.identity(),
},
itemsAvailable: configData.size,
sellerFeeBasisPoints: configData.royalties,
symbol: configData.symbol,
creators: configData.creators,
isMutable: configData.isMutable,
itemSettings: configData.hiddenSettings
? {
type: "hidden",
...configData.hiddenSettings,
// NOTE: we might not have a hash yet
hash:
configData.hiddenSettings.hash.length === 32
? configData.hiddenSettings.hash
: new Array(32).fill(0),
}
: {
// TODO: find from cache
type: "configLines",
isSequential: configData.isSequential,
prefixName: "",
nameLength: 32,
prefixUri: "",
uriLength: 200,
},
});
} else {
term.println(`[1/${totalSteps}] ${Emoji.CANDY} Loading candy machine`);
if (!PgCommon.isPk(candyMachinePkStr)) {
throw new Error(
[
`Invalid candy machine address in cache file: '${candyMachinePkStr}'.`,
"Check your cache file or run deploy to ensure your candy machine was created.",
].join(" ")
);
}
candyPubkey = new PgWeb3.PublicKey(candyMachinePkStr);
try {
await candyClient.findByAddress({
address: candyPubkey,
});
} catch {
throw new Error("Candy machine from cache does't exist on chain!");
}
}
term.println(
`${PgTerminal.bold("Candy machine ID:")} ${candyPubkey.toBase58()}`
);
// Hidden Settings check needs to be the last action in this command, so that
// we can update the hash with the final cache state.
if (!hidden) {
const stepNum = 2 + collectionStepNumber;
term.println(
`\n[${stepNum}/${totalSteps}] ${Emoji.PAPER} Writing config lines`
);
const configLineChunks = cache.getConfigLineChunks();
if (!configLineChunks[0]?.items.length) {
term.println(`\nAll config lines deployed.`);
} else {
const candy = await candyClient.findByAddress({ address: candyPubkey });
const getTotalConfigLinesUntilChunkN = (n: number) => {
return new Array(n)
.fill(null)
.reduce(
(acc, _cur, i) =>
acc + (n === i ? 0 : configLineChunks[i].items.length),
0
);
};
// Periodically save the cache
const saveCacheIntervalId = setInterval(
() => cache.syncFile(false),
5000
);
// Show progress bar
PgTerminal.setProgress(0.1);
let progressCount = 0;
const CONCURRENT = 4;
let errorCount = 0;
await Promise.all(
new Array(CONCURRENT).fill(null).map(async (_, i) => {
for (let j = 0; ; j += CONCURRENT) {
const currentChunk = configLineChunks[j + i];
if (!currentChunk) break;
try {
await candyClient.insertItems({
candyMachine: {
address: candyPubkey,
itemsAvailable: candy.itemsAvailable,
itemsLoaded: getTotalConfigLinesUntilChunkN(j + i),
// TODO: find from cache
itemSettings: {
type: "configLines",
isSequential: configData.isSequential,
prefixName: "",
nameLength: 32,
prefixUri: "",
uriLength: 200,
},
},
items: currentChunk.items,
});
for (const currentIndex of currentChunk.indices) {
cache.updateItemAtIndex(currentIndex, {
onChain: true,
});
}
} catch (e: any) {
console.log(e.message);
errorCount++;
} finally {
progressCount++;
PgTerminal.setProgress(
(progressCount / configLineChunks.length) * 100
);
}
}
})
);
// Hide progress bar
setTimeout(() => PgTerminal.setProgress(0), 1000);
// Sync and refresh the file if it's already open
clearInterval(saveCacheIntervalId);
await cache.syncFile();
if (errorCount) {
throw new Error(
`${errorCount}/${
configLineChunks.length
} of the write config line transactions has failed. Please re-run ${PgTerminal.bold(
"'sugar deploy'"
)}`
);
}
}
} else {
// If hidden settings are enabled, update the hash value with the new cache file
term.println("\nCandy machine with hidden settings deployed.");
term.println(`\nHidden settings hash: ${await hashAndUpdate()}`);
term.println("\nUpdating candy machine state with new hash value...\n");
await processUpdate(rpcUrl, undefined, candyPubkey.toBase58());
}
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/launch/launch.ts
|
import { processCreateConfig } from "../create-config";
import { processDeploy } from "../deploy";
import { processUpload } from "../upload";
import { processValidate } from "../validate";
import { processVerify } from "../verify";
import { loadConfigData } from "../../utils";
import { Emoji } from "../../../../constants";
import { PgTerminal } from "../../../../utils/pg";
export const processLaunch = async (
rpcUrl: string | undefined,
strict: boolean,
skipCollectionPrompt: boolean
) => {
const term = await PgTerminal.get();
term.println(`Starting Sugar launch... ${Emoji.LAUNCH}`);
// Config
try {
await loadConfigData();
} catch {
term.println("");
if (
await term.waitForUserInput(
"Could not load config file. Would you like to create a new config file?",
{ confirm: true, default: "yes" }
)
) {
term.println(`\n${PgTerminal.secondary(">>>")} sugar create-config\n`);
await processCreateConfig();
} else {
throw new Error("Can't continue without creating a config file.");
}
}
// Validate
term.println(`\n${PgTerminal.secondary(">>>")} sugar validate\n`);
await processValidate(strict, skipCollectionPrompt);
// Upload
term.println(`\n${PgTerminal.secondary(">>>")} sugar upload\n`);
await processUpload(rpcUrl);
// Deploy
term.println(`\n${PgTerminal.secondary(">>>")} sugar deploy\n`);
await processDeploy(rpcUrl);
// Verify
term.println(`\n${PgTerminal.secondary(">>>")} sugar verify\n`);
await processVerify(rpcUrl);
};
| 0
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
|
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/launch/index.ts
|
export * from "./launch";
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.