In this document, we are going to show you how to use a PrivateKey to sign transactions on Injective.
Every transaction on Injective follows the same flow. The flow consists of three steps: preparing, signing and broadcasting the transaction. Let's dive into each step separately and explain the process in-depth (including examples) so we can understand the whole transaction flow.
Preparing a transaction
First of, we need to prepare the transaction for signing.
Once we have prepared the transaction, we proceed to signing. Once you get the txRaw transaction from the previous step use any Cosmos native wallet to sign (ex: Keplr),
import { ChainId } from'@injectivelabs/ts-types'/* Sign the Transaction */constprivateKeyHash=''constprivateKey=PrivateKey.fromHex(privateKeyHash);constsignBytes=/* From the previous step *//** Sign transaction */constsignature=awaitprivateKey.sign(Buffer.from(signBytes));
Broadcasting a transaction
Once we have the signature ready, we need to broadcast the transaction to the Injective chain itself. After getting the signature from the second step, we need to include that signature in the signed transaction and broadcast it to the chain.
import { ChainId } from'@injectivelabs/ts-types'import { TxRestClient } from'@injectivelabs/sdk-ts'import { Network, getNetworkInfo } from'@injectivelabs/networks'/** Append Signatures */constnetwork=getNetworkInfo(Network.Testnet);consttxRaw=/* from the first step */constsignature=/* from the second step */txRaw.signatures = [signature];/** Calculate hash of the transaction */console.log(`Transaction Hash: ${TxClient.hash(txRaw)}`);consttxService=newTxGrpcClient(network.grpc);/** Simulate transaction */constsimulationResponse=awaittxService.simulate(txRaw);console.log(`Transaction simulation response: ${JSON.stringify(simulationResponse.gasInfo )}`);/** Broadcast transaction */consttxResponse=awaittxService.broadcast(txRaw);console.log(txResponse);if (txResponse.code !==0) {console.log(`Transaction failed: ${txResponse.rawLog}`);} else {console.log(`Broadcasted transaction hash: ${JSON.stringify(txResponse.txHash)}` );}
Example (Prepare + Sign + Broadcast)
Let's have a look at the whole flow (using Keplr as a signing wallet)
You can use the MsgBroadcasterWithPk class from the @injectivelabs/sdk-ts package which abstracts away most of the logic written above into a single class.
This abstraction allows you to sign transactions in a Node/CLI environment.