使用Anchor在Solana中创建智能合约
October 24th, 2022

直接上干货。

Anchor是Solana的Sealevel运行时框架工具,提供方便的开发支持。例如:

  • IDL(接口定义语言)规范

  • Rust 工具箱和eDSL(嵌入式域特定语言)- 用于编写Solana程序

  • 从IDL生成客户端的TypeScript包

  • CLI和工作区管理帮助开发完整的应用程序。

开始前先让我们熟悉一些术语:

  1. Rust:Rust是一种卓越的多用途编程语言,将用于开发智能合约。

  2. Solana工具套件:包括命令行界面CLI。

首先,我们需要创建一个新的 Anchor 项目:

anchor init counterapp

您应该会在项目结构中看到以下文件和文件夹:

  • program:智能合约所在的目录或位置

  • test:Javascript测试代码

  • migrations:启动脚本

  • app:前端应用程序构建目录

现在,让我们从程序目录中找到lib.rs文件。

declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

#[program]
pub mod counterapp {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>) -> ProgramResult {       
        Ok(())
    }
}
#[derive(Accounts)]
pub struct Initialize {}

这是最简单的CLI程序。它有一个初始化函数,当调用应用程序时,该函数会成功执行。“Initialize”结构体定义了“initialize”函数的上下文。

完成项目设置后,下一步是创建我们的计数器应用程序。为了实现这一目标,我们必须先建立一个帐户来保存数据。帐户用于在Solana Sealevel存储和检索数据。

回想一下,我们已经定义了两个结构:CounterAccount结构体是我们的帐户信息,它包含将存储计数的变量。

#[derive(Accounts)]
pub struct Create<'info> {
    
    #[account(init, payer=user, space = 16+16)]
    pub counter_account: Account<'info, CounterAccount>,
    
    #[account(mut)]
    pub user: Signer<'info>,
    
    pub system_program: Program<'info, System>,
}
#[account]
pub struct CounterAccount {
    pub count: u64,
}

Create结构是定义创建帐户上下文的指令结构。

[account (…) ] 定义在构建上下文时Anchor 预处理的指令和约束。

接下来创建我们的函数:

pub fn create(ctx: Context<Create>) -> ProgramResult {
    let counter_account = &mut ctx.accounts.counter_account;
    counter_account.count = 0;
    Ok(())
}

create函数是RPC请求处理程序,上下文是Create 结构体。

现在已经完成了功能实现,让我们编写测试函数并启动我们的智能合约。

import * as anchor from '@project-serum/anchor';
import { Program } from '@project-serum/anchor';
import { Counterapp } from '../target/types/counterapp';
describe('counterapp', () => {    
    const provider = anchor.Provider.env()
anchor.setProvider(provider);    
const program = anchor.workspace.Counterapp as Program<Counterapp>;    
const counterAccount = anchor.web3.Keypair.generate();    
it('Is initialized!', async () => {
        await program.rpc.create({
            accounts: {
                counterAccount: counterAccount.publicKey,
                user: provider.wallet.publicKey,
                systemProgram: anchor.web3.SystemProgram.programId,
            },
            signers: [counterAccount]
        } as any)
});    
it("Increment counter", async () => {
        await program.rpc.increment({
            accounts: {
                counterAccount: counterAccount.publicKey
            }
        } as any)
})    
it("Fetch account", async () => {
        const account: any = await
        program.account.counterAccount.fetch(counterAccount.publicKey)
        console.log(account.count)
    })
});

现在,运行测试。

anchor test

测试通过后,我们可以部署并启动程序。

确保 solana-test-validator  正在运行。

anchor deploy
Subscribe to cryptozyh.eth
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from cryptozyh.eth

Skeleton

Skeleton

Skeleton