Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active August 30, 2022 17:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabit3/c97d07aeef0a119763fc3f35c3cdd54a to your computer and use it in GitHub Desktop.
Save dabit3/c97d07aeef0a119763fc3f35c3cdd54a to your computer and use it in GitHub Desktop.
Example blog program - Anchor, Solana, and Rust
use anchor_lang::prelude::*;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod blog {
use super::*;
pub fn create_blog(ctx: Context<CreateBlog>, name: String, bump: u8) -> Result<()> {
ctx.accounts.blog.name = name;
ctx.accounts.blog.authority = *ctx.accounts.authority.key;
ctx.accounts.blog.bump = bump;
Ok(())
}
pub fn create_post(ctx: Context<CreatePost>, id: String) -> Result<()> {
let given_id = id.as_bytes();
let mut id = [0u8; 280];
id[..given_id.len()].copy_from_slice(given_id);
let mut post = ctx.accounts.post.load_init()?;
post.id = id;
Ok(())
}
pub fn add_post(ctx: Context<AddPost>, msg: String) -> Result<()> {
let mut post = ctx.accounts.post.load_mut()?;
post.append({
let src = msg.as_bytes();
let mut data = [0u8; 280];
data[..src.len()].copy_from_slice(src);
Item {
from: *ctx.accounts.blog.to_account_info().key,
data,
}
});
Ok(())
}
}
#[derive(Accounts)]
#[instruction(name: String, bump: u8)]
pub struct CreateBlog<'info> {
#[account(
init,
seeds = [authority.key().as_ref()],
bump = bump,
payer = authority,
space = 320,
)]
blog: Account<'info, Blog>,
#[account(signer)]
authority: AccountInfo<'info>,
system_program: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct CreatePost<'info> {
#[account(zero)]
post: Loader<'info, Post>,
}
#[derive(Accounts)]
pub struct AddPost<'info> {
#[account(
seeds = [authority.key().as_ref()],
bump = blog.bump,
has_one = authority,
)]
blog: Account<'info, Blog>,
#[account(signer)]
authority: AccountInfo<'info>,
#[account(mut)]
post: Loader<'info, Post>,
}
#[account]
pub struct Blog {
name: String,
authority: Pubkey,
bump: u8,
}
#[account(zero_copy)]
pub struct Post {
head: u64,
tail: u64,
id: [u8; 280], // Human readable name (char bytes).
items: [Item; 33607], // Leaves the account at 10,485,680 bytes.
}
impl Post {
fn append(&mut self, item: Item) {
self.items[Post::index_of(self.head)] = item;
if Post::index_of(self.head + 1) == Post::index_of(self.tail) {
self.tail += 1;
}
self.head += 1;
}
fn index_of(counter: u64) -> usize {
std::convert::TryInto::try_into(counter % 33607).unwrap()
}
}
#[zero_copy]
pub struct Item {
pub from: Pubkey,
pub data: [u8; 280],
}
#[error]
pub enum ErrorCode {
Unknown,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment