Merge pull request #130 from breez/savage-rn-try-blocks

Wrap RN promises with try blocks
This commit is contained in:
Ross Savage
2024-02-06 21:21:44 +01:00
committed by GitHub
17 changed files with 275 additions and 145 deletions

View File

@@ -5,8 +5,12 @@ import {
const exampleBuyBtc = async () => { const exampleBuyBtc = async () => {
// ANCHOR: buy-btc // ANCHOR: buy-btc
const buyBitcoinResponse = await buyBitcoin({ try {
provider: BuyBitcoinProvider.MOONPAY const buyBitcoinResponse = await buyBitcoin({
}) provider: BuyBitcoinProvider.MOONPAY
})
} catch (err) {
console.error(err)
}
// ANCHOR_END: buy-btc // ANCHOR_END: buy-btc
} }

View File

@@ -5,15 +5,22 @@ import {
const examplePrepareRedeemOnchainFunds = async (feeRate: number) => { const examplePrepareRedeemOnchainFunds = async (feeRate: number) => {
// ANCHOR: prepare-redeem-onchain-funds // ANCHOR: prepare-redeem-onchain-funds
const toAddress = 'bc1..' try {
const satPerVbyte = feeRate const toAddress = 'bc1..'
const satPerVbyte = feeRate
const prepareRedeemOnchainFundsResp = await prepareRedeemOnchainFunds({ toAddress, satPerVbyte }) const prepareRedeemOnchainFundsResp = await prepareRedeemOnchainFunds({ toAddress, satPerVbyte })
} catch (err) {
console.error(err)
}
// ANCHOR_END: prepare-redeem-onchain-funds // ANCHOR_END: prepare-redeem-onchain-funds
} }
const exampleRedeemOnchainFunds = async (satPerVbyte: number, toAddress: string) => { const exampleRedeemOnchainFunds = async (satPerVbyte: number, toAddress: string) => {
// ANCHOR: redeem-onchain-funds // ANCHOR: redeem-onchain-funds
const redeemOnchainFundsResp = await redeemOnchainFunds({ toAddress, satPerVbyte }) try {
const redeemOnchainFundsResp = await redeemOnchainFunds({ toAddress, satPerVbyte })
} catch (err) {
console.error(err)
}
// ANCHOR_END: redeem-onchain-funds // ANCHOR_END: redeem-onchain-funds
} }

View File

@@ -2,20 +2,32 @@ import { connectLsp, listLsps, lspId, lspInfo } from '@breeztech/react-native-br
const exampleAutoConnect = async () => { const exampleAutoConnect = async () => {
// ANCHOR: get-lsp-info // ANCHOR: get-lsp-info
const id = await lspId() try {
const info = await lspInfo() const id = await lspId()
const info = await lspInfo()
} catch (err) {
console.error(err)
}
// ANCHOR_END: get-lsp-info // ANCHOR_END: get-lsp-info
} }
const exampleListLsps = async () => { const exampleListLsps = async () => {
// ANCHOR: list-lsps // ANCHOR: list-lsps
const availableLsps = await listLsps() try {
const availableLsps = await listLsps()
} catch (err) {
console.error(err)
}
// ANCHOR_END: list-lsps // ANCHOR_END: list-lsps
} }
const exampleManualConnect = async () => { const exampleManualConnect = async () => {
// ANCHOR: connect-lsp // ANCHOR: connect-lsp
const id = 'your selected lsp id' try {
await connectLsp(id) const id = 'your selected lsp id'
await connectLsp(id)
} catch (err) {
console.error(err)
}
// ANCHOR_END: connect-lsp // ANCHOR_END: connect-lsp
} }

View File

@@ -5,12 +5,20 @@ import {
const exampleListCurrencies = async () => { const exampleListCurrencies = async () => {
// ANCHOR: list-fiat-currencies // ANCHOR: list-fiat-currencies
const fiatCurrencies = await listFiatCurrencies() try {
const fiatCurrencies = await listFiatCurrencies()
} catch (err) {
console.error(err)
}
// ANCHOR_END: list-fiat-currencies // ANCHOR_END: list-fiat-currencies
} }
const exampleFetchRates = async () => { const exampleFetchRates = async () => {
// ANCHOR: fetch-fiat-rates // ANCHOR: fetch-fiat-rates
const fiatRates = await fetchFiatRates() try {
const fiatRates = await fetchFiatRates()
} catch (err) {
console.error(err)
}
// ANCHOR_END: fetch-fiat-rates // ANCHOR_END: fetch-fiat-rates
} }

View File

@@ -16,32 +16,40 @@ const exampleGettingStarted = async () => {
console.log(`Received event ${e.type}`) console.log(`Received event ${e.type}`)
} }
// Create the default config try {
const seed = await mnemonicToSeed('<mnemonics words>') // Create the default config
const inviteCode = '<invite code>' const seed = await mnemonicToSeed('<mnemonics words>')
const apiKey = '<api key>' const inviteCode = '<invite code>'
const nodeConfig: NodeConfig = { const apiKey = '<api key>'
type: NodeConfigVariant.GREENLIGHT, const nodeConfig: NodeConfig = {
config: { type: NodeConfigVariant.GREENLIGHT,
inviteCode config: {
inviteCode
}
} }
const config = await defaultConfig(
EnvironmentType.PRODUCTION,
apiKey,
nodeConfig
)
// Connect to the Breez SDK make it ready for use
await connect(config, seed, onBreezEvent)
} catch (err) {
console.error(err)
} }
const config = await defaultConfig(
EnvironmentType.PRODUCTION,
apiKey,
nodeConfig
)
// Connect to the Breez SDK make it ready for use
await connect(config, seed, onBreezEvent)
// ANCHOR_END: init-sdk // ANCHOR_END: init-sdk
} }
const exampleFetchNodeInfo = async () => { const exampleFetchNodeInfo = async () => {
// ANCHOR: fetch-balance // ANCHOR: fetch-balance
const nodeState = await nodeInfo() try {
const balanceLn = nodeState.channelsBalanceMsat const nodeState = await nodeInfo()
const balanceOnchain = nodeState.onchainBalanceMsat const balanceLn = nodeState.channelsBalanceMsat
const balanceOnchain = nodeState.onchainBalanceMsat
} catch (err) {
console.error(err)
}
// ANCHOR_END: fetch-balance // ANCHOR_END: fetch-balance
} }

View File

@@ -5,16 +5,24 @@ import {
const exampleListPayments = async () => { const exampleListPayments = async () => {
// ANCHOR: list-payments // ANCHOR: list-payments
const payments = listPayments({}) try {
const payments = await listPayments({})
} catch (err) {
console.error(err)
}
// ANCHOR_END: list-payments // ANCHOR_END: list-payments
} }
const exampleListPaymentsFiltered = async () => { const exampleListPaymentsFiltered = async () => {
// ANCHOR: list-payments-filtered // ANCHOR: list-payments-filtered
const payments = listPayments({ try {
filters: [PaymentTypeFilter.SENT], const payments = await listPayments({
fromTimestamp: 1696880000, filters: [PaymentTypeFilter.SENT],
includeFailures: true fromTimestamp: 1696880000,
}) includeFailures: true
})
} catch (err) {
console.error(err)
}
// ANCHOR_END: list-payments-filtered // ANCHOR_END: list-payments-filtered
} }

View File

@@ -9,17 +9,21 @@ const exampleLnurlAuth = async () => {
// ANCHOR: lnurl-auth // ANCHOR: lnurl-auth
// Endpoint can also be of the form: // Endpoint can also be of the form:
// keyauth://domain.com/auth?key=val // keyauth://domain.com/auth?key=val
const lnurlAuthUrl = try {
'lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttvdankjm3lw3skw0tvdankjm3xdvcn6vtp8q6n2dfsx5mrjwtrxdjnqvtzv56rzcnyv3jrxv3sxqmkyenrvv6kve3exv6nqdtyv43nqcmzvdsnvdrzx33rsenxx5unqc3cxgeqgntfgu' const lnurlAuthUrl =
'lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttvdankjm3lw3skw0tvdankjm3xdvcn6vtp8q6n2dfsx5mrjwtrxdjnqvtzv56rzcnyv3jrxv3sxqmkyenrvv6kve3exv6nqdtyv43nqcmzvdsnvdrzx33rsenxx5unqc3cxgeqgntfgu'
const input = await parseInput(lnurlAuthUrl) const input = await parseInput(lnurlAuthUrl)
if (input.type === InputTypeVariant.LN_URL_AUTH) { if (input.type === InputTypeVariant.LN_URL_AUTH) {
const result = await lnurlAuth(input.data) const result = await lnurlAuth(input.data)
if (result.type === LnUrlCallbackStatusVariant.OK) { if (result.type === LnUrlCallbackStatusVariant.OK) {
console.log('Successfully authenticated') console.log('Successfully authenticated')
} else { } else {
console.log('Failed to authenticate') console.log('Failed to authenticate')
}
} }
} catch (err) {
console.error(err)
} }
// ANCHOR_END: lnurl-auth // ANCHOR_END: lnurl-auth
} }

View File

@@ -9,16 +9,20 @@ const exampleLnurlPay = async () => {
// Endpoint can also be of the // Endpoint can also be of the
// lnurlp://domain.com/lnurl-pay?key=val // lnurlp://domain.com/lnurl-pay?key=val
// lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttsv9un7um9wdekjmmw84jxywf5x43rvv35xgmr2enrxanr2cfcvsmnwe3jxcukvde48qukgdec89snwde3vfjxvepjxpjnjvtpxd3kvdnxx5crxwpjvyunsephsz36jf // lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttsv9un7um9wdekjmmw84jxywf5x43rvv35xgmr2enrxanr2cfcvsmnwe3jxcukvde48qukgdec89snwde3vfjxvepjxpjnjvtpxd3kvdnxx5crxwpjvyunsephsz36jf
const lnurlPayUrl = 'lightning@address.com' try {
const lnurlPayUrl = 'lightning@address.com'
const input = await parseInput(lnurlPayUrl) const input = await parseInput(lnurlPayUrl)
if (input.type === InputTypeVariant.LN_URL_PAY) { if (input.type === InputTypeVariant.LN_URL_PAY) {
const amountMsat = input.data.minSendable const amountMsat = input.data.minSendable
const lnUrlPayResult = await payLnurl({ const lnUrlPayResult = await payLnurl({
data: input.data, data: input.data,
amountMsat, amountMsat,
comment: 'comment' comment: 'comment'
}) })
}
} catch (err) {
console.error(err)
} }
// ANCHOR_END: lnurl-pay // ANCHOR_END: lnurl-pay
} }

View File

@@ -8,17 +8,21 @@ const exampleLnurlWithdraw = async () => {
// ANCHOR: lnurl-withdraw // ANCHOR: lnurl-withdraw
// Endpoint can also be of the form: // Endpoint can also be of the form:
// lnurlw://domain.com/lnurl-withdraw?key=val // lnurlw://domain.com/lnurl-withdraw?key=val
const lnurlWithdrawUrl = try {
'lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4exctthd96xserjv9mn7um9wdekjmmw843xxwpexdnxzen9vgunsvfexq6rvdecx93rgdmyxcuxverrvcursenpxvukzv3c8qunsdecx33nzwpnvg6ryc3hv93nzvecxgcxgwp3h33lxk' const lnurlWithdrawUrl =
'lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4exctthd96xserjv9mn7um9wdekjmmw843xxwpexdnxzen9vgunsvfexq6rvdecx93rgdmyxcuxverrvcursenpxvukzv3c8qunsdecx33nzwpnvg6ryc3hv93nzvecxgcxgwp3h33lxk'
const input = await parseInput(lnurlWithdrawUrl) const input = await parseInput(lnurlWithdrawUrl)
if (input.type === InputTypeVariant.LN_URL_WITHDRAW) { if (input.type === InputTypeVariant.LN_URL_WITHDRAW) {
const amountMsat = input.data.minWithdrawable const amountMsat = input.data.minWithdrawable
const lnUrlWithdrawResult = await withdrawLnurl({ const lnUrlWithdrawResult = await withdrawLnurl({
data: input.data, data: input.data,
amountMsat, amountMsat,
description: 'comment' description: 'comment'
}) })
}
} catch (err) {
console.error(err)
} }
// ANCHOR_END: lnurl-withdraw // ANCHOR_END: lnurl-withdraw
} }

