getOrigin static method

Origin getOrigin(
  1. String psbtHex
)

Implementation

static Origin getOrigin(String psbtHex) {
  final psbt = PSBT.parse(psbtHex);
  final unsignedTx = psbt.unsignedTransaction!;

  // Extract inputs from PSBT
  final inputs = <OriginInput>[];
  for (int i = 0; i < psbt.inputs.length; i++) {
    final psbtInput = psbt.inputs[i];
    final txInput = unsignedTx.inputs[i];

    // Handle cases where witnessUtxo might be null
    double value = 0.0;
    String address = '';

    if (psbtInput.witnessUtxo != null) {
      value = psbtInput.witnessUtxo!.amount / 100000000;
      address = psbtInput.witnessUtxo!.scriptPubKey.getAddress();
    } else if (psbtInput.previousTransaction != null) {
      // Fallback to previous transaction if available
      final prevTx = psbtInput.previousTransaction!;
      final outputIndex = txInput.index;
      if (outputIndex < prevTx.outputs.length) {
        final output = prevTx.outputs[outputIndex];
        value = output.amount / 100000000;
        address = output.scriptPubKey.getAddress();
      } else {
        // ignore: avoid_print
        print('Warning: PSBT input $i has invalid output index');
        value = 0.0;
        address = 'unknown';
      }
    } else {
      // If neither witnessUtxo nor previousTransaction is available,
      // we can't determine the exact amount and address
      // ignore: avoid_print
      print('Warning: PSBT input $i has no witnessUtxo or previousTransaction');
      value = 0.0;
      address = 'unknown';
    }

    inputs.add(OriginInput(
      prevout: Prevout(
        hash: txInput.transactionHash,
        index: txInput.index,
      ),
      sequence: txInput.sequence,
      // Default coin info - would need external data source for accurate info
      coin: Coin(
        version: 2,
        height: 0, // Unknown from PSBT
        value: value, // May not be available
        address: address, // May not be available
        coinbase: false, // Unknown from PSBT
      ),
      path: Path(
        account: null, // May be available in derivation path
        change: false, // Unknown from PSBT
      ),
    ));
  }

  // Extract outputs from PSBT
  final outputs = <OriginOutput>[];
  for (final output in unsignedTx.outputs) {
    outputs.add(OriginOutput(
      address: output.scriptPubKey.getAddress(),
      amount: (output.amount / 100000000), // Convert satoshis to BTC
      path: null, // May be available in PSBT output data
      value: output.amount.toString(),
    ));
  }

  return Origin(
    status: 'success',
    code: 20000,
    fee: 0.0,
    rate: 0,
    mtime: DateTime.now().millisecondsSinceEpoch ~/ 1000, // useless data
    version: Converter.littleEndianToInt(Converter.hexToBytes(unsignedTx.version)),
    inputs: inputs,
    outputs: outputs,
    locktime: Converter.littleEndianToInt(Converter.hexToBytes(unsignedTx.lockTime)),
    hex: psbtHex,
  );
}