Skip to content

Commit

Permalink
refactor: ensure stable reference of wallets from aggregator
Browse files Browse the repository at this point in the history
  • Loading branch information
tien committed Jun 19, 2024
1 parent 0a0ec9b commit c85358d
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
2 changes: 0 additions & 2 deletions packages/core/src/wallets/aggregator/aggregator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,4 @@ export default abstract class WalletAggregator {
abstract readonly scan: () => Wallet[] | Promise<Wallet[]>;

abstract readonly wallets$: Observable<Wallet[]>;

abstract readonly getWallets: () => Wallet[] | Promise<Wallet[]>;
}
26 changes: 18 additions & 8 deletions packages/core/src/wallets/aggregator/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import InjectedWallet from "../injected.js";
import WalletAggregator from "./aggregator.js";
import { getInjectedExtensions } from "polkadot-api/pjs-signer";
import { BehaviorSubject } from "rxjs";
import { map } from "rxjs/operators";

export default class InjectedAggregator extends WalletAggregator {
#storage: KeyedStorage | undefined;
Expand All @@ -12,24 +13,33 @@ export default class InjectedAggregator extends WalletAggregator {
this.#storage = options?.storage;
}

readonly wallets$ = new BehaviorSubject<InjectedWallet[]>([]);
readonly #walletMap$ = new BehaviorSubject(new Map<string, InjectedWallet>());

override readonly getWallets = () => this.wallets$.getValue();
readonly wallets$ = this.#walletMap$.pipe(
map((walletMap) => Array.from(walletMap.values())),
);

override readonly scan = () => {
const wallets =
getInjectedExtensions()?.map(
(name) =>
const injectedNames = getInjectedExtensions() ?? [];

const current = new Map(this.#walletMap$.value);

for (const name of injectedNames) {
if (!current.has(name)) {
current.set(
name,
new InjectedWallet(
name,
this.#storage === undefined
? undefined
: { storage: this.#storage },
),
) ?? [];
);
}
}

this.wallets$.next(wallets);
this.#walletMap$.next(current);

return wallets;
return Array.from(current.values());
};
}
2 changes: 1 addition & 1 deletion packages/core/src/wallets/initialize-wallets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const initializeWallets = async (
await Promise.all(
walletsOrAggregators.map((walletOrAggregator) =>
walletOrAggregator instanceof WalletAggregator
? walletOrAggregator.getWallets()
? walletOrAggregator.scan()
: [walletOrAggregator],
),
)
Expand Down

0 comments on commit c85358d

Please sign in to comment.