chaingate
Version:
Multi-chain cryptocurrency SDK for TypeScript — unified API for Bitcoin, Ethereum, Litecoin, Dogecoin, Bitcoin Cash, Polygon, Arbitrum, and any EVM-compatible chain. Create wallets, query balances, send transactions, and manage tokens and NFTs across UTXO
78 lines (77 loc) • 2.9 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseEvmTransaction = void 0;
const errors_1 = require("../../errors");
/** Shared base for unsigned EVM transactions. */
class BaseEvmTransaction {
/** @internal */
constructor(params) {
this.sent = false;
this.fromAddress = params.fromAddress;
this.toAddress = params.toAddress;
this.valueWei = params.valueWei;
this.data = params.data;
this.nonce = params.nonce;
this.gasLimit = params.gasLimit;
this.chainId = params.chainId;
this.balanceWei = params.balanceWei;
this.getPrivateKey = params.getPrivateKey;
this._currentFee = { ...params.initialFee };
}
/** Returns whether the wallet has enough funds for value + fee at the current gas limit. */
enoughFunds() {
const totalCost = this.valueWei + this._currentFee.maxFeePerGas * this.gasLimit;
return this.balanceWei >= totalCost;
}
/**
* Applies a fee override to this transaction.
*
* @throws {@link TransactionAlreadySentError} if the transaction has already been sent.
* @internal
*/
applyFee(fee) {
if (this.sent) {
throw new errors_1.TransactionAlreadySentError();
}
this._currentFee = {
maxFeePerGas: fee.maxFeePerGas,
maxPriorityFeePerGas: fee.maxPriorityFeePerGas,
};
if (fee.gasLimit !== undefined) {
this.gasLimit = fee.gasLimit;
}
}
/**
* Signs the transaction with the wallet's private key and broadcasts it.
*
* @returns A subclass-specific `Broadcasted*Transaction` that tracks confirmation.
* @throws {@link TransactionAlreadySentError} if the transaction has already been sent.
* @throws {@link NotEnoughFundsError} if the wallet does not have enough funds.
*/
async signAndBroadcast() {
if (this.sent) {
throw new errors_1.TransactionAlreadySentError();
}
if (!this.enoughFunds()) {
throw new errors_1.NotEnoughFundsError();
}
const privateKey = await this.getPrivateKey();
const signedRaw = this.signTransaction(privateKey, {
chainId: this.chainId,
nonce: this.nonce,
maxFeePerGas: this._currentFee.maxFeePerGas,
maxPriorityFeePerGas: this._currentFee.maxPriorityFeePerGas,
gasLimit: this.gasLimit,
to: this.toAddress,
value: this.valueWei,
data: this.data,
});
// Zero out the private key after signing.
privateKey.fill(0);
const transactionId = await this.broadcast(signedRaw);
this.sent = true;
this.recordNonceUsed();
return this.buildBroadcasted(transactionId);
}
}
exports.BaseEvmTransaction = BaseEvmTransaction;