首页 > 其他分享 >新一代公链代表Solana(9) --- 如何用VS Code开发Solana智能合约

新一代公链代表Solana(9) --- 如何用VS Code开发Solana智能合约

时间:2024-04-07 21:30:32浏览次数:17  
标签:cargo account Solana VS --- program helloworld solana luca

Solana智能合约可以使用Rust编写,所以要学习使用VS Code开发Solana智能合约,首先你得掌握如何在VS Code上面编写Rust程序。这里同学们可以参考之前的文章:

Rust开发环境搭建Visual Studio Code

Rust从入门到暴走系列

1.创建工程

在自己的workspace下,用cargo创建一个项目, 进入项目目录,添加Solana SDK依赖

luca@LucadeMacBook-Air rust-workspace % cargo new  --lib helloworld                      
     Created library `helloworld` package
luca@LucadeMacBook-Air rust-workspace % 
luca@LucadeMacBook-Air rust-workspace % cd helloworld 
luca@LucadeMacBook-Air helloworld % 
luca@LucadeMacBook-Air helloworld % cargo add solana-program
    Updating crates.io index
      Adding solana-program v1.18.9 to dependencies.
    Updating crates.io index

用VS Code打开项目
在这里插入图片描述

2.编写合约代码

在 src/lib.rs文件中,填入如下合约代码:

use solana_program::{
    account_info::{AccountInfo, next_account_info},
    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, // Public key of the account the hello world program was loaded into
    accounts: &[AccountInfo], // The account to say hello to
    _instruction_data: &[u8], // Ignored, all helloworld instructions are hellos
) -> ProgramResult {

    // Iterating accounts is safer than indexing
    let accounts_iter = &mut accounts.iter();

    // Get the account to say hello to
    let account = next_account_info(accounts_iter)?;
            
    msg!("Hello World Rust program entrypoint from {}", account.key);

    Ok(())
}

3.构建项目

在Cargo.toml中添加:

[features]
no-entrypoint = []

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

修改后的Cargo.toml完整配置为

