Using ethersjsv6 to send signed raw transactions

Victor Yeo
2 min readOct 7, 2023

Some use cases ask for sending a signed transaction. In this article, the code is developed using ethersjs v6 release 6.7.1

Firstly, we get the json rpc and connect wallet to it, to obtain the signer.

const srcRpc = "<alchemy or infura rpc url>";
const provider: JsonRpcProvider = new ethers.JsonRpcProvider(srcRpc);
const privateKey = '<private_key>';
const wallet = new ethers.Wallet(privateKey, provider);
const signer = wallet.connect(provider);

Secondly, we call the signTransaction method with the TransactionRequest object passed in.

// get the nonce
const nonce = provider.getTransactionCount(senderAddress)

// encode the data from smart contract method
const data = await myContract.methods
.demoNow(randomNumber, handleId)
.encodeABI();

// call the signTransaction
let signedTx = await signer.signTransaction({
from: fromAddress,
to: toAddress,
nonce,
gasPrice: gasPrice.toString(),
gasLimit: gasLimit.toString(),
value: 0,
data,
});

Thirdly, we prepare to send the raw transactions by setting the options for fetch method.

const requestOptions = {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({
"jsonrpc":"2.0",
"id":0,
"method":"eth_sendRawTransaction",
"params":[signedTx]
})
};

Then, we call the fetch method to send the raw transactions.

let receipt = await fetch(`${srcRpc}`, requestOptions);
console.log(`txn receipt`, receipt);

Fourthly, we can examine the content of the receipt, as below.

Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: Gunzip {
_writeState: [Uint32Array],
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
bytesWritten: 0,
_handle: [Zlib],
_outBuffer: <Buffer 7b 22 6a 73 6f 6e 72 70 63 22 3a 22 32 2e 30 22 2c 22 69 64 22 3a 30 2c 22 65 72 72 6f 72 22 3a 7b 22 63 6f 64 65 22 3a 2d 33 32 30 30 30 2c 22 6d 65 … 16334 more bytes>,
_outOffset: 0,
_chunkSize: 16384,
_defaultFlushFlag: 2,
_finishFlushFlag: 2,
_defaultFullFlushFlag: 3,
_info: undefined,
_maxOutputLength: 4294967296,
_level: -1,
_strategy: 0,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null,
[Symbol(kError)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: ‘alchemy or infura url’,
status: 200,
statusText: ‘OK’,
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}

You will be able to see “status: 200". It means the fetch call is successfully executed.

This is the end of the article.

--

--