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

[ISOLATE] Various Helpers Scripts to be isolated into separate repo #105

Open
wants to merge 6 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
"mongo:stop": "docker-compose stop",
"mongo:down": "docker-compose down",
"mongo:drop": "ts-node src/utils/drop-db.ts",
"run-sepolia": "hardhat run src/deploy/run-campaign.ts --network sepolia"
"run-sepolia": "hardhat run src/deploy/run-campaign.ts --network sepolia",
"get-balances": "ts-node src/utils/external/check-balances.ts",
"tenderly-all": "ts-node src/utils/external/tenderly-push-csv.ts"
},
"pre-commit": [
"lint"
Expand Down Expand Up @@ -77,6 +79,7 @@
"dependencies": {
"@zero-tech/zdc": "0.1.3",
"axios": "^1.4.0",
"convert-csv-to-json": "^2.44.0",
"dotenv": "16.0.3",
"mongodb": "^6.1.0",
"winston": "^3.11.0"
Expand Down
120 changes: 120 additions & 0 deletions src/utils/external/check-balances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import fs from "fs";
import { ethers } from "ethers";
import { ERC20__factory } from "../../../typechain";

const notValidStr = "NOT A VALID ETHEREUM ADDRESS";
const accountsJsonPath = "./src/utils/check-balances/DATA/accounts.json";
const fullJsonOutputPath = "./src/utils/check-balances/DATA/balances.json";

interface AccountIn {
name : string;
address : string;
}

interface Balances {
ETH : bigint | string;
WETH : bigint | string;
WBTC : bigint | string;
USDC : bigint | string;
WILD : bigint | string;
MEOW : bigint | string;
}

type TokenSymbol = keyof Balances;

interface AccountOut extends AccountIn {
balances : Balances | "NOT A VALID ETHEREUM ADDRESS";
}

const tokenAddresses = {
ETH: "no-address",
WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
WBTC: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
USDC: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
WILD: "0x2a3bFF78B79A009976EeA096a51A948a3dC00e34",
MEOW: "0x0eC78ED49C2D27b315D462d43B5BAB94d2C79bf8",
};


const provider = new ethers
.JsonRpcProvider(`https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`);


const getBalances = async () => {
const accountsJson = JSON.parse(
fs.readFileSync(accountsJsonPath, "utf8")
);

return accountsJson.reduce(
async (
acc : Promise<Array<AccountOut>>,
{ name: accountName, address: accountAddress } : AccountIn
) => {
const newAccOuter = await acc;
let balances;

if (accountAddress.slice(0, 2) !== "0x") {
console.log(`Account ${accountName} has an invalid address: ${accountAddress}`);
return [...newAccOuter, { name: accountName, address: accountAddress, balances: notValidStr }];

// TODO: remove the "else" block below if this proves to be a pointless "if" here
} else if (accountAddress !== "") {
balances = await Object.entries(tokenAddresses).reduce(
async (innerAcc : Promise<Balances>, [symbol, tokenAddress]) : Promise<Balances> => {
const balancesAcc = await innerAcc;

let balance;
if (symbol === "ETH") {
try {
balance = await provider.getBalance(accountAddress);
balancesAcc[symbol] = balance.toString();
} catch (e) {
balancesAcc[symbol] = (e as Error).message;
}

return balancesAcc;
}

const tokenContract = ERC20__factory.connect(tokenAddress, provider);

try {
balance = await tokenContract.balanceOf(accountAddress);
balancesAcc[symbol as TokenSymbol] = balance.toString();
} catch (e) {
balancesAcc[symbol as TokenSymbol] = (e as Error).message;
}

return balancesAcc;
}, Promise.resolve({} as Balances)
);
} else {
throw new Error(`Unknown case for name: ${accountName} and address: ${accountAddress}`);
}

console.log(`Added balances for Account ${accountName} and address ${accountAddress}.`);
return [
...newAccOuter,
{
name: accountName,
address: accountAddress,
balances,
},
];
}, Promise.resolve([])
);
};

const balancesToJson = async () => {
const balances = await getBalances();

console.log("GOT ALL BALANCES! Writing balances to file...");

fs.writeFileSync(fullJsonOutputPath, JSON.stringify(balances, null, 2));
};

balancesToJson()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
26 changes: 26 additions & 0 deletions src/utils/external/get-contract-creator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import axios from "axios";

const getCreatorFromEtherscan = async () => {
const contractAddresses : Array<string> = [
"0x0",
];

const inst = axios.create();

const addressesStr = contractAddresses.join(",");

const { data } = await inst.get(
`https://api.etherscan.io/api?module=contract&action=getcontractcreation&contractaddresses=${addressesStr}&apikey=${process.env.API_KEY}`
);

data.result.map((item : any) => {
console.log(`Contract: ${item.contractAddress} DEPLOYER: ${item.contractCreator}`);
});
};

getCreatorFromEtherscan()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
73 changes: 73 additions & 0 deletions src/utils/external/get-controllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import axios from "axios";
import { Registrar__factory } from "../typechain"; // legacy Registrar
import { ethers } from "ethers";


interface IEtherscanTx {
methodId : string;
functionName : string;
input : string;
}

const addresses = [
"0x0",
];


const getTransactionsForAddress = async (address : string) : Promise<Array<IEtherscanTx>> => {
const inst = axios.create();

const { data } = await inst.get(
`https://api.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999999999&page=1&offset=10&sort=asc&apikey=${process.env.ETHERSCAN_API_KEY}`
);

return data.result;
};

const getControllersForAddress = async (address : string) => {
const txes = await getTransactionsForAddress(address);

const methodIdToCheck = "0xa7fc7a07";
const functionNameToCheck = "addController(address newController)";

const historicControllers = txes.reduce(
(acc : Array<string>, tx : IEtherscanTx) => {
if (tx.functionName === functionNameToCheck) {
acc.push(`0x${tx.input.slice(-40)}`);
}
return acc;
},
[]
);

const signer = new ethers.providers.JsonRpcProvider(`https://eth-mainnet.alchemyapi.io/v2/${process.env.ALCHEMY_API_KEY}`);
const contract = Registrar__factory.connect(address, signer);

const existingControllers : Array<string> = await historicControllers.reduce(
async (acc : Promise<Array<string>>, input) => {
const newAcc = await acc;

const isController = await contract.controllers(input);

if (isController) {
return [...newAcc, input];
} else {
return newAcc;
}
},
Promise.resolve([])
);

return existingControllers;
};


getControllersForAddress(addresses[0])
.then(data => {
console.log(data);
process.exit(0);
})
.catch(error => {
console.error(error);
process.exit(1);
});
42 changes: 42 additions & 0 deletions src/utils/external/get-proxy-admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ethers } from "ethers";
import hre from "hardhat";


const _ADMIN_SLOT = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103";

const main = async () => {
const contracts = [
"0x0",
];

await contracts.reduce(
async (acc, contract) => {
await acc;

const provider = new ethers.providers.JsonRpcProvider(`https://mainnet.infura.io/v3/${process.env.API_KEY}`);
const slot = await provider.getStorageAt(
contract,
_ADMIN_SLOT
);
// method to remove zeros and return ethereum address
const proxyAdminAddr = `0x${slot.slice(26)}`;

console.log(`Contract ${contract} PROXYADMIN: ${proxyAdminAddr}`);

if (proxyAdminAddr !== ethers.constants.AddressZero) {
const prAdFact = await hre.ethers.getContractFactory("ProxyAdmin");
const proxyAdmim = prAdFact.attach(proxyAdminAddr);
// const owner = await proxyAdmim.owner();
const owner = await provider.getStorageAt(proxyAdminAddr, 0);
console.log(`Contract ${contract} OWNER OF PROXY ADMIN: ${`0x${owner.slice(26)}`}`);
}
}, Promise.resolve()
);
};

main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
8 changes: 8 additions & 0 deletions src/utils/external/make-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import csvParser from "convert-csv-to-json";


const csvPath = "./src/utils/sec-sweep/DATA/all-contracts.csv";
const jsonPath = "./src/utils/sec-sweep/DATA/all-contracts.json";
const delimiter = ",";

csvParser.fieldDelimiter(delimiter).generateJsonFileFromCsv(csvPath, jsonPath);
80 changes: 80 additions & 0 deletions src/utils/external/tenderly-push-csv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/* eslint-disable camelcase */
import axios from "axios";
import fs from "fs";
import { HardhatDeployer } from "@zero-tech/zdc";


const accountId = "zer0-os";
const projectSlug = "all-legacy-contracts";
const jsonPath = "./src/utils/sec-sweep/DATA/all-contracts.json";


const csvToTenderly = async () => {
// {
// "network_id": "42",
// "address": "0x404469525f6Ab4023Ce829D8F627d424D3986675",
// "display_name": "My new contract name"
// }
const json = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
const contracts = json.reduce(
(
acc : Array<Array<{ network_id : string; address : string; display_name : string; }>>,
{ name, address } : {
name : string;
address : string;
},
idx : number
) => {
const obj = {
network_id: "1",
address,
display_name: name,
};

const chunk = 40;

if (idx < chunk) {
acc[0].push(obj);
} else if (idx < chunk * 2) {
acc[1].push(obj);
} else if (idx < chunk * 3) {
acc[2].push(obj);
} else {
acc[3].push(obj);
}

if (!address.includes("0x")) throw new Error(`Invalid address: ${address} for name ${name}.`);

return acc;
}, [
[],
[],
[],
[],
]
);

const inst = axios.create({
baseURL: "https://api.tenderly.co/",
headers: {
"Content-Type": "application/json",
"X-Access-Key": process.env.TENDERLY_ACCESS_KEY,
},
});

for (const inner of contracts) {
const res = await inst.post(
`api/v2/accounts/${accountId}/projects/${projectSlug}/contracts`,
{ contracts: inner }
);

console.log(res.statusText);
}
};

csvToTenderly()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3293,6 +3293,11 @@ conventional-commits-parser@^5.0.0:
meow "^12.0.1"
split2 "^4.0.0"

convert-csv-to-json@^2.44.0:
version "2.44.0"
resolved "https://registry.yarnpkg.com/convert-csv-to-json/-/convert-csv-to-json-2.44.0.tgz#f4b194a699dae95244dcb4a6a4d9d374273af907"
integrity sha512-t1ol7CBfyN4VURpUc0hVO6boX/7cCdYz1tLPD2j5aU8sXjk9UQmNy9NtOc4pGOfGhjJEfeiKXF1WvlHTFtRy4A==

cookie@^0.4.1:
version "0.4.2"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.2.tgz#0e41f24de5ecf317947c82fc789e06a884824432"
Expand Down