Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Nostr Wallet Connect

Nostr Wallet Connect allows you to control your Breez SDK instance from any Nostr application which complies with the NIP47 standard.

Enabling/Disabling

To enable the Nostr Wallet Connect service, you can initialize it as a plugin after connecting to the SDK.

The config takes three optional parameters:

  • Relay URLs: Custom list of relays for the NWC node to connect to
  • Secret key: Custom Nostr secret key (hex-encoded) to start the node with
  • Listen to events: Whether or not to actively listen and reply to events (defaults to true). Can be set to false when only event broadcasting is required (e.g. zap replies).
Rust
use breez_sdk_liquid::plugin::Plugin;
use breez_sdk_liquid_nwc::{model::NwcConfig, SdkNwcService};

let nwc_config = NwcConfig {
    relay_urls: None,
    secret_key_hex: None,
    listen_to_events: None,
};
let nwc_service = Arc::new(SdkNwcService::new(nwc_config));
sdk.start_plugin(nwc_service.clone()).await?;

// ...

// Automatically stops the plugin
sdk.disconnect().await?;
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwc_service.on_stop().await;
Swift
let nwcConfig = NwcConfig(
    relayUrls: nil,
    secretKeyHex: nil,
    listenToEvents: nil
)
let nwcService = try? sdk.useNwcPlugin(config: nwcConfig)

// ...

// Automatically stops the plugin
try? sdk.disconnect()
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwcService?.stop()
Kotlin
val nwcConfig = NwcConfig(relayUrls = null, secretKeyHex = null, listenToEvents = null)
val nwcService =
        try {
            sdk.useNwcPlugin(config = nwcConfig)
        } catch (e: Exception) {
            // handle error
            return
        }

// ...

// Automatically stops the plugin
try {
    sdk.disconnect()
} catch (e: Exception) {}
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwcService.stop()
Javascript
const nwcConfig: NwcConfig = {
  relayUrls: undefined,
  secretKeyHex: undefined,
  listenToEvents: undefined
}
const nwcService = await sdk.useNwcPlugin(nwcConfig)

// ...

// Automatically stops the plugin
await sdk.disconnect()
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
await nwcService.stop()
React Native
const nwcConfig: NwcConfig = {
  relayUrls: undefined,
  secretKeyHex: undefined,
  listenToEvents: undefined
}
const nwcService = sdk.useNwcPlugin(nwcConfig)

// ...

// Automatically stops the plugin
sdk.disconnect()
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwcService.stop()
Dart
NwcConfig nwcConfig = NwcConfig(
  relayUrls: null,
  secretKeyHex: null,
  listenToEvents: null,
);
BreezNwcService nwcService = await breezSDKLiquid.instance!.useNwcPlugin(config: nwcConfig);

// ...

// Automatically stops the plugin
await breezSDKLiquid.instance!.disconnect();
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
await nwcService.onStop();
Python
nwc_config = NwcConfig(
    relay_urls=None,
    secret_key_hex=None,
    listen_to_events=None,
)
nwc_service = sdk.use_nwc_plugin(nwc_config)

# ...

# Automatically stops the plugin
sdk.disconnect()
# Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwc_service.stop()
Go
nwcConfig := breez_sdk_liquid.NwcConfig{
    RelayUrls:      nil,
    SecretKeyHex:   nil,
    ListenToEvents: nil,
}
nwcService, err := sdk.UseNwcPlugin(nwcConfig)
if err != nil {
    return nil, err
}

// ...

// Automatically stops the plugin
sdk.Disconnect()
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwcService.Stop()
C#
var nwcConfig = new NwcConfig(
    relayUrls: null,
    secretKeyHex: null,
    listenToEvents: null
);
BindingNwcService nwcService;
try
{
    nwcService = sdk.UseNwcPlugin(nwcConfig);
}
catch (Exception)
{
    // Handle error
    return null!;
}

// ...

// Automatically stops the plugin
try { sdk.Disconnect(); } catch { }
// Alternatively, you can stop the plugin manually, without disconnecting the SDK
nwcService.Stop();

Getting service information

You can retrieve information about the NWC service (wallet pubkey, relays, etc.) as follows:

