Search code examples
solana

The accounts must be put with some sequence or can be random when initiate a TransactionInstruction?


Here it is, we have a account list when create TransactionInstruction. So the list could have a random order? or it must follow some specific order?

  const keys = [
    {
      pubkey: key1,
      isSigner: true,
      isWritable: true,
    },
    {
      pubkey: key2,
      isSigner: false,
      isWritable: true,
    },
    ...
  ];

  new TransactionInstruction({
    keys,
    programId: PROGRAM_ID,
    data: txnData,
  }),

Solution

  • The list of accounts must be in the order expected by the program.

    For example, during a CreateAccount instruction, you have the from account and the new account, defined in that order: https://github.com/solana-labs/solana/blob/c8f76b8bd05c9557123dd5695b3b809e01fe9ccd/web3.js/src/system-program.ts#L655

    When processing the instruction, the runtime will take the first account as the from account, and the second account as the new account: https://github.com/solana-labs/solana/blob/c8f76b8bd05c9557123dd5695b3b809e01fe9ccd/runtime/src/system_instruction_processor.rs#L284