import { Cbor, CborByte, CborEncoded, CborUnsigned } from "."; import { CardanoTransaction } from "../transactions"; import { CardanoUTXO } from "../utxos"; import { CborArray } from "./array"; import { CborInteger } from "./integer"; import { CborUtxo } from "./utxo"; const TRANSACTION_START = 4; const encodeTransactionBody = ( encodedInputs: string, encodedOutputs: string, fee?: number, requiredSigners?: string, scriptHash?: string, collateral?: CardanoUTXO[], auxiliaryDataHash?: string ) => { const mapSize = 2 + (fee ? 1 : 0) + (requiredSigners ? 1 : 0) + (scriptHash ? 1 : 0) + (collateral ? 1 : 0) + (auxiliaryDataHash ? 1 : 0); const mapValues = [ fee ? `02${CborUnsigned.encode(fee)}` : "", auxiliaryDataHash ? `07${CborByte.encode(auxiliaryDataHash)}` : "", scriptHash ? `0B${CborByte.encode(scriptHash)}` : "", collateral ? `0D81${ CborTransaction.encodeTransaction(collateral[0].transaction).encoded }` : "", requiredSigners ? `0E81${CborByte.encode(requiredSigners)}` : "", ]; const value = `a${mapSize}00${encodedInputs}01${encodedOutputs}${mapValues.join( "" )}`; return { encoded: value, length: value.length, }; }; const encodeTransaction = ( tx: CardanoTransaction ): CborEncoded => { return { data: tx, encoded: `82${CborByte.encode(tx.hash)}${CborUnsigned.encode(tx.index)}`, }; }; const readTransaction = ( value: string ): CardanoTransaction & { headerLength: number } => { const hash = CborByte.read(value.substring(TRANSACTION_START)); const indexStart = TRANSACTION_START + 4 + hash.length; const index = CborInteger.read(value.substring(indexStart)); const indexLength = Cbor.readNextItemStringLength( value.substring(indexStart) ); return { hash, index, headerLength: indexStart + indexLength + 2, }; }; const decode = (value: string) => { const transaction = readTransaction(value); const utxo = CborUtxo.decode(value, transaction.headerLength); return { transaction: { hash: transaction.hash, index: transaction.index, }, utxo, }; }; export const CborTransaction = { encodeTransactionBody, encodeTransaction, decode, };