Rust
let info = nwc_service.get_info().await;
Swift
let info = try? nwcService.getInfo()
Kotlin
val info = nwcService.getInfo()
Javascript
const info = await nwcService.getInfo()
React Native
const info = nwcService.getInfo()
Dart
NostrServiceInfo? info = await nwcService.getInfo();
Python
info = nwc_service.get_info()
Go
info := nwcService.GetInfo()
_ = info
C#
var info = nwcService.GetInfo();

Using event listeners

You can listen to events from the NWC service just like you would with the SDK (see Listening to events).

Rust
use breez_sdk_liquid_nwc::event::{NwcEvent, NwcEventDetails, NwcEventListener};

struct MyListener {}
#[async_trait::async_trait]
impl NwcEventListener for MyListener {
    async fn on_event(&self, event: NwcEvent) {
        match event.details {
            NwcEventDetails::Connected => {
                // ...
            }
            NwcEventDetails::Disconnected => {
                // ...
            }
            NwcEventDetails::ConnectionExpired => {
                // ...
            }
            NwcEventDetails::ConnectionRefreshed => {
                // ...
            }
            NwcEventDetails::PayInvoice {
                success,
                preimage,
                fees_sat,
                error,
            } => {
                // ...
            }
            NwcEventDetails::ZapReceived { invoice } => {
                // ...
            }
            _ => {}
        }
    }
}
let event_listener = Box::new(MyListener {});
let my_listener_id = nwc_service.add_event_listener(event_listener).await;

// If you wish to remove the event_listener later on, you can call:
nwc_service.remove_event_listener(&my_listener_id).await;
// Otherwise, it will be automatically removed on service stop
Swift
class MyListener: NwcEventListener {
    func onEvent(event: NwcEvent) {
        switch event.details {
        case .connected:
            // ...
            break
        case .disconnected:
            // ...
            break
        case .connectionExpired:
            // ...
            break
        case .connectionRefreshed:
            // ...
            break
        case .payInvoice(let success, let preimage, let feesSat, let error):
            // ...
            break
        case .zapReceived(let invoice):
            // ...
            break
        default:
            break
        }
    }
}

let eventListener = MyListener()
if let myListenerId = try? nwcService.addEventListener(listener: eventListener) {
    // If you wish to remove the event_listener later on, you can call:
    try? nwcService.removeEventListener(listenerId: myListenerId)
    // Otherwise, it will be automatically removed on service stop
}
Kotlin
class MyListener : NwcEventListener {
    override fun onEvent(event: NwcEvent) {
        when (val details = event.details) {
            is NwcEventDetails.Connected -> {
                // ...
            }
            is NwcEventDetails.Disconnected -> {
                // ...
            }
            is NwcEventDetails.ConnectionExpired -> {
                // ...
            }
            is NwcEventDetails.ConnectionRefreshed -> {
                // ...
            }
            is NwcEventDetails.PayInvoice -> {
                // details.success, details.preimage, details.feesSat, details.error
                // ...
            }
            is NwcEventDetails.ZapReceived -> {
                // details.invoice
                // ...
            }
            else -> {}
        }
    }
}

val eventListener = MyListener()
try {
    val myListenerId = nwcService.addEventListener(listener = eventListener)
    // If you wish to remove the event_listener later on, you can call:
    nwcService.removeEventListener(listenerId = myListenerId)
    // Otherwise, it will be automatically removed on service stop
} catch (e: Exception) {
    // handle error
}
Javascript
class MyListener {
  onEvent = (event: NwcEvent) => {
    switch (event.details.type) {
      case 'connected':
        // ...
        break
      case 'disconnected':
        // ...
        break
      case 'connectionExpired':
        // ...
        break
      case 'connectionRefreshed':
        // ...
        break
      case 'payInvoice':
        // event.details.success, event.details.preimage, event.details.feesSat, event.details.error
        break
      case 'zapReceived':
        // event.details.invoice
        break
      default:
        break
    }
  }
}

