import { createWalletClient, custom, http, parseTransaction } from 'viem';
import { privateKeyToAccount, signTransaction } from 'viem/accounts';
import { base } from 'viem/chains';
// Example API response shape
// response = { json: { domain, types, primaryType, message }, encoded: "0x..." }
// -----------------------------------------------------------------------------
// 1. With private key — use response.encoded (raw hex), then sign
// -----------------------------------------------------------------------------
async function signRawTransactionWithPrivateKey(privateKey, response, rpcUrl) {
const privateKeyHex = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;
const account = privateKeyToAccount(privateKeyHex);
const rawTxHex = response.encoded.startsWith('0x') ? response.encoded : `0x${response.encoded}`;
const transaction = parseTransaction(rawTxHex);
const walletClient = createWalletClient({
chain: base,
account,
transport: http(rpcUrl),
});
const request = await walletClient.prepareTransactionRequest({
...transaction,
gas: transaction.gas,
});
return walletClient.signTransaction(request); // signed hex "0x02..."
}
// -----------------------------------------------------------------------------
// 2. With private key — use response.json (transaction object), then sign
// -----------------------------------------------------------------------------
async function signTransactionObjectWithPrivateKey(privateKey, response, rpcUrl) {
const privateKeyHex = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;
const account = privateKeyToAccount(privateKeyHex);
const txRequest = response.json; // { to, data, value, gas, nonce, chainId, maxFeePerGas, maxPriorityFeePerGas, type }
const walletClient = createWalletClient({
chain: base,
account,
transport: http(rpcUrl),
});
const prepared = await walletClient.prepareTransactionRequest(txRequest);
return walletClient.signTransaction(prepared);
}
// -----------------------------------------------------------------------------
// 3. With private key — sign only (no RPC), from encoded, using viem/accounts
// -----------------------------------------------------------------------------
async function signRawTransactionWithPrivateKeyNoRpc(privateKey, response) {
const privateKeyHex = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;
const rawTxHex = response.encoded.startsWith('0x') ? response.encoded : `0x${response.encoded}`;
const transaction = parseTransaction(rawTxHex);
const signedHex = await signTransaction({
privateKey: privateKeyHex,
transaction,
});
return signedHex;
}