Skip to content

Commit

Permalink
feat: centralize button visibility responsibility and delete a lot of…
Browse files Browse the repository at this point in the history
… redundant code
  • Loading branch information
zugdev committed Oct 15, 2024
1 parent 320cd40 commit db22f56
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { createClient } from "@supabase/supabase-js";
import { decodePermits } from "@ubiquibot/permit-generation/handlers";
import { Permit } from "@ubiquibot/permit-generation/types";
import { app, AppState } from "../app-state";
import { toaster } from "../toaster";
import { buttonController, toaster } from "../toaster";
import { connectWallet } from "../web3/connect-wallet";
import { checkRenderInvalidatePermitAdminControl, checkRenderMakeClaimControl } from "../web3/erc20-permit";
import { verifyCurrentNetwork } from "../web3/verify-current-network";
import { claimRewardsPagination } from "./claim-rewards-pagination";
import { renderTransaction } from "./render-transaction";
import { setClaimMessage } from "./set-claim-message";
import { useRpcHandler } from "../web3/use-rpc-handler";
import { switchNetwork } from "../web3/switch-network";
import { ethers } from "ethers";
import { getNetworkName, NetworkId } from "@ubiquity-dao/rpc-handler";

declare const SUPABASE_URL: string;
declare const SUPABASE_ANON_KEY: string;
Expand Down Expand Up @@ -47,30 +49,57 @@ export async function readClaimDataFromUrl(app: AppState) {
/* empty */
}

try {
// this would throw on mobile browsers & non-web3 browsers
window?.ethereum.on("accountsChanged", () => {
checkRenderMakeClaimControl(app).catch(console.error);
checkRenderInvalidatePermitAdminControl(app).catch(console.error);
});
} catch (err) {
/*
* handled feedback upstream already
* buttons are hidden and non-web3 infinite toast exists
*/
}
await updateButtonVisibility(app);

displayRewardDetails();
displayRewardPagination();

await renderTransaction();
if (app.networkId !== null) {
await verifyCurrentNetwork(app.networkId);
} else {
throw new Error("Network ID is null");
}

async function updateButtonVisibility(app: AppState) {
try {
const currentNetworkId = parseInt(await window.ethereum.request({ method: "eth_chainId" }), 16);

if (currentNetworkId !== app.networkId) {
console.warn(`Incorrect network. Expected ${app.networkId}, but got ${currentNetworkId}.`);
buttonController.hideAll(); // Hide all buttons if the network is incorrect
toaster.create("error", `This dApp currently does not support payouts for network ID ${currentNetworkId}`);

// Try switching to the propper network id
switchNetwork(new ethers.providers.Web3Provider(window.ethereum), app.reward.networkId).catch((error) => {
console.error(error);
if (app.networkId !== null) {
toaster.create("error", `Please switch to the ${getNetworkName(String(app.networkId) as NetworkId)} network to claim this reward.`);
}
});

return; // Stop further checks if the network is incorrect
}

await checkRenderMakeClaimControl(app);
await checkRenderInvalidatePermitAdminControl(app);
} catch (error) {
console.error("Error updating button visibility:", error);
buttonController.hideAll(); // Hide all buttons if there's an error
}
}

// Below is a listener that updates buttons on account/network change
if (window.ethereum) {
// Handle account changes
window.ethereum.on("accountsChanged", async () => {
await updateButtonVisibility(app);
});

// Handle network changes
window.ethereum.on("chainChanged", async () => {
await updateButtonVisibility(app);
});
} else {
console.warn("Ethereum provider not detected.");
}

async function getClaimedTxs(app: AppState): Promise<Record<string, string>> {
const txs: Record<string, string> = Object.create(null);
for (const claim of app.claims) {
Expand Down
11 changes: 1 addition & 10 deletions static/scripts/rewards/render-transaction/render-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { ERC20Permit, Permit, TokenType } from "@ubiquibot/permit-generation/typ
import { networkExplorers } from "@ubiquity-dao/rpc-handler";
import { app } from "../app-state";
import { buttonController, getMakeClaimButton, viewClaimButton } from "../toaster";
import { checkRenderInvalidatePermitAdminControl, claimErc20PermitHandlerWrapper, fetchTreasury } from "../web3/erc20-permit";
import { claimErc20PermitHandlerWrapper, fetchTreasury } from "../web3/erc20-permit";
import { claimErc721PermitHandler } from "../web3/erc721-permit";
import { verifyCurrentNetwork } from "../web3/verify-current-network";
import { insertErc20PermitTableData, insertErc721PermitTableData } from "./insert-table-data";
import { renderEnsName } from "./render-ens-name";
import { renderNftSymbol, renderTokenSymbol } from "./render-token-symbol";
Expand All @@ -26,8 +25,6 @@ export async function renderTransaction(): Promise<Success> {
return false;
}

verifyCurrentNetwork(app.reward.networkId).catch(console.error);

if (isErc20Permit(app.reward)) {
const treasury = await fetchTreasury(app.reward);
table.setAttribute(`data-additional-data-size`, "small");
Expand All @@ -47,16 +44,10 @@ export async function renderTransaction(): Promise<Success> {
const toElement = document.getElementById(`rewardRecipient`) as Element;
renderEnsName({ element: toElement, address: app.reward.beneficiary, networkId: app.networkId }).catch(console.error);

if (app.provider) {
checkRenderInvalidatePermitAdminControl(app).catch(console.error);
}

if (app.claimTxs[app.reward.nonce.toString()] !== undefined) {
buttonController.showViewClaim();
viewClaimButton.addEventListener("click", () => window.open(`${app.currentExplorerUrl}/tx/${app.claimTxs[app.reward.nonce.toString()]}`));
} else if (window.ethereum) {
// requires wallet connection to claim
buttonController.showMakeClaim();
getMakeClaimButton().addEventListener("click", claimErc20PermitHandlerWrapper(app));
}

Expand Down
9 changes: 0 additions & 9 deletions static/scripts/rewards/web3/handle-if-on-correct-network.ts

This file was deleted.

18 changes: 0 additions & 18 deletions static/scripts/rewards/web3/not-on-correct-network.ts

This file was deleted.

2 changes: 0 additions & 2 deletions static/scripts/rewards/web3/switch-network.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { ethers } from "ethers";
import { addNetwork } from "./add-network";
import { buttonController } from "../toaster";

export async function switchNetwork(provider: ethers.providers.Web3Provider, networkId: number): Promise<boolean> {
try {
await provider.send("wallet_switchEthereumChain", [{ chainId: "0x" + networkId.toString(16) }]);
buttonController.showMakeClaim();
return true;
} catch (error: unknown) {
// Add network if it doesn't exist.
Expand Down
23 changes: 0 additions & 23 deletions static/scripts/rewards/web3/verify-current-network.ts

This file was deleted.

0 comments on commit db22f56

Please sign in to comment.