Extract Kotlin snippets

This commit is contained in:
ok300
2023-11-14 20:51:01 +01:00
parent b541595840
commit 786a94bf69
38 changed files with 841 additions and 221 deletions

View File

@@ -0,0 +1,49 @@
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary)
}
kotlin {
androidTarget {
compilations.all {
kotlinOptions {
jvmTarget = "1.8"
}
}
}
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach {
it.binaries.framework {
baseName = "shared"
isStatic = true
}
}
sourceSets {
commonMain.dependencies {
//put your multiplatform dependencies here
implementation(libs.breez)
}
commonTest.dependencies {
implementation(libs.kotlin.test)
}
}
}
android {
namespace = "com.example.kotlinmpplib"
compileSdk = 34
defaultConfig {
minSdk = 34
}
}
dependencies {
implementation(libs.breez)
implementation("androidx.core:core-ktx:+")
}

View File

@@ -0,0 +1,18 @@
package com.example.kotlinmpplib
import breez_sdk.*
class BuyBtc {
fun buy_btc(sdk: BlockingBreezServices) {
// ANCHOR: buy-btc
try {
// Choose your provider
val provider = BuyBitcoinProvider.MOONPAY
// request the url to proceed with the Bitcoin acquisition
val url = sdk.buyBitcoin(BuyBitcoinRequest(provider)).url
} catch (e: Exception) {
// Handle error
}
// ANCHOR_END: buy-btc
}
}

View File

@@ -0,0 +1,29 @@
package com.example.kotlinmpplib
import breez_sdk.*
class ConnectingLsp {
fun get_lsp_info(sdk: BlockingBreezServices) {
// ANCHOR: get-lsp-info
try {
val lspId = sdk.lspId()
if (lspId != null) {
val lspInfo = sdk.lspInfo()
} else {
// Handle no lsp id scenario
}
} catch (e: Exception) {
// Handle error
}
// ANCHOR_END: get-lsp-info
}
fun connect_lsp(sdk: BlockingBreezServices, lspId: String) {
// ANCHOR: connect-lsp
try {
sdk.connectLsp(lspId)
} catch (e: Exception) {
// Handle error
}
// ANCHOR_END: connect-lsp
}
}

View File

