Skip to content

Commit

Permalink
Add dart snippets (#5)
Browse files Browse the repository at this point in the history
* Add dart snippets

* Remove listPaymentsFiltered

* Target published Dart/Flutter packages on git repository by default

* Fix imports

* Add BreezLiquidSDK wrapper class to manage wallet instance & SDK streams

* Add rxdart

* [Dart] Initialize Liquid SDK library

* [Dart] Update LNURL snippets

* [Dart] Update Fiat Currency snippets

* CI: update references to breez-liquid-sdk

* Flutter setup instructions: update repo links

* Dart snippets: rewrite to match Rust snippets

* CI: Update default SDK ref and package version

* Address linter issues and run dart format

* Add extension on Config
* Fix indentation
* Fix enum name
* Add print statements to remove unused_variable warnings
* Remove unused import

* CI: Re-add default value for sdk-ref

* Dart setup: add hint about initialization approach

* Dart setup: update hint with more details

* Update link syntax

---------

Co-authored-by: Erdem Yerebasmaz <[email protected]>
  • Loading branch information
ok300 and erdemyerebasmaz authored Jul 8, 2024
1 parent 71129b2 commit 6bef82c
Show file tree
Hide file tree
Showing 21 changed files with 1,157 additions and 10 deletions.
18 changes: 10 additions & 8 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ on:
workflow_dispatch:
inputs:
sdk-ref:
description: 'sdk commit/tag/branch reference. Defaults to main.'
description: 'sdk commit/tag/branch reference. Defaults to 0.1.2-dev4.'
required: false
type: string
default: main
default: 0.1.2-dev4

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
Expand All @@ -25,17 +25,19 @@ jobs:
name: setup
runs-on: ubuntu-latest
outputs:
sdk-ref: ${{ inputs.sdk-ref || '08b2e5a6e2e095a8aaa1cdb7650b3b1b7348dc65' }}
package-version: '0.1.1'
# Used only for Rust snippets
sdk-ref: ${{ inputs.sdk-ref || '0.1.2-dev4' }}
# Used for RN and Flutter snippets
package-version: '0.1.2-dev4'
steps:
- run: echo "set pre-setup output variables"

build-packages:
needs: setup
name: build packages
uses: breez/breez-sdk/.github/workflows/publish-all-platforms.yml@main
uses: breez/breez-liquid-sdk/.github/workflows/publish-all-platforms.yml@main
with:
repository: breez/breez-sdk
repository: breez/breez-liquid-sdk
ref: ${{ needs.setup.outputs.sdk-ref }}
package-version: ${{ needs.setup.outputs.package-version }}
packages-to-publish: '["csharp", "flutter", "golang", "react-native", "python"]'
Expand Down Expand Up @@ -110,8 +112,8 @@ jobs:

- uses: actions/download-artifact@v4
with:
name: breez-sdk-flutter-${{ needs.setup.outputs.package-version }}
path: snippets/dart_snippets/packages/breez-sdk-flutter
name: breez-liquid-sdk-flutter-${{ needs.setup.outputs.package-version }}
path: snippets/dart_snippets/packages/breez-liquid-sdk-flutter

- name: pub-get
working-directory: snippets/dart_snippets
Expand Down
7 changes: 7 additions & 0 deletions snippets/dart_snippets/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
packages/
.flutter-version
.flutter-plugins
.flutter-plugins-dependencies
11 changes: 11 additions & 0 deletions snippets/dart_snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## Steps to compile the snippets locally
1. Build a flutter package
- By running the publish-all-platforms CI in the breez-liquid-sdk repository (use dummy binaries)
- or by cloning https://github.com/breez/breez-liquid-sdk-flutter
2. Place the files in the folder `snippets/dart-snippets/packages/breez-liquid-sdk-flutter`
3. Happy coding

To use a local path to the flutter bindings, see the `dependency_overrides` section in `pubspec.yaml`.

## Nix
Use the command `nix develop`
30 changes: 30 additions & 0 deletions snippets/dart_snippets/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# linter:
# rules:
# - camel_case_types

analyzer:
exclude:
- packages/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
6 changes: 6 additions & 0 deletions snippets/dart_snippets/bin/dart_snippets.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart' as liquid_sdk;

void main() async {
// Initialize library
await liquid_sdk.initialize();
}
61 changes: 61 additions & 0 deletions snippets/dart_snippets/flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions snippets/dart_snippets/flake.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
description = "Flutter flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-24.05";
flake-utils.url = "github:numtide/flake-utils";
};
outputs =
{ self
, nixpkgs
, flake-utils
,
}:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
in
{
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
flutter
];
};

formatter = pkgs.nixpkgs-fmt;
});
}
22 changes: 22 additions & 0 deletions snippets/dart_snippets/lib/fiat_currencies.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<List<FiatCurrency>> listFiatCurrencies() async {
// ANCHOR: list-fiat-currencies
List<FiatCurrency> fiatCurrencyList = await breezLiquidSDK.instance!.listFiatCurrencies();
// ANCHOR_END: list-fiat-currencies
return fiatCurrencyList;
}

Future<Map<String, Rate>> fetchFiatRates() async {
// ANCHOR: fetch-fiat-rates
final List<Rate> rates = await breezLiquidSDK.instance!.fetchFiatRates();
final fiatRatesMap = rates.fold<Map<String, Rate>>({}, (map, rate) {
map[rate.coin] = rate;
return map;
});
// print your desired rate
print(fiatRatesMap["USD"]?.value);
// ANCHOR_END: fetch-fiat-rates
return fiatRatesMap;
}
50 changes: 50 additions & 0 deletions snippets/dart_snippets/lib/getting_started.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<void> initializeSDK() async {
// ANCHOR: init-sdk
// It is recommended to use a single instance of BreezSDKLiquid across your Dart/Flutter app.
//
// All of the snippets assume a BreezSDKLiquid object is created on entrypoint of the app as such:
//
// ConnectRequest req = ConnectRequest(...);
// BindingLiquidSdk instance = await connect(req: req);
//
// and is accessible throughout the app. There are various approaches on how to achieve this:
// creating a Singleton class using factory constructor, using state management libraries such as 'provider', 'GetX',
// 'Riverpod' and 'Redux' to name a few.
//
// The Dart snippets included here rely on the example approach seen on sdk_instance.dart to manage wallet connection
// and Liquid SDK streams. This approach also has essential helper methods to ensure wallet data is in sync.
// Please see sdk_instance.dart for more details:
// [sdk_instance.dart](https://github.com/breez/breez-sdk-liquid-docs/blob/main/snippets/dart_snippets/lib/sdk_instance.dart)

// Create the default config
String mnemonic = "<mnemonic words>";

// Create the default config
Config config = defaultConfig(
network: LiquidNetwork.mainnet,
);

// Customize the config object according to your needs
config = config.copyWith(workingDir: "path to an existing directory");

ConnectRequest connectRequest = ConnectRequest(mnemonic: mnemonic, config: config);

await breezLiquidSDK.connect(req: connectRequest);

// ANCHOR_END: init-sdk
}

