solana项目counter,测试过程中执行报错记录分享

news2024/9/20 21:20:40

跟随HackQuest部署counter项目,使用 Solana 官方提供的 playgroud 。这个平台让我们的部署和测试过程变得更加简便高效。

合约代码

lib.rs中复制以下代码

use anchor_lang::prelude::*;
use std::ops::DerefMut;

declare_id!("CVQCRMyzWNr8MbNhzjbfPu9YVvr97onF48Lc9ZwXotpW");

#[program]
pub mod counter {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        let counter = ctx.accounts.counter.deref_mut();
        let bump = ctx.bumps.counter;

        *counter = Counter {
            authority: *ctx.accounts.authority.key,
            count: 0,
            bump,
        };

        Ok(())
    }

    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        require_keys_eq!(
            ctx.accounts.authority.key(),
            ctx.accounts.counter.authority,
            ErrorCode::Unauthorized
        );

        ctx.accounts.counter.count += 1;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        payer = authority,
        space = Counter::SIZE,
        seeds = [b"counter"],
        bump
    )]
    counter: Account<'info, Counter>,
    #[account(mut)]
    authority: Signer<'info>,
    system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Increment<'info> {
    #[account(
        mut,
        seeds = [b"counter"],
        bump = counter.bump
    )]
    counter: Account<'info, Counter>,
    authority: Signer<'info>,
}

#[account]
pub struct Counter {
    pub authority: Pubkey,
    pub count: u64,
    pub bump: u8,
}

impl Counter {
    pub const SIZE: usize = 8 + 32 + 8 + 1;
}

#[error_code]
pub enum ErrorCode {
    #[msg("You are not authorized to perform this action.")]
    Unauthorized,
}

交换代码

client.ts中复制以下代码

const wallet = pg.wallet;
const program = pg.program;
const counterSeed = Buffer.from("counter");

const counterPubkey = await web3.PublicKey.findProgramAddressSync(
  [counterSeed],
  pg.PROGRAM_ID
);

const initializeTx = await pg.program.methods
  .initialize()
  .accounts({
    counter: counterPubkey[0],
    authority: pg.wallet.publicKey,
    systemProgram: web3.SystemProgram.programId,
  })
  .rpc();

let counterAccount = await program.account.counter.fetch(counterPubkey[0]);
console.log("account after initializing ==> ", Number(counterAccount.count));

const incrementTx = await pg.program.methods
  .increment()
  .accounts({
    counter: counterPubkey[0],
    authority: pg.wallet.publicKey,
  })
  .rpc();

counterAccount = await program.account.counter.fetch(counterPubkey[0]);
console.log("account after increasing ==>", Number(counterAccount.count));

部署和发布

  • 切换到左侧工具栏第二个按钮并点击 build
  • 点击deploy, 终端出现 “Deployment successful.” 即为部署成功。(这大约会消耗2~3个sol)

测试交互

切换到左侧第一个文件按钮并点击 Run ,运行client.ts文件,输出如图
在这里插入图片描述

再次执行就会开始报错

Running client…
client.ts:
Uncaught error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: custom program error: 0x0

各种求助之后,修改初始化代码,输出报错日志

try {
    // Initialize account
    const initializeTx = await pg.program.methods
      .initialize()
      .accounts({
        counter: counterPubkey,
        authority: pg.wallet.publicKey,
        systemProgram: web3.SystemProgram.programId,
      })
      .rpc();
  } catch (error) {
    console.error("Error fetching counter account:", error);
  }

报错日志如下:

  logs: 
   [ 'Program CVQCRMyzWNr8MbNhzjbfPu9YVvr97onF48Lc9ZwXotpW invoke [1]',
     'Program log: Instruction: Initialize',
     'Program 11111111111111111111111111111111 invoke [2]',
     'Allocate: account Address { address: 8sKt2NcKbN9E2SUE6E3NgfzwGi5ByBZxHQdCw27bMef1, base: None } already in use',
     'Program 11111111111111111111111111111111 failed: custom program error: 0x0',
     'Program CVQCRMyzWNr8MbNhzjbfPu9YVvr97onF48Lc9ZwXotpW consumed 4867 of 200000 compute units',
     'Program CVQCRMyzWNr8MbNhzjbfPu9YVvr97onF48Lc9ZwXotpW failed: custom program error: 0x0' ],
  programErrorStack: { stack: [ [Object], [Object] ] } }

根据日志信息,关键的错误是:

'Allocate: account Address { address: 8sKt2NcKbN9E2SUE6E3NgfzwGi5ByBZxHQdCw27bMef1, base: None } already in use'

这表示你尝试分配的账户地址 8sKt2NcKbN9E2SUE6E3NgfzwGi5ByBZxHQdCw27bMef1 已经被使用,因此无法进行新的初始化。这通常发生在你已经为该地址创建了账户,但可能在再次执行时未考虑到这一点。

修改initializeTx代码

