Saturday, January 11, 2025
HomeBitcoinios - Utilizing CoreBitcoin in Swift to create uncooked transaction

ios – Utilizing CoreBitcoin in Swift to create uncooked transaction


I’m new to coding, and solely know swift, obj-C remains to be overseas to me. I’ve a functioning pockets however for now am counting on BlockCypher API to construct a transaction which I do NOT need to do. Can anybody please assist inform me what I’m doing fallacious within the following code snippet. I’m making a uncooked transaction nevertheless i get a bizarre response when decoding it the place the deal with arrays are empty or null. One thing may be very fallacious, if anybody has any expertise I’d so vastly respect it as that is driving me loopy.

import UIKit

class BuildTransactionViewController: UIViewController, BTCTransactionBuilderDataSource {

var addressToSpendFrom = "n1QQYAHbw3q6UjWN6Q4d9oqa6u5iUDnPHT"
var privateKeyToSign = "cNeZkP1QPQ37C4rLvoQ8xZ5eujcjsYHZMj8CLfPPohYPvfKhzHWu"
var receiverAddress = "n1v9HH9Abs36fYf8KbwnFUfzR4prLBXhtW"
var inputData = [NSDictionary]()
var scriptArray = [String]()
var transaction = BTCTransaction()

override func viewDidLoad() {
    tremendous.viewDidLoad()

    getUTXOforAddress(deal with: addressToSpendFrom)
}

func getUTXOforAddress(deal with: String) {

    var url:NSURL!
    url = NSURL(string: "https://api.blockcypher.com/v1/btc/test3/addrs/(deal with)?unspentOnly=true")

    let job = URLSession.shared.dataTask(with: url! as URL) { (information, response, error) -> Void in

        do {

            if error != nil {

                print(error as Any)
                DispatchQueue.essential.async {
                    displayAlert(viewController: self, title: "Error", message: "Please test your interent connection.")
                }

            } else {

                if let urlContent = information {

                    do {

                        let jsonUTXOResult = strive JSONSerialization.jsonObject(with: urlContent, choices: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary

                        print("json = (jsonUTXOResult)")

                        if let utxoCheck = jsonUTXOResult["txrefs"] as? NSArray {

                            self.inputData = utxoCheck as! [NSDictionary]
                            print("utxoCheck = (utxoCheck)")

                            for merchandise in self.inputData {

                               let transactionHash = (merchandise)["tx_hash"] as! String
                                let worth = (merchandise)["value"] as! Int

                                var url:NSURL!
                                url = NSURL(string: "https://api.blockcypher.com/v1/btc/test3/txs/(transactionHash)")

                                let job = URLSession.shared.dataTask(with: url! as URL) { (information, response, error) -> Void in

                                    do {

                                        if error != nil {

                                            print(error as Any)
                                            DispatchQueue.essential.async {
                                                displayAlert(viewController: self, title: "Error", message: "Please test your interent connection.")
                                            }

                                        } else {

                                            if let urlContent = information {

                                                do {

                                                    let txHashResult = strive JSONSerialization.jsonObject(with: urlContent, choices: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary

                                                    print("txHashResult = (txHashResult)")

                                                    if let outputsCheck = txHashResult["outputs"] as? NSArray {

                                                        print("outputs = (outputsCheck)")

                                                        for output in outputsCheck {

                                                            if let valueCheck = (output as! NSDictionary)["value"] as? Int {

                                                                if valueCheck == worth {

                                                                    let script = (output as! NSDictionary)["script"] as! String
                                                                    self.scriptArray.append(script)
                                                                    print("script = (script)")
                                                                }

                                                            }

                                                        }

                                                        print("inputData = (self.inputData)")
                                                        print("scriptArray = (self.scriptArray)")
                                                        self.callBTCTransaction()

                                                    }

                                                } catch {

                                                    print("JSon processing failed")
                                                    DispatchQueue.essential.async {
                                                        displayAlert(viewController: self, title: "Error", message: "Please strive once more.")
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                job.resume()
                            }
                       }

                    } catch {

                        print("JSon processing failed")
                        DispatchQueue.essential.async {
                            displayAlert(viewController: self, title: "Error", message: "Please strive once more.")
                        }
                    }
                }
            }
        }
    }

    job.resume()

}

func callBTCTransaction() {

    let deal with = BTCAddress(string: self.receiverAddress)
    let newTransaction = BTCTransactionBuilder()
    newTransaction.dataSource = self
    newTransaction.shouldSign = true
    newTransaction.changeAddress = BTCAddress(string: self.addressToSpendFrom)
    newTransaction.outputs = [BTCTransactionOutput(value: BTCAmount(1000), address: address)]
    newTransaction.feeRate = BTCAmount(2000)
    var consequence:BTCTransactionBuilderResult? = nil
    do {
        consequence = strive newTransaction.buildTransaction()
        print("transactionRaw = (String(describing: consequence?.transaction.hex))")
    } catch {
        print("error = (error as Any)")
    }
}

func transactionBuilder(_ txbuilder: BTCTransactionBuilder!, keyForUnspentOutput txout: BTCTransactionOutput!) -> BTCKey! {
    print("transactionBuilder")

    let key = BTCKey.init(wif: self.privateKeyToSign)
    key?.isPublicKeyCompressed = true

    return key
}



func unspentOutputs(for txbuilder: BTCTransactionBuilder!) -> NSEnumerator! {

    let outputs = NSMutableArray()

    for (index, merchandise) in inputData.enumerated() {

        let txout = BTCTransactionOutput()
        txout.worth = BTCAmount((merchandise).worth(forKey: "worth") as! Int64)
        txout.script = BTCScript.init(hex: self.scriptArray[index])
        txout.index = UInt32((merchandise).worth(forKey: "tx_output_n") as! Int)
        txout.confirmations = UInt((merchandise).worth(forKey: "confirmations") as! Int)
        let transactionHash = (merchandise)["tx_hash"] as! String
        txout.transactionHash = transactionHash.information(utilizing: .utf8)
        outputs.add(txout)

    }

    print("outputs = (outputs)")

    return outputs.objectEnumerator()
}

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments