Wrap promises with try blocks

This commit is contained in:
Ross Savage
2024-02-06 20:25:50 +01:00
parent 0379597d5e
commit aec144693d
17 changed files with 275 additions and 145 deletions

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,32 +16,40 @@ const exampleGettingStarted = async () => {
console.log(`Received event ${e.type}`)
}
// Create the default config
const seed = await mnemonicToSeed('<mnemonics words>')
const inviteCode = '<invite code>'
const apiKey = '<api key>'
const nodeConfig: NodeConfig = {
type: NodeConfigVariant.GREENLIGHT,
config: {
inviteCode
try {
// Create the default config
const seed = await mnemonicToSeed('<mnemonics words>')
const inviteCode = '<invite code>'
const apiKey = '<api key>'
const nodeConfig: NodeConfig = {
type: NodeConfigVariant.GREENLIGHT,
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
}
const exampleFetchNodeInfo = async () => {
// ANCHOR: fetch-balance
const nodeState = await nodeInfo()
const balanceLn = nodeState.channelsBalanceMsat
const balanceOnchain = nodeState.onchainBalanceMsat
try {
const nodeState = await nodeInfo()
const balanceLn = nodeState.channelsBalanceMsat
const balanceOnchain = nodeState.onchainBalanceMsat
} catch (err) {
console.error(err)
}
// ANCHOR_END: fetch-balance
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,11 +2,15 @@ import { receivePayment } from '@breeztech/react-native-breez-sdk'
const exampleReceiveLightningPayment = async () => {
// ANCHOR: receive-payment
const receivePaymentResponse = await receivePayment({
amountMsat: 3_000_000,
description: 'Invoice for 3000 sats'
})
try {
const receivePaymentResponse = await receivePayment({
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
}

View File

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

View File

@@ -2,10 +2,14 @@ import { sendPayment } from '@breeztech/react-native-breez-sdk'
const exampleSendLightningPayment = async () => {
// ANCHOR: send-payment
const bolt11 = 'bolt11 invoice'
// 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'.
const amountMsat = 3000000
const response = await sendPayment({ bolt11, amountMsat })
try {
const bolt11 = 'bolt11 invoice'
// 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'.
const amountMsat = 3000000
const response = await sendPayment({ bolt11, amountMsat })
} catch (err) {
console.error(err)
}
// ANCHOR_END: send-payment
}

View File

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

View File

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

View File

@@ -2,6 +2,10 @@ import { staticBackup } from '@breeztech/react-native-breez-sdk'
const exampleStaticBackup = async () => {
// 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
}

View File

@@ -2,12 +2,20 @@ import { registerWebhook } from '@breeztech/react-native-breez-sdk'
const webhook = async () => {
// ANCHOR: register-webook
await registerWebhook('https://yourapplication.com')
try {
await registerWebhook('https://yourapplication.com')
} catch (err) {
console.error(err)
}
// ANCHOR_END: register-webook
}
const paymentWebhook = async () => {
// 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
}