Future<void> fetchBalance(String lspId) async {
// ANCHOR: fetch-balance
GetInfoResponse? nodeState = await breezLiquidSDK.instance!.getInfo();
BigInt balanceSat = nodeState.balanceSat;
BigInt pendingSendSat = nodeState.pendingSendSat;
BigInt pendingReceiveSat = nodeState.pendingReceiveSat;
// ANCHOR_END: fetch-balance
print(balanceSat);
print(pendingSendSat);
print(pendingReceiveSat);
}
9 changes: 9 additions & 0 deletions snippets/dart_snippets/lib/list_payments.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<List<Payment>> listPayments() async {
// ANCHOR: list-payments
List<Payment> paymentsList = await breezLiquidSDK.instance!.listPayments();
// ANCHOR_END: list-payments
return paymentsList;
}
21 changes: 21 additions & 0 deletions snippets/dart_snippets/lib/lnurl_auth.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<void> lnurlAuth() async {
// ANCHOR: lnurl-auth
/// Endpoint can also be of the form:
/// keyauth://domain.com/auth?key=val
String lnurlAuthUrl =
"lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttvdankjm3lw3skw0tvdankjm3xdvcn6vtp8q6n2dfsx5mrjwtrxdjnqvtzv56rzcnyv3jrxv3sxqmkyenrvv6kve3exv6nqdtyv43nqcmzvdsnvdrzx33rsenxx5unqc3cxgeqgntfgu";

InputType inputType = await parse(input: lnurlAuthUrl);
if (inputType is InputType_LnUrlAuth) {
LnUrlCallbackStatus result = await breezLiquidSDK.instance!.lnurlAuth(reqData: inputType.data);
if (result is LnUrlCallbackStatus_Ok) {
print("Successfully authenticated");
} else {
print("Failed to authenticate");
}
}
// ANCHOR_END: lnurl-auth
}
26 changes: 26 additions & 0 deletions snippets/dart_snippets/lib/lnurl_pay.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<void> lnurlPay() async {
// ANCHOR: lnurl-pay
/// Endpoint can also be of the form:
/// lnurlp://domain.com/lnurl-pay?key=val
/// lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4excttsv9un7um9wdekjmmw84jxywf5x43rvv35xgmr2enrxanr2cfcvsmnwe3jxcukvde48qukgdec89snwde3vfjxvepjxpjnjvtpxd3kvdnxx5crxwpjvyunsephsz36jf
String lnurlPayUrl = "[email protected]";

InputType inputType = await parse(input: lnurlPayUrl);
if (inputType is InputType_LnUrlPay) {
BigInt amountMsat = inputType.data.minSendable;
String optionalComment = "<comment>";
String optionalPaymentLabel = "<label>";
LnUrlPayRequest req = LnUrlPayRequest(
data: inputType.data,
amountMsat: amountMsat,
comment: optionalComment,
paymentLabel: optionalPaymentLabel,
);
LnUrlPayResult result = await breezLiquidSDK.instance!.lnurlPay(req: req);
print(result.data);
}
// ANCHOR_END: lnurl-pay
}
23 changes: 23 additions & 0 deletions snippets/dart_snippets/lib/lnurl_withdraw.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<void> lnurlWithdraw() async {
// ANCHOR: lnurl-withdraw
/// Endpoint can also be of the form:
/// lnurlw://domain.com/lnurl-withdraw?key=val
String lnurlWithdrawUrl =
"lnurl1dp68gurn8ghj7mr0vdskc6r0wd6z7mrww4exctthd96xserjv9mn7um9wdekjmmw843xxwpexdnxzen9vgunsvfexq6rvdecx93rgdmyxcuxverrvcursenpxvukzv3c8qunsdecx33nzwpnvg6ryc3hv93nzvecxgcxgwp3h33lxk";

InputType inputType = await parse(input: lnurlWithdrawUrl);
if (inputType is InputType_LnUrlWithdraw) {
BigInt amountMsat = inputType.data.minWithdrawable;
LnUrlWithdrawRequest req = LnUrlWithdrawRequest(
data: inputType.data,
amountMsat: amountMsat,
description: "<description>",
);
LnUrlWithdrawResult result = await breezLiquidSDK.instance!.lnurlWithdraw(req: req);
print(result.data);
}
// ANCHOR_END: lnurl-withdraw
}
42 changes: 42 additions & 0 deletions snippets/dart_snippets/lib/pay_onchain.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'package:dart_snippets/sdk_instance.dart';
import 'package:flutter_breez_liquid/flutter_breez_liquid.dart';

Future<OnchainPaymentLimitsResponse> getCurrentLimits() async {
// ANCHOR: get-current-pay-onchain-limits
OnchainPaymentLimitsResponse currentLimits = await breezLiquidSDK.instance!.fetchOnchainLimits();
print("Minimum amount: ${currentLimits.send.minSat} sats");
print("Maximum amount: ${currentLimits.send.maxSat} sats");
// ANCHOR_END: get-current-pay-onchain-limits
return currentLimits;
}

Future<PreparePayOnchainResponse> preparePayOnchain() async {
// ANCHOR: prepare-pay-onchain
PreparePayOnchainRequest preparePayOnchainRequest = PreparePayOnchainRequest(
receiverAmountSat: 5000 as BigInt,
);
PreparePayOnchainResponse prepareRes = await breezLiquidSDK.instance!.preparePayOnchain(
req: preparePayOnchainRequest,
);

// Check if the fees are acceptable before proceeding
BigInt feesSat = prepareRes.feesSat;
// ANCHOR_END: prepare-pay-onchain
print(feesSat);
return prepareRes;
}

Future<SendPaymentResponse> startReverseSwap({
required PreparePayOnchainResponse prepareRes,
}) async {
// ANCHOR: start-reverse-swap
String destinationAddress = "bc1..";

PayOnchainRequest req = PayOnchainRequest(
address: destinationAddress,
prepareRes: prepareRes,
);
SendPaymentResponse res = await breezLiquidSDK.instance!.payOnchain(req: req);
// ANCHOR_END: start-reverse-swap
return res;
}
Loading

0 comments on commit 6bef82c

Please sign in to comment.