Sign and Broadcast Transaction

There are two ways to sign and broadcast a transaction to the Polygon network:

  1. Using a single piece of code.
  2. Signing the transaction with a code and then broadcasting it with an API method.

Using Code

  1. Retrieve unsigned serialized transactions in Base64 encrypted format.
  2. Sign the transaction using the following code. The code example uses ethers.js 6.10.0.
require("dotenv").config();
const { ethers } = require('ethers');

async function signAndBroadcast() {
    console.log("Started");

    // Enter the serialized transaction
    const rawTransaction = process.env.RAW_TRANSACTION;

    // Enter the private key of the address used to transfer the stake amount
    const privateKey = process.env.PRIVATE_KEY;

    // Enter the selected RPC URL
    const rpcURL = process.env.RPC_URL;

    // Initialize the provider using the RPC URL
    const provider = new ethers.JsonRpcProvider(rpcURL);

    // Initialize a new Wallet instance
    const wallet = new ethers.Wallet(privateKey, provider);

    // Parse the raw transaction
    const tx = ethers.Transaction.from(rawTransaction);

    const newTx = {
        to: tx.to,
        data: tx.data,
        chainId: tx.chainId,
        value: tx.value,
        gasLimit: tx.gasLimit,
        type: 2,

        nonce: await provider.getTransactionCount(wallet.address),
        // Enter the max fee per gas and prirorty fee
        maxFeePerGas: ethers.parseUnits(process.env.MAX_FEE_PER_GAS_IN_GWEI, 'gwei'),
        maxPriorityFeePerGas: ethers.parseUnits(process.env.MAX_PRIORITY_FEE_IN_GWEI, 'gwei')
    }

    // Sign the transaction
    const signedTransaction = await wallet.signTransaction(newTx);

    // Send the signed transaction
    const transactionResponse = await provider.broadcastTransaction(signedTransaction);

    return transactionResponse;
}

signAndBroadcast()
    .then((transactionResponse) => {
        console.log(
            "Transaction broadcasted, transaction hash:",
            transactionResponse.hash
        );
    })
    .catch((error) => {
        console.error("Error:", error);
    })
    .finally(() => {
        console.log("Finished");
    });

Using Code and API

  1. Retrieve unsigned serialized transactions in Base64 encrypted format.
  2. Sign the transaction using the following code:

require("dotenv").config();
const { ethers } = require('ethers');

async function signAndBroadcast() {
    console.log("Started");

    // Enter the serialized transaction
    const rawTransaction = process.env.RAW_TRANSACTION;

    // Enter the private key of the address used to transfer the stake amount
    const privateKey = process.env.PRIVATE_KEY;

    // Enter the selected RPC URL
    const rpcURL = process.env.RPC_URL;

    // Initialize the provider using the RPC URL
    const provider = new ethers.JsonRpcProvider(rpcURL);

    // Initialize a new Wallet instance
    const wallet = new ethers.Wallet(privateKey, provider);

    // Parse the raw transaction
    const tx = ethers.Transaction.from(rawTransaction);

    const newTx = {
        to: tx.to,
        data: tx.data,
        chainId: tx.chainId,
        value: tx.value,
        gasLimit: tx.gasLimit,
        type: 2,

        nonce: await provider.getTransactionCount(wallet.address),
        // Enter the max fee per gas and prirorty fee
        maxFeePerGas: ethers.parseUnits(process.env.MAX_FEE_PER_GAS_IN_GWEI, 'gwei'),
        maxPriorityFeePerGas: ethers.parseUnits(process.env.MAX_PRIORITY_FEE_IN_GWEI, 'gwei')
    }

    // Sign the transaction
    const signedTransaction = await wallet.signTransaction(newTx);


    return signedTransaction;
}

signAndBroadcast()
    .then((signedTransaction) => {
        console.log(
            "Signed transaction is",
            signedTransaction
        );
    })
    .catch((error) => {
        console.error("Error:", error);
    })
    .finally(() => {
        console.log("Finished");
    });
  1. Send the signed transaction to the Polygon network by making a POST request to /api​/v1​/polygon​/transaction​/send.

Example request:

curl --request POST \
		 --url https://api-test.p2p.org/api/v1/polygon/transaction/send \
     --head 'accept: application/json' \
     --head 'Authorization: Bearer <token>' \
     --head 'Content-Type: application/json' \
     --data '
{
  "signedTransaction": "0x02f902d705808301674e8508530af16e830186a094681a1b3441c6bfb12f91651efd9f02c83c0702938901bc16d674ec800000b902a44f498c730000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000260000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030aa5f27070a21d79455c4a9b73c0aa4a8b1a65a1fb530d7fd8e6cd23aa16660679ac43ee4861098f6d9166aed3a4d8abb0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002001000000000000000000000028c84612d37de9209018ad96167f12169b653e9a000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000060978c565cd915f4e885b4201093d1501697610eb9ee99b9b60b70434dc330e98d5b42927725304ded48483a8b8f39506d09bcb22ee18d4f6b50257946ac5ee360385308d95c0e2bc963902d42e985c29ee489aa3c989ac1561c952a6424f107a800000000000000000000000000000000000000000000000000000000000000014cb452f6e3f10ba2175c86a0284f53fcb61404b458393391abc3d5622e3e55cdc0",
  "stakerAddress": "0x39D02C253dA1d9F85ddbEB3B6Dc30bc1EcBbFA17"
}
'
  • signedTransaction — serialized signed transaction.
  • stakerAddress — staker account address.

What's Next?