Near Transaction Signing
To sign and broadcast the transaction to the Near network, follow these steps:
-
Prepare unsigned transaction in Base64 encrypted format.
-
Sign the transaction using the following code:
import { KeyPair, Signer } from "near-api-js";
import { signTransaction, Transaction } from "near-api-js/lib/transaction";
import * as sha256 from "js-sha256";
import { KeyPairString, PublicKey } from "near-api-js/lib/utils";
// Private key (ensure this is securely stored)
const PRIVATE_KEY = "ed25519:YOUR_PRIVATE_KEY_HERE";
// Unsigned transaction in hexadecimal format
const RAW_TX_HEX = "YOUR_UNSIGNED_TRANSACTION_HEX";
// Create a signer instance using the private key
function createSigner(privateKey: string): Signer {
const keyPair = KeyPair.fromString(privateKey as KeyPairString);
return {
async getPublicKey() {
return keyPair.getPublicKey();
},
async signMessage(message: Uint8Array) {
const hash = new Uint8Array(sha256.sha256.array(message));
const signature = keyPair.sign(hash);
return {
signature: signature.signature,
publicKey: keyPair.getPublicKey(),
};
},
createKey(accountId: string, networkId?: string): Promise<PublicKey> {},
};
}
// Function to sign the transaction
async function signTransactionWithSigner(
tx: Transaction,
signer: Signer
): Promise<string> {
const [, signedTx] = await signTransaction(tx, signer);
const signedTxSerialized = signedTx.encode();
return Buffer.from(signedTxSerialized).toString("hex");
}
// Process the transaction signing
async function processTransaction() {
if (!RAW_TX_HEX) {
throw new Error("❌ Error: RAW_TX_HEX is empty. Insert your transaction!");
}
// Create signer with private key
const signer = createSigner(PRIVATE_KEY);
// Decode transaction from hex format
const tx = Transaction.decode(Buffer.from(RAW_TX_HEX, "hex"));
// Sign the transaction
const signedTxHex = await signTransactionWithSigner(tx, signer);
console.log("✅ Signed Transaction (Hex):", signedTxHex);
}
// Execute signing process
processTransaction().catch(console.error);
Upon successful execution, the script prints the signed transaction in the hexadecimal format, ready to be broadcasted:
✅ Signed Transaction (Hex): 0x...
- Broadcast the transaction to the Near network by sending a POST request to /api/v1/unified/transaction/broadcast.
What's Next?
Updated 15 days ago