本地使用rust开发solana合约,并且部署上线,本地使用TypeScript与合约交互创建cargolib项目编译项目为动态库(.so)部署合约上链创建cargolib项目cargonew--libprogram-solana安装扩展cdprogram-solan
本地使用rust开发solana合约,并且部署上线,本地使用TypeScript与合约交互
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(())
}
在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
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();
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!