diff --git a/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKMapper.kt b/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKMapper.kt deleted file mode 100644 index 421b6b46c..000000000 --- a/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKMapper.kt +++ /dev/null @@ -1,908 +0,0 @@ -package com.breezliquidsdk -import breez_liquid_sdk.* -import com.facebook.react.bridge.* -import java.util.* - -fun asBackupRequest(backupRequest: ReadableMap): BackupRequest? { - if (!validateMandatoryFields( - backupRequest, - arrayOf(), - ) - ) { - return null - } - val backupPath = if (hasNonNullKey(backupRequest, "backupPath")) backupRequest.getString("backupPath") else null - return BackupRequest( - backupPath, - ) -} - -fun readableMapOf(backupRequest: BackupRequest): ReadableMap = - readableMapOf( - "backupPath" to backupRequest.backupPath, - ) - -fun asBackupRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asBackupRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asConfig(config: ReadableMap): Config? { - if (!validateMandatoryFields( - config, - arrayOf( - "boltzUrl", - "electrumUrl", - "workingDir", - "network", - "paymentTimeoutSec", - ), - ) - ) { - return null - } - val boltzUrl = config.getString("boltzUrl")!! - val electrumUrl = config.getString("electrumUrl")!! - val workingDir = config.getString("workingDir")!! - val network = config.getString("network")?.let { asNetwork(it) }!! - val paymentTimeoutSec = config.getDouble("paymentTimeoutSec").toULong() - return Config( - boltzUrl, - electrumUrl, - workingDir, - network, - paymentTimeoutSec, - ) -} - -fun readableMapOf(config: Config): ReadableMap = - readableMapOf( - "boltzUrl" to config.boltzUrl, - "electrumUrl" to config.electrumUrl, - "workingDir" to config.workingDir, - "network" to config.network.name.lowercase(), - "paymentTimeoutSec" to config.paymentTimeoutSec, - ) - -fun asConfigList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asConfig(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asConnectRequest(connectRequest: ReadableMap): ConnectRequest? { - if (!validateMandatoryFields( - connectRequest, - arrayOf( - "config", - "mnemonic", - ), - ) - ) { - return null - } - val config = connectRequest.getMap("config")?.let { asConfig(it) }!! - val mnemonic = connectRequest.getString("mnemonic")!! - return ConnectRequest( - config, - mnemonic, - ) -} - -fun readableMapOf(connectRequest: ConnectRequest): ReadableMap = - readableMapOf( - "config" to readableMapOf(connectRequest.config), - "mnemonic" to connectRequest.mnemonic, - ) - -fun asConnectRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asConnectRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asGetInfoRequest(getInfoRequest: ReadableMap): GetInfoRequest? { - if (!validateMandatoryFields( - getInfoRequest, - arrayOf( - "withScan", - ), - ) - ) { - return null - } - val withScan = getInfoRequest.getBoolean("withScan") - return GetInfoRequest( - withScan, - ) -} - -fun readableMapOf(getInfoRequest: GetInfoRequest): ReadableMap = - readableMapOf( - "withScan" to getInfoRequest.withScan, - ) - -fun asGetInfoRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asGetInfoRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asGetInfoResponse(getInfoResponse: ReadableMap): GetInfoResponse? { - if (!validateMandatoryFields( - getInfoResponse, - arrayOf( - "balanceSat", - "pendingSendSat", - "pendingReceiveSat", - "pubkey", - ), - ) - ) { - return null - } - val balanceSat = getInfoResponse.getDouble("balanceSat").toULong() - val pendingSendSat = getInfoResponse.getDouble("pendingSendSat").toULong() - val pendingReceiveSat = getInfoResponse.getDouble("pendingReceiveSat").toULong() - val pubkey = getInfoResponse.getString("pubkey")!! - return GetInfoResponse( - balanceSat, - pendingSendSat, - pendingReceiveSat, - pubkey, - ) -} - -fun readableMapOf(getInfoResponse: GetInfoResponse): ReadableMap = - readableMapOf( - "balanceSat" to getInfoResponse.balanceSat, - "pendingSendSat" to getInfoResponse.pendingSendSat, - "pendingReceiveSat" to getInfoResponse.pendingReceiveSat, - "pubkey" to getInfoResponse.pubkey, - ) - -fun asGetInfoResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asGetInfoResponse(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asLnInvoice(lnInvoice: ReadableMap): LnInvoice? { - if (!validateMandatoryFields( - lnInvoice, - arrayOf( - "bolt11", - "network", - "payeePubkey", - "paymentHash", - "timestamp", - "expiry", - "routingHints", - "paymentSecret", - "minFinalCltvExpiryDelta", - ), - ) - ) { - return null - } - val bolt11 = lnInvoice.getString("bolt11")!! - val network = lnInvoice.getString("network")?.let { asNetwork(it) }!! - val payeePubkey = lnInvoice.getString("payeePubkey")!! - val paymentHash = lnInvoice.getString("paymentHash")!! - val description = if (hasNonNullKey(lnInvoice, "description")) lnInvoice.getString("description") else null - val descriptionHash = if (hasNonNullKey(lnInvoice, "descriptionHash")) lnInvoice.getString("descriptionHash") else null - val amountMsat = if (hasNonNullKey(lnInvoice, "amountMsat")) lnInvoice.getDouble("amountMsat").toULong() else null - val timestamp = lnInvoice.getDouble("timestamp").toULong() - val expiry = lnInvoice.getDouble("expiry").toULong() - val routingHints = lnInvoice.getArray("routingHints")?.let { asRouteHintList(it) }!! - val paymentSecret = lnInvoice.getArray("paymentSecret")?.let { asUByteList(it) }!! - val minFinalCltvExpiryDelta = lnInvoice.getDouble("minFinalCltvExpiryDelta").toULong() - return LnInvoice( - bolt11, - network, - payeePubkey, - paymentHash, - description, - descriptionHash, - amountMsat, - timestamp, - expiry, - routingHints, - paymentSecret, - minFinalCltvExpiryDelta, - ) -} - -fun readableMapOf(lnInvoice: LnInvoice): ReadableMap = - readableMapOf( - "bolt11" to lnInvoice.bolt11, - "network" to lnInvoice.network.name.lowercase(), - "payeePubkey" to lnInvoice.payeePubkey, - "paymentHash" to lnInvoice.paymentHash, - "description" to lnInvoice.description, - "descriptionHash" to lnInvoice.descriptionHash, - "amountMsat" to lnInvoice.amountMsat, - "timestamp" to lnInvoice.timestamp, - "expiry" to lnInvoice.expiry, - "routingHints" to readableArrayOf(lnInvoice.routingHints), - "paymentSecret" to readableArrayOf(lnInvoice.paymentSecret), - "minFinalCltvExpiryDelta" to lnInvoice.minFinalCltvExpiryDelta, - ) - -fun asLnInvoiceList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asLnInvoice(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asLogEntry(logEntry: ReadableMap): LogEntry? { - if (!validateMandatoryFields( - logEntry, - arrayOf( - "line", - "level", - ), - ) - ) { - return null - } - val line = logEntry.getString("line")!! - val level = logEntry.getString("level")!! - return LogEntry( - line, - level, - ) -} - -fun readableMapOf(logEntry: LogEntry): ReadableMap = - readableMapOf( - "line" to logEntry.line, - "level" to logEntry.level, - ) - -fun asLogEntryList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asLogEntry(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPayment(payment: ReadableMap): Payment? { - if (!validateMandatoryFields( - payment, - arrayOf( - "txId", - "timestamp", - "amountSat", - "paymentType", - "status", - ), - ) - ) { - return null - } - val txId = payment.getString("txId")!! - val swapId = if (hasNonNullKey(payment, "swapId")) payment.getString("swapId") else null - val timestamp = payment.getInt("timestamp").toUInt() - val amountSat = payment.getDouble("amountSat").toULong() - val feesSat = if (hasNonNullKey(payment, "feesSat")) payment.getDouble("feesSat").toULong() else null - val preimage = if (hasNonNullKey(payment, "preimage")) payment.getString("preimage") else null - val refundTxId = if (hasNonNullKey(payment, "refundTxId")) payment.getString("refundTxId") else null - val refundTxAmountSat = if (hasNonNullKey(payment, "refundTxAmountSat")) payment.getDouble("refundTxAmountSat").toULong() else null - val paymentType = payment.getString("paymentType")?.let { asPaymentType(it) }!! - val status = payment.getString("status")?.let { asPaymentState(it) }!! - return Payment( - txId, - swapId, - timestamp, - amountSat, - feesSat, - preimage, - refundTxId, - refundTxAmountSat, - paymentType, - status, - ) -} - -fun readableMapOf(payment: Payment): ReadableMap = - readableMapOf( - "txId" to payment.txId, - "swapId" to payment.swapId, - "timestamp" to payment.timestamp, - "amountSat" to payment.amountSat, - "feesSat" to payment.feesSat, - "preimage" to payment.preimage, - "refundTxId" to payment.refundTxId, - "refundTxAmountSat" to payment.refundTxAmountSat, - "paymentType" to payment.paymentType.name.lowercase(), - "status" to payment.status.name.lowercase(), - ) - -fun asPaymentList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPayment(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareReceiveRequest(prepareReceiveRequest: ReadableMap): PrepareReceiveRequest? { - if (!validateMandatoryFields( - prepareReceiveRequest, - arrayOf( - "payerAmountSat", - ), - ) - ) { - return null - } - val payerAmountSat = prepareReceiveRequest.getDouble("payerAmountSat").toULong() - return PrepareReceiveRequest( - payerAmountSat, - ) -} - -fun readableMapOf(prepareReceiveRequest: PrepareReceiveRequest): ReadableMap = - readableMapOf( - "payerAmountSat" to prepareReceiveRequest.payerAmountSat, - ) - -fun asPrepareReceiveRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareReceiveRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareReceiveResponse(prepareReceiveResponse: ReadableMap): PrepareReceiveResponse? { - if (!validateMandatoryFields( - prepareReceiveResponse, - arrayOf( - "payerAmountSat", - "feesSat", - ), - ) - ) { - return null - } - val payerAmountSat = prepareReceiveResponse.getDouble("payerAmountSat").toULong() - val feesSat = prepareReceiveResponse.getDouble("feesSat").toULong() - return PrepareReceiveResponse( - payerAmountSat, - feesSat, - ) -} - -fun readableMapOf(prepareReceiveResponse: PrepareReceiveResponse): ReadableMap = - readableMapOf( - "payerAmountSat" to prepareReceiveResponse.payerAmountSat, - "feesSat" to prepareReceiveResponse.feesSat, - ) - -fun asPrepareReceiveResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareReceiveResponse(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareSendRequest(prepareSendRequest: ReadableMap): PrepareSendRequest? { - if (!validateMandatoryFields( - prepareSendRequest, - arrayOf( - "invoice", - ), - ) - ) { - return null - } - val invoice = prepareSendRequest.getString("invoice")!! - return PrepareSendRequest( - invoice, - ) -} - -fun readableMapOf(prepareSendRequest: PrepareSendRequest): ReadableMap = - readableMapOf( - "invoice" to prepareSendRequest.invoice, - ) - -fun asPrepareSendRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareSendRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareSendResponse(prepareSendResponse: ReadableMap): PrepareSendResponse? { - if (!validateMandatoryFields( - prepareSendResponse, - arrayOf( - "invoice", - "feesSat", - ), - ) - ) { - return null - } - val invoice = prepareSendResponse.getString("invoice")!! - val feesSat = prepareSendResponse.getDouble("feesSat").toULong() - return PrepareSendResponse( - invoice, - feesSat, - ) -} - -fun readableMapOf(prepareSendResponse: PrepareSendResponse): ReadableMap = - readableMapOf( - "invoice" to prepareSendResponse.invoice, - "feesSat" to prepareSendResponse.feesSat, - ) - -fun asPrepareSendResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareSendResponse(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asReceivePaymentResponse(receivePaymentResponse: ReadableMap): ReceivePaymentResponse? { - if (!validateMandatoryFields( - receivePaymentResponse, - arrayOf( - "id", - "invoice", - ), - ) - ) { - return null - } - val id = receivePaymentResponse.getString("id")!! - val invoice = receivePaymentResponse.getString("invoice")!! - return ReceivePaymentResponse( - id, - invoice, - ) -} - -fun readableMapOf(receivePaymentResponse: ReceivePaymentResponse): ReadableMap = - readableMapOf( - "id" to receivePaymentResponse.id, - "invoice" to receivePaymentResponse.invoice, - ) - -fun asReceivePaymentResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asReceivePaymentResponse(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asRestoreRequest(restoreRequest: ReadableMap): RestoreRequest? { - if (!validateMandatoryFields( - restoreRequest, - arrayOf(), - ) - ) { - return null - } - val backupPath = if (hasNonNullKey(restoreRequest, "backupPath")) restoreRequest.getString("backupPath") else null - return RestoreRequest( - backupPath, - ) -} - -fun readableMapOf(restoreRequest: RestoreRequest): ReadableMap = - readableMapOf( - "backupPath" to restoreRequest.backupPath, - ) - -fun asRestoreRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asRestoreRequest(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asRouteHint(routeHint: ReadableMap): RouteHint? { - if (!validateMandatoryFields( - routeHint, - arrayOf( - "hops", - ), - ) - ) { - return null - } - val hops = routeHint.getArray("hops")?.let { asRouteHintHopList(it) }!! - return RouteHint( - hops, - ) -} - -fun readableMapOf(routeHint: RouteHint): ReadableMap = - readableMapOf( - "hops" to readableArrayOf(routeHint.hops), - ) - -fun asRouteHintList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asRouteHint(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asRouteHintHop(routeHintHop: ReadableMap): RouteHintHop? { - if (!validateMandatoryFields( - routeHintHop, - arrayOf( - "srcNodeId", - "shortChannelId", - "feesBaseMsat", - "feesProportionalMillionths", - "cltvExpiryDelta", - ), - ) - ) { - return null - } - val srcNodeId = routeHintHop.getString("srcNodeId")!! - val shortChannelId = routeHintHop.getDouble("shortChannelId").toULong() - val feesBaseMsat = routeHintHop.getInt("feesBaseMsat").toUInt() - val feesProportionalMillionths = routeHintHop.getInt("feesProportionalMillionths").toUInt() - val cltvExpiryDelta = routeHintHop.getDouble("cltvExpiryDelta").toULong() - val htlcMinimumMsat = if (hasNonNullKey(routeHintHop, "htlcMinimumMsat")) routeHintHop.getDouble("htlcMinimumMsat").toULong() else null - val htlcMaximumMsat = if (hasNonNullKey(routeHintHop, "htlcMaximumMsat")) routeHintHop.getDouble("htlcMaximumMsat").toULong() else null - return RouteHintHop( - srcNodeId, - shortChannelId, - feesBaseMsat, - feesProportionalMillionths, - cltvExpiryDelta, - htlcMinimumMsat, - htlcMaximumMsat, - ) -} - -fun readableMapOf(routeHintHop: RouteHintHop): ReadableMap = - readableMapOf( - "srcNodeId" to routeHintHop.srcNodeId, - "shortChannelId" to routeHintHop.shortChannelId, - "feesBaseMsat" to routeHintHop.feesBaseMsat, - "feesProportionalMillionths" to routeHintHop.feesProportionalMillionths, - "cltvExpiryDelta" to routeHintHop.cltvExpiryDelta, - "htlcMinimumMsat" to routeHintHop.htlcMinimumMsat, - "htlcMaximumMsat" to routeHintHop.htlcMaximumMsat, - ) - -fun asRouteHintHopList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asRouteHintHop(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asSendPaymentResponse(sendPaymentResponse: ReadableMap): SendPaymentResponse? { - if (!validateMandatoryFields( - sendPaymentResponse, - arrayOf( - "payment", - ), - ) - ) { - return null - } - val payment = sendPaymentResponse.getMap("payment")?.let { asPayment(it) }!! - return SendPaymentResponse( - payment, - ) -} - -fun readableMapOf(sendPaymentResponse: SendPaymentResponse): ReadableMap = - readableMapOf( - "payment" to readableMapOf(sendPaymentResponse.payment), - ) - -fun asSendPaymentResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asSendPaymentResponse(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asLiquidSdkEvent(liquidSdkEvent: ReadableMap): LiquidSdkEvent? { - val type = liquidSdkEvent.getString("type") - - if (type == "paymentFailed") { - return LiquidSdkEvent.PaymentFailed(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "paymentPending") { - return LiquidSdkEvent.PaymentPending(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "paymentRefunded") { - return LiquidSdkEvent.PaymentRefunded(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "paymentRefundPending") { - return LiquidSdkEvent.PaymentRefundPending(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "paymentSucceed") { - return LiquidSdkEvent.PaymentSucceed(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "paymentWaitingConfirmation") { - return LiquidSdkEvent.PaymentWaitingConfirmation(liquidSdkEvent.getMap("details")?.let { asPayment(it) }!!) - } - if (type == "synced") { - return LiquidSdkEvent.Synced - } - return null -} - -fun readableMapOf(liquidSdkEvent: LiquidSdkEvent): ReadableMap? { - val map = Arguments.createMap() - when (liquidSdkEvent) { - is LiquidSdkEvent.PaymentFailed -> { - pushToMap(map, "type", "paymentFailed") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.PaymentPending -> { - pushToMap(map, "type", "paymentPending") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.PaymentRefunded -> { - pushToMap(map, "type", "paymentRefunded") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.PaymentRefundPending -> { - pushToMap(map, "type", "paymentRefundPending") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.PaymentSucceed -> { - pushToMap(map, "type", "paymentSucceed") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.PaymentWaitingConfirmation -> { - pushToMap(map, "type", "paymentWaitingConfirmation") - pushToMap(map, "details", readableMapOf(liquidSdkEvent.details)) - } - is LiquidSdkEvent.Synced -> { - pushToMap(map, "type", "synced") - } - } - return map -} - -fun asLiquidSdkEventList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asLiquidSdkEvent(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asNetwork(type: String): Network = Network.valueOf(camelToUpperSnakeCase(type)) - -fun asNetworkList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is String -> list.add(asNetwork(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPaymentState(type: String): PaymentState = PaymentState.valueOf(camelToUpperSnakeCase(type)) - -fun asPaymentStateList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is String -> list.add(asPaymentState(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPaymentType(type: String): PaymentType = PaymentType.valueOf(camelToUpperSnakeCase(type)) - -fun asPaymentTypeList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is String -> list.add(asPaymentType(value)!!) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun readableMapOf(vararg values: Pair): ReadableMap { - val map = Arguments.createMap() - for ((key, value) in values) { - pushToMap(map, key, value) - } - return map -} - -fun hasNonNullKey( - map: ReadableMap, - key: String, -): Boolean = map.hasKey(key) && !map.isNull(key) - -fun validateMandatoryFields( - map: ReadableMap, - keys: Array, -): Boolean { - for (k in keys) { - if (!hasNonNullKey(map, k)) return false - } - - return true -} - -fun pushToArray( - array: WritableArray, - value: Any?, -) { - when (value) { - null -> array.pushNull() - is Payment -> array.pushMap(readableMapOf(value)) - is RouteHint -> array.pushMap(readableMapOf(value)) - is RouteHintHop -> array.pushMap(readableMapOf(value)) - is UByte -> array.pushInt(value.toInt()) - is Array<*> -> array.pushArray(readableArrayOf(value.asIterable())) - is List<*> -> array.pushArray(readableArrayOf(value)) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } -} - -fun pushToMap( - map: WritableMap, - key: String, - value: Any?, -) { - when (value) { - null -> map.putNull(key) - is Boolean -> map.putBoolean(key, value) - is Byte -> map.putInt(key, value.toInt()) - is Double -> map.putDouble(key, value) - is Int -> map.putInt(key, value) - is Long -> map.putDouble(key, value.toDouble()) - is ReadableArray -> map.putArray(key, value) - is ReadableMap -> map.putMap(key, value) - is String -> map.putString(key, value) - is UByte -> map.putInt(key, value.toInt()) - is UInt -> map.putInt(key, value.toInt()) - is UShort -> map.putInt(key, value.toInt()) - is ULong -> map.putDouble(key, value.toDouble()) - is Array<*> -> map.putArray(key, readableArrayOf(value.asIterable())) - is List<*> -> map.putArray(key, readableArrayOf(value)) - else -> throw LiquidSdkException.Generic("Unexpected type ${value::class.java.name} for key [$key]") - } -} - -fun readableArrayOf(values: Iterable<*>?): ReadableArray { - val array = Arguments.createArray() - if (values != null) { - for (value in values) { - pushToArray(array, value) - } - } - - return array -} - -fun asUByteList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is Double -> list.add(value.toInt().toUByte()) - is Int -> list.add(value.toUByte()) - is UByte -> list.add(value) - else -> throw LiquidSdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asStringList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - list.add(value.toString()) - } - return list -} - -fun errMissingMandatoryField( - fieldName: String, - typeName: String, -): String = "Missing mandatory field $fieldName for type $typeName" - -fun errUnexpectedType(typeName: String): String = "Unexpected type $typeName" - -fun errUnexpectedValue(fieldName: String): String = "Unexpected value for optional field $fieldName" - -fun camelToUpperSnakeCase(str: String): String { - val pattern = "(?<=.)[A-Z]".toRegex() - return str.replace(pattern, "_$0").uppercase() -} diff --git a/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKModule.kt b/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKModule.kt deleted file mode 100644 index a82d11b7e..000000000 --- a/packages/react-native/android/src/main/java/com/breezliquidsdk/BreezLiquidSDKModule.kt +++ /dev/null @@ -1,321 +0,0 @@ -package com.breezliquidsdk - -import breez_liquid_sdk.* -import com.facebook.react.bridge.* -import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter -import java.io.File -import java.util.* -import java.util.concurrent.ExecutorService -import java.util.concurrent.Executors - -class BreezLiquidSDKModule( - reactContext: ReactApplicationContext, -) : ReactContextBaseJavaModule(reactContext) { - private lateinit var executor: ExecutorService - private var bindingLiquidSdk: BindingLiquidSdk? = null - - companion object { - const val TAG = "RNBreezLiquidSDK" - } - - override fun initialize() { - super.initialize() - - executor = Executors.newFixedThreadPool(3) - } - - override fun getName(): String = TAG - - @Throws(LiquidSdkException::class) - fun getBindingLiquidSdk(): BindingLiquidSdk { - if (bindingLiquidSdk != null) { - return bindingLiquidSdk!! - } - - throw LiquidSdkException.Generic("Not initialized") - } - - @Throws(LiquidSdkException::class) - private fun ensureWorkingDir(workingDir: String) { - try { - val workingDirFile = File(workingDir) - - if (!workingDirFile.exists() && !workingDirFile.mkdirs()) { - throw LiquidSdkException.Generic("Mandatory field workingDir must contain a writable directory") - } - } catch (e: SecurityException) { - throw LiquidSdkException.Generic("Mandatory field workingDir must contain a writable directory") - } - } - - @ReactMethod - fun addListener(eventName: String) {} - - @ReactMethod - fun removeListeners(count: Int) {} - - @ReactMethod - fun defaultConfig( - network: String, - promise: Promise, - ) { - executor.execute { - try { - val networkTmp = asNetwork(network) - val res = defaultConfig(networkTmp) - val workingDir = File(reactApplicationContext.filesDir.toString() + "/breezLiquidSdk") - - res.workingDir = workingDir.absolutePath - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun parseInvoice( - invoice: String, - promise: Promise, - ) { - executor.execute { - try { - val res = parseInvoice(invoice) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun setLogger(promise: Promise) { - executor.execute { - try { - val emitter = reactApplicationContext.getJSModule(RCTDeviceEventEmitter::class.java) - - setLogger(BreezLiquidSDKLogger(emitter)) - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - e.printStackTrace() - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun connect( - req: ReadableMap, - promise: Promise, - ) { - if (bindingLiquidSdk != null) { - promise.reject("Generic", "Already initialized") - return - } - - executor.execute { - try { - var connectRequest = - asConnectRequest(req) ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "ConnectRequest")) } - - ensureWorkingDir(connectRequest.config.workingDir) - - bindingLiquidSdk = connect(connectRequest) - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun addEventListener(promise: Promise) { - executor.execute { - try { - val emitter = reactApplicationContext.getJSModule(RCTDeviceEventEmitter::class.java) - var eventListener = BreezLiquidSDKEventListener(emitter) - val res = getBindingLiquidSdk().addEventListener(eventListener) - - eventListener.setId(res) - promise.resolve(res) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun removeEventListener( - id: String, - promise: Promise, - ) { - executor.execute { - try { - getBindingLiquidSdk().removeEventListener(id) - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun getInfo( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val getInfoRequest = - asGetInfoRequest(req) ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "GetInfoRequest")) } - val res = getBindingLiquidSdk().getInfo(getInfoRequest) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun prepareSendPayment( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareSendRequest = - asPrepareSendRequest(req) - ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "PrepareSendRequest")) } - val res = getBindingLiquidSdk().prepareSendPayment(prepareSendRequest) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun sendPayment( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareSendResponse = - asPrepareSendResponse(req) - ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "PrepareSendResponse")) } - val res = getBindingLiquidSdk().sendPayment(prepareSendResponse) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun prepareReceivePayment( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareReceiveRequest = - asPrepareReceiveRequest(req) - ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "PrepareReceiveRequest")) } - val res = getBindingLiquidSdk().prepareReceivePayment(prepareReceiveRequest) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun receivePayment( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareReceiveResponse = - asPrepareReceiveResponse(req) - ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "PrepareReceiveResponse")) } - val res = getBindingLiquidSdk().receivePayment(prepareReceiveResponse) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun listPayments(promise: Promise) { - executor.execute { - try { - val res = getBindingLiquidSdk().listPayments() - promise.resolve(readableArrayOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun sync(promise: Promise) { - executor.execute { - try { - getBindingLiquidSdk().sync() - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun backup( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val backupRequest = - asBackupRequest(req) ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "BackupRequest")) } - getBindingLiquidSdk().backup(backupRequest) - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun restore( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val restoreRequest = - asRestoreRequest(req) ?: run { throw LiquidSdkException.Generic(errMissingMandatoryField("req", "RestoreRequest")) } - getBindingLiquidSdk().restore(restoreRequest) - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun disconnect(promise: Promise) { - executor.execute { - try { - getBindingLiquidSdk().disconnect() - bindingLiquidSdk = null - promise.resolve(readableMapOf("status" to "ok")) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } -} diff --git a/packages/react-native/ios/BreezLiquidSDKMapper.swift b/packages/react-native/ios/BreezLiquidSDKMapper.swift deleted file mode 100644 index 75e3ee646..000000000 --- a/packages/react-native/ios/BreezLiquidSDKMapper.swift +++ /dev/null @@ -1,1095 +0,0 @@ -import BreezLiquidSDK -import Foundation - -enum BreezLiquidSDKMapper { - static func asBackupRequest(backupRequest: [String: Any?]) throws -> BackupRequest { - var backupPath: String? - if hasNonNilKey(data: backupRequest, key: "backupPath") { - guard let backupPathTmp = backupRequest["backupPath"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "backupPath")) - } - backupPath = backupPathTmp - } - - return BackupRequest( - backupPath: backupPath) - } - - static func dictionaryOf(backupRequest: BackupRequest) -> [String: Any?] { - return [ - "backupPath": backupRequest.backupPath == nil ? nil : backupRequest.backupPath, - ] - } - - static func asBackupRequestList(arr: [Any]) throws -> [BackupRequest] { - var list = [BackupRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var backupRequest = try asBackupRequest(backupRequest: val) - list.append(backupRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "BackupRequest")) - } - } - return list - } - - static func arrayOf(backupRequestList: [BackupRequest]) -> [Any] { - return backupRequestList.map { v -> [String: Any?] in dictionaryOf(backupRequest: v) } - } - - static func asConfig(config: [String: Any?]) throws -> Config { - guard let boltzUrl = config["boltzUrl"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "boltzUrl", typeName: "Config")) - } - guard let electrumUrl = config["electrumUrl"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "electrumUrl", typeName: "Config")) - } - guard let workingDir = config["workingDir"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "workingDir", typeName: "Config")) - } - guard let networkTmp = config["network"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "network", typeName: "Config")) - } - let network = try asNetwork(network: networkTmp) - - guard let paymentTimeoutSec = config["paymentTimeoutSec"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentTimeoutSec", typeName: "Config")) - } - - return Config( - boltzUrl: boltzUrl, - electrumUrl: electrumUrl, - workingDir: workingDir, - network: network, - paymentTimeoutSec: paymentTimeoutSec - ) - } - - static func dictionaryOf(config: Config) -> [String: Any?] { - return [ - "boltzUrl": config.boltzUrl, - "electrumUrl": config.electrumUrl, - "workingDir": config.workingDir, - "network": valueOf(network: config.network), - "paymentTimeoutSec": config.paymentTimeoutSec, - ] - } - - static func asConfigList(arr: [Any]) throws -> [Config] { - var list = [Config]() - for value in arr { - if let val = value as? [String: Any?] { - var config = try asConfig(config: val) - list.append(config) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "Config")) - } - } - return list - } - - static func arrayOf(configList: [Config]) -> [Any] { - return configList.map { v -> [String: Any?] in dictionaryOf(config: v) } - } - - static func asConnectRequest(connectRequest: [String: Any?]) throws -> ConnectRequest { - guard let configTmp = connectRequest["config"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "config", typeName: "ConnectRequest")) - } - let config = try asConfig(config: configTmp) - - guard let mnemonic = connectRequest["mnemonic"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "mnemonic", typeName: "ConnectRequest")) - } - - return ConnectRequest( - config: config, - mnemonic: mnemonic - ) - } - - static func dictionaryOf(connectRequest: ConnectRequest) -> [String: Any?] { - return [ - "config": dictionaryOf(config: connectRequest.config), - "mnemonic": connectRequest.mnemonic, - ] - } - - static func asConnectRequestList(arr: [Any]) throws -> [ConnectRequest] { - var list = [ConnectRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var connectRequest = try asConnectRequest(connectRequest: val) - list.append(connectRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "ConnectRequest")) - } - } - return list - } - - static func arrayOf(connectRequestList: [ConnectRequest]) -> [Any] { - return connectRequestList.map { v -> [String: Any?] in dictionaryOf(connectRequest: v) } - } - - static func asGetInfoRequest(getInfoRequest: [String: Any?]) throws -> GetInfoRequest { - guard let withScan = getInfoRequest["withScan"] as? Bool else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "withScan", typeName: "GetInfoRequest")) - } - - return GetInfoRequest( - withScan: withScan) - } - - static func dictionaryOf(getInfoRequest: GetInfoRequest) -> [String: Any?] { - return [ - "withScan": getInfoRequest.withScan, - ] - } - - static func asGetInfoRequestList(arr: [Any]) throws -> [GetInfoRequest] { - var list = [GetInfoRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var getInfoRequest = try asGetInfoRequest(getInfoRequest: val) - list.append(getInfoRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "GetInfoRequest")) - } - } - return list - } - - static func arrayOf(getInfoRequestList: [GetInfoRequest]) -> [Any] { - return getInfoRequestList.map { v -> [String: Any?] in dictionaryOf(getInfoRequest: v) } - } - - static func asGetInfoResponse(getInfoResponse: [String: Any?]) throws -> GetInfoResponse { - guard let balanceSat = getInfoResponse["balanceSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "balanceSat", typeName: "GetInfoResponse")) - } - guard let pendingSendSat = getInfoResponse["pendingSendSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "pendingSendSat", typeName: "GetInfoResponse")) - } - guard let pendingReceiveSat = getInfoResponse["pendingReceiveSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "pendingReceiveSat", typeName: "GetInfoResponse")) - } - guard let pubkey = getInfoResponse["pubkey"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "pubkey", typeName: "GetInfoResponse")) - } - - return GetInfoResponse( - balanceSat: balanceSat, - pendingSendSat: pendingSendSat, - pendingReceiveSat: pendingReceiveSat, - pubkey: pubkey - ) - } - - static func dictionaryOf(getInfoResponse: GetInfoResponse) -> [String: Any?] { - return [ - "balanceSat": getInfoResponse.balanceSat, - "pendingSendSat": getInfoResponse.pendingSendSat, - "pendingReceiveSat": getInfoResponse.pendingReceiveSat, - "pubkey": getInfoResponse.pubkey, - ] - } - - static func asGetInfoResponseList(arr: [Any]) throws -> [GetInfoResponse] { - var list = [GetInfoResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var getInfoResponse = try asGetInfoResponse(getInfoResponse: val) - list.append(getInfoResponse) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "GetInfoResponse")) - } - } - return list - } - - static func arrayOf(getInfoResponseList: [GetInfoResponse]) -> [Any] { - return getInfoResponseList.map { v -> [String: Any?] in dictionaryOf(getInfoResponse: v) } - } - - static func asLnInvoice(lnInvoice: [String: Any?]) throws -> LnInvoice { - guard let bolt11 = lnInvoice["bolt11"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "bolt11", typeName: "LnInvoice")) - } - guard let networkTmp = lnInvoice["network"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "network", typeName: "LnInvoice")) - } - let network = try asNetwork(network: networkTmp) - - guard let payeePubkey = lnInvoice["payeePubkey"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "payeePubkey", typeName: "LnInvoice")) - } - guard let paymentHash = lnInvoice["paymentHash"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentHash", typeName: "LnInvoice")) - } - var description: String? - if hasNonNilKey(data: lnInvoice, key: "description") { - guard let descriptionTmp = lnInvoice["description"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "description")) - } - description = descriptionTmp - } - var descriptionHash: String? - if hasNonNilKey(data: lnInvoice, key: "descriptionHash") { - guard let descriptionHashTmp = lnInvoice["descriptionHash"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "descriptionHash")) - } - descriptionHash = descriptionHashTmp - } - var amountMsat: UInt64? - if hasNonNilKey(data: lnInvoice, key: "amountMsat") { - guard let amountMsatTmp = lnInvoice["amountMsat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "amountMsat")) - } - amountMsat = amountMsatTmp - } - guard let timestamp = lnInvoice["timestamp"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "timestamp", typeName: "LnInvoice")) - } - guard let expiry = lnInvoice["expiry"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "expiry", typeName: "LnInvoice")) - } - guard let routingHintsTmp = lnInvoice["routingHints"] as? [[String: Any?]] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "routingHints", typeName: "LnInvoice")) - } - let routingHints = try asRouteHintList(arr: routingHintsTmp) - - guard let paymentSecret = lnInvoice["paymentSecret"] as? [UInt8] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentSecret", typeName: "LnInvoice")) - } - guard let minFinalCltvExpiryDelta = lnInvoice["minFinalCltvExpiryDelta"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "minFinalCltvExpiryDelta", typeName: "LnInvoice")) - } - - return LnInvoice( - bolt11: bolt11, - network: network, - payeePubkey: payeePubkey, - paymentHash: paymentHash, - description: description, - descriptionHash: descriptionHash, - amountMsat: amountMsat, - timestamp: timestamp, - expiry: expiry, - routingHints: routingHints, - paymentSecret: paymentSecret, - minFinalCltvExpiryDelta: minFinalCltvExpiryDelta - ) - } - - static func dictionaryOf(lnInvoice: LnInvoice) -> [String: Any?] { - return [ - "bolt11": lnInvoice.bolt11, - "network": valueOf(network: lnInvoice.network), - "payeePubkey": lnInvoice.payeePubkey, - "paymentHash": lnInvoice.paymentHash, - "description": lnInvoice.description == nil ? nil : lnInvoice.description, - "descriptionHash": lnInvoice.descriptionHash == nil ? nil : lnInvoice.descriptionHash, - "amountMsat": lnInvoice.amountMsat == nil ? nil : lnInvoice.amountMsat, - "timestamp": lnInvoice.timestamp, - "expiry": lnInvoice.expiry, - "routingHints": arrayOf(routeHintList: lnInvoice.routingHints), - "paymentSecret": lnInvoice.paymentSecret, - "minFinalCltvExpiryDelta": lnInvoice.minFinalCltvExpiryDelta, - ] - } - - static func asLnInvoiceList(arr: [Any]) throws -> [LnInvoice] { - var list = [LnInvoice]() - for value in arr { - if let val = value as? [String: Any?] { - var lnInvoice = try asLnInvoice(lnInvoice: val) - list.append(lnInvoice) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "LnInvoice")) - } - } - return list - } - - static func arrayOf(lnInvoiceList: [LnInvoice]) -> [Any] { - return lnInvoiceList.map { v -> [String: Any?] in dictionaryOf(lnInvoice: v) } - } - - static func asLogEntry(logEntry: [String: Any?]) throws -> LogEntry { - guard let line = logEntry["line"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "line", typeName: "LogEntry")) - } - guard let level = logEntry["level"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "level", typeName: "LogEntry")) - } - - return LogEntry( - line: line, - level: level - ) - } - - static func dictionaryOf(logEntry: LogEntry) -> [String: Any?] { - return [ - "line": logEntry.line, - "level": logEntry.level, - ] - } - - static func asLogEntryList(arr: [Any]) throws -> [LogEntry] { - var list = [LogEntry]() - for value in arr { - if let val = value as? [String: Any?] { - var logEntry = try asLogEntry(logEntry: val) - list.append(logEntry) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "LogEntry")) - } - } - return list - } - - static func arrayOf(logEntryList: [LogEntry]) -> [Any] { - return logEntryList.map { v -> [String: Any?] in dictionaryOf(logEntry: v) } - } - - static func asPayment(payment: [String: Any?]) throws -> Payment { - guard let txId = payment["txId"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "txId", typeName: "Payment")) - } - var swapId: String? - if hasNonNilKey(data: payment, key: "swapId") { - guard let swapIdTmp = payment["swapId"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "swapId")) - } - swapId = swapIdTmp - } - guard let timestamp = payment["timestamp"] as? UInt32 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "timestamp", typeName: "Payment")) - } - guard let amountSat = payment["amountSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "amountSat", typeName: "Payment")) - } - var feesSat: UInt64? - if hasNonNilKey(data: payment, key: "feesSat") { - guard let feesSatTmp = payment["feesSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "feesSat")) - } - feesSat = feesSatTmp - } - var preimage: String? - if hasNonNilKey(data: payment, key: "preimage") { - guard let preimageTmp = payment["preimage"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "preimage")) - } - preimage = preimageTmp - } - var refundTxId: String? - if hasNonNilKey(data: payment, key: "refundTxId") { - guard let refundTxIdTmp = payment["refundTxId"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "refundTxId")) - } - refundTxId = refundTxIdTmp - } - var refundTxAmountSat: UInt64? - if hasNonNilKey(data: payment, key: "refundTxAmountSat") { - guard let refundTxAmountSatTmp = payment["refundTxAmountSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "refundTxAmountSat")) - } - refundTxAmountSat = refundTxAmountSatTmp - } - guard let paymentTypeTmp = payment["paymentType"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentType", typeName: "Payment")) - } - let paymentType = try asPaymentType(paymentType: paymentTypeTmp) - - guard let statusTmp = payment["status"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "status", typeName: "Payment")) - } - let status = try asPaymentState(paymentState: statusTmp) - - return Payment( - txId: txId, - swapId: swapId, - timestamp: timestamp, - amountSat: amountSat, - feesSat: feesSat, - preimage: preimage, - refundTxId: refundTxId, - refundTxAmountSat: refundTxAmountSat, - paymentType: paymentType, - status: status - ) - } - - static func dictionaryOf(payment: Payment) -> [String: Any?] { - return [ - "txId": payment.txId, - "swapId": payment.swapId == nil ? nil : payment.swapId, - "timestamp": payment.timestamp, - "amountSat": payment.amountSat, - "feesSat": payment.feesSat == nil ? nil : payment.feesSat, - "preimage": payment.preimage == nil ? nil : payment.preimage, - "refundTxId": payment.refundTxId == nil ? nil : payment.refundTxId, - "refundTxAmountSat": payment.refundTxAmountSat == nil ? nil : payment.refundTxAmountSat, - "paymentType": valueOf(paymentType: payment.paymentType), - "status": valueOf(paymentState: payment.status), - ] - } - - static func asPaymentList(arr: [Any]) throws -> [Payment] { - var list = [Payment]() - for value in arr { - if let val = value as? [String: Any?] { - var payment = try asPayment(payment: val) - list.append(payment) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "Payment")) - } - } - return list - } - - static func arrayOf(paymentList: [Payment]) -> [Any] { - return paymentList.map { v -> [String: Any?] in dictionaryOf(payment: v) } - } - - static func asPrepareReceiveRequest(prepareReceiveRequest: [String: Any?]) throws -> PrepareReceiveRequest { - guard let payerAmountSat = prepareReceiveRequest["payerAmountSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceiveRequest")) - } - - return PrepareReceiveRequest( - payerAmountSat: payerAmountSat) - } - - static func dictionaryOf(prepareReceiveRequest: PrepareReceiveRequest) -> [String: Any?] { - return [ - "payerAmountSat": prepareReceiveRequest.payerAmountSat, - ] - } - - static func asPrepareReceiveRequestList(arr: [Any]) throws -> [PrepareReceiveRequest] { - var list = [PrepareReceiveRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareReceiveRequest = try asPrepareReceiveRequest(prepareReceiveRequest: val) - list.append(prepareReceiveRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveRequest")) - } - } - return list - } - - static func arrayOf(prepareReceiveRequestList: [PrepareReceiveRequest]) -> [Any] { - return prepareReceiveRequestList.map { v -> [String: Any?] in dictionaryOf(prepareReceiveRequest: v) } - } - - static func asPrepareReceiveResponse(prepareReceiveResponse: [String: Any?]) throws -> PrepareReceiveResponse { - guard let payerAmountSat = prepareReceiveResponse["payerAmountSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceiveResponse")) - } - guard let feesSat = prepareReceiveResponse["feesSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareReceiveResponse")) - } - - return PrepareReceiveResponse( - payerAmountSat: payerAmountSat, - feesSat: feesSat - ) - } - - static func dictionaryOf(prepareReceiveResponse: PrepareReceiveResponse) -> [String: Any?] { - return [ - "payerAmountSat": prepareReceiveResponse.payerAmountSat, - "feesSat": prepareReceiveResponse.feesSat, - ] - } - - static func asPrepareReceiveResponseList(arr: [Any]) throws -> [PrepareReceiveResponse] { - var list = [PrepareReceiveResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareReceiveResponse = try asPrepareReceiveResponse(prepareReceiveResponse: val) - list.append(prepareReceiveResponse) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveResponse")) - } - } - return list - } - - static func arrayOf(prepareReceiveResponseList: [PrepareReceiveResponse]) -> [Any] { - return prepareReceiveResponseList.map { v -> [String: Any?] in dictionaryOf(prepareReceiveResponse: v) } - } - - static func asPrepareSendRequest(prepareSendRequest: [String: Any?]) throws -> PrepareSendRequest { - guard let invoice = prepareSendRequest["invoice"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "PrepareSendRequest")) - } - - return PrepareSendRequest( - invoice: invoice) - } - - static func dictionaryOf(prepareSendRequest: PrepareSendRequest) -> [String: Any?] { - return [ - "invoice": prepareSendRequest.invoice, - ] - } - - static func asPrepareSendRequestList(arr: [Any]) throws -> [PrepareSendRequest] { - var list = [PrepareSendRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareSendRequest = try asPrepareSendRequest(prepareSendRequest: val) - list.append(prepareSendRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PrepareSendRequest")) - } - } - return list - } - - static func arrayOf(prepareSendRequestList: [PrepareSendRequest]) -> [Any] { - return prepareSendRequestList.map { v -> [String: Any?] in dictionaryOf(prepareSendRequest: v) } - } - - static func asPrepareSendResponse(prepareSendResponse: [String: Any?]) throws -> PrepareSendResponse { - guard let invoice = prepareSendResponse["invoice"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "PrepareSendResponse")) - } - guard let feesSat = prepareSendResponse["feesSat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareSendResponse")) - } - - return PrepareSendResponse( - invoice: invoice, - feesSat: feesSat - ) - } - - static func dictionaryOf(prepareSendResponse: PrepareSendResponse) -> [String: Any?] { - return [ - "invoice": prepareSendResponse.invoice, - "feesSat": prepareSendResponse.feesSat, - ] - } - - static func asPrepareSendResponseList(arr: [Any]) throws -> [PrepareSendResponse] { - var list = [PrepareSendResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareSendResponse = try asPrepareSendResponse(prepareSendResponse: val) - list.append(prepareSendResponse) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PrepareSendResponse")) - } - } - return list - } - - static func arrayOf(prepareSendResponseList: [PrepareSendResponse]) -> [Any] { - return prepareSendResponseList.map { v -> [String: Any?] in dictionaryOf(prepareSendResponse: v) } - } - - static func asReceivePaymentResponse(receivePaymentResponse: [String: Any?]) throws -> ReceivePaymentResponse { - guard let id = receivePaymentResponse["id"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "id", typeName: "ReceivePaymentResponse")) - } - guard let invoice = receivePaymentResponse["invoice"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "ReceivePaymentResponse")) - } - - return ReceivePaymentResponse( - id: id, - invoice: invoice - ) - } - - static func dictionaryOf(receivePaymentResponse: ReceivePaymentResponse) -> [String: Any?] { - return [ - "id": receivePaymentResponse.id, - "invoice": receivePaymentResponse.invoice, - ] - } - - static func asReceivePaymentResponseList(arr: [Any]) throws -> [ReceivePaymentResponse] { - var list = [ReceivePaymentResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var receivePaymentResponse = try asReceivePaymentResponse(receivePaymentResponse: val) - list.append(receivePaymentResponse) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "ReceivePaymentResponse")) - } - } - return list - } - - static func arrayOf(receivePaymentResponseList: [ReceivePaymentResponse]) -> [Any] { - return receivePaymentResponseList.map { v -> [String: Any?] in dictionaryOf(receivePaymentResponse: v) } - } - - static func asRestoreRequest(restoreRequest: [String: Any?]) throws -> RestoreRequest { - var backupPath: String? - if hasNonNilKey(data: restoreRequest, key: "backupPath") { - guard let backupPathTmp = restoreRequest["backupPath"] as? String else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "backupPath")) - } - backupPath = backupPathTmp - } - - return RestoreRequest( - backupPath: backupPath) - } - - static func dictionaryOf(restoreRequest: RestoreRequest) -> [String: Any?] { - return [ - "backupPath": restoreRequest.backupPath == nil ? nil : restoreRequest.backupPath, - ] - } - - static func asRestoreRequestList(arr: [Any]) throws -> [RestoreRequest] { - var list = [RestoreRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var restoreRequest = try asRestoreRequest(restoreRequest: val) - list.append(restoreRequest) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "RestoreRequest")) - } - } - return list - } - - static func arrayOf(restoreRequestList: [RestoreRequest]) -> [Any] { - return restoreRequestList.map { v -> [String: Any?] in dictionaryOf(restoreRequest: v) } - } - - static func asRouteHint(routeHint: [String: Any?]) throws -> RouteHint { - guard let hopsTmp = routeHint["hops"] as? [[String: Any?]] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "hops", typeName: "RouteHint")) - } - let hops = try asRouteHintHopList(arr: hopsTmp) - - return RouteHint( - hops: hops) - } - - static func dictionaryOf(routeHint: RouteHint) -> [String: Any?] { - return [ - "hops": arrayOf(routeHintHopList: routeHint.hops), - ] - } - - static func asRouteHintList(arr: [Any]) throws -> [RouteHint] { - var list = [RouteHint]() - for value in arr { - if let val = value as? [String: Any?] { - var routeHint = try asRouteHint(routeHint: val) - list.append(routeHint) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "RouteHint")) - } - } - return list - } - - static func arrayOf(routeHintList: [RouteHint]) -> [Any] { - return routeHintList.map { v -> [String: Any?] in dictionaryOf(routeHint: v) } - } - - static func asRouteHintHop(routeHintHop: [String: Any?]) throws -> RouteHintHop { - guard let srcNodeId = routeHintHop["srcNodeId"] as? String else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "srcNodeId", typeName: "RouteHintHop")) - } - guard let shortChannelId = routeHintHop["shortChannelId"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "shortChannelId", typeName: "RouteHintHop")) - } - guard let feesBaseMsat = routeHintHop["feesBaseMsat"] as? UInt32 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "feesBaseMsat", typeName: "RouteHintHop")) - } - guard let feesProportionalMillionths = routeHintHop["feesProportionalMillionths"] as? UInt32 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "feesProportionalMillionths", typeName: "RouteHintHop")) - } - guard let cltvExpiryDelta = routeHintHop["cltvExpiryDelta"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "cltvExpiryDelta", typeName: "RouteHintHop")) - } - var htlcMinimumMsat: UInt64? - if hasNonNilKey(data: routeHintHop, key: "htlcMinimumMsat") { - guard let htlcMinimumMsatTmp = routeHintHop["htlcMinimumMsat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "htlcMinimumMsat")) - } - htlcMinimumMsat = htlcMinimumMsatTmp - } - var htlcMaximumMsat: UInt64? - if hasNonNilKey(data: routeHintHop, key: "htlcMaximumMsat") { - guard let htlcMaximumMsatTmp = routeHintHop["htlcMaximumMsat"] as? UInt64 else { - throw LiquidSdkError.Generic(message: errUnexpectedValue(fieldName: "htlcMaximumMsat")) - } - htlcMaximumMsat = htlcMaximumMsatTmp - } - - return RouteHintHop( - srcNodeId: srcNodeId, - shortChannelId: shortChannelId, - feesBaseMsat: feesBaseMsat, - feesProportionalMillionths: feesProportionalMillionths, - cltvExpiryDelta: cltvExpiryDelta, - htlcMinimumMsat: htlcMinimumMsat, - htlcMaximumMsat: htlcMaximumMsat - ) - } - - static func dictionaryOf(routeHintHop: RouteHintHop) -> [String: Any?] { - return [ - "srcNodeId": routeHintHop.srcNodeId, - "shortChannelId": routeHintHop.shortChannelId, - "feesBaseMsat": routeHintHop.feesBaseMsat, - "feesProportionalMillionths": routeHintHop.feesProportionalMillionths, - "cltvExpiryDelta": routeHintHop.cltvExpiryDelta, - "htlcMinimumMsat": routeHintHop.htlcMinimumMsat == nil ? nil : routeHintHop.htlcMinimumMsat, - "htlcMaximumMsat": routeHintHop.htlcMaximumMsat == nil ? nil : routeHintHop.htlcMaximumMsat, - ] - } - - static func asRouteHintHopList(arr: [Any]) throws -> [RouteHintHop] { - var list = [RouteHintHop]() - for value in arr { - if let val = value as? [String: Any?] { - var routeHintHop = try asRouteHintHop(routeHintHop: val) - list.append(routeHintHop) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "RouteHintHop")) - } - } - return list - } - - static func arrayOf(routeHintHopList: [RouteHintHop]) -> [Any] { - return routeHintHopList.map { v -> [String: Any?] in dictionaryOf(routeHintHop: v) } - } - - static func asSendPaymentResponse(sendPaymentResponse: [String: Any?]) throws -> SendPaymentResponse { - guard let paymentTmp = sendPaymentResponse["payment"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "payment", typeName: "SendPaymentResponse")) - } - let payment = try asPayment(payment: paymentTmp) - - return SendPaymentResponse( - payment: payment) - } - - static func dictionaryOf(sendPaymentResponse: SendPaymentResponse) -> [String: Any?] { - return [ - "payment": dictionaryOf(payment: sendPaymentResponse.payment), - ] - } - - static func asSendPaymentResponseList(arr: [Any]) throws -> [SendPaymentResponse] { - var list = [SendPaymentResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var sendPaymentResponse = try asSendPaymentResponse(sendPaymentResponse: val) - list.append(sendPaymentResponse) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "SendPaymentResponse")) - } - } - return list - } - - static func arrayOf(sendPaymentResponseList: [SendPaymentResponse]) -> [Any] { - return sendPaymentResponseList.map { v -> [String: Any?] in dictionaryOf(sendPaymentResponse: v) } - } - - static func asLiquidSdkEvent(liquidSdkEvent: [String: Any?]) throws -> LiquidSdkEvent { - let type = liquidSdkEvent["type"] as! String - if type == "paymentFailed" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentFailed(details: _details) - } - if type == "paymentPending" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentPending(details: _details) - } - if type == "paymentRefunded" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentRefunded(details: _details) - } - if type == "paymentRefundPending" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentRefundPending(details: _details) - } - if type == "paymentSucceed" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentSucceed(details: _details) - } - if type == "paymentWaitingConfirmation" { - guard let detailsTmp = liquidSdkEvent["details"] as? [String: Any?] else { - throw LiquidSdkError.Generic(message: errMissingMandatoryField(fieldName: "details", typeName: "LiquidSdkEvent")) - } - let _details = try asPayment(payment: detailsTmp) - - return LiquidSdkEvent.paymentWaitingConfirmation(details: _details) - } - if type == "synced" { - return LiquidSdkEvent.synced - } - - throw LiquidSdkError.Generic(message: "Unexpected type \(type) for enum LiquidSdkEvent") - } - - static func dictionaryOf(liquidSdkEvent: LiquidSdkEvent) -> [String: Any?] { - switch liquidSdkEvent { - case let .paymentFailed( - details - ): - return [ - "type": "paymentFailed", - "details": dictionaryOf(payment: details), - ] - - case let .paymentPending( - details - ): - return [ - "type": "paymentPending", - "details": dictionaryOf(payment: details), - ] - - case let .paymentRefunded( - details - ): - return [ - "type": "paymentRefunded", - "details": dictionaryOf(payment: details), - ] - - case let .paymentRefundPending( - details - ): - return [ - "type": "paymentRefundPending", - "details": dictionaryOf(payment: details), - ] - - case let .paymentSucceed( - details - ): - return [ - "type": "paymentSucceed", - "details": dictionaryOf(payment: details), - ] - - case let .paymentWaitingConfirmation( - details - ): - return [ - "type": "paymentWaitingConfirmation", - "details": dictionaryOf(payment: details), - ] - - case .synced: - return [ - "type": "synced", - ] - } - } - - static func arrayOf(liquidSdkEventList: [LiquidSdkEvent]) -> [Any] { - return liquidSdkEventList.map { v -> [String: Any?] in dictionaryOf(liquidSdkEvent: v) } - } - - static func asLiquidSdkEventList(arr: [Any]) throws -> [LiquidSdkEvent] { - var list = [LiquidSdkEvent]() - for value in arr { - if let val = value as? [String: Any?] { - var liquidSdkEvent = try asLiquidSdkEvent(liquidSdkEvent: val) - list.append(liquidSdkEvent) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "LiquidSdkEvent")) - } - } - return list - } - - static func asNetwork(network: String) throws -> Network { - switch network { - case "mainnet": - return Network.mainnet - - case "testnet": - return Network.testnet - - default: throw LiquidSdkError.Generic(message: "Invalid variant \(network) for enum Network") - } - } - - static func valueOf(network: Network) -> String { - switch network { - case .mainnet: - return "mainnet" - - case .testnet: - return "testnet" - } - } - - static func arrayOf(networkList: [Network]) -> [String] { - return networkList.map { v -> String in valueOf(network: v) } - } - - static func asNetworkList(arr: [Any]) throws -> [Network] { - var list = [Network]() - for value in arr { - if let val = value as? String { - var network = try asNetwork(network: val) - list.append(network) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "Network")) - } - } - return list - } - - static func asPaymentState(paymentState: String) throws -> PaymentState { - switch paymentState { - case "created": - return PaymentState.created - - case "pending": - return PaymentState.pending - - case "complete": - return PaymentState.complete - - case "failed": - return PaymentState.failed - - case "timedOut": - return PaymentState.timedOut - - default: throw LiquidSdkError.Generic(message: "Invalid variant \(paymentState) for enum PaymentState") - } - } - - static func valueOf(paymentState: PaymentState) -> String { - switch paymentState { - case .created: - return "created" - - case .pending: - return "pending" - - case .complete: - return "complete" - - case .failed: - return "failed" - - case .timedOut: - return "timedOut" - } - } - - static func arrayOf(paymentStateList: [PaymentState]) -> [String] { - return paymentStateList.map { v -> String in valueOf(paymentState: v) } - } - - static func asPaymentStateList(arr: [Any]) throws -> [PaymentState] { - var list = [PaymentState]() - for value in arr { - if let val = value as? String { - var paymentState = try asPaymentState(paymentState: val) - list.append(paymentState) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PaymentState")) - } - } - return list - } - - static func asPaymentType(paymentType: String) throws -> PaymentType { - switch paymentType { - case "receive": - return PaymentType.receive - - case "send": - return PaymentType.send - - default: throw LiquidSdkError.Generic(message: "Invalid variant \(paymentType) for enum PaymentType") - } - } - - static func valueOf(paymentType: PaymentType) -> String { - switch paymentType { - case .receive: - return "receive" - - case .send: - return "send" - } - } - - static func arrayOf(paymentTypeList: [PaymentType]) -> [String] { - return paymentTypeList.map { v -> String in valueOf(paymentType: v) } - } - - static func asPaymentTypeList(arr: [Any]) throws -> [PaymentType] { - var list = [PaymentType]() - for value in arr { - if let val = value as? String { - var paymentType = try asPaymentType(paymentType: val) - list.append(paymentType) - } else { - throw LiquidSdkError.Generic(message: errUnexpectedType(typeName: "PaymentType")) - } - } - return list - } - - static func hasNonNilKey(data: [String: Any?], key: String) -> Bool { - if let val = data[key] { - return !(val == nil || val is NSNull) - } - - return false - } - - static func errMissingMandatoryField(fieldName: String, typeName: String) -> String { - return "Missing mandatory field \(fieldName) for type \(typeName)" - } - - static func errUnexpectedType(typeName: String) -> String { - return "Unexpected type \(typeName)" - } - - static func errUnexpectedValue(fieldName: String) -> String { - return "Unexpected value for optional field \(fieldName)" - } -} diff --git a/packages/react-native/ios/RNBreezLiquidSDK.m b/packages/react-native/ios/RNBreezLiquidSDK.m deleted file mode 100644 index 2f20e42d0..000000000 --- a/packages/react-native/ios/RNBreezLiquidSDK.m +++ /dev/null @@ -1,97 +0,0 @@ -#import -#import - -@interface RCT_EXTERN_MODULE(RNBreezLiquidSDK, RCTEventEmitter) - -RCT_EXTERN_METHOD( - defaultConfig: (NSString*)network - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - parseInvoice: (NSString*)invoice - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - setLogger: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - connect: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - addEventListener: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - removeEventListener: (NSString*)id - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - getInfo: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - prepareSendPayment: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - sendPayment: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - prepareReceivePayment: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - receivePayment: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - listPayments: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - sync: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - backup: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - restore: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - disconnect: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -@end \ No newline at end of file diff --git a/packages/react-native/ios/RNBreezLiquidSDK.swift b/packages/react-native/ios/RNBreezLiquidSDK.swift deleted file mode 100644 index 6cb821c11..000000000 --- a/packages/react-native/ios/RNBreezLiquidSDK.swift +++ /dev/null @@ -1,266 +0,0 @@ -import BreezLiquidSDK -import Foundation - -@objc(RNBreezLiquidSDK) -class RNBreezLiquidSDK: RCTEventEmitter { - static let TAG: String = "BreezLiquidSDK" - - public static var emitter: RCTEventEmitter! - public static var hasListeners: Bool = false - public static var supportedEvents: [String] = ["breezLiquidSdkLog"] - - private var bindingLiquidSdk: BindingLiquidSdk! - - static var breezLiquidSdkDirectory: URL { - let applicationDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! - let breezLiquidSdkDirectory = applicationDirectory.appendingPathComponent("breezLiquidSdk", isDirectory: true) - - if !FileManager.default.fileExists(atPath: breezLiquidSdkDirectory.path) { - try! FileManager.default.createDirectory(atPath: breezLiquidSdkDirectory.path, withIntermediateDirectories: true) - } - - return breezLiquidSdkDirectory - } - - override init() { - super.init() - RNBreezLiquidSDK.emitter = self - } - - @objc - override static func moduleName() -> String! { - TAG - } - - static func addSupportedEvent(name: String) { - RNBreezLiquidSDK.supportedEvents.append(name) - } - - override func supportedEvents() -> [String]! { - return RNBreezLiquidSDK.supportedEvents - } - - override func startObserving() { - RNBreezLiquidSDK.hasListeners = true - } - - override func stopObserving() { - RNBreezLiquidSDK.hasListeners = false - } - - @objc - override static func requiresMainQueueSetup() -> Bool { - return false - } - - func getBindingLiquidSdk() throws -> BindingLiquidSdk { - if bindingLiquidSdk != nil { - return bindingLiquidSdk - } - - throw LiquidSdkError.Generic(message: "Not initialized") - } - - private func ensureWorkingDir(workingDir: String) throws { - do { - if !FileManager.default.fileExists(atPath: workingDir) { - try FileManager.default.createDirectory(atPath: workingDir, withIntermediateDirectories: true) - } - } catch { - throw LiquidSdkError.Generic(message: "Mandatory field workingDir must contain a writable directory") - } - } - - @objc(defaultConfig:resolve:reject:) - func defaultConfig(_ network: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let networkTmp = try BreezLiquidSDKMapper.asNetwork(network: network) - var res = BreezLiquidSDK.defaultConfig(network: networkTmp) - res.workingDir = RNBreezLiquidSDK.breezLiquidSdkDirectory.path - resolve(BreezLiquidSDKMapper.dictionaryOf(config: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(parseInvoice:resolve:reject:) - func parseInvoice(_ invoice: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - var res = try BreezLiquidSDK.parseInvoice(invoice: invoice) - resolve(BreezLiquidSDKMapper.dictionaryOf(lnInvoice: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(setLogger:reject:) - func setLogger(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - try BreezLiquidSDK.setLogger(Logger: BreezLiquidSDKLogger()) - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(connect:resolve:reject:) - func connect(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - if bindingLiquidSdk != nil { - reject("Generic", "Already initialized", nil) - return - } - - do { - var connectRequest = try BreezLiquidSDKMapper.asConnectRequest(connectRequest: req) - try ensureWorkingDir(workingDir: connectRequest.config.workingDir) - - bindingLiquidSdk = try BreezLiquidSDK.connect(req: connectRequest) - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(addEventListener:reject:) - func addEventListener(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - var eventListener = BreezLiquidSDKEventListener() - var res = try getBindingLiquidSdk().addEventListener(listener: eventListener) - - eventListener.setId(id: res) - resolve(res) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(removeEventListener:resolve:reject:) - func removeEventListener(_ id: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - try getBindingLiquidSdk().removeEventListener(id: id) - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(getInfo:resolve:reject:) - func getInfo(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let getInfoRequest = try BreezLiquidSDKMapper.asGetInfoRequest(getInfoRequest: req) - var res = try getBindingLiquidSdk().getInfo(req: getInfoRequest) - resolve(BreezLiquidSDKMapper.dictionaryOf(getInfoResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(prepareSendPayment:resolve:reject:) - func prepareSendPayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareSendRequest = try BreezLiquidSDKMapper.asPrepareSendRequest(prepareSendRequest: req) - var res = try getBindingLiquidSdk().prepareSendPayment(req: prepareSendRequest) - resolve(BreezLiquidSDKMapper.dictionaryOf(prepareSendResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(sendPayment:resolve:reject:) - func sendPayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareSendResponse = try BreezLiquidSDKMapper.asPrepareSendResponse(prepareSendResponse: req) - var res = try getBindingLiquidSdk().sendPayment(req: prepareSendResponse) - resolve(BreezLiquidSDKMapper.dictionaryOf(sendPaymentResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(prepareReceivePayment:resolve:reject:) - func prepareReceivePayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareReceiveRequest = try BreezLiquidSDKMapper.asPrepareReceiveRequest(prepareReceiveRequest: req) - var res = try getBindingLiquidSdk().prepareReceivePayment(req: prepareReceiveRequest) - resolve(BreezLiquidSDKMapper.dictionaryOf(prepareReceiveResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(receivePayment:resolve:reject:) - func receivePayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareReceiveResponse = try BreezLiquidSDKMapper.asPrepareReceiveResponse(prepareReceiveResponse: req) - var res = try getBindingLiquidSdk().receivePayment(req: prepareReceiveResponse) - resolve(BreezLiquidSDKMapper.dictionaryOf(receivePaymentResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(listPayments:reject:) - func listPayments(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - var res = try getBindingLiquidSdk().listPayments() - resolve(BreezLiquidSDKMapper.arrayOf(paymentList: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(sync:reject:) - func sync(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - try getBindingLiquidSdk().sync() - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(backup:resolve:reject:) - func backup(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let backupRequest = try BreezLiquidSDKMapper.asBackupRequest(backupRequest: req) - try getBindingLiquidSdk().backup(req: backupRequest) - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(restore:resolve:reject:) - func restore(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let restoreRequest = try BreezLiquidSDKMapper.asRestoreRequest(restoreRequest: req) - try getBindingLiquidSdk().restore(req: restoreRequest) - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(disconnect:reject:) - func disconnect(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - try getBindingLiquidSdk().disconnect() - bindingLiquidSdk = nil - resolve(["status": "ok"]) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - func rejectErr(err: Error, reject: @escaping RCTPromiseRejectBlock) { - var errorName = "Generic" - var message = "\(err)" - if let errAssociated = Mirror(reflecting: err).children.first { - errorName = errAssociated.label ?? errorName - if let associatedMessage = Mirror(reflecting: errAssociated.value).children.first { - message = associatedMessage.value as! String - } - } - reject(errorName, message, err) - } -}