Solana web3.js使用!

  • dlnuchunge
  • 更新于 2024-04-17 13:06
  • 阅读 3542

前端如果想和Solana链交互的话,可以使用Solanaweb3.jsnpm指令安装一下就可以了npminstall@solana/web3.js

前端如果想和Solana链交互的话,可以使用Solana web3.js npm指令安装一下就可以了
npm install @solana/web3.js

1、查询SOL余额

    let connect = new Connection(clusterApiUrl('devnet'));  //先链接集群网络,我链的devnet
    let secretKey = Uint8Array.from([254, 233, 47, 184, 38, 87, 109, 215, 23, 19, 232, 58, 158, 100, 20, 113, 114, 166, 245, 54, 156, 124, 150, 200, 102, 168, 189, 23, 167, 217, 250, 37, 4, 250, 253, 205, 123, 153, 120, 40, 76, 97, 155, 241, 245, 242, 16, 124, 107, 84, 183, 155, 167, 20, 153, 15, 155, 181, 72, 219, 246, 224, 14, 112])
    let pay = Keypair.fromSecretKey(secretKey); //导入账号
    let balance = await connect.getBalance(pay.publicKey); //查询余额,默认是lamports
    console.log("balance", `${balance / LAMPORTS_PER_SOL}Sol`);  //打印SOL余额(10亿lamports = 1SOL)

2、转账SOL

solana交易的最小单位是指令,一笔交易可以有多个指令。 转账就是一个指令,可以通过SystemProgram.transfer生成转账的指令。

   let toPubkey = new PublicKey("B2V5kYvGyBGyoYvFJzYJh8ighH2Hn6FdM8xxgqMq9cbK");
   //生成转账指令
   let instruction = SystemProgram.transfer({
        fromPubkey: pay.publicKey,  //转出账户公钥
        toPubkey: toPubkey,   //转入账号公钥
        lamports: 10000000,  //数量(10亿lamports = 1SOL)
    })

    //获取最近区块信息,交易里面需要
    let latestBlockhash = await connect.getLatestBlockhash();
    let messageV0 = new TransactionMessage({
        payerKey: pay.publicKey,  //付gas费账户公钥
        recentBlockhash: latestBlockhash.blockhash,  
        instructions: [instruction]  //把指令添加到指令数组
    }).compileToV0Message();

    //生成交易,现在都用VersionedTransaction, Transaction类型已经不用了
    let transaction= new VersionedTransaction(messageV0);
    transaction.sign([pay]);  //签名
    let result = await connect.sendTransaction(transaction); //发起交易
    console.log("result", result);

3、与链上合约(程序)交互

我先发一个最简单的Hello world程序到solana链上。 程序地址是 4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1 。 1713260322858.jpg

和程序交互的话,和转账流程差不多,都是发起一笔交易, 只不过指令需要自己构建一下。

    let key1 = {pubkey: pay.publicKey, isSigner: false, isWritable: false}
    let data = Buffer.from([0]);
    let instruction2 = new TransactionInstruction({
      programId: new PublicKey("4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1"), //程序地址
      keys: [key1], //合约里面使用的账号信息
      data: data,  //传给合约的参数
    })

    let messageV0 = new TransactionMessage({
      payerKey: pay.publicKey,
      recentBlockhash: latestBlockhash.blockhash,
      instructions: [instruction2]
    }).compileToV0Message();

    let t = new VersionedTransaction(messageV0);
    t.sign([pay]);
    let result2 = await connect.sendTransaction(t);  //返回交易哈希
    console.log("result", result2);  

可通过浏览器查看交易https://solscan.io/tx/JUPxVeREzv4mmhmtTVGjY2GXx9fMsds1RiARDoHeP3ko4SQgd5yZtQk53QSWCgoM2oBP6yjd1BM4p2Faso8ahh2?cluster=devnet 1713256292326.png

4、监听某个账户

如果你想监听链上某个账户,可以使用onAccountChange方法, 监听的话,需要websocket链接,可以使用免费测试节点 wss://docs-demo.solana-devnet.quiknode.pro/ wss://docs-demo.solana-testnet.quiknode.pro/ wss://docs-demo.solana-mainnet.quiknode.pro/

let connect = new Connection(clusterApiUrl('devnet'), {wsEndpoint:"wss://docs-demo.solana-devnet.quiknode.pro/"});
let secretKey = Uint8Array.from([254, 233, 47, 184, 38, 87, 109, 215, 23, 19, 232, 58, 158, 100, 20, 113, 114, 166, 245, 54, 156, 124, 150, 200, 102, 168, 189, 23, 167, 217, 250, 37, 4, 250, 253, 205, 123, 153, 120, 40, 76, 97, 155, 241, 245, 242, 16, 124, 107, 84, 183, 155, 167, 20, 153, 15, 155, 181, 72, 219, 246, 224, 14, 112])
let pay = Keypair.fromSecretKey(secretKey);
connect.onAccountChange(
    pay.publicKey, //监听的账户
    (updatedAccountInfo, context) =>{  //回调方法
       console.log("Updated account info: ", updatedAccountInfo);
    },
    "confirmed"
);
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

2 条评论

请先 登录 后评论
dlnuchunge
dlnuchunge
0x0d2e...8b3F
看好Web3,自学Web3前端,想找份Web3相关工作!