Thursday, November 21, 2024
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 continues 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 mistaken within the following code snippet. I’m making a uncooked transaction nonetheless i get a bizarre response when decoding it the place the handle arrays are empty or null. One thing could be very mistaken, if anybody has any expertise I’d so tremendously admire 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(handle: addressToSpendFrom)
}

func getUTXOforAddress(handle: String) {

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

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

        do {

            if error != nil {

                print(error as Any)
                DispatchQueue.foremost.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 activity = URLSession.shared.dataTask(with: url! as URL) { (information, response, error) -> Void in

                                    do {

                                        if error != nil {

                                            print(error as Any)
                                            DispatchQueue.foremost.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.foremost.async {
                                                        displayAlert(viewController: self, title: "Error", message: "Please strive once more.")
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                activity.resume()
                            }
                       }

                    } catch {

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

    activity.resume()

}

func callBTCTransaction() {

    let handle = 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

Most Popular

Recent Comments