View File

@@ -8,47 +8,66 @@ import {
const exampleReceiveOnchain = async () => { const exampleReceiveOnchain = async () => {
// ANCHOR: generate-receive-onchain-address // ANCHOR: generate-receive-onchain-address
const swapInfo = await receiveOnchain({}) try {
const swapInfo = await receiveOnchain({})
// Send your funds to the below bitcoin address // Send your funds to the below bitcoin address
const address = swapInfo.bitcoinAddress const address = swapInfo.bitcoinAddress
console.log(`Minimum amount allowed to deposit in sats: ${swapInfo.minAllowedDeposit}`) console.log(`Minimum amount allowed to deposit in sats: ${swapInfo.minAllowedDeposit}`)
console.log(`Maximum amount allowed to deposit in sats: ${swapInfo.maxAllowedDeposit}`) console.log(`Maximum amount allowed to deposit in sats: ${swapInfo.maxAllowedDeposit}`)
} catch (err) {
console.error(err)
}
// ANCHOR_END: generate-receive-onchain-address // ANCHOR_END: generate-receive-onchain-address
} }
const exampleInProgressSwap = async () => { const exampleInProgressSwap = async () => {
// ANCHOR: in-progress-swap // ANCHOR: in-progress-swap
const swapInfo = await inProgressSwap() try {
const swapInfo = await inProgressSwap()
} catch (err) {
console.error(err)
}
// ANCHOR_END: in-progress-swap // ANCHOR_END: in-progress-swap
} }
const exampleListRefundables = async () => { const exampleListRefundables = async () => {
// ANCHOR: list-refundables // ANCHOR: list-refundables
const refundables = await listRefundables() try {
const refundables = await listRefundables()
} catch (err) {
console.error(err)
}
// ANCHOR_END: list-refundables // ANCHOR_END: list-refundables
} }
const exampleRefund = async () => { const exampleRefund = async () => {
// ANCHOR: execute-refund // ANCHOR: execute-refund
const refundables = await listRefundables() try {
const toAddress = '...' const refundables = await listRefundables()
const satPerVbyte = 5 const toAddress = '...'
const satPerVbyte = 5
const refundResponse = await refund({ const refundResponse = await refund({
swapAddress: refundables[0].bitcoinAddress, swapAddress: refundables[0].bitcoinAddress,
toAddress, toAddress,
satPerVbyte satPerVbyte
}) })
} catch (err) {
console.error(err)
}
// ANCHOR_END: execute-refund // ANCHOR_END: execute-refund
} }
const exampleOpenChannelFee = async () => { const exampleOpenChannelFee = async () => {
// ANCHOR: get-channel-opening-fees // ANCHOR: get-channel-opening-fees
const amountMsat = 10000 try {
const amountMsat = 10000
const openChannelFeeResponse = await openChannelFee({ const openChannelFeeResponse = await openChannelFee({
amountMsat amountMsat
}) })
} catch (err) {
console.error(err)
}
// ANCHOR_END: get-channel-opening-fees // ANCHOR_END: get-channel-opening-fees
} }

View File

@@ -2,11 +2,15 @@ import { receivePayment } from '@breeztech/react-native-breez-sdk'
const exampleReceiveLightningPayment = async () => { const exampleReceiveLightningPayment = async () => {
// ANCHOR: receive-payment // ANCHOR: receive-payment
const receivePaymentResponse = await receivePayment({ try {
amountMsat: 3_000_000, const receivePaymentResponse = await receivePayment({
description: 'Invoice for 3000 sats' amountMsat: 3_000_000,
}) description: 'Invoice for 3000 sats'
})
const invoice = receivePaymentResponse.lnInvoice const invoice = receivePaymentResponse.lnInvoice
} catch (err) {
console.error(err)
}
// ANCHOR_END: receive-payment // ANCHOR_END: receive-payment
} }

View File

@@ -8,11 +8,15 @@ import {
const exampleFetchReverseSwapFees = async () => { const exampleFetchReverseSwapFees = async () => {
// ANCHOR: estimate-current-reverse-swap-total-fees // ANCHOR: estimate-current-reverse-swap-total-fees
const currentFees = await fetchReverseSwapFees({ sendAmountSat: 50000 }) try {
const currentFees = await fetchReverseSwapFees({ sendAmountSat: 50000 })
console.log( console.log(
`Total estimated fees for reverse swap: ${currentFees.totalEstimatedFees}` `Total estimated fees for reverse swap: ${currentFees.totalEstimatedFees}`
) )
} catch (err) {
console.error(err)
}
// ANCHOR_END: estimate-current-reverse-swap-total-fees // ANCHOR_END: estimate-current-reverse-swap-total-fees
} }
@@ -25,36 +29,48 @@ const exampleListCurrentFees = (currentFees: ReverseSwapPairInfo) => {
const maxAmount = async () => { const maxAmount = async () => {
// ANCHOR: max-reverse-swap-amount // ANCHOR: max-reverse-swap-amount
const maxAmount = await maxReverseSwapAmount() try {
const maxAmount = await maxReverseSwapAmount()
console.log( console.log(
`Max reverse swap amount: ${maxAmount.totalSat}` `Max reverse swap amount: ${maxAmount.totalSat}`
) )
} catch (err) {
console.error(err)
}
// ANCHOR_END: max-reverse-swap-amount // ANCHOR_END: max-reverse-swap-amount
} }
const exampleSendOnchain = async (currentFees: ReverseSwapPairInfo) => { const exampleSendOnchain = async (currentFees: ReverseSwapPairInfo) => {
// ANCHOR: start-reverse-swap // ANCHOR: start-reverse-swap
const onchainRecipientAddress = 'bc1..' try {
const amountSat = currentFees.min const onchainRecipientAddress = 'bc1..'
const satPerVbyte = 5 const amountSat = currentFees.min
const satPerVbyte = 5
const reverseSwapInfo = await sendOnchain({ const reverseSwapInfo = await sendOnchain({
amountSat, amountSat,
onchainRecipientAddress, onchainRecipientAddress,
pairHash: currentFees.feesHash, pairHash: currentFees.feesHash,
satPerVbyte satPerVbyte
}) })
} catch (err) {
console.error(err)
}
// ANCHOR_END: start-reverse-swap // ANCHOR_END: start-reverse-swap
} }
const exampleInProgressReverseSwaps = async () => { const exampleInProgressReverseSwaps = async () => {
// ANCHOR: check-reverse-swaps-status // ANCHOR: check-reverse-swaps-status
const swaps = await inProgressReverseSwaps() try {
for (const swap of swaps) { const swaps = await inProgressReverseSwaps()
console.log( for (const swap of swaps) {
`Reverse swap ${swap.id} in progress, status is ${swap.status}` console.log(
) `Reverse swap ${swap.id} in progress, status is ${swap.status}`
)
}
} catch (err) {
console.error(err)
} }
// ANCHOR_END: check-reverse-swaps-status // ANCHOR_END: check-reverse-swaps-status
} }

View File

@@ -2,10 +2,14 @@ import { sendPayment } from '@breeztech/react-native-breez-sdk'
const exampleSendLightningPayment = async () => { const exampleSendLightningPayment = async () => {
// ANCHOR: send-payment // ANCHOR: send-payment
const bolt11 = 'bolt11 invoice' try {
// The `amountMsat` param is optional and should only passed if the bolt11 doesn't specify an amount. const bolt11 = 'bolt11 invoice'
// The amountMsat is required in case an amount is not specified in the bolt11 invoice'. // The `amountMsat` param is optional and should only passed if the bolt11 doesn't specify an amount.
const amountMsat = 3000000 // The amountMsat is required in case an amount is not specified in the bolt11 invoice'.
const response = await sendPayment({ bolt11, amountMsat }) const amountMsat = 3000000
const response = await sendPayment({ bolt11, amountMsat })
} catch (err) {
console.error(err)
}
// ANCHOR_END: send-payment // ANCHOR_END: send-payment
} }

View File

@@ -5,12 +5,16 @@ import {
const exampleSendSpontaneousPayment = async () => { const exampleSendSpontaneousPayment = async () => {
// ANCHOR: send-spontaneous-payment // ANCHOR: send-spontaneous-payment
const nodeId = '...' try {
const nodeId = '...'
const sendPaymentResponse = await sendSpontaneousPayment({ const sendPaymentResponse = await sendSpontaneousPayment({
nodeId, nodeId,
amountMsat: 3000000 amountMsat: 3000000
}) })
} catch (err) {
console.error(err)
}
// ANCHOR_END: send-spontaneous-payment // ANCHOR_END: send-spontaneous-payment
} }
@@ -24,15 +28,19 @@ const stringToBytes = (str: string): number[] => {
const exampleSendSpontaneousPaymentWithTlvs = async () => { const exampleSendSpontaneousPaymentWithTlvs = async () => {
// ANCHOR: send-spontaneous-payment-with-tlvs // ANCHOR: send-spontaneous-payment-with-tlvs
const nodeId = '...' try {
const extraTlvs: TlvEntry[] = [ const nodeId = '...'
{ fieldNumber: 34349334, value: stringToBytes('Hello world!') } const extraTlvs: TlvEntry[] = [
] { fieldNumber: 34349334, value: stringToBytes('Hello world!') }
]
const sendPaymentResponse = await sendSpontaneousPayment({ const sendPaymentResponse = await sendSpontaneousPayment({
nodeId, nodeId,
amountMsat: 3000000, amountMsat: 3000000,
extraTlvs extraTlvs
}) })
} catch (err) {
console.error(err)
}
// ANCHOR_END: send-spontaneous-payment-with-tlvs // ANCHOR_END: send-spontaneous-payment-with-tlvs
} }

View File

@@ -2,17 +2,25 @@ import { serviceHealthCheck, reportIssue, ReportIssueRequestVariant } from '@bre
const healthCheckStatus = async () => { const healthCheckStatus = async () => {
// ANCHOR: health-check-status // ANCHOR: health-check-status
const healthCheck = await serviceHealthCheck() try {
console.log(`Current service status is: ${healthCheck.status}`) const healthCheck = await serviceHealthCheck()
console.log(`Current service status is: ${healthCheck.status}`)
} catch (err) {
console.error(err)
}
// ANCHOR_END: health-check-status // ANCHOR_END: health-check-status
} }
const reportPaymentFailure = async () => { const reportPaymentFailure = async () => {
// ANCHOR: report-payment-failure // ANCHOR: report-payment-failure
const paymentHash = '...' try {
await reportIssue({ const paymentHash = '...'
type: ReportIssueRequestVariant.PAYMENT_FAILURE, await reportIssue({
data: { paymentHash } type: ReportIssueRequestVariant.PAYMENT_FAILURE,
}) data: { paymentHash }
})
} catch (err) {
console.error(err)
}
// ANCHOR_END: report-payment-failure // ANCHOR_END: report-payment-failure
} }

View File

@@ -2,6 +2,10 @@ import { staticBackup } from '@breeztech/react-native-breez-sdk'
const exampleStaticBackup = async () => { const exampleStaticBackup = async () => {
// ANCHOR: static-channel-backup // ANCHOR: static-channel-backup
const backupData = await staticBackup({ workingDir: '<working directory>' }) try {
const backupData = await staticBackup({ workingDir: '<working directory>' })
} catch (err) {
console.error(err)
}
// ANCHOR_END: static-channel-backup // ANCHOR_END: static-channel-backup
} }

View File

@@ -2,12 +2,20 @@ import { registerWebhook } from '@breeztech/react-native-breez-sdk'
const webhook = async () => { const webhook = async () => {
// ANCHOR: register-webook // ANCHOR: register-webook
await registerWebhook('https://yourapplication.com') try {
await registerWebhook('https://yourapplication.com')
} catch (err) {
console.error(err)
}
// ANCHOR_END: register-webook // ANCHOR_END: register-webook
} }
const paymentWebhook = async () => { const paymentWebhook = async () => {
// ANCHOR: register-payment-webook // ANCHOR: register-payment-webook
await registerWebhook('https://your-nds-service.com/notify?platform=ios&token=<PUSH_TOKEN>') try {
await registerWebhook('https://your-nds-service.com/notify?platform=ios&token=<PUSH_TOKEN>')
} catch (err) {
console.error(err)
}
// ANCHOR_END: register-payment-webook // ANCHOR_END: register-payment-webook
} }