rust开发solana合约

本地使用rust开发solana合约,并且部署上线,本地使用TypeScript与合约交互创建cargolib项目编译项目为动态库(.so)部署合约上链创建cargolib项目cargonew--libprogram-solana安装扩展cdprogram-solan

本地使用rust开发solana合约,并且部署上线,本地使用TypeScript与合约交互

  1. 创建cargo lib项目
  2. 编译项目为动态库(.so)
  3. 部署合约上链

创建cargo lib项目

cargo new --lib program-solana

安装扩展

cd program-solana
cargo add borsh  # 安装开源包,二进制编码包
cargo add solana-program # solana开发包

编写合约

use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

// declare and export the program's entrypoint
entrypoint!(process_instruction);

// program entrypoint's implementation
pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8]
) -> ProgramResult {
    // log a message to the blockchain
    msg!("Hello, world!");

    // gracefully exit the program
    Ok(())
}

编译rust合约为动态库(.so文件)

在cargo.toml添加

[lib]
name = "program_solana"
crate-type = ["cdylib", "lib"]

编译合约

cargo build-bpf  # 会在target/deploy/program_solana.so文件

部署合约上链

solana program deploy target/deploy/program_solana.so
Program Id: 5HHcKZifkrLLXLasmJCrV738GkXWTbw7UWbka3xH8Gff

image.png

合约交互

import solanaWeb3 from '@solana/web3.js';
import fs from 'fs';

const TESTNET_URL = "https://api.devnet.solana.com"
const TOKEN_PROGRAM_ID = new solanaWeb3.PublicKey('5HHcKZifkrLLXLasmJCrV738GkXWTbw7UWbka3xH8Gff');

const keyPairJson = JSON.parse(fs.readFileSync('/Users/admin/.config/solana/id.json', 'utf-8'));
const payer = solanaWeb3.Keypair.fromSecretKey(new Uint8Array(keyPairJson));
// 创建连接和相关的密钥对
const connection = new solanaWeb3.Connection(TESTNET_URL);

class HelloProgram {
    public ProgramId:solanaWeb3.PublicKey
    constructor() {
        this.ProgramId = TOKEN_PROGRAM_ID
    }
    public createHelloData() :Buffer {
        return Buffer.from([0]);
    }
}

async function main() {
    // 创建交易
    const transaction = new solanaWeb3.Transaction();
    console.log("address:", payer.publicKey.toBase58());
     // 创建指令
    const instructionData =  new HelloProgram().createHelloData(); // instructionId 是一个标识方法的数字,args 是方法参数的字节表示。需要根据实际的智能合约进行构造。
    const instruction = new solanaWeb3.TransactionInstruction({
        keys: [{ pubkey: payer.publicKey, isSigner: false, isWritable: true }],
        programId: TOKEN_PROGRAM_ID,
        data: instructionData, 
     });
    // 将指令添加到交易中
    transaction.add(instruction);

     // 为交易签名
     const { blockhash,lastValidBlockHeight } = await connection.getLatestBlockhash("finalized");
     transaction.recentBlockhash = blockhash
     transaction.sign(payer);

      // 发送交易
    const txid = await connection.sendRawTransaction(transaction.serialize());
    console.log('Transaction sent:', txid);
}

main();
  • 原创
  • 学分: 36
  • 分类: Solana
  • 标签:
点赞 2
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
runtoweb3.com
runtoweb3.com
0x5F12...732b
江湖只有他的大名,没有他的介绍。