[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
solana-program = "1.18.9"

[features]
no-entrypoint = []

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

构建:

luca@LucadeMacBook-Air helloworld % cargo build-sbf
   Compiling proc-macro2 v1.0.79
   Compiling unicode-ident v1.0.12
   Compiling version_check v0.9.4
   .........................
   Compiling bincode v1.3.3
   Compiling helloworld v0.1.0 (/Users/luca/dev/rust-workspace/helloworld)
    Finished release [optimized] target(s) in 34.78s

生成deploy文件
在这里插入图片描述

但是同学们可能会遇到这个报错:

luca@LucadeMacBook-Air helloworld % cargo-build-sbf
error: package `solana-program v1.18.9` cannot be built because it requires rustc 1.75.0 or newer, while the currently active rustc version is 1.68.0-dev
Either upgrade to rustc 1.75.0 or newer, or use
cargo update -p [email protected] --precise ver
where `ver` is the latest version of `solana-program` supporting rustc 1.68.0-dev

然后你会检查自己的Rust版本,是1.77.1,高于1.75.0。

luca@LucadeMacBook-Air helloworld % rustc -V
rustc 1.77.1 (7cf61ebde 2024-03-27)

这个时候你可能会陷入疑惑。但其实cargo-build-sbf使用的是自带的rustc版本1.68.0,不会使用默认的rust版本

luca@LucadeMacBook-Air helloworld % cargo-build-sbf --version
solana-cargo-build-sbf 1.17.25
platform-tools v1.37
rustc 1.68.0

我们可以考虑升级一下,然后就可以正常构建了

solana-install init 1.18.9

4.发布智能合约

设置testnet

luca@LucadeMacBook-Air helloworld % solana config set --url https://api.testnet.solana.com  
Config File: /Users/luca/.config/solana/cli/config.yml
RPC URL: https://api.testnet.solana.com 
WebSocket URL: wss://api.testnet.solana.com/ (computed)
Keypair Path: /Users/luca/.config/solana/id.json 
Commitment: confirmed

发布合约

solana program deploy /Users/luca/dev/rust-workspace/helloworld/target/deploy/helloworld.so

Program Id: BiEjWMFBfRCup21wQMcC7TxioLQZcnFxBXWKSxZoGV1Q

查看浏览器记录:
https://solscan.io/account/BiEjWMFBfRCup21wQMcC7TxioLQZcnFxBXWKSxZoGV1Q?cluster=devnet
在这里插入图片描述

5.Rust客户端测试

Cargo.toml

[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
solana-program = "1.18.9"
solana-sdk = "1.18.9"
solana-rpc-client = "1.18.9"
bs58 = "0.5.0"

lib.rs

use std::str::FromStr;

use solana_sdk::signature::Signer;
use solana_rpc_client::rpc_client;
use solana_sdk::signer::keypair;
use solana_sdk::transaction;
use solana_program::instruction;
use solana_program::pubkey;

const RPC_ADDR: &str = "https://api.devnet.solana.com";


fn main() {
    let helloworld = pubkey::Pubkey::from_str("BiEjWMFBfRCup21wQMcC7TxioLQZcnFxBXWKSxZoGV1Q").unwrap();
    
    let me = keypair::Keypair::from_base58_string("UtwQ...es0");
    println!("me is {}", me.pubkey());

    let client = rpc_client::RpcClient::new(RPC_ADDR);

    let account_metas = vec![
        instruction::AccountMeta::new(me.pubkey(), true),
    ];

    let instruction = instruction::Instruction::new_with_bytes(
        helloworld,
        "hello".as_bytes(),
        account_metas,
    );
    let ixs = vec![instruction];

    let latest_blockhash = client.get_latest_blockhash().unwrap();
    let sig = client.send_and_confirm_transaction(&transaction::Transaction::new_signed_with_payer(
        &ixs,
        Some(&me.pubkey()),
        &[&me],
        latest_blockhash,
    )).unwrap();

    println!("tx:{}", sig);
}

运行结果:

me is E3NAyseUZrgwSbYe2g47TuFJr5CxAeneK63mR4Ufbqhh
tx:W9aMuL8LGRwYRx2Xge4jj71i4ggcZVLMJairjn11T77qhZkg81YJ9HkKHW4x3ws5CPrXcTTxUmtveZkSPKyqXCR

查看浏览器:
https://solscan.io/tx/W9aMuL8LGRwYRx2Xge4jj71i4ggcZVLMJairjn11T77qhZkg81YJ9HkKHW4x3ws5CPrXcTTxUmtveZkSPKyqXCR?cluster=devnet
在这里插入图片描述

标签:cargo,account,Solana,VS,---,program,helloworld,solana,luca
From: https://blog.csdn.net/qiangyipan1900/article/details/137395917

相关文章

  • VS2019+open CV4.5.5的配置
    1.去openCV的官网下载对应版本:OpenCV-OpenComputerVisionLibrary2.右击此电脑--属性--高级系统设置--环境变量--点击变量Path的右边进行新建分别输入:D:\opencv\opencv\build\x64\vc15\binD:\opencv\opencv\build\x64\vc14\bin%OPENCV_DIR%\bin3.打开op......
  • 【51单片机入门记录】RTC(实时时钟)-DS1302应用
    目录一、DS1302相关写函数(1)Write_Ds1302(2)Write_Ds1302_Byte二、DS130相关数据操作流程及相关代码(1)DS1302初始化数据操作流程及相关代码(shijian[i]/10<<4)|(shijian[i]%10)的作用:将十进制转换为BCD码。代码呈现(2)DS1302获取数据操作流程及相关代码代码呈现三、应用举例-......
  • 2-42. 场景切换淡入淡出和动态 UI 显示
    添加Canvas添加FadePanel通过修改CanvasGroup的Alpha就能隐藏或者显示FadePanel在FadePanel下面添加文字和动画动画图片如下图所示切换场景时淡入淡出修改Settings修改Player解决摄像机抖动问题修改Bounds范围项目相关代码代码仓库:https:/......
  • 前端【VUE】06-vue【组件组成】【组件通信】【进阶语法】
    一、组件的三大组成部分(结构/样式/逻辑)组件的三大组成部分组件的样式冲突scoped1、components目录下components/BaseOne.vue1<template>2<divclass="base-one">3BaseOne4</div>5</template>67<script>8exportdefault{9......
  • 1.数据类型-----内建数据类型
    内建数据类型:相比于verilog中的reg和wire之外,sv中新推出了logic类型:在sv中与logic相对应的是bit类型,他们均可以构建矢量类型(vector),他们的区别在于:logic为四值逻辑,既可以表示0、1、x、z。bit为二值逻辑,只可以表示1、0。为什么sv在一开始做设计的时候有4值了还要引入二值呢?:::......
  • 8.1 使用 rpm 命令-安装-查看-卸载-rpm 软件包
    8.1软件包的管理软件包的类型rpm二进制包------》已经使用GCC编译后的rpm概述:RPM是RedHatPackageManager(RPM软件包管理器)的缩写,这一文件格式名称虽然打上了RedHat的标志,但是其原始设计理念是开放式的,现在包括OpenLinux、SUSE以及TurboLi......
  • C语言06-数组、函数
    第10章数组10.1数组的概念①数组四要素(1)数组名:本质上是一个标识符常量,命名需要符合标识符规范。(2)元素:同一个数组中的元素必须是相同的数据类型。(3)下标(索引、角标):从0开始的连续数字。(4)数组的长度:表示元素的个数。②C语言数组特点(不用记)(1)创建数组时会在内存中开辟......
  • VS Code 使用技巧
    VSCode使用技巧1.常用快捷键自动格式化 Shift+Alt+F向下复制行 Shift+Alt+下箭头,可以改成Ctrl+D选中多个 Alt+鼠标点击切换单行注释 Ctrl+/切换多行注释Shitf+Alt+A可以改成Ctrl+Shift+/Ctrl+/ ——同时多个单行注释Shift+Alt+f——给整篇代码对齐shi......
  • 通讯录----顺序表版本
    1.通讯录的实现逻辑对于通讯录,我们做的无非就是初始化,销毁。添加联系人数据,修改联系人数据,删除联系人数据,查找联系人数据,展示联系人数据;这个不就和我们的顺序表的逻辑如出一辙吗,顺序表实现的功能不就是数据的初始化,修改,删除(头删和尾删),添加(头插和尾插),顺序表的打印,这些我们是可......
  • Python基础篇-Python基础01
    Python基础-day1!!!注意:本系列所写的文章全部是学习笔记,来自于观看视频的笔记记录,防止丢失。观看的视频笔记来自于:哔哩哔哩武沛齐老师的视频:2022Python的web开发(完整版)入门全套教程,零基础入门到项目实战1.文档工具typora2.环境搭建安装Python解释器学习Python语法Python......