Skip to content

Commit

Permalink
Updated Balance struct - added BalanceUtils to get balance by Asset Id
Browse files Browse the repository at this point in the history
  • Loading branch information
i5hi committed Apr 13, 2024
1 parent b8ce946 commit 7ca84fa
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 84 deletions.
106 changes: 52 additions & 54 deletions example/lib/test_app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import 'package:flutter/material.dart';
import 'package:lwk_dart/lwk_dart.dart';
import 'package:path_provider/path_provider.dart';

class DecodedPset {
final int amount;
final int fee;
// class DecodedPset {
// final int amount;
// final int fee;

DecodedPset({required this.amount, required this.fee});
}
// DecodedPset({required this.amount, required this.fee});
// }

class TestApp extends StatefulWidget {
const TestApp({super.key});
Expand Down Expand Up @@ -62,16 +62,16 @@ class TestApp extends StatefulWidget {
return true;
}

static Future<Balance> balance(Wallet wallet) async {
final Balance balance = await wallet.balance();
static Future<Balances> balance(Wallet wallet) async {
final Balances balance = await wallet.balance();
return balance;
}

static Future<List<Map<String, int>>> txs(Wallet wallet) async {
static Future<List<Map<String, Tx>>> txs(Wallet wallet) async {
final txs = await wallet.txs();
List<Map<String, int>> res = [];
List<Map<String, Tx>> res = [];
for (int i = 0; i < txs.length; i++) {
res.add({txs[i].txid: txs[i].amount});
res.add({txs[i].txid: txs[i]});
}
return res;
}
Expand All @@ -82,14 +82,13 @@ class TestApp extends StatefulWidget {
return pset;
}

static Future<DecodedPset> decode(Wallet wallet, String pset) async {
final decodedPset = await wallet.decode(pset: pset);
return DecodedPset(amount: decodedPset.balances.lbtc, fee: decodedPset.fee);
static Future<PsetAmounts> decode(Wallet wallet, String pset) async {
return await wallet.decode(pset: pset);
}

static Future<Uint8List> sign(Wallet wallet, String pset) async {
final signedTxBytes =
await wallet.sign(network: network, pset: pset, mnemonic: mnemonic);
await wallet.sign(network: network, pset: pset, mnemonic: mnemonic);

return signedTxBytes;
}
Expand All @@ -109,11 +108,11 @@ class _TestAppState extends State<TestApp> {
bool loading = false;
Wallet? wallet;
bool isWalletSynced = false;
Balance? balance;
Balances? balance;
List<Map<String, int>>? txs;
String newAddress = "...";
String? pset;
DecodedPset? decodedPset;
PsetAmounts? decodedPset;
Uint8List? signedTxBytes;
String? tx;

Expand All @@ -132,8 +131,9 @@ class _TestAppState extends State<TestApp> {
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
backgroundColor:
MaterialStatePropertyAll<Color>(Colors.red.shade400),
foregroundColor: const MaterialStatePropertyAll<Color>(Colors.white),
MaterialStatePropertyAll<Color>(Colors.red.shade400),
foregroundColor:
const MaterialStatePropertyAll<Color>(Colors.white),
),
),
),
Expand Down Expand Up @@ -216,9 +216,7 @@ class _TestAppState extends State<TestApp> {
'Get Balance',
),
),
Text(balance == null
? "..."
: "${balance!.lbtc} sats"),
Text(balance == null ? "..." : "${balance} sats"),
],
),
Column(
Expand All @@ -231,7 +229,7 @@ class _TestAppState extends State<TestApp> {
final res = await TestApp.txs(wallet!);
setState(() {
loading = false;
txs = res;
txs = res.cast<Map<String, int>>();
});
},
child: const Text(
Expand All @@ -241,26 +239,26 @@ class _TestAppState extends State<TestApp> {
txs == null
? const Text("...")
: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.red.shade400,
width: 2,
),
),
height: 300,
child: ListView.builder(
itemCount: txs!.length,
itemBuilder:
(BuildContext context, int index) {
return ListTile(
title: Text(
'Transaction ID: ${txs![index].keys}'),
subtitle: Text(
'Amount: ${txs![index].values}'),
);
},
),
),
decoration: BoxDecoration(
border: Border.all(
color: Colors.red.shade400,
width: 2,
),
),
height: 300,
child: ListView.builder(
itemCount: txs!.length,
itemBuilder:
(BuildContext context, int index) {
return ListTile(
title: Text(
'Transaction ID: ${txs![index].keys}'),
subtitle: Text(
'Amount: ${txs![index].values}'),
);
},
),
),
],
),
Column(
Expand Down Expand Up @@ -303,16 +301,16 @@ class _TestAppState extends State<TestApp> {
pset == null
? const Text("...")
: Container(
height: 300,
decoration: BoxDecoration(
border: Border.all(
color: Colors.red.shade400,
width: 2,
),
),
child: SingleChildScrollView(
child: Text(pset!)),
),
height: 300,
decoration: BoxDecoration(
border: Border.all(
color: Colors.red.shade400,
width: 2,
),
),
child: SingleChildScrollView(
child: Text(pset!)),
),
],
),
Column(
Expand All @@ -323,7 +321,7 @@ class _TestAppState extends State<TestApp> {
loading = true;
});
final res =
await TestApp.decode(wallet!, pset!);
await TestApp.decode(wallet!, pset!);
setState(() {
loading = false;
decodedPset = res;
Expand All @@ -336,7 +334,7 @@ class _TestAppState extends State<TestApp> {
decodedPset == null
? const Text("...")
: Text(
'Amount: ${decodedPset!.amount}, Fee: ${decodedPset!.fee}'),
'Amount: ${decodedPset!.balances}, Fee: ${decodedPset!.fee}'),
],
),
Column(
Expand Down
33 changes: 16 additions & 17 deletions lib/src/generated/bindings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,13 @@ class LwkBridgeImpl implements LwkBridge {
argNames: ["walletId", "index"],
);

Future<List<(String, int)>> balanceStaticMethodApi(
Future<List<Balance>> balanceStaticMethodApi(
{required String walletId, dynamic hint}) {
var arg0 = _platform.api2wire_String(walletId);
return _platform.executeNormal(FlutterRustBridgeTask(
callFfi: (port_) =>
_platform.inner.wire_balance__static_method__Api(port_, arg0),
parseSuccessData: _wire2api_list___record__String_i64,
parseSuccessData: _wire2api_list_balance,
parseErrorData: _wire2api_lwk_error,
constMeta: kBalanceStaticMethodApiConstMeta,
argValues: [walletId],
Expand Down Expand Up @@ -301,17 +301,6 @@ class LwkBridgeImpl implements LwkBridge {
return raw as String;
}

(String, int) _wire2api___record__String_i64(dynamic raw) {
final arr = raw as List<dynamic>;
if (arr.length != 2) {
throw Exception('Expected 2 elements, got ${arr.length}');
}
return (
_wire2api_String(arr[0]),
_wire2api_i64(arr[1]),
);
}

Address _wire2api_address(dynamic raw) {
final arr = raw as List<dynamic>;
if (arr.length != 3)
Expand All @@ -323,6 +312,16 @@ class LwkBridgeImpl implements LwkBridge {
);
}

Balance _wire2api_balance(dynamic raw) {
final arr = raw as List<dynamic>;
if (arr.length != 2)
throw Exception('unexpected arr length: expect 2 but see ${arr.length}');
return Balance(
assetId: _wire2api_String(arr[0]),
value: _wire2api_i64(arr[1]),
);
}

int _wire2api_box_autoadd_u32(dynamic raw) {
return raw as int;
}
Expand All @@ -331,8 +330,8 @@ class LwkBridgeImpl implements LwkBridge {
return castInt(raw);
}

List<(String, int)> _wire2api_list___record__String_i64(dynamic raw) {
return (raw as List<dynamic>).map(_wire2api___record__String_i64).toList();
List<Balance> _wire2api_list_balance(dynamic raw) {
return (raw as List<dynamic>).map(_wire2api_balance).toList();
}

List<Tx> _wire2api_list_tx(dynamic raw) {
Expand Down Expand Up @@ -372,7 +371,7 @@ class LwkBridgeImpl implements LwkBridge {
throw Exception('unexpected arr length: expect 2 but see ${arr.length}');
return PsetAmounts(
fee: _wire2api_u64(arr[0]),
balances: _wire2api_list___record__String_i64(arr[1]),
balances: _wire2api_list_balance(arr[1]),
);
}

Expand All @@ -383,7 +382,7 @@ class LwkBridgeImpl implements LwkBridge {
return Tx(
timestamp: _wire2api_u32(arr[0]),
kind: _wire2api_String(arr[1]),
balances: _wire2api_list___record__String_i64(arr[2]),
balances: _wire2api_list_balance(arr[2]),
txid: _wire2api_String(arr[3]),
outputs: _wire2api_list_tx_out(arr[4]),
inputs: _wire2api_list_tx_out(arr[5]),
Expand Down
16 changes: 13 additions & 3 deletions lib/src/generated/bridge_definitions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ abstract class LwkBridge {

FlutterRustBridgeTaskConstMeta get kAddressStaticMethodApiConstMeta;

Future<List<(String, int)>> balanceStaticMethodApi(
Future<List<Balance>> balanceStaticMethodApi(
{required String walletId, dynamic hint});

FlutterRustBridgeTaskConstMeta get kBalanceStaticMethodApiConstMeta;
Expand Down Expand Up @@ -92,6 +92,16 @@ class Address {
});
}

class Balance {
final String assetId;
final int value;

const Balance({
required this.assetId,
required this.value,
});
}

/// Possible errors emitted
class LwkError implements FrbException {
final String msg;
Expand All @@ -118,7 +128,7 @@ class OutPoint {

class PsetAmounts {
final int fee;
final List<(String, int)> balances;
final List<Balance> balances;

const PsetAmounts({
required this.fee,
Expand All @@ -129,7 +139,7 @@ class PsetAmounts {
class Tx {
final int timestamp;
final String kind;
final List<(String, int)> balances;
final List<Balance> balances;
final String txid;
final List<TxOut> outputs;
final List<TxOut> inputs;
Expand Down
21 changes: 20 additions & 1 deletion lib/src/root.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,26 @@ Future<void> setCurrentDirectory() async {
}
}

typedef Balances = List<(String, int)>;
typedef Balances = List<Balance>;

class BalanceUtils {
static int getBalanceByAssetId(List<Balance> balances, String assetId) {
for (var balance in balances) {
if (balance.assetId == assetId) {
return balance.value;
}
}
return 0; // Return 0 if no balance is found for the asset ID
}

static int getLBtcBalance(List<Balance> balances) {
return getBalanceByAssetId(balances, lBtcAssetId);
}

static int getLTestBalance(List<Balance> balances) {
return getBalanceByAssetId(balances, lTestAssetId);
}
}

class Descriptor {
final String _descriptor;
Expand Down
19 changes: 18 additions & 1 deletion rust/src/bridge_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use std::sync::Arc;
use crate::error::LwkError;
use crate::network::Network;
use crate::types::Address;
use crate::types::Balance;
use crate::types::OutPoint;
use crate::types::PsetAmounts;
use crate::types::Tx;
Expand Down Expand Up @@ -141,7 +142,7 @@ fn wire_balance__static_method__Api_impl(
port_: MessagePort,
wallet_id: impl Wire2Api<String> + UnwindSafe,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, Vec<(String, i64)>, _>(
FLUTTER_RUST_BRIDGE_HANDLER.wrap::<_, _, _, Vec<Balance>, _>(
WrapInfo {
debug_name: "balance__static_method__Api",
port: Some(port_),
Expand Down Expand Up @@ -328,6 +329,22 @@ impl rust2dart::IntoIntoDart<Address> for Address {
}
}

impl support::IntoDart for Balance {
fn into_dart(self) -> support::DartAbi {
vec![
self.asset_id.into_into_dart().into_dart(),
self.value.into_into_dart().into_dart(),
]
.into_dart()
}
}
impl support::IntoDartExceptPrimitive for Balance {}
impl rust2dart::IntoIntoDart<Balance> for Balance {
fn into_into_dart(self) -> Self {
self
}
}

impl support::IntoDart for LwkError {
fn into_dart(self) -> support::DartAbi {
vec![self.msg.into_into_dart().into_dart()].into_dart()
Expand Down
Loading

0 comments on commit 7ca84fa

Please sign in to comment.