import { AuxDataSet, AuxiliaryData, parseAuxData } from "./auxiliary-data"; import { TxBody, parseTxBodies, parseTxBody } from "./txBody"; import { TxWitnessSet, parseTxWitness } from "./txWitnessSet"; import {cborBackend} from "cbor-rpc"; import { blake } from "../lib/blake"; import { RawTransaction } from "./cddlTypes"; export interface RawTxWithParse extends RawTransaction { parse: () => Transaction; hash: ()=> Buffer; } export class Transaction { body: TxBody; witnessSet: TxWitnessSet; auxiliaryData?: AuxiliaryData; valid: boolean; hash: Buffer; private constructor(tx: RawTransaction) { this.body = parseTxBody(tx[0]); this.witnessSet = parseTxWitness(tx[1]); this.valid = tx[2]; this.auxiliaryData = parseAuxData(tx[3]) || undefined; this.hash = blake.hash32(cborBackend.encode(tx[0])); } public static fromCborObject(obj: RawTransaction): Transaction { return new Transaction(obj); } /** * Fastest way to read transaction content from bytes. * The RawTransaction Typescript type adheres strictly to the CDDL definition of a transaction. * The CBOR object is decoded annd simply returned * as a RawTransaction without validating structure. * @param bytes CBOR encoded transaction bytes */ public static fromBytesAsRawObject(bytes: Buffer): RawTxWithParse { let rawTx = cborBackend.decode(bytes); (rawTx as any).parse = () => this.fromCborObject(rawTx); (rawTx as any).hash = () => blake.hash32(cborBackend.encode(rawTx[0])); return rawTx as RawTransaction & { parse: () => Transaction; hash: ()=> Buffer; }; } public static fromBytes(bytes: Buffer): Transaction { return Transaction.fromCborObject(cborBackend.decode(bytes)); } } export function parseTransactionBytes(transaction: Buffer): RawTxWithParse { const result = cborBackend.decode(transaction); result.parse = () => { return Transaction.fromCborObject(result); }; result.hash = () => blake.hash32(cborBackend.encode(result[0])); return result; } export function removeUndefined(obj: Record): Record { const newObj: Record = {}; for (const [key, value] of Object.entries(obj)) { if (value !== undefined) { newObj[key] = value; } } return newObj; }