# eth_sendRawTransaction - MegaETH RPC Method

Submits a pre-signed transaction for broadcast to MegaETH.

> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.

## When to Use This Method

The `eth_sendRawTransaction` method serves these key scenarios for high-frequency DeFi developers, gaming studios, and teams building real-time applications:

- **Submit pre-signed transactions** - Broadcast transactions that were signed offline or in a secure enclave, keeping private keys away from the RPC endpoint
- **Broadcast from offline signers** - Air-gapped devices and hardware wallets first sign, then use this method to push the signed payload to MegaETH
- **Resubmit stuck transactions** - Replace pending transactions with the same nonce and a higher gas price when the original is not being included in blocks
- **Deploy contracts programmatically** - Submit contract creation transactions containing compiled bytecode and constructor arguments

## Common Use Cases

### 1. Sign and Send an ETH Transfer

Build, sign, and broadcast a native ETH transfer with proper nonce management. The nonce must be retrieved from the node immediately before signing to avoid conflicts with pending transactions.

```javascript
import { JsonRpcProvider, Wallet, parseEther, Transaction } from 'ethers';

const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const wallet = new Wallet('PRIVATE_KEY', provider);

async function sendNativeTransfer(to, amountInEth) {
  const tx = await wallet.sendTransaction({
    to: to,
    value: parseEther(amountInEth)
  });

  console.log('Transaction submitted:', tx.hash);

  const receipt = await tx.wait();
  console.log(`Confirmed in block ${receipt.blockNumber}, gas used: ${receipt.gasUsed}`);
  return receipt;
}

const receipt = await sendNativeTransfer('0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', '0.01');
```

### 2. Resubmit a Stuck Transaction

If a pending transaction is not being confirmed due to low gas, submit a replacement with the same nonce and a higher gas price. The replacement must use an increased fee to be accepted by the MegaETH mempool.

```javascript
import { JsonRpcProvider, Wallet, parseEther } from 'ethers';

const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const wallet = new Wallet('PRIVATE_KEY', provider);

async function speedUpTransaction(originalTxHash, gasMultiplier = 1.5) {
  const pendingTx = await provider.getTransaction(originalTxHash);
  if (!pendingTx) throw new Error('Transaction not found');

  const feeData = await provider.getFeeData();

  const replacementTx = {
    to: pendingTx.to,
    value: pendingTx.value,
    data: pendingTx.data,
    nonce: pendingTx.nonce,
    maxFeePerGas: feeData.maxFeePerGas * BigInt(Math.floor(gasMultiplier * 100)) / 100n,
    maxPriorityFeePerGas: feeData.maxPriorityFeePerGas * BigInt(Math.floor(gasMultiplier * 100)) / 100n,
    gasLimit: pendingTx.gasLimit
  };

  const tx = await wallet.sendTransaction(replacementTx);
  console.log('Replacement transaction:', tx.hash);
  return tx;
}

const newTx = await speedUpTransaction('0x...');
```

### 3. Deploy a Compiled Contract

Submit a contract deployment transaction containing the compiled bytecode. The `to` field is omitted for contract creation transactions; the contract address is deterministically derived from the sender address and nonce.

```javascript
import { JsonRpcProvider, Wallet, ContractFactory } from 'ethers';

const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const wallet = new Wallet('PRIVATE_KEY', provider);

const contractAbi = ['constructor(string memory name, uint256 supply)'];
const contractBytecode = '0x608060...';

async function deployContract(constructorArgs) {
  const factory = new ContractFactory(contractAbi, contractBytecode, wallet);
  const contract = await factory.deploy(...constructorArgs);

  console.log('Deployment tx:', contract.deploymentTransaction().hash);

  await contract.waitForDeployment();
  console.log('Contract deployed at:', await contract.getAddress());
  return contract;
}

const contract = await deployContract(['MyToken', 1000000]);
```

## Best Practices

- Always sign transactions client-side: never send private keys to any RPC endpoint, including <https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY>
- Track nonces carefully to avoid gaps or conflicts: retrieve the pending nonce from `eth_getTransactionCount` with `"pending"` tag before each signing
- The return value is a transaction hash: use `eth_getTransactionReceipt` to poll for confirmation status
- Handle replacement transactions correctly: the replacement must use the same nonce with a higher gas price
- Use `eth_estimateGas` to set an appropriate gas limit before signing and sending

## Request Parameters

- `signedTransactionData` (`DATA, required`): The signed transaction data (RLP encoded)

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "eth_sendRawTransaction",
  "params": ["0xf86c..."],
  "id": 1
}
```

## Response Fields

- `result` (`DATA, required`): 32-byte transaction hash

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x..."
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_sendRawTransaction",
    "params": ["0xf86c808504a817c80082520894..."],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider, Wallet, parseEther } from 'ethers';

const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const wallet = new Wallet('YOUR_PRIVATE_KEY', provider);

// Send native tokens
async function sendTransaction(to, value) {
  const tx = await wallet.sendTransaction({
    to: to,
    value: parseEther(value)
  });

  console.log('Transaction hash:', tx.hash);

  // Wait for confirmation
  const receipt = await tx.wait();
  console.log('Confirmed in block:', receipt.blockNumber);

  return receipt;
}

// Send to contract
async function sendContractTransaction(contract, method, args, value = '0') {
  const tx = await contract[method](https://www.dwellir.com/docs/megaeth/...args, {
    value: parseEther(value)
  });

  return await tx.wait();
}
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))

def send_transaction(private_key, to, value_in_ether):
    account = w3.eth.account.from_key(private_key)

    # Build transaction
    tx = {
        'nonce': w3.eth.get_transaction_count(account.address),
        'to': to,
        'value': w3.to_wei(value_in_ether, 'ether'),
        'gas': 21000,
        'gasPrice': w3.eth.gas_price,
        'chainId': w3.eth.chain_id
    }

    # Sign transaction
    signed_tx = account.sign_transaction(tx)

    # Send transaction
    tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
    print(f'Transaction hash: {tx_hash.hex()}')

    # Wait for confirmation
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    print(f'Confirmed in block: {receipt["blockNumber"]}')

    return receipt
```

```go
package main

import (
    "context"
    "crypto/ecdsa"
    "fmt"
    "log"
    "math/big"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY")
    if err != nil {
        log.Fatal(err)
    }

    publicKey := privateKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

    nonce, _ := client.PendingNonceAt(context.Background(), fromAddress)
    value := big.NewInt(1000000000000000000)
    gasLimit := uint64(21000)
    gasPrice, _ := client.SuggestGasPrice(context.Background())

    toAddress := common.HexToAddress("0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f")
    tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil)

    chainID, _ := client.NetworkID(context.Background())
    signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)

    err = client.SendTransaction(context.Background(), signedTx)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex())
}
```

## Related Methods

- [`eth_estimateGas`](https://www.dwellir.com/docs/megaeth/eth_estimateGas) - Estimate gas required
- [`eth_gasPrice`](https://www.dwellir.com/docs/megaeth/eth_gasPrice) - Get current gas price
- [`eth_getTransactionReceipt`](https://www.dwellir.com/docs/megaeth/eth_getTransactionReceipt) - Get transaction result
