Skip to content

Commit

Permalink
Merge pull request #276 from IOTA-NET/275-docs-wallet-events-examples
Browse files Browse the repository at this point in the history
275 docs wallet events examples
  • Loading branch information
wireless90 authored Feb 1, 2024
2 parents abb298c + 99edc5c commit 7938a61
Show file tree
Hide file tree
Showing 6 changed files with 171 additions and 3 deletions.
82 changes: 82 additions & 0 deletions IotaSDK.NET.Main/Examples/Events/Subscribe To Events/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Let's subscribe to some Wallet Events!
## Code Example

The following example will:

1. Create a wallet
2. Retrieve your spending account
3. Sync account
4. Subscribe to TransactionInclusion Event
5. Register a callback for the TransactionInclusion Event
6. Enable Background Syncing


```cs
public static class SubscribeToEventsExample
{
public static async Task Run()
{
//Register all of the dependencies into a collection of services
IServiceCollection services = new ServiceCollection().AddIotaSDKServices();

//Install services to service provider which is used for dependency injection
IServiceProvider serviceProvider = services.BuildServiceProvider();

//Use serviceprovider to create a scope, which disposes of all services at end of scope
using (IServiceScope scope = serviceProvider.CreateScope())
{
//Request IWallet service from service provider
IWallet wallet = scope.ServiceProvider.GetRequiredService<IWallet>();

//Build wallet using a fluent-style configuration api
wallet = await wallet
.ConfigureWalletOptions()
.SetCoinType(TypeOfCoin.Shimmer)
.SetStoragePath("./walletdb")
.Then()
.ConfigureClientOptions()
.AddNodeUrl("https://api.testnet.shimmer.network")
.SetFaucetUrl("https://faucet.testnet.shimmer.network/api/enqueue")
.IsLocalPow()
.Then()
.ConfigureSecretManagerOptions()
.SetPassword("password")
.SetSnapshotPath("./mystronghold")
.Then()
.InitializeAsync();


//Let's proceed to retrieve our previously created"spending" account.
IAccount spendingAccount = (await wallet.GetAccountAsync("spending")).Payload;
await spendingAccount.SyncAcountAsync();

/*
* Available events are: ConsolidationRequired | NewOutput | SpentOutput | TransactionInclusion | TransactionProgress | LedgerAddressGeneration
* Let's get automatically notified when our transaction succeeds.
* Hence we need to subscribe to TransactionInclusion event
* */

await wallet.SubscribeToEventsAsync(WalletEventType.TransactionInclusion);

wallet.OnTransactionInclusion += Wallet_OnTransactionInclusion;

//We put our wallet into periodic sync mode,
//If it notices our tx getting confirmed, it would alert us
await wallet.StartBackgroundSyncAsync(intervalInMilliseconds: 5000);

//Lets send a tx to ourselves!
string spendingAddress = (await spendingAccount.GetAddressesAsync()).Payload.First().Address;
await spendingAccount.SendBaseCoinAsync(amount: 1000000, spendingAddress);

//Just to not let program exit
Console.ReadLine();

}
}
private static void Wallet_OnTransactionInclusion(object? sender, WalletEventNotification e)
{
string transactionId = (e.Event as TransactionInclusionWalletEvent)!.TransactionId;
Console.WriteLine($"Tx ID: {transactionId} just got confirmed!");
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using IotaSDK.NET.Common.Extensions;
using IotaSDK.NET.Common.Interfaces;
using IotaSDK.NET.Domain.Events;
using IotaSDK.NET.Domain.Tokens;

using Microsoft.Extensions.DependencyInjection;

namespace IotaSDK.NET.Main.Examples.Native_Tokens.Burn_Native_Tokens
{
public static class SubscribeToEventsExample
{
public static async Task Run()
{
//Register all of the dependencies into a collection of services
IServiceCollection services = new ServiceCollection().AddIotaSDKServices();

//Install services to service provider which is used for dependency injection
IServiceProvider serviceProvider = services.BuildServiceProvider();

//Use serviceprovider to create a scope, which disposes of all services at end of scope
using (IServiceScope scope = serviceProvider.CreateScope())
{
//Request IWallet service from service provider
IWallet wallet = scope.ServiceProvider.GetRequiredService<IWallet>();

//Build wallet using a fluent-style configuration api
wallet = await wallet
.ConfigureWalletOptions()
.SetCoinType(TypeOfCoin.Shimmer)
.SetStoragePath("./walletdb")
.Then()
.ConfigureClientOptions()
.AddNodeUrl("https://api.testnet.shimmer.network")
.SetFaucetUrl("https://faucet.testnet.shimmer.network/api/enqueue")
.IsLocalPow()
.Then()
.ConfigureSecretManagerOptions()
.SetPassword("password")
.SetSnapshotPath("./mystronghold")
.Then()
.InitializeAsync();


//Let's proceed to retrieve our previously created"spending" account.
IAccount spendingAccount = (await wallet.GetAccountAsync("spending")).Payload;
await spendingAccount.SyncAcountAsync();

/*
* Available events are: ConsolidationRequired | NewOutput | SpentOutput | TransactionInclusion | TransactionProgress | LedgerAddressGeneration
* Let's get automatically notified when our transaction succeeds.
* Hence we need to subscribe to TransactionInclusion event
* */

await wallet.SubscribeToEventsAsync(WalletEventType.TransactionInclusion);

wallet.OnTransactionInclusion += Wallet_OnTransactionInclusion;

//We put our wallet into periodic sync mode,
//If it notices our tx getting confirmed, it would alert us
await wallet.StartBackgroundSyncAsync(intervalInMilliseconds: 5000);

//Lets send a tx to ourselves!
string spendingAddress = (await spendingAccount.GetAddressesAsync()).Payload.First().Address;
await spendingAccount.SendBaseCoinAsync(amount: 1000000, spendingAddress);

//Just to not let program exit
Console.ReadLine();

}
}
private static void Wallet_OnTransactionInclusion(object? sender, WalletEventNotification e)
{
string transactionId = (e.Event as TransactionInclusionWalletEvent)!.TransactionId;
Console.WriteLine($"Tx ID: {transactionId} just got confirmed!");
}
}
}
3 changes: 2 additions & 1 deletion IotaSDK.NET.Main/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ static async Task Main(string[] args)
//await SendNativeTokensExample.Run();
//await MeltNativeTokensExample.Run();
//await GetFoundryImmutableMetadataExample.Run();
await BurnNativeTokensExample.Run();
//await BurnNativeTokensExample.Run();
await SubscribeToEventsExample.Run();
}

}
Expand Down
9 changes: 8 additions & 1 deletion IotaSDK.NET/Common/Interfaces/IWallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ public interface IWallet : IDisposable

Task<IotaSDKResponse<string>> GenerateEd25519AddressCommandAsync(int accountIndex, int addressIndex, AddressGenerationOptions? addressGenerationOptions = null, HumanReadablePart? bech32Hrp = null);

Task<IotaSDKResponse<bool>> SubscribeToEventsAsync(WalletEventType walletEventTypes, WalletEventHandler callback);
Task<IotaSDKResponse<bool>> SubscribeToEventsAsync(WalletEventType walletEventTypes);

public event EventHandler<WalletEventNotification> OnConsolidationRequired;
public event EventHandler<WalletEventNotification> OnLedgerAddressGeneration;
public event EventHandler<WalletEventNotification> OnNewOutput;
public event EventHandler<WalletEventNotification> OnSpentOutput;
public event EventHandler<WalletEventNotification> OnTransactionInclusion;
public event EventHandler<WalletEventNotification> OnTransactionProgress;
}
}
2 changes: 1 addition & 1 deletion IotaSDK.NET/Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ public async Task<IotaSDKResponse<string>> GenerateEd25519AddressCommandAsync(in
return await _mediator.Send(new GenerateEd25519AddressCommand(_walletHandle, accountIndex, addressIndex, addressGenerationOptions, bech32Hrp));
}

public async Task<IotaSDKResponse<bool>> SubscribeToEventsAsync(WalletEventType walletEventTypes, WalletEventHandler callback)
public async Task<IotaSDKResponse<bool>> SubscribeToEventsAsync(WalletEventType walletEventTypes)
{
return await _mediator.Send(new SubscribeToEventsCommand(_walletHandle, walletEventTypes, WalletEventCallback));
}
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ To install,
<li>StartBackgroundSync</li>
<li>StopBackgroundSync</li>
<li>StoreMnemonic</li>
<li>SubscribeToEvents</li>
</ul>
</details>

Expand Down

0 comments on commit 7938a61

Please sign in to comment.