const eventListener = new MyListener()
const myListenerId = await nwcService.addEventListener(eventListener)
// If you wish to remove the event_listener later on, you can call:
await nwcService.removeEventListener(myListenerId)
// Otherwise, it will be automatically removed on service stop
React Native
class MyListener {
  onEvent = (event: NwcEvent) => {
    if (event.details instanceof NwcEventDetails.Connected) {
      // ...
    } else if (event.details instanceof NwcEventDetails.Disconnected) {
      // ...
    } else if (event.details instanceof NwcEventDetails.ConnectionExpired) {
      // ...
    } else if (event.details instanceof NwcEventDetails.ConnectionRefreshed) {
      // ...
    } else if (event.details instanceof NwcEventDetails.PayInvoice) {
      // event.details.inner.success, event.details.inner.preimage, event.details.inner.feesSat, event.details.inner.error
      // ...
    } else if (event.details instanceof NwcEventDetails.ZapReceived) {
      // ...
    }
  }
}

const eventListener = new MyListener()
const myListenerId = nwcService.addEventListener(eventListener)
// If you wish to remove the event_listener later on, you can call:
nwcService.removeEventListener(myListenerId)
// Otherwise, it will be automatically removed on service stop
Dart
final eventStream = nwcService.addEventListener().asBroadcastStream();
eventStream.listen((event) async {
  if (event.details is NwcEventDetails_Connected) {
    // ...
  } else if (event.details is NwcEventDetails_Disconnected) {
    // ...
  } else if (event.details is NwcEventDetails_ConnectionExpired) {
    // ...
  } else if (event.details is NwcEventDetails_ConnectionRefreshed) {
    // ...
  } else if (event.details is NwcEventDetails_PayInvoice) {
    final details = event.details as NwcEventDetails_PayInvoice;
    // details.success, details.preimage, details.feesSat, details.error
    // ...
  } else if (event.details is NwcEventDetails_ZapReceived) {
    final details = event.details as NwcEventDetails_ZapReceived;
    // details.invoice
    // ...
  }
});
Python
class MyListener(NwcEventListener):
    def on_event(self, event: NwcEvent):
        if isinstance(event.details, NwcEventDetails.CONNECTED):
            pass  # ...
        elif isinstance(event.details, NwcEventDetails.DISCONNECTED):
            pass  # ...
        elif isinstance(event.details, NwcEventDetails.CONNECTION_EXPIRED):
            pass  # ...
        elif isinstance(event.details, NwcEventDetails.CONNECTION_REFRESHED):
            pass  # ...
        elif isinstance(event.details, NwcEventDetails.PAY_INVOICE):
            # event.details.success, event.details.preimage, event.details.fees_sat, event.details.error
            pass  # ...
        elif isinstance(event.details, NwcEventDetails.ZAP_RECEIVED):
            # event.details.invoice
            pass  # ...

event_listener = MyListener()
my_listener_id = nwc_service.add_event_listener(event_listener)
# If you wish to remove the event_listener later on, you can call:
nwc_service.remove_event_listener(my_listener_id)
# Otherwise, it will be automatically removed on service stop
Go
type MyNwcListener struct{}

func (MyNwcListener) OnEvent(event breez_sdk_liquid.NwcEvent) {
    switch details := event.Details.(type) {
    case breez_sdk_liquid.NwcEventDetailsConnected:
        // ...
    case breez_sdk_liquid.NwcEventDetailsDisconnected:
        // ...
    case breez_sdk_liquid.NwcEventDetailsConnectionExpired:
        // ...
    case breez_sdk_liquid.NwcEventDetailsConnectionRefreshed:
        // ...
    case breez_sdk_liquid.NwcEventDetailsPayInvoice:
        // details.Success, details.Preimage, details.FeesSat, details.Error
        _ = details
        // ...
    case breez_sdk_liquid.NwcEventDetailsZapReceived:
        // details.Invoice
        _ = details
        // ...
    }
}