let counterAccount;
try {
  counterAccount = await program.account.counter.fetch(counterPubkey);
  console.log("Counter account already exists:", counterAccount);
} catch (error) {
  if (error.message.includes("Account does not exist")) {
    console.log("Counter account does not exist, proceeding with initialization...");
    // Initialize account
    const initializeTx = await pg.program.methods
      .initialize()
      .accounts({
        counter: counterPubkey,
        authority: pg.wallet.publicKey,
        systemProgram: web3.SystemProgram.programId,
      })
      .rpc();
  } else {
    console.error("Error fetching counter account:", error);
  }
}

执行结果:
在这里插入图片描述

修复后完整client.ts代码

const wallet = pg.wallet;
const program = pg.program;
const counterSeed = Buffer.from("counter");

const [counterPubkey, bump] = web3.PublicKey.findProgramAddressSync(
  [counterSeed],
  pg.PROGRAM_ID
);


let counterAccount;
try {
  counterAccount = await program.account.counter.fetch(counterPubkey);
  console.log("Counter account already exists:", counterAccount);
} catch (error) {
  if (error.message.includes("Account does not exist")) {
    console.log(
      "Counter account does not exist, proceeding with initialization..."
    );
    // Initialize account
    const initializeTx = await pg.program.methods
      .initialize()
      .accounts({
        counter: counterPubkey,
        authority: pg.wallet.publicKey,
        systemProgram: web3.SystemProgram.programId,
      })
      .rpc();
  } else {
    console.error("Error fetching counter account:", error);
  }
}

const incrementTx = await pg.program.methods
  .increment()
  .accounts({
    counter: counterPubkey,
    authority: pg.wallet.publicKey,
  })
  .rpc();

counterAccount = await program.account.counter.fetch(counterPubkey);
console.log("account after increasing ==>", Number(counterAccount.count));

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2150130.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

12种常见的华为杯数学建模竞赛matlab代码(建议收藏)

