Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update wallet events #1789

Merged
merged 11 commits into from
Jan 10, 2024
11 changes: 5 additions & 6 deletions bindings/nodejs/examples/exchange/4-listen-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
// Run with command:
// yarn run-example ./exchange/4-listen-events.ts

import { Wallet, Event, WalletEventType } from '@iota/sdk';
import { Wallet, WalletEvent, WalletEventType } from '@iota/sdk';

// This example uses secrets in environment variables for simplicity which should not be done in production.
require('dotenv').config({ path: '.env' });

async function run() {
try {
for (const envVar of ['WALLET_DB_PATH']) {
for (const envVar of ['WALLET_DB_PATH', 'FAUCET_URL']) {
if (!(envVar in process.env)) {
throw new Error(
`.env ${envVar} is undefined, see .env.example`,
Expand All @@ -24,9 +24,8 @@ async function run() {
storagePath: process.env.WALLET_DB_PATH,
});

const callback = function (err: any, event: Event) {
console.log('AccountIndex:', event.accountIndex);
console.log('Event:', event.event);
const callback = function (err: any, event: WalletEvent) {
console.log('Event:', event);

// Exit after receiving an event.
process.exit(0);
Expand All @@ -37,7 +36,7 @@ async function run() {

// Use the faucet to send testnet tokens to your address.
console.log(
'Fill your address with the faucet: https://faucet.testnet.shimmer.network/',
`Fill your address with the faucet: ${process.env.FAUCET_URL}`,
);

const address = await wallet.address();
Expand Down
6 changes: 2 additions & 4 deletions bindings/nodejs/examples/wallet/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import {
Event,
ConsolidationRequiredWalletEvent,
WalletEvent,
TransactionProgressWalletEvent,
SelectingInputsProgress,
} from '@iota/sdk';
Expand All @@ -24,13 +23,12 @@ async function run() {
// Create the wallet
const wallet = await getUnlockedWallet();

const callback = function (err: any, event: Event) {
const callback = function (err: any, event: WalletEvent) {
console.log('Event:', event);
};

await wallet.listen([], callback);

await wallet.emitTestEvent(new ConsolidationRequiredWalletEvent());
await wallet.emitTestEvent(
new TransactionProgressWalletEvent(new SelectingInputsProgress()),
);
Expand Down
46 changes: 5 additions & 41 deletions bindings/nodejs/lib/types/wallet/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,45 +13,20 @@ import { HexEncodedString } from '../utils';
*/
export type TransactionId = string;

/**
* An wallet account event.
*/
class Event {
/**
* The account index for which the event was emitted.
*/
accountIndex: number;
/**
* The wallet event.
*/
event: WalletEvent;

/**
* @param accountIndex The account index.
* @param event The wallet event.
*/
constructor(accountIndex: number, event: WalletEvent) {
this.accountIndex = accountIndex;
this.event = event;
}
}

/**
* All of the wallet event types.
*/
enum WalletEventType {
/** Consolidation is required. */
ConsolidationRequired = 0,
/** Nano Ledger has generated an address. */
LedgerAddressGeneration = 1,
LedgerAddressGeneration = 0,
/** A new output was created. */
NewOutput = 2,
NewOutput = 1,
/** An output was spent. */
SpentOutput = 3,
SpentOutput = 2,
/** A transaction was included into the ledger. */
TransactionInclusion = 4,
TransactionInclusion = 3,
/** A progress update while submitting a transaction. */
TransactionProgress = 5,
TransactionProgress = 4,
}

/**
Expand All @@ -68,15 +43,6 @@ abstract class WalletEvent {
}
}

/**
* A 'consolidation required' wallet event.
*/
class ConsolidationRequiredWalletEvent extends WalletEvent {
constructor() {
super(WalletEventType.ConsolidationRequired);
}
}

/**
* A 'ledger address generation' wallet event.
*/
Expand Down Expand Up @@ -280,10 +246,8 @@ class BroadcastingProgress extends TransactionProgress {
}

export {
Event,
WalletEventType,
WalletEvent,
ConsolidationRequiredWalletEvent,
LedgerAddressGenerationWalletEvent,
NewOutputWalletEvent,
SpentOutputWalletEvent,
Expand Down
8 changes: 4 additions & 4 deletions bindings/nodejs/lib/wallet/wallet-method-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import {
} from '../bindings';
import {
WalletEventType,
WalletEvent,
WalletOptions,
__WalletMethod__,
Event,
} from '../types/wallet';
import { Client, ClientMethodHandler } from '../client';
import { SecretManager, SecretManagerMethodHandler } from '../secret_manager';
Expand Down Expand Up @@ -74,17 +74,17 @@ export class WalletMethodHandler {
*/
async listen(
eventTypes: WalletEventType[],
callback: (error: Error, event: Event) => void,
callback: (error: Error, event: WalletEvent) => void,
): Promise<void> {
return listenWallet(
this.methodHandler,
eventTypes,
function (err: any, data: string) {
const parsed = JSON.parse(data);
const parsed: WalletEvent = JSON.parse(data);
callback(
// Send back raw error instead of parsing
err,
new Event(parsed.accountIndex, parsed.event),
parsed,
);
},
).catch((error: any) => {
Expand Down
3 changes: 1 addition & 2 deletions bindings/nodejs/lib/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ import type {
WalletOptions,
WalletEventType,
WalletEvent,
Event,
} from '../types/wallet';
import { IAuth, IClientOptions, LedgerNanoStatus } from '../types/client';
import { SecretManager } from '../secret_manager';
Expand Down Expand Up @@ -169,7 +168,7 @@ export class Wallet {
*/
async listen(
eventTypes: WalletEventType[],
callback: (error: Error, event: Event) => void,
callback: (error: Error, event: WalletEvent) => void,
): Promise<void> {
return this.methodHandler.listen(eventTypes, callback);
}
Expand Down
3 changes: 1 addition & 2 deletions bindings/python/examples/exchange/4_listen_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@
def callback(event):
"""Callback function for the event listener"""
event_dict = json.loads(event)
print('AccountIndex:', event_dict["accountIndex"])
print('Event:', event_dict["event"])
print('Event:', event)
DaughterOfMars marked this conversation as resolved.
Show resolved Hide resolved

# Exit after receiving an event.
# pylint: disable=global-statement
Expand Down
22 changes: 10 additions & 12 deletions bindings/python/iota_sdk/types/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,14 @@ class WalletEventType(IntEnum):
"""Types of wallet events.

Attributes:
ConsolidationRequired (0): Consolidation is required.
LedgerAddressGeneration (1): Nano Ledger has generated an address.
NewOutput (2): A new output was created.
SpentOutput (3): An output was spent.
TransactionInclusion (4): A transaction was included into the ledger.
TransactionProgress (5): A progress update while submitting a transaction.
LedgerAddressGeneration (0): Nano Ledger has generated an address.
NewOutput (1): A new output was created.
SpentOutput (2): An output was spent.
TransactionInclusion (3): A transaction was included into the ledger.
Thoralf-M marked this conversation as resolved.
Show resolved Hide resolved
TransactionProgress (4): A progress update while submitting a transaction.
"""
ConsolidationRequired = 0
LedgerAddressGeneration = 1
NewOutput = 2
SpentOutput = 3
TransactionInclusion = 4
TransactionProgress = 5
LedgerAddressGeneration = 0
NewOutput = 1
SpentOutput = 2
TransactionInclusion = 3
TransactionProgress = 4
3 changes: 0 additions & 3 deletions sdk/src/client/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ pub enum Error {
/// Block types error
#[error("{0}")]
Block(#[from] crate::types::block::Error),
/// The wallet has enough funds, but split on too many outputs
#[error("the wallet has enough funds, but split on too many outputs: {0}, max. is 128, consolidate them")]
ConsolidationRequired(usize),
/// Crypto.rs error
#[error("{0}")]
Crypto(#[from] crypto::Error),
Expand Down
5 changes: 1 addition & 4 deletions sdk/src/wallet/core/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,6 @@ where
#[cfg(feature = "storage")]
self.save(&storage_manager).await?;

#[cfg(feature = "events")]
let event_emitter = tokio::sync::RwLock::new(EventEmitter::new());

// It happened that inputs got locked, the transaction failed, but they weren't unlocked again, so we do this
// here
#[cfg(feature = "storage")]
Expand All @@ -253,7 +250,7 @@ where
client,
secret_manager: self.secret_manager.expect("make WalletInner::secret_manager optional?"),
#[cfg(feature = "events")]
event_emitter,
event_emitter: tokio::sync::RwLock::new(EventEmitter::new()),
#[cfg(feature = "storage")]
storage_options,
#[cfg(feature = "storage")]
Expand Down
55 changes: 24 additions & 31 deletions sdk/src/wallet/core/operations/address_generation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,41 +36,34 @@ impl Wallet {
// needs to have it visible on the computer first, so we need to generate it without the
// prompt first
let options = options.into();
#[cfg(feature = "events")]
DaughterOfMars marked this conversation as resolved.
Show resolved Hide resolved
if options.as_ref().map_or(false, |o| o.ledger_nano_prompt) {
#[cfg(feature = "events")]
{
let changed_options = options.map(|mut options| {
// Change options so ledger will not show the prompt the first time
options.ledger_nano_prompt = false;
options
});
// Generate without prompt to be able to display it
let address = ledger_nano
.generate_ed25519_addresses(
coin_type,
account_index,
address_index..address_index + 1,
changed_options,
)
.await?;
let changed_options = options.map(|mut options| {
// Change options so ledger will not show the prompt the first time
options.ledger_nano_prompt = false;
options
});
// Generate without prompt to be able to display it
let address = ledger_nano
.generate_ed25519_addresses(
coin_type,
account_index,
address_index..address_index + 1,
changed_options,
)
.await?;

let bech32_hrp = self.bech32_hrp().await;
let bech32_hrp = self.bech32_hrp().await;

self.emit(WalletEvent::LedgerAddressGeneration(AddressData {
address: address[0].to_bech32(bech32_hrp),
}))
.await;
}

// Generate with prompt so the user can verify
ledger_nano
.generate_ed25519_addresses(coin_type, account_index, address_index..address_index + 1, options)
.await?
} else {
ledger_nano
.generate_ed25519_addresses(coin_type, account_index, address_index..address_index + 1, options)
.await?
self.emit(WalletEvent::LedgerAddressGeneration(AddressData {
address: address[0].to_bech32(bech32_hrp),
}))
.await;
}
// Generate with prompt so the user can verify
ledger_nano
.generate_ed25519_addresses(coin_type, account_index, address_index..address_index + 1, options)
.await?
}
#[cfg(feature = "stronghold")]
SecretManager::Stronghold(stronghold) => {
Expand Down
3 changes: 0 additions & 3 deletions sdk/src/wallet/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ pub enum Error {
new_bip_path: Option<Bip44>,
old_bip_path: Option<Bip44>,
},
/// Funds are spread over too many outputs
#[error("funds are spread over too many outputs {output_count}/{output_count_max}, consolidation required")]
ConsolidationRequired { output_count: usize, output_count_max: u16 },
/// Crypto.rs error
#[error("{0}")]
Crypto(#[from] crypto::Error),
Expand Down
Loading
Loading