Refactor wallet storage and subscription handling
- Updated WalletStore to manage localStorage and handle storage events more effectively. - Introduced mockAccountsSubscribe in constants for better account subscription handling. - Removed unnecessary storage subscription from InjectionConfig. - Enhanced Wallet class to utilize new account and metadata management methods.
This commit is contained in:
1 parent
1966988769
commit
38574daace
6 files changed
+78
-44
No files matched your search
+6
-6
@@ -1,7 +1,7 @@
|
||||
import type { InjectedExtension } from "@polkadot/extension-inject/types";
|
||||
|
||||
export const VARAN_WALLET_LS_KEY = 'VARAN_WALLET';
|
||||
|
||||
|
||||
window.addEventListener('storage', (ev) => {
|
||||
if (ev.storageArea !== localStorage || ev.key !== VARAN_WALLET_LS_KEY) return;
|
||||
|
||||
})
|
||||
export const mockAccountsSubscribe: InjectedExtension['accounts']['subscribe'] = () => {
|
||||
console.warn('Accounts subscribe does not currently support in Varan Wallet');
|
||||
return () => {};
|
||||
};
|
||||
@@ -6,7 +6,6 @@ export const parseWalletsFromStartParam = (webApp: WebApp): ConnectResult['walle
|
||||
if (!startParam) return null;
|
||||
|
||||
const result = decodeResult(startParam);
|
||||
console.log('parseWalletsFromStartParam', result);
|
||||
return 'wallets' in result ? result.wallets : null;
|
||||
};
|
||||
|
||||
|
||||
+11
-6
@@ -20,9 +20,14 @@ const defaultStore: WalletStoreType = {
|
||||
}
|
||||
|
||||
export class WalletStore {
|
||||
constructor(
|
||||
private readonly store: WalletStorage,
|
||||
) {
|
||||
private readonly store: WalletStorage;
|
||||
private readonly storeSubscribe: (cb: (ev: StorageEvent) => void) => void;
|
||||
|
||||
constructor() {
|
||||
this.store = window.localStorage as WalletStorage;
|
||||
this.storeSubscribe = (cb): void => {
|
||||
window.addEventListener('storage', cb);
|
||||
};
|
||||
this._setupListeners();
|
||||
}
|
||||
|
||||
@@ -38,12 +43,12 @@ export class WalletStore {
|
||||
};
|
||||
|
||||
private get _store(): WalletStoreType {
|
||||
return JSON.parse(this.store.getItem(VARAN_WALLET_LS_KEY) || '{}') as WalletStoreType;
|
||||
return Object.assign(defaultStore, JSON.parse(this.store.getItem(VARAN_WALLET_LS_KEY) || '{}')) as WalletStoreType;
|
||||
}
|
||||
|
||||
private _setupListeners(): void {
|
||||
let currentState = this._store;
|
||||
this.store.subscribe(ev => {
|
||||
this.storeSubscribe(ev => {
|
||||
ev.stopImmediatePropagation();
|
||||
if (ev.key !== VARAN_WALLET_LS_KEY) return;
|
||||
|
||||
@@ -103,7 +108,7 @@ export class WalletStore {
|
||||
}
|
||||
|
||||
get<Key extends keyof WalletStoreType>(key: Key): WalletStoreType[Key] {
|
||||
return this._store[key];
|
||||
return this._store[key] || defaultStore[key];
|
||||
}
|
||||
|
||||
set<Key extends keyof WalletStoreType>(key: Key, value: WalletStoreType[Key]): void {
|
||||
|
||||
+1
-4
@@ -5,15 +5,12 @@ declare global {
|
||||
interface Window extends InjectedWindow {}
|
||||
}
|
||||
|
||||
export type WalletStorage = Storage & {
|
||||
subscribe: (cb: (ev: StorageEvent) => void) => void;
|
||||
}
|
||||
export type WalletStorage = Storage;
|
||||
|
||||
export type InjectionConfig = {
|
||||
callbackUrl: string;
|
||||
isDev?: boolean;
|
||||
connectTimeout?: number;
|
||||
storage?: WalletStorage;
|
||||
}
|
||||
|
||||
export type WebApp = typeof WebAppConst;
|
||||
|
||||
@@ -5,12 +5,6 @@ const defaultInjectionConfig: Required<InjectionConfig> = {
|
||||
callbackUrl: '',
|
||||
isDev: false,
|
||||
connectTimeout: 30_000,
|
||||
storage: {
|
||||
...localStorage,
|
||||
subscribe: (cb) => {
|
||||
window.addEventListener('storage', cb);
|
||||
},
|
||||
} ,
|
||||
}
|
||||
|
||||
const injectVaranWallet = (webApp: WebApp, config: InjectionConfig = defaultInjectionConfig): void => {
|
||||
|
||||
+60
-21
@@ -1,10 +1,11 @@
|
||||
import type { ConnectRequest, SignTransactionRequest, WebApp } from "./types";
|
||||
import type { InjectionConfig } from "./types";
|
||||
import { WalletStore } from "./store";
|
||||
import type { InjectedAccount, InjectedExtension, InjectedWindowProvider } from "@polkadot/extension-inject/types";
|
||||
import type { Injected, InjectedAccount, InjectedExtension, InjectedMetadataKnown, InjectedWindowProvider } from "@polkadot/extension-inject/types";
|
||||
import { encodeRequest } from "./encryption";
|
||||
import { SignerPayloadRaw, SignerResult } from "@polkadot/types/types";
|
||||
import { generateRequestId, parseSignedTxFromStartParam, parseWalletsFromStartParam } from "./helpers";
|
||||
import { mockAccountsSubscribe } from "./constants";
|
||||
|
||||
export class Wallet implements InjectedWindowProvider {
|
||||
private readonly varanWalletUrl!: string;
|
||||
@@ -15,10 +16,10 @@ export class Wallet implements InjectedWindowProvider {
|
||||
|
||||
constructor(
|
||||
private readonly webApp: WebApp,
|
||||
{ callbackUrl, isDev, connectTimeout, storage }: Required<InjectionConfig>,
|
||||
{ callbackUrl, isDev, connectTimeout }: Required<InjectionConfig>,
|
||||
) {
|
||||
this.varanWalletUrl = isDev ? 'https://t.me/devReptileBot?startapp=' : 'https://t.me/varanwalletbot?startapp=';
|
||||
this.store = new WalletStore(storage);
|
||||
this.store = new WalletStore();
|
||||
this.callbackUrl = callbackUrl;
|
||||
this.connectTimeout = connectTimeout;
|
||||
void this._startParamsCheck();
|
||||
@@ -28,6 +29,12 @@ export class Wallet implements InjectedWindowProvider {
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
private get signer(): InjectedExtension['signer'] {
|
||||
return {
|
||||
signRaw: (raw) => this.signRawTransaction(raw),
|
||||
};
|
||||
}
|
||||
|
||||
private async _startParamsCheck(): Promise<void> {
|
||||
let actions = 0;
|
||||
const newWalletAddresses = parseWalletsFromStartParam(this.webApp);
|
||||
@@ -66,7 +73,7 @@ export class Wallet implements InjectedWindowProvider {
|
||||
|
||||
|
||||
if (actions) {
|
||||
this.webApp.close();
|
||||
// this.webApp.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +89,29 @@ export class Wallet implements InjectedWindowProvider {
|
||||
return Promise.resolve(accounts.map(this.formatAccount));
|
||||
}
|
||||
|
||||
private get extensionAccounts(): InjectedExtension['accounts'] {
|
||||
return {
|
||||
get: () => this.accounts,
|
||||
subscribe: mockAccountsSubscribe
|
||||
};
|
||||
}
|
||||
|
||||
private get extensionMetadata(): InjectedExtension['metadata'] {
|
||||
const metadata = this.store.get('injectedMetadataKnown');
|
||||
const setMetadata = async (metadata: InjectedMetadataKnown) => {
|
||||
await this.store.set('injectedMetadataKnown', metadata);
|
||||
return true;
|
||||
};
|
||||
if (!metadata) return {
|
||||
get: () => Promise.resolve([]),
|
||||
provide: setMetadata,
|
||||
};
|
||||
return {
|
||||
get: () => Promise.resolve([metadata]),
|
||||
provide: setMetadata,
|
||||
};
|
||||
}
|
||||
|
||||
private async signRawTransaction(raw: SignerPayloadRaw): Promise<SignerResult> {
|
||||
const accounts = await this.accounts;
|
||||
if (!accounts.length) throw new Error('No accounts found');
|
||||
@@ -143,27 +173,36 @@ export class Wallet implements InjectedWindowProvider {
|
||||
}
|
||||
|
||||
async connect(): Promise<InjectedExtension> {
|
||||
await Promise.race([
|
||||
this._connect(),
|
||||
new Promise<void>((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new Error('Connect timeout'));
|
||||
}, this.connectTimeout);
|
||||
})
|
||||
]);
|
||||
const accounts = await this.accounts;
|
||||
if (!accounts.length) {
|
||||
await Promise.race([
|
||||
this._connect(),
|
||||
new Promise<void>((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new Error('Connect timeout'));
|
||||
}, this.connectTimeout);
|
||||
})
|
||||
]);
|
||||
}
|
||||
|
||||
return Promise.resolve({
|
||||
name: this.name,
|
||||
version: this.version,
|
||||
accounts: {
|
||||
get: () => this.accounts,
|
||||
subscribe: () => {
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
signer: {
|
||||
signRaw: (raw) => this.signRawTransaction(raw),
|
||||
},
|
||||
accounts: this.extensionAccounts,
|
||||
signer: this.signer,
|
||||
metadata: this.extensionMetadata,
|
||||
});
|
||||
}
|
||||
|
||||
async enable(): Promise<Injected> {
|
||||
const accounts = await this.accounts;
|
||||
if (!accounts.length) {
|
||||
throw new Error('Please connect first');
|
||||
}
|
||||
return {
|
||||
accounts: this.extensionAccounts,
|
||||
signer: this.signer,
|
||||
metadata: this.extensionMetadata,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user