Search code examples
node.jsethereum

Get raw transaction from transaction Id using web3js or something similar in nodejs


So i will give an example let's say i have the transaction id https://etherscan.io/tx/0xafef64d0d03db9f13c6c3f8aec5902167ea680bd0ffa0268d89a426d624b2ae1

In etherscan i can use their menu to see the raw transaction which will be

0xf8a915850516aab3ad82be7c947d1afa7b718fb893db30a3abc0cfc608aacfebb080b844095ea7b300000000000000000000000022b1cbb8d98a01a3b71d034bb899775a76eb1cc2ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff26a003daa35e6aa4a7cd439133411a390ff0796420d5cb39e9e276db75b01218ed41a028605f36c601527bd435b36da5403ee972fc2fb2c8f70959199bcdba0d0e8c77

I can't get this with etherscan api or geth rpc , i have found eth_getRawTransaction but it give just 0x for transfer transaction is there anyway i can find the raw transaction using nodejs code

thank you

I think i need to rlp encode the transaction or something like that , i'm lost


Solution

  • A raw transaction is an object. This hex string represents a serialized transaction object.

    Example code below.

    Note that ethers requires you to parse out the signature and other params of an already mined/validated transaction, and pass the signature as a second argument. There's probably a more generic way of doing that, I couldn't think of any right now.

    const tx = await provider.getTransaction("0xafef64d0d03db9f13c6c3f8aec5902167ea680bd0ffa0268d89a426d624b2ae1");
    
    const unsignedTx = {
        to: tx.to,
        nonce: tx.nonce,
        gasLimit: tx.gasLimit,
        gasPrice: tx.gasPrice,
        data: tx.data,
        value: tx.value,
        chainId: tx.chainId
    };
    const signature = {
        v: tx.v,
        r: tx.r,
        s: tx.s
    }
    
    const serialized = ethers.utils.serializeTransaction(unsignedTx, signature);
    console.log(serialized);
    

    Docs: