2

I'm trying to call a simple hello_world method from my Solana Anchor program, but I keep getting this error:

TypeError: Cannot read properties of undefined (reading 'encode')
    at .../node_modules/@coral-xyz/anchor/dist/cjs/program/namespace/index.js:35:100

Here’s my JavaScript code:

import { Program, AnchorProvider, setProvider } from '@coral-xyz/anchor';
import { PublicKey, Connection, Keypair } from '@solana/web3.js';
import bs58 from 'bs58';
import idl from './operator.json';

const connection = new Connection("http://127.0.0.1:8899"); // Localnet
const scionx = Keypair.fromSecretKey(bs58.decode("my_secret_key"));

const provider = new AnchorProvider(connection, scionx, { commitment: "confirmed" });
setProvider(provider);

const programID = new PublicKey("CMjNnp9yvMUqKJF2jB6E5HHpktwhm1ax9rHzh5risdNK");
const program = new Program(idl, programID, provider);

const tx = await program.methods.helloWorld().accounts({
  user: scionx.publicKey
}).rpc();

console.log("Transaction signature:", tx);

Here’s the relevant part of my Rust contract:

use anchor_lang::prelude::*;

#[program]
pub mod operator {
    pub fn hello_world(_ctx: Context<HelloWorld>) -> Result<()> {
        msg!("Hello, World!");
        Ok(())
    }
}

#[derive(Accounts)]
pub struct HelloWorld<'info> {
    pub user: Signer<'info>,
}

The program deploys fine, but I get the error when trying to call hello_world. Any ideas what might be wrong? Thanks!

1 Answer 1

2

Try using the bs58 module that anchor re-exports

import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes";

You can also get information about your Solana environment on the anchor client using

const provider = anchor.AnchorProvider.env()

This will read the details of your workspace and use them to initialize the anchor provider.

If you need a different signer for the txs, you can append them using the signers() method to your tx

3
  • got the same issue
    – Bolo
    Commented Oct 14 at 16:36
  • Is there a reason for initializing the anchor provider instead of letting it be detected from the workspace? Tutorial
    – Jimii
    Commented Oct 14 at 17:13
  • as soon I've work with the workspace. All work ty
    – Bolo
    Commented Oct 15 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.