1.使用神经网络模型(向量量子化方法LVQ)解决分类/预测问题 clc;clear;​% 第一类蝗虫的触角和翅膀p1 [1.24, 1.27; 1.36, 1.74; 1.38, 1.64; 1.38, 1.82; 1.38, 1.90; 1.40, 1.70; 1.48, 1.82; 1.54, 1.82; 1.56, 2.08];​% 第二类蝗虫的触角和翅膀p2 [1.14, 1.82;…

电脑视频编辑常用软件:12个在线视频剪辑方法,这份免费攻略真实在!

您是否曾为视频剪辑而感到困惑&#xff0c;不知从何入手&#xff1f;面对众多的视频编辑软件和复杂的操作流程&#xff0c;怎样才能快速上手&#xff0c;制作出高质量的视频呢&#xff1f;许多内容创作者在编辑或上传较长视频时&#xff0c;常常遭遇到时间和质量的困扰。为了解…

利用Metasploit进行信息收集与扫描

Metasploit之信息收集和扫描 在本文中&#xff0c;我们将学习以下内容 使用Metasploit被动收集信息 使用Metasploit主动收集信息 使用Nmap进行端口扫描 使用db_nmap方式进行端口扫描 使用ARP进行主机发现 UDP服务探测 SMB扫描和枚举 SSH版本扫描 FTP扫描 SMTP枚举 …

【计算机网络 - 基础问题】每日 3 题(十三)

✍个人博客&#xff1a;Pandaconda-CSDN博客 &#x1f4e3;专栏地址&#xff1a;http://t.csdnimg.cn/fYaBd &#x1f4da;专栏简介&#xff1a;在这个专栏中&#xff0c;我将会分享 C 面试中常见的面试题给大家~ ❤️如果有收获的话&#xff0c;欢迎点赞&#x1f44d;收藏&…

关于安卓App自动化测试的一些想法

安卓App自动化一般使用PythonAppium。页面元素通常是使用AndroidStudio中的UI Automator Viewer工具来进行页面元素的追踪。但是这里涉及到一个问题就是&#xff0c;安卓apk在每次打包的时候&#xff0c;会进行页面的混淆以及加固&#xff0c;所以导致每次apk打包之后会出现页面…

Java客户端SpringDataRedis(RedisTemplate使用)

文章目录 ⛄概述⛄快速入门❄️❄️导入依赖❄️❄️配置文件❄️❄️测试代码 ⛄数据化序列器⛄StringRedisTemplate⛄RedisTemplate的两种序列化实践方案总结 ⛄概述 SpringData是Spring中数据操作的模块&#xff0c;包含对各种数据库的集成&#xff0c;其中对Redis的集成模…

python获取滑块验证码需要滑动的距离

我们以这个网站为例: http://120.86.191.138/hbgs/zwgk/dirData.do?dirId402881204e959150014e959f42f30014&subjectId93e889f2501d3fe8015024305bdf0efc 往后点到第四页后会出现验证码 一.获取到背景图片和缺口图片 我们发现图片是base64格式通过API直接发送 二.识别缺…

铲屎官进!宠物空气净化器真的有用吗?哪款去浮毛效果好

国庆小长假就要来了&#xff0c;别人都在苦恼抢票问题&#xff0c;而我在想会不会被我妈赶出家门... 毕业后我就留在了广州上班&#xff0c;独自一人租房难免会感觉孤独&#xff0c;就养了一只小猫和我作伴。这次放假这么久&#xff0c;我不放心留它一个人在家&#xff0c;也没…

vulhub搭建漏洞环境docker-compose up -d命令执行报错以及解决方法汇总

在利用vulhub靶场搭建环境进行漏洞复现时&#xff0c;我们通常要使用这一步命令&#xff1a; docker-compose up -d 但是经常报错&#xff0c;今天我们来说几个常见的报错以及解决方法&#xff1a; 1.报错提示&#xff1a; ERROR: Couldnt connect to Docker daemon at httpdoc…

基于atlas环境下YOLOV7的睡岗识别

做到这里&#xff0c;其实只是想探索下新的检测框架、探索下atlas下ACL的推理方式。整个过程持续了3-4周把&#xff0c;回顾一下&#xff0c;感觉还是需要一些技巧才能拿下&#xff0c;如果没有任何经验的是断难搞定此代码的。主要基于华为的官方例子&#xff0c;里面修改了原始…

ApplicationEvent 事件泛型封装记录

一、一个事件的封装、发布以及监听 事件类封装 把需要的信息封装到一个事件类中 Data public class Person {private String name; }Data public class PersonEvent {private Person person;private String addOrUpdate;public PersonEvent(Person person, String addOrUpda…

【云安全】云服务安全攻防

一、云服务安全事件 1、CVE-2021-44228&#xff1a; AWS Log4Shell热补丁漏洞&#xff0c;用来进行容器逃逸和权限提升 2、CVE-2022-30137&#xff1a; Microsoft Azure Service Fabic权限提升漏洞&#xff0c;允许攻击者在容器内提升权限至主机节点root权限 FabricScape: Esca…

神奇的css动画:animation、transform、transition

前言 动画包括两个部分&#xff1a;描述动画的样式和用于指定动画开始、结束以及中间点样式的关键帧。 相比较于传统的脚本实现动画技术&#xff0c;使用css动画三个主要优点: 1.能够非常容易创建简单动画&#xff0c;甚至不需要了解JavaScript就能创建动画 2.动画运行效果…

Trainer API训练属于自己行业的本地大语言模型 医疗本地问答大模型示例

Trainer API 是 Hugging Face transformers 库中强大而灵活的工具&#xff0c;简化了深度学习模型的训练和评估过程。通过提供高层次的接口和多种功能&#xff0c;Trainer API 使研究人员和开发者能够更快地构建和优化自然语言处理模型 文章目录 前言一、Trainer API它能做什么…

Machine Learning Specialization 学习笔记(3)

文章目录 前言一、神经网络基本概念基本组成工作流程训练过程类型应用举例不同层次特征的学习 为什么从基础特征到复杂特征逐渐推进什么是感受野更简单的解释具体示例总结 二、TensorFlow实现简单神经网络安装及环境配置数据预处理标准化 Dense层Convolutional Layer训练DEBUG …

独立站技能树/工具箱1.0 总纲篇丨出海笔记

正所谓要把一件事做到90分很难&#xff0c;但做到60分基本上照着SOP做到位都没问题&#xff0c;如果我们能把每件事都做到60分&#xff0c;那绝对比至少60%的人都强&#xff0c;除非你的对手不讲武德——那就是他很可能看了我这篇文章&#xff0c;不但每方面都超过及格线&#…

MySQL高阶1853-转换日期格式

目录 题目 准备数据 分析数据 总结 题目 给定一个Days表&#xff0c;请你编写SQL查询语句&#xff0c;将Days表中的每一个日期转化为"day_name, month_name day, year"格式的字符串。 返回的结果表 不计顺序 。 准备数据 Create table If Not Exists Days (d…

Arthas 全攻略:让调试变得简单

文章目录 一、简介二、命令列表 一、简介 Arthas 是一款线上监控诊断产品&#xff0c;通过全局视角实时查看应用 load、内存、gc、线程的状态信息&#xff0c;并能在不修改应用代码的情况下&#xff0c;对业务问题进行诊断&#xff0c;包括查看方法调用的出入参、异常&#xff…

排序---冒泡排序、堆排序

一、冒泡排序 相邻两个位置交换&#xff0c;假设排升序&#xff0c;就不断把最大的往后拿&#xff0c;所以这段序列从后往前变得有序。 //flag为0&#xff0c;即这个数组已经是有序的了&#xff0c;节省循环次数 二、堆排序&#xff08;数组实现&#xff09; 具体原理介绍看这…

jetcache-阿里多级缓存框架神器一定要掌握

文章目录 1. 简介2. springboot集成jetcache2.1 引入依赖2.2 配置文件2.3 高级API模式&#xff1a;通过CacheManager使用缓存&#xff0c;2.7 版本才可使用2.4 &#xff08;推荐&#xff09;AOP模式&#xff1a;通过Cached,CacheUpdate,CacheInvalidate注解 1. 简介 JetCache是…