import { getNetworkInfo, Network } from "@injectivelabs/networks";
import {
TxClient,
TxRestApi,
createTransaction,
} from "@injectivelabs/sdk-ts/core/tx";
import {
PrivateKey,
} from "@injectivelabs/sdk-ts/core/accounts";
import {
MsgSendToEth,
} from "@injectivelabs/sdk-ts/core/modules";
import {
ChainRestAuthApi,
} from "@injectivelabs/sdk-ts/client/chain";
import { toChainFormat, getDefaultStdFee } from "@injectivelabs/utils";
/** MsgSendToEth Example */
(async () => {
const network = getNetworkInfo(Network.Mainnet); // Gets the rpc/lcd endpoints
const privateKeyHash =
"f9db9bf330e23cb7839039e944adef6e9df447b90b503d5b4464c90bea9022f3";
const privateKey = PrivateKey.fromPrivateKey(privateKeyHash);
const injectiveAddress = privateKey.toBech32();
const ethAddress = privateKey.toHex();
const publicKey = privateKey.toPublicKey().toBase64();
/** Account Details **/
const accountDetails = await new ChainRestAuthApi(network.rest).fetchAccount(
injectiveAddress
);
/** Prepare the Message */
const amount = {
amount: toChainFormat(0.01).toFixed(),
denom: "inj",
};
const bridgeFee = {
amount: toChainFormat(0.01).toFixed(),
denom: "inj",
};
const msg = MsgSendToEth.fromJSON({
amount,
bridgeFee,
injectiveAddress,
address: ethAddress,
});
/** Prepare the Transaction **/
const { signBytes, txRaw } = createTransaction({
message: msg,
pubKey: publicKey,
fee: getDefaultStdFee(),
sequence: parseInt(accountDetails.account.base_account.sequence, 10),
accountNumber: parseInt(
accountDetails.account.base_account.account_number,
10
),
chainId: network.chainId,
});
/** Sign transaction */
const signature = await privateKey.sign(Buffer.from(signBytes));
/** Append Signatures */
txRaw.signatures = [signature];
/** Calculate hash of the transaction */
console.log(`Transaction Hash: ${TxClient.hash(txRaw)}`);
const txService = new TxRestApi(network.rest);
/** Simulate transaction */
const simulationResponse = await txService.simulate(txRaw);
console.log(
`Transaction simulation response: ${JSON.stringify(
simulationResponse.gasInfo
)}`
);
/** Broadcast transaction */
const txResponse = await txService.broadcast(txRaw);
if (txResponse.code !== 0) {
console.log(`Transaction failed: ${txResponse.rawLog}`);
} else {
console.log(
`Broadcasted transaction hash: ${JSON.stringify(txResponse.txhash)}`
);
}
})();