Search code examples
solanasolana-web3jssolana-transaction-instruction

solana web3 API: how to obtain data created with splToken.createTransferInstruction()


Would appreciate guidance on how to obtain the data back in the variables, which was entered into splToken.createTransferInstruction(), step-by-step, from the buffer variable in the code snippet below:

    var transaction = new web3.Transaction();
    transaction.add(
      splToken.createTransferInstruction(
        fromTokenAccount,
        toTokenAccount,
        senderPublicKey,
        amount,
        [],
        splToken.TOKEN_PROGRAM_ID,
      )
    );

    // Setting the variables for the transaction
    transaction.feePayer = provider.publicKey;    
    let blockhashObj = await connection.getRecentBlockhash();
    transaction.recentBlockhash = await blockhashObj.blockhash;
    // Transaction constructor initialized successfully
    if(transaction) { console.log('Txn created successfully'); }
    // Request creator to sign the transaction (allow the transaction)
    let signed = await provider.signTransaction(transaction);
    let buffer = signed.serialize();

Using web3.Transaction.from(buffer) I obtained a Transaction object - see image from the browser's console:

Transaction object in browser's console

I need to do something with instructions[0].data, I suppose to break it into byte lengths that will allow me to repopulate from the signed transaction:

  • fromTokenAccount,
  • toTokenAccount,
  • senderPublicKey,
  • amount,
  • [], // would this be a variable or zero-byte?
  • splToken.TOKEN_PROGRAM_ID, from the splToken.createTransferInstruction() above.

Much appreciated!


Solution

  • From the TransactionInstruction, you can use decodeTransferInstruction to get back the initial parameters. In your case, you can call:

    let tx = web3.Transaction.from(buffer);
    let decodedIx = decodeTransferInstruction(tx.instructions[0]);
    console.log(decodedIx.keys.source);
    console.log(decodedIx.keys.destination);
    console.log(decodedIx.keys.owner);
    console.log(decodedIx.data.amount);
    

    Full source code available at: https://github.com/solana-labs/solana-program-library/blob/24baf875e9e19c26d694d28c557d33848c3a9180/token/js/src/instructions/transfer.ts#L87