Skip to content

Commit

Permalink
fix: refactor address watchers
Browse files Browse the repository at this point in the history
  • Loading branch information
JackHamer09 committed Apr 27, 2023
1 parent daa7c96 commit aecdbb6
Show file tree
Hide file tree
Showing 12 changed files with 100 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<template v-for="(item, index) in computedTransactions" :key="index">
<CommonCardWithLineButtons>
<AddressCardParsed
:address="walletAddress!"
:address="account.address!"
:destination="destinations.zkSyncLite"
:tooltip="`${getActionName(item.type)} from ${destinations.zkSyncLite.label} (L2)`"
/>
Expand Down Expand Up @@ -142,6 +142,7 @@ import type { PropType } from "vue";
import type { IncomingTxFeeType } from "zksync/build/types";
import { useDestinationsStore } from "@/store/destinations";
import { useOnboardStore } from "@/store/onboard";
import { usePreferencesStore } from "@/store/preferences";
import { useLiteAccountActivationStore } from "@/store/zksync/lite/accountActivation";
import { useLiteTransactionsHistoryStore } from "@/store/zksync/lite/transactionsHistory";
Expand Down Expand Up @@ -186,7 +187,7 @@ const props = defineProps({
const liteTransactionsHistoryStore = useLiteTransactionsHistoryStore();
const liteAccountActivationStore = useLiteAccountActivationStore();
const walletLiteStore = useLiteWalletStore();
const { walletAddress } = storeToRefs(walletLiteStore);
const { account } = storeToRefs(useOnboardStore());
const { destinations } = storeToRefs(useDestinationsStore());
const { previousTransactionAddress } = storeToRefs(usePreferencesStore());
const { status, error, transactionHashes, commitTransaction } = useTransaction(() =>
Expand Down
18 changes: 9 additions & 9 deletions composables/useObservable.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
type CallbackFunction = () => void;
class Observable {
private subscribers: CallbackFunction[] = [];
type CallbackFunction<T> = (param: T) => void;
class Observable<T> {
private subscribers: CallbackFunction<T>[] = [];

public subscribe(callback: CallbackFunction) {
public subscribe(callback: CallbackFunction<T>) {
this.subscribers.push(callback);
const unsubscribe = () => {
this.unsubscribe(callback);
};
return unsubscribe;
}

public unsubscribe(callback: CallbackFunction) {
public unsubscribe(callback: CallbackFunction<T>) {
const index = this.subscribers.indexOf(callback);
if (index !== -1) {
this.subscribers.splice(index, 1);
}
}

public notify() {
public notify(param: T) {
this.subscribers.forEach((callback) => {
callback();
callback(param);
});
}
}

export default () => {
const observable = new Observable();
export default <T>() => {
const observable = new Observable<T>();

return {
subscribe: observable.subscribe.bind(observable),
Expand Down
13 changes: 13 additions & 0 deletions pages/balances.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@
</template>

<script lang="ts" setup>
import { onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { useOnboardStore } from "@/store/onboard";
import { useLiteWalletStore } from "@/store/zksync/lite/wallet";
import { groupBalancesByAmount } from "@/utils/mappers";
const onboardStore = useOnboardStore();
const walletLiteStore = useLiteWalletStore();
const { balance, balanceInProgress, balanceError, allBalancePricesLoaded } = storeToRefs(walletLiteStore);
Expand All @@ -40,6 +44,15 @@ const fetch = () => {
walletLiteStore.requestBalance();
};
fetch();
const unsubscribe = onboardStore.subscribeOnAccountChange((newAddress) => {
if (!newAddress) return;
fetch();
});
onBeforeUnmount(() => {
unsubscribe();
});
</script>

<style lang="scss" scoped></style>
13 changes: 12 additions & 1 deletion pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,18 @@
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { computed, onBeforeUnmount } from "vue";
import { PaperAirplaneIcon, PlusIcon } from "@heroicons/vue/24/outline";
import { storeToRefs } from "pinia";
import { useDestinationsStore } from "@/store/destinations";
import { useOnboardStore } from "@/store/onboard";
import { useLiteWalletStore } from "@/store/zksync/lite/wallet";
import { parseTokenAmount, removeSmallAmount } from "@/utils/formatters";
import { isOnlyZeroes } from "@/utils/helpers";
const onboardStore = useOnboardStore();
const walletLiteStore = useLiteWalletStore();
const { balance, balanceInProgress, balanceError, allBalancePricesLoaded } = storeToRefs(walletLiteStore);
const { destinations } = storeToRefs(useDestinationsStore());
Expand Down Expand Up @@ -107,6 +109,15 @@ const displayedBalances = computed(() => {
return false;
});
});
const unsubscribe = onboardStore.subscribeOnAccountChange((newAddress) => {
if (!newAddress) return;
fetch();
});
onBeforeUnmount(() => {
unsubscribe();
});
</script>

<style lang="scss" scoped>
Expand Down
5 changes: 4 additions & 1 deletion pages/payments/all.vue
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,11 @@ import { storeToRefs } from "pinia";
import TransactionsGroupedByBatch from "@/components/transaction/zksync/lite/TransactionsGroupedByBatch.vue";
import { useDestinationsStore } from "@/store/destinations";
import { useOnboardStore } from "@/store/onboard";
import { useLiteTransactionsHistoryStore } from "@/store/zksync/lite/transactionsHistory";
import { groupTransactionsByDate } from "@/utils/mappers";
const onboardStore = useOnboardStore();
const liteTransactionsHistoryStore = useLiteTransactionsHistoryStore();
const {
transactions,
Expand All @@ -82,7 +84,8 @@ const fetch = () => {
};
fetch();
const unsubscribe = liteTransactionsHistoryStore.subscribeOnAccountChange(() => {
const unsubscribe = onboardStore.subscribeOnAccountChange((newAddress) => {
if (!newAddress) return;
fetch();
});
Expand Down
5 changes: 4 additions & 1 deletion pages/payments/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ import { storeToRefs } from "pinia";
import ZkSyncLiteTransactionLineItem from "@/components/transaction/zksync/lite/ZkSyncLiteTransactionLineItem.vue";
import { useDestinationsStore } from "@/store/destinations";
import { useOnboardStore } from "@/store/onboard";
import { useLiteTransactionsHistoryStore } from "@/store/zksync/lite/transactionsHistory";
const onboardStore = useOnboardStore();
const liteTransactionsHistoryStore = useLiteTransactionsHistoryStore();
const { transactions, recentTransactionsRequestInProgress, recentTransactionsRequestError } =
storeToRefs(liteTransactionsHistoryStore);
Expand All @@ -71,7 +73,8 @@ const fetch = () => {
};
fetch();
const unsubscribe = liteTransactionsHistoryStore.subscribeOnAccountChange(() => {
const unsubscribe = onboardStore.subscribeOnAccountChange((newAddress) => {
if (!newAddress) return;
fetch();
});
Expand Down
5 changes: 4 additions & 1 deletion store/ens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ export const useEnsStore = defineStore("ens", () => {
};

fetchName();
watch(() => account.value.address, fetchName);

onboardStore.subscribeOnAccountChange(() => {
fetchName();
});

return {
name: computed(() => ensName.value),
Expand Down
12 changes: 12 additions & 0 deletions store/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { EthereumClient, modalConnectors, walletConnectProvider } from "@web3mod
import { Web3Modal } from "@web3modal/html";
import { defineStore, storeToRefs } from "pinia";

import useObservable from "@/composables/useObservable";

import { useRuntimeConfig } from "#imports";
import { chains, useNetworkStore } from "@/store/network";
import { formatError } from "@/utils/formatters";
Expand Down Expand Up @@ -91,6 +93,14 @@ export const useOnboardStore = defineStore("onboard", () => {
await switchNetwork().catch(() => undefined);
};

const { subscribe: subscribeOnAccountChange, notify: notifyOnAccountChange } = useObservable<string | undefined>();
watch(
() => account.value.address,
() => {
notifyOnAccountChange(account.value.address);
}
);

return {
account: computed(() => account.value),
network: computed(() => network.value),
Expand All @@ -104,5 +114,7 @@ export const useOnboardStore = defineStore("onboard", () => {
setCorrectNetwork,

getEthereumProvider: () => provider({ chainId: selectedEthereumNetwork.value.id }),

subscribeOnAccountChange,
};
});
25 changes: 13 additions & 12 deletions store/zksync/lite/accountActivation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getChangePubkeyLegacyMessage, MAX_TIMESTAMP } from "zksync/build/utils"

import type { PubKeyHash } from "zksync/build/types";

import { useOnboardStore } from "@/store/onboard";
import { useLiteWalletStore } from "@/store/zksync/lite/wallet";
import { formatError } from "@/utils/formatters";

Expand All @@ -21,8 +22,10 @@ type AccountActivationTx = {
};

export const useLiteAccountActivationStore = defineStore("liteAccountActivation", () => {
const onboardStore = useOnboardStore();
const liteWalletStore = useLiteWalletStore();
const { walletAddress, isAuthorized, isRemoteWallet, accountState } = storeToRefs(liteWalletStore);
const { account } = storeToRefs(onboardStore);
const { isAuthorized, isRemoteWallet, accountState } = storeToRefs(liteWalletStore);
const storageAccountActivations = useStorage<{ [userAddress: string]: AccountActivationTx }>(
"account-activations",
{}
Expand All @@ -33,6 +36,7 @@ export const useLiteAccountActivationStore = defineStore("liteAccountActivation"
inProgress: accountActivationCheckInProgress,
execute: checkAccountActivation,
reset: resetAccountActivation,
reload: reloadAccountActivation,
} = usePromise<boolean>(async () => {
const wallet = await liteWalletStore.getWalletInstance();
if (!wallet) throw new Error("Wallet is not available");
Expand All @@ -58,7 +62,8 @@ export const useLiteAccountActivationStore = defineStore("liteAccountActivation"
});

const isAccountActivationSigned = computed(() => {
const signedActivation = storageAccountActivations.value[walletAddress.value!];
if (!account.value.address) return false;
const signedActivation = storageAccountActivations.value[account.value.address];
if (signedActivation && !accountState.value) {
return true;
} else if (signedActivation && accountState.value) {
Expand Down Expand Up @@ -109,7 +114,7 @@ export const useLiteAccountActivationStore = defineStore("liteAccountActivation"
accountState.id!
);
const ethSignature = (await wallet.ethMessageSigner().getEthMessageSignature(changePubKeyMessage)).signature;
storageAccountActivations.value[walletAddress.value!] = {
storageAccountActivations.value[account.value.address!] = {
accountId: accountState.id!,
account: wallet.address(),
newPkHash: newPubKeyHash,
Expand All @@ -126,25 +131,21 @@ export const useLiteAccountActivationStore = defineStore("liteAccountActivation"
const wallet = await liteWalletStore.getWalletInstance(true);
if (!wallet) throw new Error("Wallet is not available");

const signedActivation = storageAccountActivations.value[walletAddress.value!];
const signedActivation = storageAccountActivations.value[account.value.address!];
return await wallet.signer!.signSyncChangePubKey({
...signedActivation,
fee: "0",
feeTokenId,
});
};

watch(walletAddress, (address, oldAddress) => {
if (address) {
if (oldAddress) {
checkAccountActivation({ force: true });
} else {
checkAccountActivation();
}
onboardStore.subscribeOnAccountChange((newAddress) => {
resetAccountActivationSign();
if (newAddress) {
reloadAccountActivation();
} else {
resetAccountActivation();
}
resetAccountActivationSign();
});

return {
Expand Down
16 changes: 3 additions & 13 deletions store/zksync/lite/transactionsHistory.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { defineStore, storeToRefs } from "pinia";

import useObservable from "@/composables/useObservable";

import type { ZkSyncLiteTransaction } from "@/utils/zksync/lite/mappers";
import type { PaginationQuery } from "zksync/build/types";

Expand All @@ -11,10 +9,11 @@ import { useLiteTokensStore } from "@/store/zksync/lite/tokens";
import { mapApiTransaction } from "@/utils/zksync/lite/mappers";

export const useLiteTransactionsHistoryStore = defineStore("liteTransactionsHistory", () => {
const onboardStore = useOnboardStore();
const liteProviderStore = useLiteProviderStore();
const liteTokensStore = useLiteTokensStore();
const { tokens } = storeToRefs(liteTokensStore);
const { account } = storeToRefs(useOnboardStore());
const { account } = storeToRefs(onboardStore);

const transactionsRequest = async (pagination: PaginationQuery<string>): Promise<ZkSyncLiteTransaction[]> => {
const provider = await liteProviderStore.requestProvider();
Expand Down Expand Up @@ -113,18 +112,11 @@ export const useLiteTransactionsHistoryStore = defineStore("liteTransactionsHist
{ cache: false }
);

const { subscribe: subscribeOnAccountChange, notify: notifyOnAccountChange } = useObservable();
subscribeOnAccountChange(() => {
onboardStore.subscribeOnAccountChange(() => {
transactions.value = [];
resetRecentTransactionsRequest();
resetPreviousTransactionsRequest();
});
watch(
() => account.value.address,
() => {
notifyOnAccountChange();
}
);

return {
transactions: computed<ZkSyncLiteTransaction[]>(() =>
Expand All @@ -150,7 +142,5 @@ export const useLiteTransactionsHistoryStore = defineStore("liteTransactionsHist
previousTransactionsRequestInProgress,
previousTransactionsRequestError,
requestPreviousTransactions,

subscribeOnAccountChange,
};
});
Loading

0 comments on commit aecdbb6

Please sign in to comment.