Solana: Can't make createAccount work, createAccountWithSeed works

908 Views Asked by At

I am currently trying to learn on writing programs for Solana and interacting with those.

I am using the example-helloworld code. In order to interact with the helloworld program, the nodejs code creates an account with seed:

const transaction = new Transaction().add(
    SystemProgram.createAccountWithSeed({
        fromPubkey: payer.publicKey,
        basePubkey: payer.publicKey,
        seed: GREETING_SEED,
        newAccountPubkey: greetedPubkey,
        lamports,
        space: GREETING_SIZE,
        programId,
    })
)
tx = client.send_transaction(transaction, payer)

My understanding is, that it creates a data account, owned by the program with the programId. Not sure why with seed yet.

I tried to replace this piece of code with the following:

const transaction = new Transaction().add(
    SystemProgram.createAccount({
        fromPubkey: payer.publicKey,
        newAccountPubkey: greetedPubkey,
        lamports,
        space: GREETING_SIZE,
        programId,
    })
)
tx = client.send_transaction(transaction, payer)

but it is not working. Once the transaction is send, I get the following error:

{'code': -32602, 'message': 'invalid transaction: Transaction failed to sanitize accounts offsets correctly'}

Anyone who can explain the difference and what I am doing wrong??

1

There are 1 best solutions below

0
On BEST ANSWER

When creating an account with createAccount, you must provide a signature from that new account. So in your case, greetedPubkey must be a Keypair, just like payer. You can do:

const greeted = Keypair.generate();
const transaction = new Transaction().add(
    SystemProgram.createAccount({
        fromPubkey: payer.publicKey,
        newAccountPubkey: greeted.publicKey,
        lamports,
        space: GREETING_SIZE,
        programId,
    })
);
tx = client.send_transaction(transaction, payer, greeted);

createAccountWithSeed is special because it derives a new address from the base, meaning that you don't need to sign with the new address, only with the base address.