Created
February 11, 2022 12:44
-
-
Save Nithsua/28dfaf2a5e9618b34e96c4e5be92690e to your computer and use it in GitHub Desktop.
Minting NFT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use anchor_lang::prelude::*; | |
use anchor_spl::token::{self, InitializeAccount, InitializeMint, MintTo, SetAuthority, Transfer}; | |
declare_id!(""); | |
#[program] | |
pub mod neft { | |
use super::*; | |
pub fn create_nft(ctx: Context<CreateNFT>, authority: Pubkey) -> ProgramResult { | |
ctx.accounts.initialize_token(authority); | |
ctx.accounts.create_token_account(); | |
ctx.accounts.mint_token(); | |
ctx.accounts.set_token_authority(); | |
Ok(()) | |
} | |
} | |
#[derive(Accounts)] | |
pub struct CreateNFT<'info> { | |
#[account(mut)] | |
pub mint: AccountInfo<'info>, | |
pub to: AccountInfo<'info>, | |
#[account(signer)] | |
pub authority: AccountInfo<'info>, | |
pub token_program: AccountInfo<'info>, | |
pub rent: AccountInfo<'info>, | |
} | |
impl<'info> CreateNFT<'info> { | |
fn initialize_token(&self, authority: Pubkey) -> ProgramResult { | |
let token_accounts = InitializeMint { | |
mint: self.mint.clone(), | |
rent: self.rent.clone(), | |
}; | |
let result = token::initialize_mint( | |
CpiContext::new(self.token_program.clone(), token_accounts), | |
0, | |
&authority, | |
None, | |
); | |
result | |
} | |
fn create_token_account(&self) -> ProgramResult { | |
let token_accounts = InitializeAccount { | |
account: self.to.clone(), | |
mint: self.mint.clone(), | |
authority: self.authority.clone(), | |
rent: self.rent.clone(), | |
}; | |
let result = | |
token::initialize_account(CpiContext::new(self.token_program.clone(), token_accounts)); | |
result | |
} | |
fn mint_token(&self) -> ProgramResult { | |
let token_accounts = MintTo { | |
authority: self.authority.clone(), | |
mint: self.mint.clone(), | |
to: self.to.clone(), | |
}; | |
let result = token::mint_to( | |
CpiContext::new(self.token_program.clone(), token_accounts), | |
1, | |
); | |
result | |
} | |
fn set_token_authority(&self) -> ProgramResult { | |
let token_accounts = SetAuthority { | |
current_authority: self.authority.clone(), | |
account_or_mint: self.mint.clone(), | |
}; | |
let result = token::set_authority( | |
CpiContext::new(self.token_program.clone(), token_accounts), | |
spl_token::instruction::AuthorityType::MintTokens, | |
None, | |
); | |
result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment