UNPKG

ox

Version:

Ethereum Standard Library

517 lines 17.5 kB
import * as Errors from './Errors.js'; import * as Hex from './Hex.js'; import * as Transaction from './Transaction.js'; import * as TxEnvelopeEip1559 from './TxEnvelopeEip1559.js'; import * as TxEnvelopeEip2930 from './TxEnvelopeEip2930.js'; import * as TxEnvelopeEip4844 from './TxEnvelopeEip4844.js'; import * as TxEnvelopeEip7702 from './TxEnvelopeEip7702.js'; import * as TxEnvelopeLegacy from './TxEnvelopeLegacy.js'; import * as Value from './Value.js'; /** * Asserts a {@link ox#(TransactionEnvelope:namespace).TxEnvelope} is valid. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * TransactionEnvelope.assert({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * ``` * * @param envelope - The transaction envelope to assert. */ export function assert(envelope) { const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.assert(envelope); if (type === 'eip2930') return TxEnvelopeEip2930.assert(envelope); if (type === 'eip1559') return TxEnvelopeEip1559.assert(envelope); if (type === 'eip4844') return TxEnvelopeEip4844.assert(envelope); if (type === 'eip7702') return TxEnvelopeEip7702.assert(envelope); return TxEnvelopeEip1559.assert(envelope); } /** * Deserializes a {@link ox#(TransactionEnvelope:namespace).TxEnvelope} from its serialized form. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const envelope = TransactionEnvelope.deserialize( * '0x02df0180808080808080c0' as TransactionEnvelope.Serialized * ) * ``` * * @param serialized - The serialized transaction envelope. * @returns Deserialized Transaction Envelope. */ export function deserialize(serialized) { const type = getSerializedType(serialized); if (type === 'legacy') return TxEnvelopeLegacy.deserialize(serialized); if (type === 'eip2930') return TxEnvelopeEip2930.deserialize(serialized); if (type === 'eip1559') return TxEnvelopeEip1559.deserialize(serialized); if (type === 'eip4844') return TxEnvelopeEip4844.deserialize(serialized); return TxEnvelopeEip7702.deserialize(serialized); } /** * Converts an arbitrary transaction object or serialized transaction into a Transaction Envelope. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const envelope = TransactionEnvelope.from({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * ``` * * @param envelope - The transaction envelope. * @param options - Options. * @returns Transaction Envelope. */ export function from(envelope, options = {}) { if (typeof envelope === 'string') return deserialize(envelope); const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.from(envelope, options); if (type === 'eip2930') return TxEnvelopeEip2930.from(envelope, options); if (type === 'eip1559') return TxEnvelopeEip1559.from(envelope, options); if (type === 'eip4844') return TxEnvelopeEip4844.from(envelope, options); if (type === 'eip7702') return TxEnvelopeEip7702.from(envelope, options); return TxEnvelopeEip1559.from(envelope, options); } /** * Returns the payload to sign for a {@link ox#(TransactionEnvelope:namespace).TxEnvelope}. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const payload = TransactionEnvelope.getSignPayload({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * ``` * * @param envelope - The transaction envelope. * @returns The sign payload. */ export function getSignPayload(envelope) { const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.getSignPayload(envelope); if (type === 'eip2930') return TxEnvelopeEip2930.getSignPayload(envelope); if (type === 'eip1559') return TxEnvelopeEip1559.getSignPayload(envelope); if (type === 'eip4844') return TxEnvelopeEip4844.getSignPayload(envelope); if (type === 'eip7702') return TxEnvelopeEip7702.getSignPayload(envelope); return TxEnvelopeEip1559.getSignPayload(envelope); } /** * Returns the type of a Transaction Envelope. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const type = TransactionEnvelope.getType({ * maxFeePerGas: 1n * }) * // @log: 'eip1559' * ``` * * @param envelope - The transaction envelope. * @returns Transaction Envelope type. */ export function getType(envelope) { const type = envelope.type; if (type) { // Guard against accidental RPC-style type strings that map to a known // canonical envelope type ('0x0'…'0x4'). Canonical envelopes use // 'legacy' | 'eip2930' | 'eip1559' | 'eip4844' | 'eip7702'. RPC payloads // should be normalized through `TransactionRequest.fromRpc` (which // translates via `Transaction.fromRpcType`) before reaching the envelope // layer. Other custom `0x*` types (e.g. OP-Stack `0x7e`) pass through. if (typeof type === 'string' && type in Transaction.fromRpcType) throw new InvalidTypeError({ type }); return type; } if ('authorizationList' in envelope && envelope.authorizationList !== undefined) return 'eip7702'; if (('blobs' in envelope && envelope.blobs !== undefined) || ('blobVersionedHashes' in envelope && envelope.blobVersionedHashes !== undefined) || ('sidecars' in envelope && envelope.sidecars !== undefined) || ('maxFeePerBlobGas' in envelope && envelope.maxFeePerBlobGas !== undefined)) return 'eip4844'; if (('maxFeePerGas' in envelope && envelope.maxFeePerGas !== undefined) || ('maxPriorityFeePerGas' in envelope && envelope.maxPriorityFeePerGas !== undefined)) return 'eip1559'; if ('gasPrice' in envelope && envelope.gasPrice !== undefined) { if ('accessList' in envelope && envelope.accessList !== undefined) return 'eip2930'; return 'legacy'; } return 'eip1559'; } /** * Returns the type of a serialized Transaction Envelope. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const type = TransactionEnvelope.getSerializedType( * '0x02df0180808080808080c0' * ) * // @log: 'eip1559' * ``` * * @param serialized - The serialized transaction envelope. * @returns Transaction Envelope type. */ export function getSerializedType(serialized) { if (Hex.size(serialized) === 0) throw new InvalidSerializedTypeError({ serialized }); const serializedType = Hex.slice(serialized, 0, 1); if (serializedType === TxEnvelopeEip2930.serializedType) return 'eip2930'; if (serializedType === TxEnvelopeEip1559.serializedType) return 'eip1559'; if (serializedType === TxEnvelopeEip4844.serializedType) return 'eip4844'; if (serializedType === TxEnvelopeEip7702.serializedType) return 'eip7702'; if (Hex.toNumber(serializedType) >= 0xc0) return 'legacy'; throw new InvalidSerializedTypeError({ serialized }); } /** * Hashes a {@link ox#(TransactionEnvelope:namespace).TxEnvelope}. This is the "transaction hash". * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const hash = TransactionEnvelope.hash( * { * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }, * { presign: true } * ) * ``` * * @param envelope - The transaction envelope to hash. * @param options - Options. * @returns The hash of the transaction envelope. */ export function hash(envelope, options = {}) { const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.hash(envelope, options); if (type === 'eip2930') return TxEnvelopeEip2930.hash(envelope, options); if (type === 'eip1559') return TxEnvelopeEip1559.hash(envelope, options); if (type === 'eip4844') return TxEnvelopeEip4844.hash(envelope, options); if (type === 'eip7702') return TxEnvelopeEip7702.hash(envelope, options); return TxEnvelopeEip1559.hash(envelope, options); } /** * Serializes a {@link ox#(TransactionEnvelope:namespace).TxEnvelope}. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const serialized = TransactionEnvelope.serialize({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * ``` * * @param envelope - The transaction envelope to serialize. * @param options - Options. * @returns Serialized transaction envelope. */ export function serialize(envelope, options = {}) { const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.serialize(envelope, options); if (type === 'eip2930') return TxEnvelopeEip2930.serialize(envelope, options); if (type === 'eip1559') return TxEnvelopeEip1559.serialize(envelope, options); if (type === 'eip4844') return TxEnvelopeEip4844.serialize(envelope, options); if (type === 'eip7702') return TxEnvelopeEip7702.serialize(envelope, options); return TxEnvelopeEip1559.serialize(envelope, options); } /** * Converts a {@link ox#(TransactionEnvelope:namespace).TxEnvelope} to an {@link ox#(TransactionEnvelope:namespace).Rpc}. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const envelope_rpc = TransactionEnvelope.toRpc({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * ``` * * @param envelope - The transaction envelope. * @returns RPC representation. */ export function toRpc(envelope) { const type = getType(envelope); if (type === 'legacy') return TxEnvelopeLegacy.toRpc(envelope); if (type === 'eip2930') return TxEnvelopeEip2930.toRpc(envelope); if (type === 'eip1559') return TxEnvelopeEip1559.toRpc(envelope); if (type === 'eip4844') return TxEnvelopeEip4844.toRpc(envelope); if (type === 'eip7702') return TxEnvelopeEip7702.toRpc(envelope); return TxEnvelopeEip1559.toRpc(envelope); } /** * Converts a {@link ox#(TransactionEnvelope:namespace).TxEnvelope} to a {@link ox#TransactionRequest.TransactionRequest}. * * Flattens any EIP-7594 `sidecars` back into the top-level `blobs` field. * Signature fields (`r`, `s`, `yParity`, `v`) are preserved — Ox's * `TransactionRequest` extends the Execution API `GenericTransaction` * shape to optionally carry signed payloads. Pair with * {@link ox#TransactionRequest.(toRpc:function)} to produce an * `eth_sendTransaction`-shaped payload. * * Note: the 4844 round-trip * `TxEnvelope → TransactionRequest → TxEnvelope` is **lossy** — * `sidecars.commitments` and `sidecars.cellProofs` are not preserved on * the `TransactionRequest` shape. Callers that need full round-trip * parity must carry sidecars out of band. * * @example * ```ts twoslash * import { TransactionEnvelope, TxEnvelopeEip1559 } from 'ox' * * const envelope = TxEnvelopeEip1559.from({ * chainId: 1, * maxFeePerGas: 1n, * to: '0x0000000000000000000000000000000000000000', * value: 1n * }) * * const request = * TransactionEnvelope.toTransactionRequest(envelope) * // @log: { * // @log: chainId: 1, * // @log: maxFeePerGas: 1n, * // @log: to: '0x0000000000000000000000000000000000000000', * // @log: type: 'eip1559', * // @log: value: 1n, * // @log: } * ``` * * @param envelope - The transaction envelope to convert. * @returns A transaction request. */ export function toTransactionRequest(envelope) { const { // Flatten sidecars; surface their `blobs` payload instead. sidecars, blobs, ...rest } = envelope; const request = { ...rest }; const blobs_ = blobs ?? sidecars?.blobs; if (blobs_) request.blobs = blobs_; return request; } /** * Validates a {@link ox#(TransactionEnvelope:namespace).TxEnvelope}. Returns `true` if the envelope is valid, `false` otherwise. * * @example * ```ts twoslash * import { TransactionEnvelope } from 'ox' * * const valid = TransactionEnvelope.validate({ * chainId: 1, * maxFeePerGas: 1n, * type: 'eip1559' * }) * // @log: true * ``` * * @param envelope - The transaction envelope to validate. */ export function validate(envelope) { try { assert(envelope); return true; } catch { return false; } } /** * Thrown when a fee cap is too high. * * @example * ```ts twoslash * import { TxEnvelopeEip1559 } from 'ox' * * TxEnvelopeEip1559.assert({ * maxFeePerGas: 2n ** 256n - 1n + 1n, * chainId: 1 * }) * // @error: TransactionEnvelope.FeeCapTooHighError: The fee cap (`maxFeePerGas`/`maxPriorityFeePerGas` = 115792089237316195423570985008687907853269984665640564039457584007913.129639936 gwei) cannot be higher than the maximum allowed value (2^256-1). * ``` */ export class FeeCapTooHighError extends Errors.BaseError { name = 'TransactionEnvelope.FeeCapTooHighError'; constructor({ feeCap, } = {}) { super(`The fee cap (\`maxFeePerGas\`/\`maxPriorityFeePerGas\`${feeCap ? ` = ${Value.formatGwei(feeCap)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`); } } /** * Thrown when a gas price is too high. * * @example * ```ts twoslash * import { TxEnvelopeLegacy } from 'ox' * * TxEnvelopeLegacy.assert({ * gasPrice: 2n ** 256n - 1n + 1n, * chainId: 1 * }) * // @error: TransactionEnvelope.GasPriceTooHighError: The gas price (`gasPrice` = 115792089237316195423570985008687907853269984665640564039457584007913.129639936 gwei) cannot be higher than the maximum allowed value (2^256-1). * ``` */ export class GasPriceTooHighError extends Errors.BaseError { name = 'TransactionEnvelope.GasPriceTooHighError'; constructor({ gasPrice, } = {}) { super(`The gas price (\`gasPrice\`${gasPrice ? ` = ${Value.formatGwei(gasPrice)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`); } } /** * Thrown when a chain ID is invalid. * * @example * ```ts twoslash * import { TxEnvelopeEip1559 } from 'ox' * * TxEnvelopeEip1559.assert({ chainId: 0 }) * // @error: TransactionEnvelope.InvalidChainIdError: Chain ID "0" is invalid. * ``` */ export class InvalidChainIdError extends Errors.BaseError { name = 'TransactionEnvelope.InvalidChainIdError'; constructor({ chainId }) { super(typeof chainId !== 'undefined' ? `Chain ID "${chainId}" is invalid.` : 'Chain ID is invalid.'); } } /** * Thrown when a serialized transaction is invalid. * * @example * ```ts twoslash * import { TxEnvelopeEip1559 } from 'ox' * * TxEnvelopeEip1559.deserialize('0x02c0') * // @error: TransactionEnvelope.InvalidSerializedError: Invalid serialized transaction of type "eip1559" was provided. * // @error: Serialized Transaction: "0x02c0" * // @error: Missing Attributes: chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gas, to, value, data, accessList * ``` */ export class InvalidSerializedError extends Errors.BaseError { name = 'TransactionEnvelope.InvalidSerializedError'; constructor({ attributes, serialized, type, }) { const missing = Object.entries(attributes) .map(([key, value]) => (typeof value === 'undefined' ? key : undefined)) .filter(Boolean); super(`Invalid serialized transaction of type "${type}" was provided.`, { metaMessages: [ `Serialized Transaction: "${serialized}"`, missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '', ].filter(Boolean), }); } } /** Thrown when a serialized transaction type cannot be resolved. */ export class InvalidSerializedTypeError extends Errors.BaseError { name = 'TransactionEnvelope.InvalidSerializedTypeError'; constructor({ serialized }) { super('Serialized transaction type is invalid.', { metaMessages: [`Serialized Transaction: "${serialized}"`], }); } } /** Thrown when a transaction envelope type cannot be resolved. */ export class InvalidTypeError extends Errors.BaseError { name = 'TransactionEnvelope.InvalidTypeError'; constructor({ type } = {}) { super(type ? `Transaction type "${type}" is invalid.` : 'Cannot infer transaction type from provided envelope.'); } } /** * Thrown when a tip is higher than a fee cap. * * @example * ```ts twoslash * import { TxEnvelopeEip1559 } from 'ox' * * TxEnvelopeEip1559.assert({ * chainId: 1, * maxFeePerGas: 10n, * maxPriorityFeePerGas: 11n * }) * // @error: TransactionEnvelope.TipAboveFeeCapError: The provided tip (`maxPriorityFeePerGas` = 11 gwei) cannot be higher than the fee cap (`maxFeePerGas` = 10 gwei). * ``` */ export class TipAboveFeeCapError extends Errors.BaseError { name = 'TransactionEnvelope.TipAboveFeeCapError'; constructor({ maxPriorityFeePerGas, maxFeePerGas, } = {}) { super([ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${Value.formatGwei(maxPriorityFeePerGas)} gwei` : ''}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${Value.formatGwei(maxFeePerGas)} gwei` : ''}).`, ].join('\n')); } } //# sourceMappingURL=TxEnvelope.js.map