Solana开发学习笔记(一)——从Hello World出发

时间:2024-06-18  分类:电子
);
consttransaction=newTransaction().add(
SystemProgram.createAccountWithSeed({
fromPubkey:payer.publicKey,
basePubkey:payer.publicKey,
seed:GREETING_SEED,
newAccountPubkey:greetedPubkey,
lamports,
space:GREETING_SIZE,
programId,
}),
);
awaitsendAndConfirmTransaction(connection,transaction,[payer]);
}
}

客户端再调用sayHello函数向链上程序发送交易。一个交易可以包含一个或多个不同的指令,当前该交易包含了一个指令,指令中带有要调用链上程序的ProgramId以及客户端要交互的账户地址。需要注意的是,如果交易中包含多个不同的指令,其中有一个指令执行失败,那么所有指令所做的操作都会被还原。


exportasyncfunctionsayHello():Promise<void>{
console.log(Sayinghelloto,greetedPubkey.toBase58());
constinstruction=newTransactionInstruction({
keys:[{pubkey:greetedPubkey,isSigner:false,isWritable:true}],
programId,
data:Buffer.alloc(0),//Allinstructionsarehellos
});
awaitsendAndConfirmTransaction(
connection,
newTransaction().add(instruction),
[payer],
);
}

最后,客户端调用reportGreetings函数访问账户数据,查询链上程序被有效调用的次数。


exportasyncfunctionreportGreetings():Promise<void>{
constaccountInfo=awaitconnection.getAccountInfo(greetedPubkey);
if(accountInfo===null){
throwError:cannotfindthegreetedaccount;
}
constgreeting=borsh.deserialize(
GreetingSchema,
GreetingAccount,
accountInfo.data,
);
console.log(
greetedPubkey.toBase58(),
hasbeengreeted,
greeting.counter,
time(s),
);
}

1.3.2HelloWorld构建与部署


1.创建项目


使用gitclone命令下载example-helloworld项目。


gitclonehttps://github.net/solana-labs/example-helloworld.git
cdexample-helloworld

2.构建链上程序


运行以下命令,在program-rust目录下构建链上程序。


cdsrc/program-rust/
cargobuild-bpf

构建完成后,src/program-rust/target/deploy目录下的helloworld.so就是可在Solana集群部署的链上程序的BPF字节码文件。


3.启动本地集群


当前项目在本地集群部署运行,因此首先选择localhost集群,运行以下命令。


solanaconfigset--urllocalhost

本地集群设置成功,会出现以下内容。


ConfigFile:~/.config/solana/cli/config.yml
RPCURL:http://localhost:8899. WebSocketURL:ws://localhost:8900/(computed)
KeypairPath:~/.config/solana/id.json
Commitment:confirmed

再运行以下命令,启动localhost集群。


solana-test-validator

看到以下内容,代表本地集群已成功启动。


Ledgerlocation:test-ledger
Log:test-ledger/validator.log
Identity:A4HuRgmABNCe94epY2mU7q6WqEHCo2B9iBFE5Yphiw5u
GenesisHash:96TF9n1uuyFv4rAKECffA61jLrgYjMjNRZ3hJpP6HSr7. Version:1.7.18. ShredVersion:13390. GossipAddress:127.0.0.1:1024. TPUAddress:127.0.0.1:1027. JSONRPCURL:http://127.0.0.1:8899. ⠉00:00:42|ProcessedSlot:45430|ConfirmedSlot:45430|FinalizedSlot:45398|SnapshotSlot:45300|Transactions:45452|◎499.772930000.

4.部署链上程序


运行以下命令,在localhost集群部署链上程序。


solanaprogramdeploytarget/deploy/helloworld.so
//ProgramId:6AArMEBpFhhtU2mBnEMEPeEH7xkhfUwPseUeG4fhLYto

链上程序部署成功会返回ProgramId,它类似于以太坊智能合约的地址。


5.调用链上程序


helloworld已成功部署,可以与它进行交互了!example-helloworld项目提供了一个简单的客户端,在运行客户端之前先安装依赖软件包。


npminstall

由于我们调整了链上程序的构建方式,没有使用该项目默认的npmrunbuild:program-rust命令,因此需要修改client目录下的hello_world.ts文件,将第48行代码定义的变量PROGRAM_PATH的路径由../../dist/program改为../program-rust/target/deploy。再运行以下命令,启动客户端去调用链上程序。


npmrunstart

客户端成功调用链上程序,输出内容如下所示。如果再次运行客户端,第10行所显示的次数会加一。至此,我们已经成功在Solana集群部署链上程序并与之交互了。


>helloworld@0.0.1start
>ts-nodesrc/client/main.ts
LetssayhellotoaSolanaaccount...
Connectiontoclusterestablished:http://localhost:8899{feature-set:3179062686,solana-core:1.6.23}
Usingaccount4xRm2FYmRB8WdxJk6nXicVMgsPnsxChEnpQwFDGwdcSScontaining499999999.93435186SOLtopayforfees
Usingprogram6AArMEBpFhhtU2mBnEMEPeEH7xkhfUwPseUeG4fhLYto
CreatingaccountEq7bcsg5p6AaYiPnfiia99ESsuq4B4jYpVbWZhQ94Zvytosayhelloto
SayinghellotoEq7bcsg5p6AaYiPnfiia99ESsuq4B4jYpVbWZhQ94Zvy
Eq7bcsg5p6AaYiPnfiia99ESsuq4B4jYpVbWZhQ94Zvyhasbeengreeted1time(s)
Success

如果没有输出期望值,请首先确认是否已正确启动了本地集群,构建并部署好了链上程序。此外,可以运行以下命令查看程序日志,日志包括程序日志消息以及程序失败信息。


solanalogs

包含程序失败信息的日志如下所示,检查日志找出程序失败的原因。


<imgsrc="https://learnblockchain.cn/css/default/copy.svg"/><code>Transactionexecutedinslot5621:
Signature:4pya5iyvNfAZj9sVWHzByrxdKB84uA5sCxLceBwr9UyuETX2QwnKg56MgBKWSM4breVRzHmpb1EZQXFPPmJnEtsJ
Status:ErrorprocessingInstruction0:Programfailedtocomplete
LogMessages:
ProgramG5bbS1ipWzqQhekkiCLn6u7Y1jJdnGK85ceSYLx2kKbAinvoke[1]
Programlog:HelloWorldRustprogramentrypoint
ProgramG5bbS1ipWzqQhekkiCLn6u7Y1jJdnGK85ceSYLx2kKbAconsumed200000of200000computeunits
Programfailedtocomplete:exceededmaximumnumberofinstructionsallowed(200000)atinstruction#334. ProgramG5bbS1ipWzqQhekkiCLn6u7Y1jJdnGK85ceSYLx2kKbAfailed:Programfailedtocomplete

1.4本章小节


本章对Solana区块链的基本概念进行了简要介绍,Solana的智能合约叫做链上程序。在开始Solana链上程序开发之前,需要先安装和配置相关的编程环境,我们着重介绍了SolanaCLI的安装和配置。


HelloWorld是一个官方演示项目,通过对这个项目源码的解读,我们了解了如何使用Rust开发链上程序,并使用SolanaCLI来构建与部署,以及使用SolanaJavaScriptSDK与链上程序进行交互。



-->> 3/3 文章结束,返回第一页

以上就是Solana开发学习笔记(一)——从Hello World出发的全部内容,望能这篇Solana开发学习笔记(一)——从Hello World出发可以帮助您解决问题,能够解决大家的实际问题是非常好学习网一直努力的方向和目标。