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

Refactor/general cleanup #203

Merged
merged 11 commits into from
Mar 20, 2024
5 changes: 5 additions & 0 deletions .knip.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"entry": ["static/scripts/rewards/init.ts"],
"ignore": ["lib/**"]
}
54 changes: 0 additions & 54 deletions build/plugins/invert-colors.ts

This file was deleted.

4 changes: 1 addition & 3 deletions globals.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Ethereum } from "ethereum-protocol";

declare global {
interface Window {
ethereum: Ethereum;
}
const ethereum: Ethereum;
}
21 changes: 4 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,13 @@
],
"dependencies": {
"@ethersproject/providers": "^5.7.2",
"@octokit/core": "^5.1.0",
"@octokit/plugin-create-or-update-text-file": "^4.0.1",
"@octokit/plugin-throttling": "^8.1.3",
"@octokit/rest": "^20.0.2",
"@sinclair/typebox": "^0.32.14",
"@supabase/supabase-js": "2.39.7",
"@types/libsodium-wrappers": "^0.7.13",
"@sinclair/typebox": "^0.32.15",
"@supabase/supabase-js": "^2.39.8",
"@uniswap/permit2-sdk": "^1.2.0",
"axios": "^1.6.7",
"dotenv": "^16.4.4",
"ethers": "^5.7.2",
"godb": "^0.6.2",
"libsodium-wrappers": "^0.7.13",
"npm-run-all": "^4.1.5",
"retry-axios": "^3.1.3",
"yaml": "^2.3.4"
"npm-run-all": "^4.1.5"
},
"devDependencies": {
"@commitlint/cli": "^18.6.1",
Expand All @@ -61,11 +52,8 @@
"@typescript-eslint/eslint-plugin": "^7.0.1",
"@typescript-eslint/parser": "^7.0.1",
"cspell": "^8.3.2",
"cspell-dict-html": "^1.2.5",
"esbuild": "^0.20.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-sonarjs": "^0.24.0",
"husky": "^9.0.11",
"knip": "^5.0.1",
Expand All @@ -74,8 +62,7 @@
"npm-run-all": "^4.1.5",
"prettier": "^3.2.5",
"tsx": "^4.7.1",
"typescript": "^5.3.3",
"yarn-upgrade-all": "^0.7.2"
"typescript": "^5.3.3"
},
"lint-staged": {
"*.ts": [
Expand Down
2 changes: 1 addition & 1 deletion scripts/typescript/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const colors = {
bgCyan: "\x1b[46m",
bgWhite: "\x1b[47m",
};
export function colorizeText(text: string, color: keyof typeof colors): string {
function colorizeText(text: string, color: keyof typeof colors): string {
return colors[color].concat(text).concat(colors.reset);
}

Expand Down
12 changes: 6 additions & 6 deletions static/scripts/rewards/ButtonController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export class ButtonController {
}

public showLoader(): void {
if (window.ethereum) {
if (ethereum) {
this._controls.setAttribute(LOADER, "true");
} else {
throw new Error("Can not show loader without `window.ethereum`");
throw new Error("Can not show loader without `ethereum`");
}
}

Expand All @@ -27,10 +27,10 @@ export class ButtonController {
}

public showMakeClaim(): void {
if (window.ethereum) {
if (ethereum) {
this._controls.setAttribute(MAKE_CLAIM, "true");
} else {
throw new Error("Can not show make claim button without `window.ethereum`");
throw new Error("Can not show make claim button without `ethereum`");
}
}

Expand All @@ -47,10 +47,10 @@ export class ButtonController {
}

public showInvalidator(): void {
if (window.ethereum) {
if (ethereum) {
this._controls.setAttribute(INVALIDATOR, "true");
} else {
throw new Error("Can not show invalidator button without `window.ethereum`");
throw new Error("Can not show invalidator button without `ethereum`");
}
}

Expand Down
4 changes: 2 additions & 2 deletions static/scripts/rewards/app-state.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JsonRpcProvider } from "@ethersproject/providers";
import { JsonRpcProvider, JsonRpcSigner } from "@ethersproject/providers";
import { networkExplorers } from "./constants";
import { RewardPermit } from "./render-transaction/tx-type";

Expand All @@ -7,7 +7,7 @@ export class AppState {
public claimTxs: Record<string, string> = {};
private _provider!: JsonRpcProvider;
private _currentIndex = 0;
private _signer;
private _signer: JsonRpcSigner | null = null;

get signer() {
return this._signer;
Expand Down
8 changes: 4 additions & 4 deletions static/scripts/rewards/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@

declare const extraRpcs: Record<string, string[]>; // @DEV: passed in at build time check build/esbuild-build.ts

export enum NetworkIds {
enum NetworkIds {
Mainnet = 1,
Goerli = 5,
Gnosis = 100,
Anvil = 31337,
}

export enum Tokens {
enum Tokens {
DAI = "0x6b175474e89094c44da98b954eedeac495271d0f",
WXDAI = "0xe91d153e0b41518a2ce8dd3d7944fa863463a97d",
}

export const networkNames = {
const networkNames = {
[NetworkIds.Mainnet]: "Ethereum Mainnet",
[NetworkIds.Goerli]: "Goerli Testnet",
[NetworkIds.Gnosis]: "Gnosis Chain",
Expand Down Expand Up @@ -53,4 +53,4 @@ export const networkRpcs: Record<number, string[]> = {
};

export const permit2Address = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
export const nftAddress = "0xAa1bfC0e51969415d64d6dE74f27CDa0587e645b";
const nftAddress = "0xAa1bfC0e51969415d64d6dE74f27CDa0587e645b";
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function claimRewardsPagination(rewardsCount: HTMLElement) {
if (prevTxButton) prevTxButton.addEventListener("click", () => transactionHandler("previous"));
}

export function transactionHandler(direction: "next" | "previous") {
function transactionHandler(direction: "next" | "previous") {
removeAllEventListeners(getMakeClaimButton()) as HTMLButtonElement;
direction === "next" ? app.nextPermit() : app.previousPermit();
table.setAttribute(`data-make-claim`, "error");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BigNumber, ethers } from "ethers";
import { AppState, app } from "../app-state";
import { Erc20Permit, Erc721Permit } from "./tx-type";

export function shortenAddress(address: string): string {
function shortenAddress(address: string): string {
return `${address.slice(0, 10)}...${address.slice(-8)}`;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,13 @@ export async function readClaimDataFromUrl(app: AppState) {
app.claims = decodeClaimData(base64encodedTxData).flat();
app.claimTxs = await getClaimedTxs(app);
app.provider = await useFastestRpc(app);
if (window.ethereum) {
app.signer = await connectWallet().catch(console.error);
window.ethereum.on("accountsChanged", () => {
if (ethereum) {
try {
app.signer = await connectWallet();
} catch (error) {
/* empty */
}
ethereum.on("accountsChanged", () => {
checkRenderMakeClaimControl(app).catch(console.error);
checkRenderInvalidatePermitAdminControl(app).catch(console.error);
});
Expand All @@ -46,7 +50,11 @@ export async function readClaimDataFromUrl(app: AppState) {
displayRewardPagination();

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

async function getClaimedTxs(app: AppState): Promise<Record<string, string>> {
Expand All @@ -66,17 +74,10 @@ function decodeClaimData(base64encodedTxData: string): RewardPermit[] {

try {
permit = JSON.parse(atob(base64encodedTxData));
} catch (error) {
console.error(error);
setClaimMessage({ type: "Error", message: `1. Invalid claim data passed in URL` });
table.setAttribute(`data-make-claim`, "error");
throw error;
}
try {
return [Value.Decode(Type.Array(claimTxT), permit)];
} catch (error) {
console.error(error);
setClaimMessage({ type: "Error", message: `2. Invalid claim data passed in URL` });
setClaimMessage({ type: "Error", message: `Invalid claim data passed in URL` });
table.setAttribute(`data-make-claim`, "error");
throw error;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export async function renderTransaction(): Promise<Success> {
if (app.claimTxs[app.reward.permit.nonce.toString()] !== undefined) {
buttonController.showViewClaim();
viewClaimButton.addEventListener("click", () => window.open(`${app.currentExplorerUrl}/tx/${app.claimTxs[app.reward.permit.nonce.toString()]}`));
} else if (window.ethereum) {
} else if (ethereum) {
// requires wallet connection to claim
buttonController.showMakeClaim();
getMakeClaimButton().addEventListener("click", claimErc20PermitHandlerWrapper(app));
Expand Down
6 changes: 3 additions & 3 deletions static/scripts/rewards/toaster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ export const toaster = {
},
};

export const controls = document.getElementById("controls") as HTMLDivElement;
const controls = document.getElementById("controls") as HTMLDivElement;
export function getMakeClaimButton() {
return document.getElementById("make-claim") as HTMLButtonElement;
}
export const viewClaimButton = document.getElementById("view-claim") as HTMLButtonElement;
export const notifications = document.querySelector(".notifications") as HTMLUListElement;
const notifications = document.querySelector(".notifications") as HTMLUListElement;
export const buttonController = new ButtonController(controls);

export function createToast(meaning: keyof typeof toaster.icons, text: string) {
function createToast(meaning: keyof typeof toaster.icons, text: string) {
if (meaning != "info") buttonController.hideLoader();
const toastDetails = {
timer: 5000,
Expand Down
2 changes: 1 addition & 1 deletion static/scripts/rewards/web3/connect-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { buttonController, toaster } from "../toaster";

export async function connectWallet(): Promise<JsonRpcSigner | null> {
try {
const wallet = new ethers.providers.Web3Provider(window.ethereum);
const wallet = new ethers.providers.Web3Provider(ethereum);

await wallet.send("eth_requestAccounts", []);

Expand Down
10 changes: 5 additions & 5 deletions static/scripts/rewards/web3/erc20-permit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export function claimErc20PermitHandlerWrapper(app: AppState) {
};
}

export async function checkPermitClaimable(app: AppState): Promise<boolean> {
async function checkPermitClaimable(app: AppState): Promise<boolean> {
let isClaimed: boolean;
try {
isClaimed = await isNonceClaimed(app);
Expand Down Expand Up @@ -248,7 +248,7 @@ invalidateButton.addEventListener("click", async function invalidateButtonClickH
});

//mimics https://github.com/Uniswap/permit2/blob/a7cd186948b44f9096a35035226d7d70b9e24eaf/src/SignatureTransfer.sol#L150
export async function isNonceClaimed(app: AppState): Promise<boolean> {
async function isNonceClaimed(app: AppState): Promise<boolean> {
const provider = app.provider;

const permit2Contract = new ethers.Contract(permit2Address, permit2Abi, provider);
Expand All @@ -266,7 +266,7 @@ export async function isNonceClaimed(app: AppState): Promise<boolean> {
return bit.and(flipped).eq(0);
}

export async function invalidateNonce(signer: JsonRpcSigner, nonce: BigNumberish): Promise<void> {
async function invalidateNonce(signer: JsonRpcSigner, nonce: BigNumberish): Promise<void> {
const permit2Contract = new ethers.Contract(permit2Address, permit2Abi, signer);
const { wordPos, bitPos } = nonceBitmap(nonce);
// mimics https://github.com/ubiquity/pay.ubq.fi/blob/c9e7ed90718fe977fd9f348db27adf31d91d07fb/scripts/solidity/test/Permit2.t.sol#L428
Expand All @@ -277,15 +277,15 @@ export async function invalidateNonce(signer: JsonRpcSigner, nonce: BigNumberish
}

// mimics https://github.com/Uniswap/permit2/blob/db96e06278b78123970183d28f502217bef156f4/src/SignatureTransfer.sol#L142
export function nonceBitmap(nonce: BigNumberish): { wordPos: BigNumber; bitPos: number } {
function nonceBitmap(nonce: BigNumberish): { wordPos: BigNumber; bitPos: number } {
// wordPos is the first 248 bits of the nonce
const wordPos = BigNumber.from(nonce).shr(8);
// bitPos is the last 8 bits of the nonce
const bitPos = BigNumber.from(nonce).and(255).toNumber();
return { wordPos, bitPos };
}

export async function updatePermitTxHash(app: AppState, hash: string): Promise<boolean> {
async function updatePermitTxHash(app: AppState, hash: string): Promise<boolean> {
const { error } = await supabase
.from("permits")
.update({ transaction: hash })
Expand Down
2 changes: 1 addition & 1 deletion static/scripts/rewards/web3/erc721-permit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function claimErc721PermitHandler(reward: Erc721Permit) {
};
}

export async function isNonceRedeemed(reward: Erc721Permit, provider: JsonRpcProvider): Promise<boolean> {
async function isNonceRedeemed(reward: Erc721Permit, provider: JsonRpcProvider): Promise<boolean> {
const nftContract = new ethers.Contract(reward.permit.permitted.token, nftRewardAbi, provider);
return nftContract.nonceRedeemed(reward.request.nonce);
}
6 changes: 3 additions & 3 deletions static/scripts/rewards/web3/verify-current-network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import { notOnCorrectNetwork } from "./not-on-correct-network";

// verifyCurrentNetwork checks if the user is on the correct network and displays an error if not
export async function verifyCurrentNetwork(desiredNetworkId: number) {
if (!window.ethereum) {
if (!ethereum) {
buttonController.hideAll();
return;
}

const web3provider = new ethers.providers.Web3Provider(window.ethereum);
const web3provider = new ethers.providers.Web3Provider(ethereum);

const network = await web3provider.getNetwork();
const currentNetworkId = network.chainId;

// watch for network changes
window.ethereum.on("chainChanged", <T>(newNetworkId: T | string) => handleIfOnCorrectNetwork(parseInt(newNetworkId as string, 16), desiredNetworkId));
ethereum.on("chainChanged", <T>(newNetworkId: T | string) => handleIfOnCorrectNetwork(parseInt(newNetworkId as string, 16), desiredNetworkId));

// if its not on ethereum mainnet, gnosis, or goerli, display error
notOnCorrectNetwork(currentNetworkId, desiredNetworkId, web3provider);
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"include": ["src", "lib/chainlist/constants/extraRpcs.js", "static", "build", "scripts/typescript", "globals.d.ts"],
"include": ["src", "static", "build", "scripts/typescript", "globals.d.ts"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
Expand Down
Loading
Loading