@@ -0,0 +1,53 @@
package com.example.kotlinmpplib
import breez_sdk.*
class FiatCurrencies {
fun list_fiat_currencies(sdk: BlockingBreezServices) {
// ANCHOR: list-fiat-currencies
try {
val fiatCurrencyList = sdk.listFiatCurrencies()
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: list-fiat-currencies
}
fun fetch_fiat_rates(sdk: BlockingBreezServices) {
// ANCHOR: fetch-fiat-rates
try {
val fiatRatesMap = sdk.fetchFiatRates()
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: fetch-fiat-rates
}
fun get_fiat_currencies_and_rates(sdk: BlockingBreezServices) {
// ANCHOR: get-fiat-currencies-and-rates
fun fiatCurrenciesAndRate(): Map<FiatCurrency, Rate> = try {
val fiatCurrencies = sdk.listFiatCurrencies()
val fiatRates = sdk.fetchFiatRates()
val ratesMap = mutableMapOf<String, Rate>()
for (rate in fiatRates) {
ratesMap[rate.coin.lowercase()] = rate
}
val sorted = fiatCurrencies.sortedBy { it.info.name }
val result = LinkedHashMap<FiatCurrency, Rate>()
for (currency in sorted) {
val rate = ratesMap[currency.id.lowercase()]
if (rate != null) {
result[currency] = rate
}
}
result
} catch (e: Throwable) {
// Handle error
emptyMap()
}
// ANCHOR_END: get-fiat-currencies-and-rates
}
}

View File

@@ -0,0 +1,47 @@
package com.example.kotlinmpplib
import breez_sdk.*
class GettingStarted {
fun start() {
// ANCHOR: init-sdk
// SDK events listener
class SDKListener : EventListener {
override fun onEvent(e: BreezEvent) {
// Log.v("SDKListener", "Received event $e")
}
}
// Select your seed, invite code and eviroment
val seed = mnemonicToSeed("<mnemonic words>")
val inviteCode = "<invite code>"
val apiKey = "<api key>"
// Create the default config
val greenlightNodeConfig = GreenlightNodeConfig(null, inviteCode)
val nodeConfig = NodeConfig.Greenlight(greenlightNodeConfig)
val config = defaultConfig(EnvironmentType.PRODUCTION, apiKey, nodeConfig)
// Customize the config object according to your needs
config.workingDir = "path to an existing directory"
try {
// Connect to the Breez SDK make it ready for use
val sdk = connect(config, seed, SDKListener())
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: init-sdk
}
fun fetch_balance(sdk: BlockingBreezServices) {
// ANCHOR: fetch-balance
try {
val nodeInfo = sdk.nodeInfo()
val lnBalance = nodeInfo?.channelsBalanceMsat
val onchainBalance = nodeInfo?.onchainBalanceMsat
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: fetch-balance
}
}

View File

@@ -0,0 +1,29 @@
package com.example.kotlinmpplib
import breez_sdk.*
class ListPayments {
fun list_payments(sdk: BlockingBreezServices) {
// ANCHOR: list-payments
try {
val payments = sdk.listPayments(ListPaymentsRequest())
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: list-payments
}
fun list_payments_filtered(sdk: BlockingBreezServices) {
// ANCHOR: list-payments-filtered
try {
val payments = sdk.listPayments(
ListPaymentsRequest(
listOf(PaymentTypeFilter.SENT),
fromTimestamp = 1696880000,
includeFailures = true
))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: list-payments-filtered
}
}

View File

@@ -0,0 +1,23 @@
package com.example.kotlinmpplib
import breez_sdk.*
class LnurlAuth {
fun lnurl_auth(sdk: BlockingBreezServices) {
// ANCHOR: lnurl-auth
// Endpoint can also be of the form:
// keyauth://domain.com/auth?key=val
val lnurlAuthUrl = "lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7..."
try {
val inputType = parseInput(lnurlAuthUrl)
if (inputType is InputType.LnUrlAuth) {
when (val result = sdk.lnurlAuth(inputType.data)) {
LnUrlCallbackStatus.Ok -> {} // Log.v("Breez", "Successfully authenticated")
is LnUrlCallbackStatus.ErrorStatus -> {} // Log.v("Breez", "Failed to authenticate: ${result.data.reason}")
}
}
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: lnurl-auth
}
}

View File

@@ -0,0 +1,23 @@
package com.example.kotlinmpplib
import breez_sdk.*
class LnurlPay {
fun lnurl_pay(sdk: BlockingBreezServices) {
// ANCHOR: lnurl-pay
// Endpoint can also be of the form:
// lnurlp://domain.com/lnurl-pay?key=val
// lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttsv9un7um9wdekjmmw84jxywf5x43rvv35xgmr2enrxanr2cfcvsmnwe3jxcukvde48qukgdec89snwde3vfjxvepjxpjnjvtpxd3kvdnxx5crxwpjvyunsephsz36jf
val lnurlPayUrl = "lightning@address.com";
try {
val inputType = parseInput(lnurlPayUrl)
if (inputType is InputType.LnUrlPay) {
val requestData = inputType.data
val amountMsat = requestData.minSendable
sdk.payLnurl(LnUrlPayRequest(requestData, amountMsat, "comment"))
}
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: lnurl-pay
}
}

View File

@@ -0,0 +1,23 @@
package com.example.kotlinmpplib
import breez_sdk.*
class LnurlWithdraw {
fun lnurl_withdraw(sdk: BlockingBreezServices) {
// ANCHOR: lnurl-withdraw
// Endpoint can also be of the form:
// lnurlw://domain.com/lnurl-withdraw?key=val
val lnurlWithdrawUrl = "lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7..."
try {
val inputType = parseInput(lnurlWithdrawUrl)
if (inputType is InputType.LnUrlWithdraw) {
val requestData = inputType.data
val amountMsat = requestData.minWithdrawable
val comment = "Any comment"
sdk.withdrawLnurl(LnUrlWithdrawRequest(requestData, amountMsat, comment))
}
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: lnurl-withdraw
}
}

View File

@@ -0,0 +1,60 @@
package com.example.kotlinmpplib
import breez_sdk.*
class ReceiveOnchain {
fun generate_receive_onchain_address(sdk: BlockingBreezServices) {
// ANCHOR: generate-receive-onchain-address
try {
val swapInfo = sdk.receiveOnchain(ReceiveOnchainRequest())
// Send your funds to the bellow bitcoin address
val address = swapInfo.bitcoinAddress
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: generate-receive-onchain-address
}
fun in_progress_swap(sdk: BlockingBreezServices) {
// ANCHOR: in-progress-swap
try {
val swapInfo = sdk.inProgressSwap()
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: in-progress-swap
}
fun list_refundables(sdk: BlockingBreezServices) {
// ANCHOR: list-refundables
try {
val refundables = sdk.listRefundables()
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: list-refundables
}
fun execute_refund(sdk: BlockingBreezServices) {
// ANCHOR: execute-refund
val swapAddress = "..."
val destinationAddress = "..."
val satPerVbyte = 1.toUInt()
try {
sdk.refund(RefundRequest(swapAddress, destinationAddress, satPerVbyte))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: execute-refund
}
fun get_channel_opening_fees(sdk: BlockingBreezServices) {
// ANCHOR: get-channel-opening-fees
try {
val amountMsat = 5_000.toULong();
val channelFees = sdk.openChannelFee(OpenChannelFeeRequest(amountMsat))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: get-channel-opening-fees
}
}

View File

@@ -0,0 +1,17 @@
package com.example.kotlinmpplib
import breez_sdk.*
class ReceivePayment {
fun receive_payment(sdk: BlockingBreezServices) {
// ANCHOR: receive-payment
try {
val invoice = sdk.receivePayment(ReceivePaymentRequest(
3_000_000.toULong(),
"Invoice for 3000 sats",
))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: receive-payment
}
}

View File

@@ -0,0 +1,43 @@
package com.example.kotlinmpplib
import breez_sdk.*
class SendOnchain {
fun estimate_current_rev_swap_fees(sdk: BlockingBreezServices) {
// ANCHOR: estimate-current-reverse-swap-total-fees
try {
val fees = sdk.fetchReverseSwapFees(ReverseSwapFeesRequest(50_000_u))
// Log.v("Breez", "Total estimated fees for reverse swap: ${fees.totalEstimatedFees}")
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: estimate-current-reverse-swap-total-fees
}
fun get_current_rev_swap_min_max(sdk: BlockingBreezServices, fees: ReverseSwapPairInfo) {
// ANCHOR: get-current-reverse-swap-min-max
// Log.v("Breez", "Minimum amount, in sats: ${fees.min}")
// Log.v("Breez", "Maximum amount, in sats: ${fees.max}")
// ANCHOR_END: get-current-reverse-swap-min-max
}
fun start_reverse_swap(sdk: BlockingBreezServices, fees: ReverseSwapPairInfo) {
// ANCHOR: start-reverse-swap
val address = "bc1.."
val amountSat = 123.toULong()
val satPerVbyte = 1.toUInt()
try {
sdk.sendOnchain(SendOnchainRequest(amountSat, address, fees.feesHash, satPerVbyte))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: start-reverse-swap
}
fun check_rev_swap_status(sdk: BlockingBreezServices) {
// ANCHOR: check-reverse-swaps-status
for (rs in sdk.inProgressReverseSwaps()) {
// Log.v("Breez", "Reverse swap ${rs.id} in progress, status is ${rs.status}")
}
// ANCHOR_END: check-reverse-swaps-status
}
}

View File

@@ -0,0 +1,19 @@
package com.example.kotlinmpplib
import breez_sdk.*
class SendPayment {
fun send_payment(sdk: BlockingBreezServices) {
// ANCHOR: send-payment
val bolt11 = "..."
try {
// The `amountMsat` param is optional and should only passed if the bolt11 doesn't specify an amount.
// The amountMsat is required in case an amount is not specified in the bolt11 invoice'.
val amountMsat = 3_000_000.toULong()
val req = SendPaymentRequest(bolt11, amountMsat)
val response = sdk.sendPayment(req)
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: send-payment
}
}

View File

@@ -0,0 +1,17 @@
package com.example.kotlinmpplib
import breez_sdk.*
class SendSpontaneousPayment {
fun send_spontaneous_payment(sdk: BlockingBreezServices) {
// ANCHOR: send-spontaneous-payment
val nodeId = "..."
val amountMsat = 3_000_000.toULong()
try {
val response = sdk.sendSpontaneousPayment(
SendSpontaneousPaymentRequest(nodeId, amountMsat))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: send-spontaneous-payment
}
}

View File

@@ -0,0 +1,14 @@
package com.example.kotlinmpplib
import breez_sdk.*
class StaticChannelBackup {
fun backup(sdk: BlockingBreezServices) {
// ANCHOR: static-channel-backup
try {
val backupData = staticBackup(StaticBackupRequest("<working directory>"))
} catch (e: Exception) {
// handle error
}
// ANCHOR_END: static-channel-backup
}
}