func NwcEvents(nwcService *breez_sdk_liquid.BindingNwcService) error {
    eventListener := MyNwcListener{}
    myListenerId := nwcService.AddEventListener(eventListener)

    // If you wish to remove the event_listener later on, you can call:
    nwcService.RemoveEventListener(myListenerId)
    // Otherwise, it will be automatically removed on service stop
C#
public class MyListener : NwcEventListener
{
    public void OnEvent(NwcEvent e)
    {
        switch (e.details)
        {
            case NwcEventDetails.Connected:
                // ...
                break;
            case NwcEventDetails.Disconnected:
                // ...
                break;
            case NwcEventDetails.ConnectionExpired:
                // ...
                break;
            case NwcEventDetails.ConnectionRefreshed:
                // ...
                break;
            case NwcEventDetails.PayInvoice payInvoice:
                // payInvoice.success, payInvoice.preimage, payInvoice.feesSat, payInvoice.error
                // ...
                break;
            case NwcEventDetails.ZapReceived zapReceived:
                // zapReceived.invoice
                // ...
                break;
            default:
                break;
        }
    }
}

public void NwcEvents(BindingNwcService nwcService)
{
    var eventListener = new MyListener();
    try
    {
        var myListenerId = nwcService.AddEventListener(eventListener);
        // If you wish to remove the event_listener later on, you can call:
        nwcService.RemoveEventListener(myListenerId);
        // Otherwise, it will be automatically removed on service stop
    }
    catch (Exception)
    {
        // Handle error
    }

Listing connection payments

You can list payments for each NWC connection as follows:

Rust
nwc_service
    .list_connection_payments("my new connection".to_string())
    .await?;
Swift
let payments = try? nwcService.listConnectionPayments(name: "my new connection")
Kotlin
try {
    nwcService.listConnectionPayments(name = "my new connection")
} catch (e: Exception) {
    // handle error
}
Javascript
const payments = await nwcService.listConnectionPayments('my new connection')
React Native
const payments = nwcService.listConnectionPayments('my new connection')
Dart
await nwcService.listConnectionPayments(name: "my new connection");
Python
try:
    nwc_service.list_connection_payments("my new connection")
except Exception as error:
    logging.error(error)
    raise
Go
if _, err := nwcService.ListConnectionPayments("my new connection"); err != nil {
    return err
}
C#
try
{
    nwcService.ListConnectionPayments("my new connection");
}
catch (Exception)
{
    // Handle error
}

NWC Connections

To communicate with the SDK, the connection string must be shared with the NWC application. These special URIs can be generated by calling the service methods described below:

Adding a connection

When creating a connection, there are various configuration options, specifically:

  • Expiry: Connections can either live indefinitely, or for a set number of minutes. When a connection expires, you won't be able to use it through its associated NWC apps
  • Budget: Connections may have a budget, which means they only allow spending within a certain amount before refusing to pay. This budget can be periodic, thus making it reset after a set amount of time, or fixed, meaning the connection won't be able to send funds after the budget is reached
  • Receive-only: Whether or not a connection should only be used for receiving
Rust
use breez_sdk_liquid_nwc::model::{AddConnectionRequest, PeriodicBudgetRequest};

// This connection will only allow spending at most 10_000 sats/hour
let periodic_budget_req = PeriodicBudgetRequest {
    max_budget_sat: 10000,
    renewal_time_mins: Some(60), // Renews every hour
};
let add_response = nwc_service
    .add_connection(AddConnectionRequest {
        name: "my new connection".to_string(),
        expiry_time_mins: Some(60), // Expires after one hour
        periodic_budget_req: Some(periodic_budget_req),
        receive_only: None, // Defaults to false
    })
    .await?;
println!("{}", add_response.connection.connection_string);
Swift
// This connection will only allow spending at most 10,000 sats/hour
let periodicBudgetReq = PeriodicBudgetRequest(
    maxBudgetSat: 10000,
    renewalTimeMins: 60  // Renews every hour
)
if let addResponse = try? nwcService.addConnection(
    req: AddConnectionRequest(
        name: "my new connection",
        receiveOnly: nil,  // Defaults to false
        expiryTimeMins: 60,  // Expires after one hour
        periodicBudgetReq: periodicBudgetReq
    ))
{
    print(addResponse.connection.connectionString)
}
Kotlin
// This connection will only allow spending at most 10,000 sats/hour
val periodicBudgetReq =
        PeriodicBudgetRequest(
                maxBudgetSat = 10000UL,
                renewalTimeMins = 60U // Renews every hour
        )
try {
    val addResponse =
            nwcService.addConnection(
                    AddConnectionRequest(
                            name = "my new connection",
                            expiryTimeMins = 60U, // Expires after one hour
                            periodicBudgetReq = periodicBudgetReq,
                            receiveOnly = null // Defaults to false
                    )
            )
    println(addResponse.connection.connectionString)
} catch (e: Exception) {
    // handle error
}
Javascript
// This connection will only allow spending at most 10,000 sats/hour
const req: AddConnectionRequest = {
  name: 'my new connection',
  expiryTimeMins: 60, // Expires after one hour
  periodicBudgetReq: {
    maxBudgetSat: 10000,
    renewalTimeMins: 60 // Renews every hour
  },
  receiveOnly: undefined // Defaults to false
}
const addResponse = await nwcService.addConnection(req)
console.log(addResponse.connection.connectionString)
React Native
// This connection will only allow spending at most 10,000 sats/hour
const req: AddConnectionRequest = {
  name: 'my new connection',
  expiryTimeMins: 60, // Expires after one hour
  periodicBudgetReq: {
    maxBudgetSat: BigInt(10000),
    renewalTimeMins: 60 // Renews every hour
  },
  receiveOnly: undefined // Defaults to false
}
const addResponse = nwcService.addConnection(req)
console.log(addResponse.connection.connectionString)
Dart
// This connection will only allow spending at most 10,000 sats/hour
PeriodicBudgetRequest periodicBudgetReq = PeriodicBudgetRequest(
  maxBudgetSat: BigInt.from(10000),
  renewalTimeMins: 60, // Renews every hour
);
final addResponse = await nwcService.addConnection(
  req: AddConnectionRequest(
    name: "my new connection",
    expiryTimeMins: 60, // Expires after one hour
    periodicBudgetReq: periodicBudgetReq,
    receiveOnly: null, // Defaults to false
  ),
);
print(addResponse.connection.connectionString);
Python
# This connection will only allow spending at most 10,000 sats/hour
periodic_budget_req = PeriodicBudgetRequest(
    max_budget_sat=10000,
    renewal_time_mins=60,  # Renews every hour
)
try:
    add_response = nwc_service.add_connection(
        AddConnectionRequest(
            name="my new connection",
            expiry_time_mins=60,  # Expires after one hour
            periodic_budget_req=periodic_budget_req,
            receive_only=None,  # Defaults to False
        )
    )
    logging.debug(add_response.connection.connection_string)
except Exception as error:
    logging.error(error)
    raise
Go
// This connection will only allow spending at most 10,000 sats/hour
renewalTimeMins := uint32(60)
periodicBudgetReq := breez_sdk_liquid.PeriodicBudgetRequest{
    MaxBudgetSat:    10000,
    RenewalTimeMins: &renewalTimeMins, // Renews every hour
}
expiryTimeMins := uint32(60)
req := breez_sdk_liquid.AddConnectionRequest{
    Name:              "my new connection",
    ExpiryTimeMins:    &expiryTimeMins, // Expires after one hour
    PeriodicBudgetReq: &periodicBudgetReq,
    ReceiveOnly:       nil, // Defaults to false
}
addResponse, err := nwcService.AddConnection(req)
if err != nil {
    return err
}
log.Printf("%s", addResponse.Connection.ConnectionString)
C#
// This connection will only allow spending at most 10,000 sats/hour
var periodicBudgetReq = new PeriodicBudgetRequest(
    maxBudgetSat: 10000,
    renewalTimeMins: 60  // Renews every hour
);
try
{
    var addResponse = nwcService.AddConnection(new AddConnectionRequest(
        name: "my new connection",
        expiryTimeMins: 60,  // Expires after one hour
        periodicBudgetReq: periodicBudgetReq,
        receiveOnly: null  // Defaults to false
    ));
    Console.WriteLine(addResponse.connection.connectionString);
}
catch (Exception)
{
    // Handle error
}

Editing a connection

Editing a connection is similar to adding, but with two extra fields:

  • Remove expiry: Removes the expiry when set to true
  • Remove budget: Removes the periodic budget when set to true

Setting any other field will update the corresponding connection's details if a connection with that name exists.

Note: Modifying a connection will reset both its budget and expiry timers

Rust
use breez_sdk_liquid_nwc::model::EditConnectionRequest;

let new_expiry_time = 60 * 24;
let edit_response = nwc_service
    .edit_connection(EditConnectionRequest {
        name: "my new connection".to_string(),
        expiry_time_mins: Some(new_expiry_time), // The connection will now expire after 1 day
        periodic_budget_req: None,
        receive_only: None,
        remove_expiry: None,
        remove_periodic_budget: Some(true), // The periodic budget has been removed
    })
    .await?;
println!("{}", edit_response.connection.connection_string);
Swift
let newExpiryTime: UInt32 = 60 * 24
if let editResponse = try? nwcService.editConnection(
    req: EditConnectionRequest(
        name: "my new connection",
        receiveOnly: nil,
        expiryTimeMins: newExpiryTime,  // The connection will now expire after 1 day
        removeExpiry: nil,
        periodicBudgetReq: nil,
        removePeriodicBudget: true  // The periodic budget has been removed
    ))
{
    print(editResponse.connection.connectionString)
}
Kotlin
val newExpiryTime = 60u * 24u
try {
    val editResponse =
            nwcService.editConnection(
                    EditConnectionRequest(
                            name = "my new connection",
                            expiryTimeMins =
                                    newExpiryTime, // The connection will now expire after 1
                            // day
                            periodicBudgetReq = null,
                            receiveOnly = null,
                            removeExpiry = null,
                            removePeriodicBudget =
                                    true // The periodic budget has been removed
                    )
            )
    println(editResponse.connection.connectionString)
} catch (e: Exception) {
    // handle error
}
Javascript
const newExpiryTime = 60 * 24
const req: EditConnectionRequest = {
  name: 'my new connection',
  expiryTimeMins: newExpiryTime, // The connection will now expire after 1 day
  periodicBudgetReq: undefined,
  receiveOnly: undefined,
  removeExpiry: undefined,
  removePeriodicBudget: true // The periodic budget has been removed
}
const editResponse = await nwcService.editConnection(req)
console.log(editResponse.connection.connectionString)
React Native
const newExpiryTime = 60 * 24
const req: EditConnectionRequest = {
  name: 'my new connection',
  expiryTimeMins: newExpiryTime, // The connection will now expire after 1 day
  periodicBudgetReq: undefined,
  receiveOnly: undefined,
  removeExpiry: undefined,
  removePeriodicBudget: true // The periodic budget has been removed
}
const editResponse = nwcService.editConnection(req)
console.log(editResponse.connection.connectionString)
Dart
int newExpiryTime = 60 * 24;
final editResponse = await nwcService.editConnection(
  req: EditConnectionRequest(
    name: "my new connection",
    expiryTimeMins: newExpiryTime, // The connection will now expire after 1 day
    periodicBudgetReq: null,
    receiveOnly: null,
    removeExpiry: null,
    removePeriodicBudget: true, // The periodic budget has been removed
  ),
);
print(editResponse.connection.connectionString);
Python
new_expiry_time = 60 * 24
try:
    edit_response = nwc_service.edit_connection(
        EditConnectionRequest(
            name="my new connection",
            expiry_time_mins=new_expiry_time,  # The connection will now expire after 1 day
            periodic_budget_req=None,
            receive_only=None,
            remove_expiry=None,
            remove_periodic_budget=True,  # The periodic budget has been removed
        )
    )
    logging.debug(edit_response.connection.connection_string)
except Exception as error:
    logging.error(error)
    raise
Go
newExpiryTime := uint32(60 * 24)
removePeriodicBudget := true
req := breez_sdk_liquid.EditConnectionRequest{
    Name:                 "my new connection",
    ExpiryTimeMins:       &newExpiryTime, // The connection will now expire after 1 day
    PeriodicBudgetReq:    nil,
    ReceiveOnly:          nil,
    RemoveExpiry:         nil,
    RemovePeriodicBudget: &removePeriodicBudget, // The periodic budget has been removed
}
editResponse, err := nwcService.EditConnection(req)
if err != nil {
    return err
}
log.Printf("%s", editResponse.Connection.ConnectionString)
C#
uint newExpiryTime = 60 * 24;
try
{
    var editResponse = nwcService.EditConnection(new EditConnectionRequest(
        name: "my new connection",
        expiryTimeMins: newExpiryTime,  // The connection will now expire after 1 day
        periodicBudgetReq: null,
        receiveOnly: null,
        removeExpiry: null,
        removePeriodicBudget: true  // The periodic budget has been removed
    ));
    Console.WriteLine(editResponse.connection.connectionString);
}
catch (Exception)
{
    // Handle error
}

Listing connections

Rust
let connections = nwc_service.list_connections().await?;
for (connection_name, connection) in connections {
    println!(
        "Connection: {} - Expires at: {:?}, Periodic Budget: {:?}",
        connection_name, connection.expires_at, connection.periodic_budget
    );
    // ...
}
Swift
if let connections = try? nwcService.listConnections() {
    for (connectionName, connection) in connections {
        print(
            "Connection: \(connectionName) - Expires at: \(String(describing: connection.expiresAt)), Periodic Budget: \(String(describing: connection.periodicBudget))"
        )
        // ...
    }
}
Kotlin
try {
    val connections = nwcService.listConnections()
    for ((connectionName, connection) in connections) {
        println(
                "Connection: $connectionName - Expires at: ${connection.expiresAt}, Periodic Budget: ${connection.periodicBudget}"
        )
        // ...
    }
} catch (e: Exception) {
    // handle error
}
Javascript
const connections = await nwcService.listConnections()
for (const [connectionName, connection] of Object.entries(connections)) {
  console.log(
    `Connection: ${connectionName} - Expires at: ${connection.expiresAt}, Periodic Budget: ${JSON.stringify(connection.periodicBudget)}`
  )
  // ...
}
React Native
const connections = nwcService.listConnections()
for (const [connectionName, connection] of Object.entries(connections)) {
  console.log(
    `Connection: ${connectionName} - Expires at: ${connection.expiresAt}, Periodic Budget: ${JSON.stringify(connection.periodicBudget)}`
  )
  // ...
}
Dart
Map<String, NwcConnection> connections = await nwcService.listConnections();
for (var entry in connections.entries) {
  print(
    "Connection: ${entry.key} - Expires at: ${entry.value.expiresAt}, Periodic Budget: ${entry.value.periodicBudget}",
  );
  // ...
}
Python
try:
    connections = nwc_service.list_connections()
    for connection_name, connection in connections.items():
        logging.debug(
            f"Connection: {connection_name} - Expires at: {connection.expires_at}, Periodic Budget: {connection.periodic_budget}"
        )
        # ...
except Exception as error:
    logging.error(error)
    raise
Go
connections, err := nwcService.ListConnections()
if err != nil {
    return err
}
for connectionName, connection := range connections {
    log.Printf(
        "Connection: %s - Expires at: %v, Periodic Budget: %v",
        connectionName, connection.ExpiresAt, connection.PeriodicBudget,
    )
    // ...
}
C#
try
{
    var connections = nwcService.ListConnections();
    foreach (var (connectionName, connection) in connections)
    {
        Console.WriteLine(
            $"Connection: {connectionName} - Expires at: {connection.expiresAt}, Periodic Budget: {connection.periodicBudget}"
        );
        // ...
    }
}
catch (Exception)
{
    // Handle error
}

Removing a connection

Note: Removing a connection will make it so you won't be able to use it with the apps which were previously associated with it.

Rust
nwc_service
    .remove_connection("my new connection".to_string())
    .await?;
Swift
try? nwcService.removeConnection(name: "my new connection")
Kotlin
try {
    nwcService.removeConnection(name = "my new connection")
} catch (e: Exception) {
    // handle error
}
Javascript
await nwcService.removeConnection('my new connection')
React Native
nwcService.removeConnection('my new connection')
Dart
await nwcService.removeConnection(name: "my new connection");
Python
try:
    nwc_service.remove_connection("my new connection")
except Exception as error:
    logging.error(error)
    raise
Go
if err := nwcService.RemoveConnection("my new connection"); err != nil {
    return err
}
C#
try
{
    nwcService.RemoveConnection("my new connection");
}
catch (Exception)
{
    // Handle error
}