3

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!

MiKK
  • 89
  • 7
  • If a transaction signature is available, as a workaround, use web3.Connection.getParsedTransaction(). In TypeScript, the 'parsed' object has to be accssed via "['parsed']". In JavaScript, can access it like a JSON with ".parsed". – MiKK Mar 26 '22 at 18:49

1 Answers1

3

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

Jon C
  • 7,019
  • 10
  • 17
  • Much obliged. decodeTransferInstruction is part of splToken, docs is [here](https://solana-labs.github.io/solana-program-library/token/js/modules.html#decodeTransferInstruction) – MiKK Mar 29 '22 at 04:38