diff --git a/packages/commands/.eslintignore b/packages/commands/.eslintignore deleted file mode 100644 index 7e44b06f..00000000 --- a/packages/commands/.eslintignore +++ /dev/null @@ -1,11 +0,0 @@ -# folders -lib/ -node_modules/ -# files -**/*.less -**/*.css -**/*.scss -**/*.json -**/*.png -**/*.svg -generated/ diff --git a/packages/commands/.eslintrc.js b/packages/commands/.eslintrc.js deleted file mode 100644 index b0c93729..00000000 --- a/packages/commands/.eslintrc.js +++ /dev/null @@ -1,140 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', // Specifies the ESLint parser - extends: ['../common/.eslintrc.js'], - parserOptions: { - ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features - sourceType: 'module', // Allows for the use of imports, - ecmaFeatures: { - jsx: true, // Allows for the parsing of JSX, - }, - project: 'tsconfig.json', - tsconfigRootDir: '.', - projectFolderIgnoreList: [ - 'node_modules/*', - 'node_modules', - 'dist', - 'build', - '.yarn', - 'build-utils', - 'docs', - './src/generated/*', - 'generated/*', - ], - }, - env: { - browser: true, - es6: true, - node: true, - }, -}; - -// module.exports = { -// parser: '@typescript-eslint/parser', // Specifies the ESLint parser -// parserOptions: { -// ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features -// sourceType: 'module', // Allows for the use of imports, -// ecmaFeatures: { -// jsx: false, // Allows for the parsing of JSX -// }, -// tsconfigRootDir: '.', -// project: ['./tsconfig.json'], -// projectFolderIgnoreList: ['node_modules', 'dist', 'build', '.yarn', 'build-utils'], -// extraFileExtensions: ['.sol'], -// }, -// env: { -// browser: true, -// es6: true, -// node: true, -// }, -// extends: [ -// 'plugin:import/errors', -// 'plugin:import/warnings', -// 'plugin:import/typescript', -// 'plugin:prettier/recommended', -// 'plugin:@typescript-eslint/eslint-recommended', -// 'plugin:@typescript-eslint/recommended', -// 'plugin:@typescript-eslint/recommended-requiring-type-checking', -// 'standard-kit/prettier/typescript', -// 'standard-kit/prettier/node', -// 'plugin:mocha/recommended', -// ], -// plugins: ['prettier', '@typescript-eslint', 'unused-imports'], -// rules: { -// 'prettier/prettier': [ -// 'warn', -// { -// endOfLine: 'auto', -// }, -// ], -// '@typescript-eslint/ban-ts-comment': 'off', -// '@typescript-eslint/no-empty-function': 'warn', -// 'no-unused-vars': 'off', -// '@typescript-eslint/no-unused-vars': 'warn', -// 'unused-imports/no-unused-imports-ts': 'warn', -// 'unused-imports/no-unused-vars-ts': ['error', { vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' }], -// '@typescript-eslint/no-use-before-define': ['error'], -// '@typescript-eslint/no-unsafe-member-access': 0, -// '@typescript-eslint/no-unsafe-assignment': 0, -// '@typescript-eslint/no-explicit-any': 0, -// '@typescript-eslint/no-unsafe-call': 'warn', -// '@typescript-eslint/unbound-method': 0, -// '@typescript-eslint/restrict-template-expressions': ['warn', { allowBoolean: true, allowNumber: true }], -// 'prefer-destructuring': 'off', -// 'no-param-reassign': 'error', -// 'import/order': [ -// 'warn', -// { -// alphabetize: { -// order: 'asc' /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */, -// caseInsensitive: true /* ignore case. Options: [true, false] */, -// }, -// 'newlines-between': 'always', -// }, -// ], -// 'no-duplicate-imports': 'warn', -// 'import/named': 'off', -// 'import/namespace': 'off', -// 'import/default': 'off', -// 'import/no-named-as-default-member': 'error', -// 'import/extensions': 'off', -// 'import/no-unresolved': 'off', -// 'import/prefer-default-export': 'off', -// 'import/no-unused-modules': ['off'], -// 'import/no-unassigned-import': 'off', -// 'import/no-extraneous-dependencies': [ -// 'warn', -// { -// devDependencies: true, -// optionalDependencies: false, -// peerDependencies: false, -// }, -// ], -// 'sort-keys': 'off', -// 'comma-dangle': 'off', -// '@typescript-eslint/comma-dangle': ['off'], -// 'no-use-before-define': 'off', -// 'spaced-comment': 'warn', -// 'max-len': 'off', -// indent: 'off', -// 'no-console': 'off', -// 'arrow-body-style': 'off', -// 'no-multiple-empty-lines': 'warn', -// 'no-restricted-globals': 'off', -// 'eslint linebreak-style': 'off', -// 'object-curly-newline': 'off', -// 'no-shadow': 'off', -// 'no-void': ['error', { allowAsStatement: true }], -// 'mocha/no-mocha-arrows': 'off', -// 'mocha/no-hooks-for-single-case': 'off', -// 'mocha/max-top-level-suites': ['warn', { limit: 3 }], -// }, -// overrides: [ -// { -// files: ['*.test.ts', '*.test.tsx'], -// rules: { -// '@typescript-eslint/no-non-null-assertion': 'off', -// }, -// }, -// ], -// settings: {}, -// }; diff --git a/packages/commands/README.md b/packages/commands/README.md deleted file mode 100644 index 458b3cc4..00000000 --- a/packages/commands/README.md +++ /dev/null @@ -1 +0,0 @@ -# scripts diff --git a/packages/commands/package.json b/packages/commands/package.json deleted file mode 100644 index 2bac887a..00000000 --- a/packages/commands/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "@scaffold-eth/commands", - "version": "0.0.0", - "private": true, - "scripts": { - "scaffold": "ts-node --project tsconfig.json ./src/commands/scaffoldCommands.ts", - "lint": "eslint --config ./.eslintrc.js --ignore-path ./.eslintignore ./src", - "lint:report": "eslint --config ./.eslintrc.js --ignore-path ./.eslintignore --output-file eslint_report.json --format json ./src", - "format": "yarn prettier -w ./src ", - "format:check": "yarn prettier -c ./src" - }, - "devDependencies": { - "@scaffold-eth/common": "0.0.0", - "@swc/core": "^1.3.1", - "@swc/helpers": "^0.4.11", - "@types/debounce": "^1.2.1", - "@types/edit-json-file": "^1.7.0", - "@types/shelljs": "^0.8.11", - "@types/throttle-debounce": "^5.0.0", - "@typescript-eslint/eslint-plugin": "^5.37.0", - "@typescript-eslint/parser": "^5.37.0", - "chalk": "^4.1.2", - "cross-env": "^7.0.3", - "edit-json-file": "^1.7.0", - "eslint": "^8.23.1", - "eslint-config-airbnb": "^19.0.4", - "eslint-config-airbnb-typescript": "^17.0.0", - "eslint-config-prettier": "^8.5.0", - "eslint-config-standard-kit": "^0.15.1", - "eslint-plugin-import": "^2.26.0", - "eslint-plugin-jsx-a11y": "^6.6.1", - "eslint-plugin-mocha": "^10.1.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^4.2.1", - "eslint-plugin-react": "^7.31.8", - "eslint-plugin-react-hooks": "^4.6.0", - "eslint-plugin-unused-imports": "^2.0.0", - "husky": "^8.0.1", - "lint-staged": "^13.0.3", - "prettier": "^2.7.1", - "prettier-plugin-solidity": "^1.0.0-dev.23", - "shx": "^0.3.4", - "ts-invariant": "^0.10.3", - "ts-node": "^10.9.1", - "ts-toolbelt": "^9.6.0", - "tsconfig-paths": "^4.1.0", - "typescript": "^4.8.3" - }, - "dependencies": { - "commander": "^9.4.0", - "shelljs": "^0.8.5", - "shx": "^0.3.4", - "throttle-debounce": "^5.0.0", - "zod": "^3.19.1" - } -} diff --git a/packages/commands/src/commands/functions/config.ts b/packages/commands/src/commands/functions/config.ts deleted file mode 100644 index 0b448e4e..00000000 --- a/packages/commands/src/commands/functions/config.ts +++ /dev/null @@ -1,125 +0,0 @@ -import chalk from 'chalk'; - -import { - TSolidityToolkits, - TReactBuilds, - TNetworkNamesList, - scaffoldConfigSchema, - TScaffoldConfig, -} from '~common/models'; -import { set, editor, load } from '~~/helpers/configManager'; - -export type DeepPartial = { - [P in keyof T]?: DeepPartial; -}; - -export const createConfig = (config: TScaffoldConfig): void => { - set('build', config.build); - set('runtime', config.runtime); - - editor.save(); - console.log(chalk.green(`✅ Success! Created scaffold.config.json in packages/common/src`)); - console.log(chalk.green('With: '), config); -}; - -export const parseCreateConfigArgs = (...args: string[]): Parameters => { - console.log(); - try { - const input: DeepPartial = { - build: { - solidityToolkit: args[0] as TSolidityToolkits, - reactBuild: args[1] as TReactBuilds, - }, - runtime: { - targetNetwork: args[2] as TNetworkNamesList, - availableNetworks: args[3] - .split(',') - .filter((y) => y.length > 0) - .map((x) => x.trim()) as TNetworkNamesList[], - }, - }; - - const config = scaffoldConfigSchema.safeParse(input); - - if (config.success === false) { - console.log(chalk.red('❌ Error! Invalid config values!')); - config.error.errors.forEach((err) => { - console.log(chalk.red(' - ', err.message, ';')); - }); - console.log('arguments: ', input); - throw ''; - } - - return [config.data]; - } catch (err) { - console.log(chalk.red('❌ Error! Invalid parameters, could not parse them!')); - throw err; - } -}; - -export const setConfig = (config: DeepPartial): void => { - const oldConfig = load(); - set('build', { ...oldConfig.build, ...config.build }); - set('runtime', { ...oldConfig.runtime, ...config.runtime }); - - editor.save(); - console.log(chalk.green(`✅ Success! Created scaffold.config.json in packages/common/src`)); - console.log(chalk.green('With: '), config); -}; - -const validateConfig = (input: DeepPartial): DeepPartial => { - try { - const config = scaffoldConfigSchema.deepPartial().safeParse(input); - - if (config.success === false) { - console.log(chalk.red('❌ Error! Invalid config values!')); - config.error.errors.forEach((err) => { - console.log(chalk.red(' - ', err.message, ';')); - }); - console.log('arguments: ', input); - throw ''; - } - - return config.data; - } catch (err) { - console.log(chalk.red('❌ Error! Invalid parameters, could not parse them!')); - throw err; - } -}; - -export const parseReactBuild = (...args: string[]): Parameters => { - console.log(); - const input: DeepPartial = { - build: { - reactBuild: args[0] as TReactBuilds, - }, - }; - - return [validateConfig(input)]; -}; - -export const parseSolidityToolkit = (...args: string[]): Parameters => { - console.log(); - const input: DeepPartial = { - build: { - solidityToolkit: args[0] as TSolidityToolkits, - }, - }; - - return [validateConfig(input)]; -}; - -export const parseNetwork = (...args: string[]): Parameters => { - console.log(); - const input: DeepPartial = { - runtime: { - targetNetwork: args[0] as TNetworkNamesList, - availableNetworks: args[1] - .split(',') - .filter((y) => y.length > 0) - .map((x) => x.trim()) as TNetworkNamesList[], - }, - }; - - return [validateConfig(input)]; -}; diff --git a/packages/commands/src/commands/functions/launchReact.ts b/packages/commands/src/commands/functions/launchReact.ts deleted file mode 100644 index bd1876b7..00000000 --- a/packages/commands/src/commands/functions/launchReact.ts +++ /dev/null @@ -1,34 +0,0 @@ -import chalk from 'chalk'; -import shell from 'shelljs'; - -import { processUnknownArgs } from './processUnknownArgs'; - -import { load, printConfig } from '~~/helpers/configManager'; - -export const startReact = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - - if (config.build.reactBuild === 'vite') { - shell.exec('yarn workspace @scaffold-eth/vite-app start' + passthroughArgs, {}); - } else if (config.build.reactBuild === 'nextjs') { - shell.exec('yarn workspace @scaffold-eth/nextjs-app dev' + passthroughArgs); - } else { - console.log(chalk.red('❌ Error! Invalid react build tool in config!')); - } -}; - -export const buildReact = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - - if (config.build.reactBuild === 'vite') { - shell.exec('yarn workspace @scaffold-eth/vite-app build' + passthroughArgs); - } else if (config.build.reactBuild === 'nextjs') { - shell.exec('yarn workspace @scaffold-eth/nextjs-app build' + passthroughArgs); - } else { - console.log(chalk.red('❌ Error! Invalid solidity toolkit in config!')); - } -}; diff --git a/packages/commands/src/commands/functions/launchSolidity.ts b/packages/commands/src/commands/functions/launchSolidity.ts deleted file mode 100644 index c7af31e6..00000000 --- a/packages/commands/src/commands/functions/launchSolidity.ts +++ /dev/null @@ -1,76 +0,0 @@ -import fs from 'fs'; - -import chalk from 'chalk'; -import shell from 'shelljs'; - -import { processUnknownArgs } from './processUnknownArgs'; - -import { printError } from '~~/commands/functions/printError'; -import { load, printConfig } from '~~/helpers/configManager'; - -const createCommonGeneratedFolder = (): void => { - const commonGeneratedPath = '../common/src/generated'; - const exists = fs.existsSync(commonGeneratedPath); - - if (!exists) { - console.log(chalk.green('Creating folder' + commonGeneratedPath)); - fs.mkdirSync(commonGeneratedPath); - } -}; - -export const compileSolidity = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - - createCommonGeneratedFolder(); - - if (config.build.solidityToolkit === 'hardhat') { - const output = shell.exec('yarn workspace @scaffold-eth/solidity compile:hardhat' + passthroughArgs); - printError(output, 'Could not compile'); - } else if (config.build.solidityToolkit === 'foundry') { - const output = shell.exec('yarn workspace @scaffold-eth/solidity compile:foundry' + passthroughArgs); - printError(output, 'Could not compile'); - shell.exec('yarn workspace @scaffold-eth/solidity compile:foundry:post '); - } else { - console.log(chalk.red('❌ Error! Invalid solidity toolkit in config!')); - } - - const output = shell.exec('yarn workspace @scaffold-eth/common contracts:build'); - printError(output); -}; - -export const deploySolidity = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - - createCommonGeneratedFolder(); - - if (config.build.solidityToolkit === 'hardhat') { - const output = shell.exec('yarn workspace @scaffold-eth/solidity deploy:hardhat' + passthroughArgs); - printError(output, 'Could not deploy'); - shell.exec('yarn workspace @scaffold-eth/solidity deploy:hardhat:post'); - } else if (config.build.solidityToolkit === 'foundry') { - const output = shell.exec('yarn workspace @scaffold-eth/solidity deploy:foundry' + passthroughArgs); - printError(output, 'Could not deploy'); - shell.exec('yarn workspace @scaffold-eth/solidity deploy:foundry:post'); - } else { - console.log(chalk.red('❌ Error! Invalid react build tool in config!')); - } -}; - -export const startChain = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - console.log(passthroughArgs); - - if (config.build.solidityToolkit === 'hardhat') { - shell.exec('yarn workspace @scaffold-eth/solidity chain:hardhat' + passthroughArgs); - } else if (config.build.solidityToolkit === 'foundry') { - shell.exec('yarn workspace @scaffold-eth/solidity chain:foundry' + passthroughArgs); - } else { - console.log(chalk.red('❌ Error! Invalid solidity toolkit in config!')); - } -}; diff --git a/packages/commands/src/commands/functions/launchTests.ts b/packages/commands/src/commands/functions/launchTests.ts deleted file mode 100644 index 80e0e32a..00000000 --- a/packages/commands/src/commands/functions/launchTests.ts +++ /dev/null @@ -1,18 +0,0 @@ -import chalk from 'chalk'; -import shell from 'shelljs'; - -import { processUnknownArgs } from '~~/commands/functions/processUnknownArgs'; -import { load, printConfig } from '~~/helpers/configManager'; - -export const testSolidity = (args: string[]): void => { - const config = load(); - printConfig(config); - const passthroughArgs = processUnknownArgs(args); - if (config.build.solidityToolkit === 'hardhat') { - shell.exec('yarn workspace @scaffold-eth/solidity hardhat test' + passthroughArgs); - } else if (config.build.solidityToolkit === 'foundry') { - shell.exec('yarn workspace @scaffold-eth/solidity exec forge test' + passthroughArgs); - } else { - console.log(chalk.red('❌ Error! Invalid solidity toolkit in config!')); - } -}; diff --git a/packages/commands/src/commands/functions/printError.ts b/packages/commands/src/commands/functions/printError.ts deleted file mode 100644 index 1f3ba12f..00000000 --- a/packages/commands/src/commands/functions/printError.ts +++ /dev/null @@ -1,9 +0,0 @@ -import chalk from 'chalk'; -import shell from 'shelljs'; - -export const printError = (output: shell.ShellString, additionalMsg: string = ''): void => { - if (output.stderr.includes('Error HH')) { - console.log(chalk.red('Error running commmand! ' + additionalMsg)); - console.log(); - } -}; diff --git a/packages/commands/src/commands/functions/processUnknownArgs.ts b/packages/commands/src/commands/functions/processUnknownArgs.ts deleted file mode 100644 index e315c6b2..00000000 --- a/packages/commands/src/commands/functions/processUnknownArgs.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const processUnknownArgs = (args: string[] | string): string => { - if (Array.isArray(args) && args.join != null) { - return ' ' + args.join(' '); - } else if (typeof args === 'string') { - return ` ${args}`; - } - - return ''; -}; diff --git a/packages/commands/src/commands/functions/watchSolidity.ts b/packages/commands/src/commands/functions/watchSolidity.ts deleted file mode 100644 index 0c2eeca5..00000000 --- a/packages/commands/src/commands/functions/watchSolidity.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { existsSync } from 'fs'; -import { watch } from 'node:fs/promises'; - -import chalk from 'chalk'; -import { throttle } from 'throttle-debounce'; -import { invariant } from 'ts-invariant'; - -import { deploySolidity, compileSolidity } from './launchSolidity'; - -import { load, printConfig } from '~~/helpers/configManager'; - -export const watchSolidity = (minWatchTime: number): void => { - const config = load(); - printConfig(config); - let throttleTime = minWatchTime ?? 20; - if (Number.isNaN(throttleTime)) throttleTime = 20; - if (throttleTime < 10) throttleTime = 10; - if (throttleTime >= 600) throttleTime = 600; - - console.log(chalk.white('Watching solidity contracts for changes...', `minWatchTime: ${throttleTime} (s)`)); - - const contactsDir = '../solidity-ts/contracts'; - const deployDir = '../solidity-ts/deploy'; - invariant(existsSync(contactsDir), 'directory does not exist' + contactsDir); - invariant(existsSync(deployDir), 'directory does not exist' + deployDir); - - const deploy = throttle( - throttleTime * 1000, - (): void => { - deploySolidity([]); - console.log(); - console.log(chalk.white('-------------------------------')); - console.log(chalk.white('Watching solidity contracts for changes...', `minWatchTime: ${throttleTime} (s)`)); - }, - { noLeading: true } - ); - - const compile = throttle( - throttleTime * 1000, - () => { - compileSolidity([]); - deploy(); - }, - { noLeading: true } - ); - - void (async (): Promise => { - try { - const watcher = watch(contactsDir, { recursive: true }); - for await (const event of watcher) { - console.log(event); - compile(); - } - } catch (err) { - throw err; - } - })(); - - void (async (): Promise => { - try { - const watcher = watch(deployDir, { recursive: true }); - for await (const event of watcher) { - console.log(event); - deploy(); - } - } catch (err) { - throw err; - } - })(); -}; diff --git a/packages/commands/src/commands/scaffoldCommands.ts b/packages/commands/src/commands/scaffoldCommands.ts deleted file mode 100644 index 337434b5..00000000 --- a/packages/commands/src/commands/scaffoldCommands.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { Command } from 'commander'; - -import { - createConfig, - parseCreateConfigArgs, - setConfig, - parseReactBuild, - parseSolidityToolkit, - parseNetwork, -} from './functions/config'; - -import { buildReact, startReact } from '~~/commands/functions/launchReact'; -import { compileSolidity, deploySolidity, startChain } from '~~/commands/functions/launchSolidity'; -import { testSolidity } from '~~/commands/functions/launchTests'; -import { watchSolidity } from '~~/commands/functions/watchSolidity'; - -const program = new Command(); - -program.name('scaffold').description('Scaffold-Eth-Typescript Commands'); - -/** ********************************* */ -/* Config Commands */ - -program - .command('reset-config') - .description('Create scaffold.config.json') - .action(() => { - createConfig(...parseCreateConfigArgs('hardhat', 'vite', 'localhost', 'localhost')); - }); - -program - .command('set-config') - .description('Set scaffold.config.json file') - .argument('', ': Solidity tooklit: use `hardhat` or `foundry`') - .argument('', 'React frontend: use nextjs or vite for your frontend') - .argument('', ': An network your toolkit should target. (e.g. `localhost` or "localhost, mainnet")') - .argument('', ': An array of networks to target. (e.g. `localhost` or "localhost, mainnet")') - .action((...args: string[]) => { - createConfig(...parseCreateConfigArgs(...args)); - }); - -program - .command('set-react') - .description('Set the react build tool') - .argument('[react build tool]', 'Use nextjs or vite for your frontend', 'vite') - .action((...args: string[]) => { - setConfig(...parseReactBuild(...args)); - }); - -program - .command('set-solidity') - .description('Set the solidity toolkit') - .argument('[react build tool]', 'Use foundry or hardhat for your frontend', 'hardhat') - .action((...args: string[]) => { - setConfig(...parseSolidityToolkit(...args)); - }); - -program - .command('set-network') - .description('Set your networks') - .argument('', ': An network your toolkit should target. (e.g. `localhost` or "localhost, mainnet")') - .argument('', ': An array of networks to target. (e.g. `localhost` or "localhost, mainnet")') - .action((...args: string[]) => { - setConfig(...parseNetwork(...args)); - }); - -/** ********************************* */ -/* React Build Commands */ - -program - .command('start') - .description('Start the react front end') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - startReact(args); - }); - -program - .command('build') - .description('Build the react front end') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - buildReact(args); - }); - -/** ********************************* */ -/* Solidity commands */ - -program - .command('deploy') - .description('Deploy your contracts') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - deploySolidity(args); - }); - -program - .command('compile') - .description('Compile the solidity contracts') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - compileSolidity(args); - }); - -program - .command('chain') - .description('Start a local ethereum node, hardhat or anvil') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - startChain(args); - }); - -program - .command('test') - .description('Run solidity tests') - .argument('[args...]') - .allowUnknownOption(true) - .allowExcessArguments(true) - .action((args: string[]) => { - testSolidity(args); - }); - -program - .command('watch') - .description('Watch and build contracts automatically') - .argument('[time]', 'Time (seconds) after which a build should be triggered. Minimum is 10s, max 10min') - .action((throttleTimeStr: string) => { - const throttleTime = parseInt(throttleTimeStr); - watchSolidity(throttleTime); - }); - -program.parse(); diff --git a/packages/commands/src/helpers/configManager.ts b/packages/commands/src/helpers/configManager.ts deleted file mode 100644 index 12f05b1b..00000000 --- a/packages/commands/src/helpers/configManager.ts +++ /dev/null @@ -1,36 +0,0 @@ -import chalk from 'chalk'; -import editJson from 'edit-json-file'; - -import { scaffoldConfigSchema, TScaffoldConfig } from '~common/models'; - -const packagesPath = '../../packages'; -const configPath = packagesPath + '/common/src/scaffold.config.json'; - -export const editor = editJson(configPath); - -type TConfigKeys = keyof TScaffoldConfig; -export const set = (key: TConfigKeys, value: any): void => { - editor.set(key, value); -}; - -export const load = (): TScaffoldConfig => { - const input = editor.read(); - const config = scaffoldConfigSchema.safeParse(input); - - if (config.success) { - return config.data; - } else { - console.log(chalk.red('❌ Error! Invalid scaffold.config.json!')); - console.log(chalk.yellow('🏁 Did you run `yarn scaffold create-config`?')); - console.log(config.error); - throw 'Error, Invalid Scaffold Config: scaffold.config.json'; - } -}; - -export const printConfig = (config: TScaffoldConfig): void => { - console.log('----------------------------------------------------'); - console.log(chalk.green('✔️ Loaded scaffold.config.json:')); - console.log(config); - console.log('----------------------------------------------------'); - console.log(); -}; diff --git a/packages/commands/tsconfig.json b/packages/commands/tsconfig.json deleted file mode 100644 index 0f5a7696..00000000 --- a/packages/commands/tsconfig.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "compilerOptions": { - "sourceMap": true, - // "inlineSources": true, - "allowJs": false, - "declarationMap": true, - "declaration": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "CommonJS", - "moduleResolution": "node", - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "incremental": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "paths": { - "~~/*": ["./src/*"], - "~common/*": ["../common/src/*"] - } - }, - "ts-node": { - "swc": true, - "require": ["tsconfig-paths/register"], - "compilerOptions": { - "module": "CommonJS" - }, - "moduleTypes": { - "**/*": "cjs" - } - }, - "include": ["src", "../common/src"], - "exclude": [ - "**/node_modules", - "node_modules", - ".husky", - "**/*.css", - "./tailwind.config.js", - "**/.yalc/", - "**/.yalc/**/*", - ".yalc/**/*" - ] -} diff --git a/packages/common/.eslintignore b/packages/common/.eslintignore deleted file mode 100644 index fc7bb0ed..00000000 --- a/packages/common/.eslintignore +++ /dev/null @@ -1,9 +0,0 @@ -# folders -lib/ -node_modules/**/* -**/*.md -docs/**/* -website/**/* -docusaurus/**/* -build/**/* -**/generated/**/* \ No newline at end of file diff --git a/packages/common/.eslintrc.js b/packages/common/.eslintrc.js deleted file mode 100644 index 463a7f03..00000000 --- a/packages/common/.eslintrc.js +++ /dev/null @@ -1,175 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', // Specifies the ESLint parser - ignorePatterns: ['**/*.pcss', '**/*.css', '**/*.less'], - parserOptions: { - ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features - sourceType: 'module', // Allows for the use of imports, - ecmaFeatures: { - jsx: false, // Allows for the parsing of JSX, - }, - project: './tsconfig.json', - tsconfigRootDir: '.', - projectFolderIgnoreList: [ - 'node_modules/*', - 'node_modules', - 'dist', - 'build', - '.yarn', - 'build-utils', - 'docs', - './src/styles', - './src/generated/*', - 'generated/*', - ], - }, - env: { - browser: true, - es6: true, - node: true, - }, - extends: [ - 'plugin:import/errors', - 'plugin:import/warnings', - 'plugin:import/typescript', - 'plugin:react-hooks/recommended', - 'plugin:react/recommended', - 'plugin:prettier/recommended', - 'plugin:@typescript-eslint/eslint-recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:@typescript-eslint/recommended-requiring-type-checking', - ], - plugins: ['prettier', 'react', 'react-hooks', 'unused-imports'], - rules: { - eqeqeq: ['error', 'smart'], - 'react/jsx-wrap-multilines': 'warn', - 'react/jsx-uses-react': 'off', - 'react/react-in-jsx-scope': 'off', - 'react/jsx-filename-extension': 'off', - 'react/jsx-indent': 'off', - 'react/require-default-props': 'off', - 'react/jsx-one-expression-per-line': 'off', - 'react/jsx-closing-tag-location': 'off', - 'react/jsx-indent-props': 'off', - 'react/jsx-closing-bracket-location': 'off', - 'react/prop-types': 'off', - 'react-hooks/rules-of-hooks': 'error', - 'react/display-name': 'off', - 'react-hooks/exhaustive-deps': [ - 'warn', - { - additionalHooks: '(useRecoilCallback)', - }, - ], - 'prettier/prettier': [ - 'warn', - { - endOfLine: 'auto', - }, - ], - '@typescript-eslint/ban-ts-comment': [ - 'warn', - { - 'ts-expect-error': false, - 'ts-ignore': true, - 'ts-nocheck': false, - 'ts-check': false, - }, - ], - '@typescript-eslint/no-empty-function': 'warn', - 'no-unused-vars': 'off', - '@typescript-eslint/no-unused-vars': 'off', - 'unused-imports/no-unused-imports-ts': 'warn', - 'unused-imports/no-unused-vars-ts': [ - 'warn', - { vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' }, - ], - '@typescript-eslint/no-use-before-define': ['error'], - '@typescript-eslint/no-inferrable-types': 'off', - '@typescript-eslint/no-unsafe-assignment': 'warn', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-unsafe-call': 'warn', - '@typescript-eslint/explicit-function-return-type': 'error', - '@typescript-eslint/unbound-method': 'off', - '@typescript-eslint/no-unsafe-member-access': 'warn', - '@typescript-eslint/restrict-template-expressions': 'off', - 'prefer-destructuring': 'off', - 'prefer-template': 'off', - 'react/destructuring-assignment': 'off', - 'no-param-reassign': 'error', - 'import/order': [ - 'warn', - { - alphabetize: { - order: 'asc' /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */, - caseInsensitive: true /* ignore case. Options: [true, false] */, - }, - 'newlines-between': 'always', - }, - ], - 'no-duplicate-imports': 'warn', - 'import/named': 'off', - 'import/namespace': 'off', - 'import/default': 'off', - 'import/no-named-as-default-member': 'error', - 'import/extensions': 'off', - 'import/no-unresolved': 'off', - 'import/prefer-default-export': 'off', - 'import/no-unused-modules': ['off'], - 'import/no-unassigned-import': 'off', - 'import/no-extraneous-dependencies': [ - 'error', - { - devDependencies: true, - optionalDependencies: false, - peerDependencies: false, - }, - ], - 'no-underscore-dangle': [ - 'off', - { - allow: ['obj'], - allowFunctionParams: false, - allowAfterSuper: true, - allowAfterThis: true, - allowAfterThisConstructor: true, - enforceInMethodNames: true, - }, - ], - 'sort-keys': 'off', - 'comma-dangle': 'off', - '@typescript-eslint/comma-dangle': ['off'], - 'no-use-before-define': 'off', - 'spaced-comment': 'warn', - 'max-len': 'off', - indent: 'off', - 'no-console': 'off', - 'arrow-body-style': 'off', - 'no-multiple-empty-lines': 'warn', - 'no-restricted-globals': 'off', - 'eslint linebreak-style': 'off', - 'object-curly-newline': 'off', - 'no-shadow': 'off', - 'no-void': ['error', { allowAsStatement: true }], - }, - overrides: [ - { - files: ['*.test.ts', '*.test.tsx'], - rules: { - '@typescript-eslint/no-non-null-assertion': 'off', - }, - }, - ], - settings: { - react: { - createClass: 'createReactClass', // Regex for Component Factory to use, - // default to "createReactClass" - pragma: 'React', // Pragma to use, default to "React" - fragment: 'Fragment', // Fragment to use (may be a property of ), default to "Fragment" - version: 'detect', // React version. "detect" automatically picks the version you have installed. - // You can also use `16."off"`, `16.3`, etc, if you want to override the detected value. - // default to latest and warns if missing - // It will default to "detect" in the future - }, - }, - reportUnusedDisableDirectives: true, -}; diff --git a/packages/common/.prettierrc b/packages/common/.prettierrc deleted file mode 100644 index 42e0464d..00000000 --- a/packages/common/.prettierrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "singleQuote": true, - "bracketSpacing": true, - "trailingComma": "es5", - "requirePragma": false, - "arrowParens": "always", - "bracketSameLine": true, - "tabWidth": 2, - "printWidth": 120, - "endOfLine": "lf" -} diff --git a/packages/common/README.MD b/packages/common/README.MD deleted file mode 100644 index 8355c4b0..00000000 --- a/packages/common/README.MD +++ /dev/null @@ -1,3 +0,0 @@ -A local package in the `scaffold-eth-typescript` workspace. Used to store variables, shared functions and env used by `solidity-ts` and `vite-app-ts` so that code is not duplicated. - -NOTE: Make sure you only use relative paths within this package, this ensures it works with yarn workspaces. diff --git a/packages/common/package.json b/packages/common/package.json deleted file mode 100644 index 71524b92..00000000 --- a/packages/common/package.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "name": "@scaffold-eth/common", - "version": "0.0.0", - "author": "Shravan Sunder", - "description": "Common package to be used by solidity-ts and vite-app-ts in the scaffold-eth-typescript workspace", - "license": "MIT", - "private": true, - "main": "./src/index.ts", - "module": "./src/index.ts", - "browser": "./src/index.ts", - "types": "./src/index.ts", - "scripts": { - "contracts:build": "yarn contracts:touch && yarn contracts:toolkit && yarn contracts:external", - "contracts:touch": "yarn shx cp -n './scripts/hardhat_contracts.json.bak' './src/generated/hardhat_contracts.json' && yarn shx cp -n './scripts/foundry_contracts.json.bak' './src/generated/foundry_contracts.json'", - "contracts:toolkit": "yarn shx cp -r '../solidity-ts/generated/contract-types' './src/generated'", - "contracts:external": "yarn shx cp -r './scripts/eth-sdk-config.ts.bak' './src/generated/eth-sdk.config.ts' && yarn eth-sdk -p ./src/generated", - "watch": "tsc -w --noEmit", - "clean": "yarn shx rm -rf ./src/generated/*", - "lint": "eslint --config ./.eslintrc.js --ignore-path ./.eslintignore ./src", - "lint:report": "eslint --config ./.eslintrc.js --ignore-path ./.eslintignore --output-file eslint_report.json --format json ./src", - "format": "yarn prettier -w ./src ", - "format:check": "yarn prettier -c ./src", - "dev:link:components": "yalc link eth-components", - "dev:link:hooks": "yalc link eth-hooks", - "dev:unlink": "yalc remove eth-hooks && yalc remove eth-components" - }, - "dependencies": { - "@ant-design/icons": "^4.7.0", - "@coinbase/wallet-sdk": "^3.5.2", - "@emotion/react": "^11.10.4", - "@ethersproject/abi": "^5.7.0", - "@ethersproject/abstract-provider": "^5.7.0", - "@ethersproject/address": "^5.7.0", - "@ethersproject/bignumber": "^5.7.0", - "@ethersproject/bytes": "^5.7.0", - "@ethersproject/contracts": "^5.7.0", - "@ethersproject/networks": "^5.7.1", - "@ethersproject/providers": "^5.7.1", - "@ethersproject/signing-key": "^5.7.0", - "@ethersproject/solidity": "^5.7.0", - "@ethersproject/units": "^5.7.0", - "@portis/web3": "^4.1.0", - "@ramp-network/ramp-instant-sdk": "^3.2.0", - "@uniswap/sdk": "^3.0.3", - "@uniswap/token-lists": "^1.0.0-beta.30", - "@walletconnect/ethereum-provider": "^1.8.0", - "@walletconnect/web3-provider": "^1.8.0", - "antd": "^4.23.1", - "authereum": "^0.1.14", - "buffer": "^6.0.3", - "eth-components": "3.6.0-beta04", - "eth-hooks": "5.0.2-beta27", - "ethers": "^5.7.1", - "fortmatic": "^2.4.0", - "react": "^18.2.0", - "react-css-theme-switcher": "^0.3.0", - "react-dom": "^18.2.0", - "react-error-boundary": "^3.1.4", - "react-query": "^3.39.2", - "request": "^2.88.2", - "stream": "^0.0.2", - "stream-browserify": "^3.0.0", - "timers-browserify": "^2.0.12", - "ts-invariant": "^0.10.3", - "use-debounce": "^8.0.4", - "usehooks-ts": "^2.6.0", - "util": "^0.12.4", - "walletconnect": "^1.7.8", - "web3modal": "^1.9.9", - "zod": "^3.19.1" - }, - "devDependencies": { - "@dethcrypto/eth-sdk": "0.3.3", - "@types/node": "^16.11.59", - "@types/react": "^18.0.20", - "@types/react-dom": "^18.0.6", - "@typescript-eslint/eslint-plugin": "^5.37.0", - "@typescript-eslint/parser": "^5.37.0", - "bufferutil": "^4.0.6", - "eslint": "^8.23.1", - "eslint-config-airbnb": "^19.0.4", - "eslint-config-airbnb-typescript": "^17.0.0", - "eslint-config-prettier": "^8.5.0", - "eslint-plugin-import": "^2.26.0", - "eslint-plugin-jsx-a11y": "^6.6.1", - "eslint-plugin-mocha": "^10.1.0", - "eslint-plugin-prettier": "^4.2.1", - "eslint-plugin-react": "^7.31.8", - "eslint-plugin-react-hooks": "^4.6.0", - "eslint-plugin-unused-imports": "^2.0.0", - "husky": "^8.0.1", - "lint-staged": "^13.0.3", - "pinst": "^3.0.0", - "prettier": "^2.7.1", - "prettier-eslint": "^15.0.1", - "shx": "^0.3.4", - "ts-node": "^10.9.1", - "ts-patch": "^2.0.2", - "ts-toolbelt": "^9.6.0", - "tsconfig-paths": "^4.1.0", - "typescript": "^4.8.3", - "typescript-transform-paths": "^3.3.1", - "utf-8-validate": "^5.0.9", - "yalc": "^1.0.0-pre.53" - }, - "keywords": [ - "blockchain", - "ethereum", - "react", - "create-eth-app", - "typescript" - ], - "installConfig": { - "hoistingLimits": "workspaces" - } -} diff --git a/packages/common/scripts/eth-sdk-config.ts.bak b/packages/common/scripts/eth-sdk-config.ts.bak deleted file mode 100644 index d217506f..00000000 --- a/packages/common/scripts/eth-sdk-config.ts.bak +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This file was automatically generated from eth-sdk.config.ts.bak - */ - -import { defineConfig } from '@dethcrypto/eth-sdk'; -/* the following import should be relative due to eth-sdk limitations */ -import { contractsByNetworkName } from '../functions/contractsByNetworkName'; - -console.log(contractsByNetworkName); - -export default defineConfig({ - contracts: contractsByNetworkName, - outputPath: './src/generated/external-contracts/', - typechainFlags: { - discriminateTypes: true, - alwaysGenerateOverloads: false, - }, -}); diff --git a/packages/common/scripts/foundry_contracts.json.bak b/packages/common/scripts/foundry_contracts.json.bak deleted file mode 100644 index 9e26dfee..00000000 --- a/packages/common/scripts/foundry_contracts.json.bak +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/packages/common/scripts/hardhat_contracts.json.bak b/packages/common/scripts/hardhat_contracts.json.bak deleted file mode 100644 index 0967ef42..00000000 --- a/packages/common/scripts/hardhat_contracts.json.bak +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/packages/common/scripts/ipfs.js b/packages/common/scripts/ipfs.js deleted file mode 100644 index 2306919d..00000000 --- a/packages/common/scripts/ipfs.js +++ /dev/null @@ -1,89 +0,0 @@ -const ipfsAPI = require("ipfs-http-client"); -const chalk = require("chalk"); -const { clearLine } = require("readline"); - -const { globSource } = ipfsAPI; - -const infura = { host: "ipfs.infura.io", port: "5001", protocol: "https" }; -// run your own ipfs daemon: https://docs.ipfs.io/how-to/command-line-quick-start/#install-ipfs -// const localhost = { host: "localhost", port: "5001", protocol: "http" }; - -const ipfs = ipfsAPI(infura); - -const ipfsGateway = "https://ipfs.io/ipfs/"; -const ipnsGateway = "https://ipfs.io/ipns/"; - -const addOptions = { - pin: true, -}; - -const pushDirectoryToIPFS = async path => { - try { - const response = await ipfs.add(globSource(path, { recursive: true }), addOptions); - return response; - } catch (e) { - return {}; - } -}; - -const publishHashToIPNS = async ipfsHash => { - try { - const response = await ipfs.name.publish(`/ipfs/${ipfsHash}`); - return response; - } catch (e) { - return {}; - } -}; - -const nodeMayAllowPublish = ipfsClient => { - // You must have your own IPFS node in order to publish an IPNS name - // This contains a blacklist of known nodes which do not allow users to publish IPNS names. - const nonPublishingNodes = ["ipfs.infura.io"]; - const { host } = ipfsClient.getEndpointConfig(); - return !nonPublishingNodes.some(nodeUrl => host.includes(nodeUrl)); -}; - -const deploy = async () => { - console.log("🛰 Sending to IPFS..."); - const { cid } = await pushDirectoryToIPFS("./build"); - if (!cid) { - console.log(`📡 App deployment failed`); - return false; - } - console.log(`📡 App deployed to IPFS with hash: ${chalk.cyan(cid.toString())}`); - - console.log(); - - let ipnsName = ""; - if (nodeMayAllowPublish(ipfs)) { - console.log(`✍️ Publishing /ipfs/${cid.toString()} to IPNS...`); - process.stdout.write(" Publishing to IPNS can take up to roughly two minutes.\r"); - ipnsName = (await publishHashToIPNS(cid.toString())).name; - clearLine(process.stdout, 0); - if (!ipnsName) { - console.log(" Publishing IPNS name on node failed."); - } - console.log(`🔖 App published to IPNS with name: ${chalk.cyan(ipnsName)}`); - console.log(); - } - - console.log("🚀 Deployment to IPFS complete!"); - console.log(); - - console.log(`Use the link${ipnsName && "s"} below to access your app:`); - console.log(` IPFS: ${chalk.cyan(`${ipfsGateway}${cid.toString()}`)}`); - if (ipnsName) { - console.log(` IPNS: ${chalk.cyan(`${ipnsGateway}${ipnsName}`)}`); - console.log(); - console.log( - "Each new deployment will have a unique IPFS hash while the IPNS name will always point at the most recent deployment.", - ); - console.log( - "It is recommended that you share the IPNS link so that people always see the newest version of your app.", - ); - } - console.log(); - return true; -}; - -deploy(); diff --git a/packages/common/src/components/ErrorFallback.tsx b/packages/common/src/components/ErrorFallback.tsx deleted file mode 100644 index 35aba8c6..00000000 --- a/packages/common/src/components/ErrorFallback.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import React, { FC } from 'react'; -import { ErrorBoundary, FallbackProps } from 'react-error-boundary'; - -const componentMessages = (error: Error): { msg: string; showDetails: boolean; msgDetails: string } => { - const msg = 'Uhoh! There was an error!'; - const showDetails = true; // dev flag needed //todo - - let msgDetails = error?.stack?.slice(0, 400) ?? ''; - msgDetails += '\n\r...\n\r'; - if ((error?.stack?.length ?? 0) > 600) { - msgDetails += error?.stack?.slice(error?.stack?.length - 600, error?.stack?.length); - } - - return { msg, showDetails, msgDetails }; -}; - -const consoleLog = (error: Error, componentStack: string | undefined): void => { - console.log('--------------------'); - console.log('ErrorBoundary'); - console.log(error.stack); - console.log(componentStack); - console.log('--------------------'); -}; - -export const ErrorFallback: FC = ({ error }) => { - // TODO in future, change this so that it takes dev or production into account when rendering - // https://github.com/bvaughn/react-error-boundary - - const { msg, showDetails, msgDetails } = componentMessages(error); - consoleLog(error, error?.stack ?? ''); - - return ( - <> - {!showDetails &&
{msg}
} - {showDetails && ( - <> -
{msg}
-
-
{msgDetails}
-
- - )} - - ); -}; -export { ErrorBoundary }; diff --git a/packages/common/src/components/FaucetHintButton.tsx b/packages/common/src/components/FaucetHintButton.tsx deleted file mode 100644 index e436b43b..00000000 --- a/packages/common/src/components/FaucetHintButton.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { parseEther } from '@ethersproject/units'; -import { Button } from 'antd'; -import { transactor } from 'eth-components/functions'; -import { IEthComponentsSettings } from 'eth-components/models'; -import { useBalance } from 'eth-hooks'; -import { useEthersAppContext } from 'eth-hooks/context'; -import { IEthersContext } from 'eth-hooks/models'; -import { utils } from 'ethers'; -import React, { FC, useMemo, useState } from 'react'; -import { useDebounce } from 'use-debounce'; - -import { IScaffoldAppProviders } from '~common/models/IScaffoldAppProviders'; - -/** - * Is Faucet available? - * @param scaffoldAppProviders - * @param ethersAppContext - * @returns - */ -export const getFaucetAvailable = ( - scaffoldAppProviders: IScaffoldAppProviders, - ethersAppContext: IEthersContext, - faucetEnabled: boolean -): boolean => { - const result = - (ethersAppContext?.provider && - ethersAppContext?.chainId != null && - ethersAppContext?.chainId === scaffoldAppProviders.currentTargetNetwork.chainId && - scaffoldAppProviders.currentTargetNetwork.name === 'localhost') ?? - false; - return result && faucetEnabled; -}; - -interface IFaucetButton { - scaffoldAppProviders: IScaffoldAppProviders; - gasPrice: number | undefined; - faucetEnabled: boolean; - ethComponentSettings: IEthComponentsSettings; -} - -export const FaucetHintButton: FC = (props) => { - const ethersAppContext = useEthersAppContext(); - - const [yourLocalBalance] = useBalance(ethersAppContext.account ?? ''); - const signer = props.scaffoldAppProviders.localAdaptor?.signer; - /** - * create transactor for faucet - */ - const faucetTx = transactor(props.ethComponentSettings, signer, undefined, undefined, true); - - /** - * facuet is only available on localhost - */ - const isAvailable = getFaucetAvailable(props.scaffoldAppProviders, ethersAppContext, props.faucetEnabled); - const [faucetAvailable] = useDebounce(isAvailable, 500, { - trailing: true, - }); - const [faucetClicked, setFaucetClicked] = useState(false); - - const faucetHint = useMemo(() => { - const min = parseFloat(utils.formatUnits(yourLocalBalance?.toBigInt() ?? 0, 'ether')); - const lowFunds = yourLocalBalance && min < 0.002; - const allowFaucet = faucetAvailable && !faucetClicked && lowFunds; - - if (allowFaucet && ethersAppContext?.account != null) { - return ( -
- -
- ); - } else { - return <>; - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [yourLocalBalance, faucetAvailable, ethersAppContext?.account, faucetTx]); - - return <> {faucetHint} ; -}; diff --git a/packages/common/src/components/Ramp.tsx b/packages/common/src/components/Ramp.tsx deleted file mode 100644 index d64b8fef..00000000 --- a/packages/common/src/components/Ramp.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import { DollarCircleOutlined } from '@ant-design/icons'; -import { RampInstantSDK } from '@ramp-network/ramp-instant-sdk'; -import { Button, Divider, Modal } from 'antd'; -import React, { useState, FC } from 'react'; - -import { TNetworkDefinition } from '~common/constants'; - -interface IRampProps { - price: number; - address: string; - networks: Record; - color?: string; -} - -/** - * Displays current ETH price and gives options to buy ETH through Wyre/Ramp/Coinbase or get through Rinkeby/Ropsten/Kovan/Goerli - * - ~ Features ~ - - - Ramp opens directly in the application, component uses RampInstantSDK - - Provide price={price} and current ETH price will be displayed - - Provide address={address} and your address will be pasted into Wyre/Ramp instantly - * @param props - * @returns - */ -export const Ramp: FC = (props) => { - const [modalUp, setModalUp] = useState('down'); - - const type = 'default'; - - const allFaucets = []; - for (const n in props.networks) { - if (props.networks[n].chainId !== 31337 && props.networks[n].chainId !== 1) { - allFaucets.push( -

- -

- ); - } - } - - return ( -
- - { - setModalUp('down'); - }} - footer={[ - , - ]}> -

- -

-

- {' '} - -

- -

- -

- - - -

Testnet ETH

- - {allFaucets} -
-
- ); -}; diff --git a/packages/common/src/components/ThemeSwitcher.tsx b/packages/common/src/components/ThemeSwitcher.tsx deleted file mode 100644 index 2a651073..00000000 --- a/packages/common/src/components/ThemeSwitcher.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { Switch } from 'antd'; -import { useEthersAppContext } from 'eth-hooks/context'; -import React, { FC, useEffect, useState } from 'react'; -import { useThemeSwitcher } from 'react-css-theme-switcher'; -import { useIsomorphicLayoutEffect } from 'usehooks-ts'; - -const loadTheme = (): string => { - if (typeof window != null) { - return window?.localStorage?.getItem('theme') ?? 'light'; - } - return 'light'; -}; - -const saveTheme = (theme: string): void => { - if (typeof window != null) { - window?.localStorage?.setItem('theme', theme); - } -}; - -export const ThemeSwitcher: FC = () => { - const [isDarkMode, setIsDarkMode] = useState(false); - const { switcher, currentTheme, status, themes } = useThemeSwitcher(); - const ethersAppContext = useEthersAppContext(); - - useEffect(() => { - saveTheme(currentTheme ?? ''); - if (currentTheme === 'light' || currentTheme === 'dark') { - ethersAppContext?.setModalTheme?.(currentTheme); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [currentTheme]); - - const toggleTheme = (isChecked: boolean): void => { - setIsDarkMode(isChecked); - switcher({ theme: isChecked ? themes.dark : themes.light }); - ethersAppContext?.setModalTheme?.(isDarkMode ? 'dark' : 'light'); - }; - - useIsomorphicLayoutEffect(() => { - const theme = loadTheme(); - setIsDarkMode(theme === 'dark'); - toggleTheme(theme === 'dark'); - }, []); - - if (status === 'loading' || status === 'idle') { - return <>; - } - - return ( -
- {currentTheme === 'light' ? '☀️' : '🌜'} - -
- ); -}; diff --git a/packages/common/src/components/context/contractContext.ts b/packages/common/src/components/context/contractContext.ts deleted file mode 100644 index 273e5d84..00000000 --- a/packages/common/src/components/context/contractContext.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { contractsContextFactory } from 'eth-hooks/context'; - -import { appContractsConfig } from '~common/config'; - -/** - * This file initalises the contractContextFactory and exports the types - * 🙅🏽‍♂️ You don't need to change this file. - */ - -/** - * ### Summary - * This type describes all your contracts, it is the return of {@link getappContractsConfig} - */ -export type TAppConnectorList = ReturnType; - -/** - * #### Summary - * Call contractContextFactory with the `appContractsConfig` from `appContracts.config.ts` - * - * ##### Notes - * - This will create your ContractContext used by App.tsx - * - This will create your hooks to access contracts - * - The type is your contract connect config. - */ -export const { useAppContracts, useLoadAppContracts, useConnectAppContracts, useContractsAppStore } = - contractsContextFactory(appContractsConfig); diff --git a/packages/common/src/components/context/index.ts b/packages/common/src/components/context/index.ts deleted file mode 100644 index 56dd3dcc..00000000 --- a/packages/common/src/components/context/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './contractContext'; diff --git a/packages/common/src/components/hooks/index.ts b/packages/common/src/components/hooks/index.ts deleted file mode 100644 index 854fc0b5..00000000 --- a/packages/common/src/components/hooks/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './useAntNotification'; -export * from './useBurnerFallback'; -export * from './useGetLoginConnector'; -export * from './useGetWeb3ModalConfig'; -export * from './useScaffoldAppProviders'; diff --git a/packages/common/src/components/hooks/useAntNotification.ts b/packages/common/src/components/hooks/useAntNotification.ts deleted file mode 100644 index 0d50bef1..00000000 --- a/packages/common/src/components/hooks/useAntNotification.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { notification } from 'antd'; -import { NotificationInstance } from 'antd/lib/notification'; -import { ReactElement, useEffect } from 'react'; - -let notificationApi: NotificationInstance; - -export const useAntNotification = (): NotificationInstance => { - return notificationApi; -}; - -export const useCreateAntNotificationHolder = (): ReactElement => { - const [api, notificationHolder] = notification?.useNotification(); - - useEffect(() => { - notificationApi = api; - }, [api]); - - return notificationHolder; -}; diff --git a/packages/common/src/components/hooks/useBurnerFallback.ts b/packages/common/src/components/hooks/useBurnerFallback.ts deleted file mode 100644 index 87db2ca9..00000000 --- a/packages/common/src/components/hooks/useBurnerFallback.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { useBurnerSigner } from 'eth-hooks'; -import { useEthersAppContext } from 'eth-hooks/context'; -import { useEffect } from 'react'; - -import { IScaffoldAppProviders } from '../../models/IScaffoldAppProviders'; - -import { networkDefinitions } from '~common/constants/networkDefinitions'; - -export const useBurnerFallback = (appProviders: IScaffoldAppProviders, enable: boolean): void => { - const ethersAppContext = useEthersAppContext(); - const burnerFallback = useBurnerSigner(appProviders.localAdaptor?.provider); - const localAddress = appProviders.localAdaptor?.signer; - - useEffect(() => { - const sameUrl = - ethersAppContext.provider?.connection?.url === networkDefinitions.localhost.rpcUrl || - ethersAppContext.provider?.connection?.url === - networkDefinitions.localhost.rpcUrl.replace('127.0.0.1', 'localhost'); - /** - * if the current provider is local provider then use the burner fallback - */ - if ( - burnerFallback?.signer && - burnerFallback?.account !== ethersAppContext.account && - ethersAppContext.chainId === networkDefinitions.localhost.chainId && - sameUrl && - ethersAppContext.changeSigner && - localAddress != null && - enable - ) { - void ethersAppContext.changeSigner?.(burnerFallback.signer); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ - ethersAppContext.account, - localAddress, - ethersAppContext.changeSigner, - burnerFallback.signer, - burnerFallback?.account, - enable, - ]); -}; diff --git a/packages/common/src/components/hooks/useGetLoginConnector.ts b/packages/common/src/components/hooks/useGetLoginConnector.ts deleted file mode 100644 index 9885ff11..00000000 --- a/packages/common/src/components/hooks/useGetLoginConnector.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { EthersModalConnector } from 'eth-hooks/context'; -import { TCreateEthersModalConnector } from 'eth-hooks/models'; -import { useCallback } from 'react'; -import { ICoreOptions } from 'web3modal'; - -export const useGetCreateLoginConnector = ( - currentTheme: string | undefined, - web3Config: Partial | undefined -): TCreateEthersModalConnector => { - const createLoginConnector: TCreateEthersModalConnector = useCallback( - (id?: string) => { - if (web3Config) { - const connector = new EthersModalConnector( - { ...web3Config, theme: currentTheme }, - { reloadOnNetworkChange: false, immutableProvider: false }, - id - ); - return connector; - } - }, - [web3Config, currentTheme] - ); - - return createLoginConnector; -}; diff --git a/packages/common/src/components/hooks/useGetWeb3ModalConfig.ts b/packages/common/src/components/hooks/useGetWeb3ModalConfig.ts deleted file mode 100644 index e0b04541..00000000 --- a/packages/common/src/components/hooks/useGetWeb3ModalConfig.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { useEffect, useState } from 'react'; -import { invariant } from 'ts-invariant'; -import { ICoreOptions } from 'web3modal'; - -export const useGetWeb3ModalConfig = ( - hasLocalProvider: boolean = false, - config: { infuraId: string } -): Partial | undefined => { - const [data, setData] = useState(false); - const [web3Config, setWeb3Config] = useState?.>(); - - useEffect(() => { - // import async to split bundles - const importedConfig = import('../../config/web3Modal.config'); - - importedConfig - .then((getter) => { - getter - .getWeb3ModalConfig(hasLocalProvider, config) - .then((config) => { - setWeb3Config(config); - }) - .catch((e) => { - invariant.error('Web3Modal", "cannot load web3 modal config', e); - }); - }) - .catch((e) => { - invariant.error('Web3Modal", "cannot load web3 modal config', e); - }); - }, []); - - return web3Config; -}; diff --git a/packages/common/src/components/hooks/useScaffoldAppProviders.ts b/packages/common/src/components/hooks/useScaffoldAppProviders.ts deleted file mode 100644 index 3c282428..00000000 --- a/packages/common/src/components/hooks/useScaffoldAppProviders.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { StaticJsonRpcProvider } from '@ethersproject/providers'; -import { useEthersAdaptorFromProviderOrSigners } from 'eth-hooks'; -import { EthersModalConnector, TEthersModalConnector, useEthersAppContext } from 'eth-hooks/context'; -import { useEffect } from 'react'; -import { useThemeSwitcher } from 'react-css-theme-switcher'; - -import { useGetCreateLoginConnector } from '~common/components/hooks/useGetLoginConnector'; -import { useGetWeb3ModalConfig } from '~common/components/hooks/useGetWeb3ModalConfig'; -import { customWeb3ModalProviders } from '~common/config/web3Modal.config'; -import { TNetworkDefinition } from '~common/constants'; -import { IScaffoldAppProviders } from '~common/models/IScaffoldAppProviders'; - -export const useScaffoldAppProviders = (config: { - mainnetProvider: StaticJsonRpcProvider | undefined; - localProvider: StaticJsonRpcProvider | undefined; - targetNetworks: { [chainId: number]: TNetworkDefinition }; - infuraId: string; - connectToBurnerAutomatically: boolean; -}): IScaffoldAppProviders => { - const ethersAppContext = useEthersAppContext(); - const [mainnetAdaptor] = useEthersAdaptorFromProviderOrSigners(config.mainnetProvider); - const [localAdaptor] = useEthersAdaptorFromProviderOrSigners(config.localProvider); - - const hasLocalProvider = config?.localProvider !== undefined; - const web3Config = useGetWeb3ModalConfig(hasLocalProvider, { infuraId: config.infuraId }); - - const { currentTheme } = useThemeSwitcher(); - - const createLoginConnector = useGetCreateLoginConnector(currentTheme, web3Config); - - useEffect(() => { - /** - * This is for to auto connect to the burner wallet when there is no cached provier - * you can turn it off by settting {@link const_ConnectToBurnerOnFirstLoad} to false - * @param connector - * @returns - */ - const autoConnectToBurner = (connector: TEthersModalConnector | undefined): TEthersModalConnector | undefined => { - let newConnector = connector; - if (config.connectToBurnerAutomatically && connector && connector?.loadWeb3Modal) { - connector.loadWeb3Modal(); - if (connector != null && !connector.hasCachedProvider()) { - newConnector = new EthersModalConnector( - { ...web3Config, theme: currentTheme }, - { reloadOnNetworkChange: false, immutableProvider: false }, - customWeb3ModalProviders.localhostKey - ); - } - } - return newConnector; - }; - - if (!ethersAppContext.active && createLoginConnector) { - let connector = createLoginConnector(undefined); - connector = autoConnectToBurner(connector); - if (connector) void ethersAppContext.activate(connector); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [web3Config, config.connectToBurnerAutomatically, createLoginConnector]); - - const currentTargetNetwork = - ethersAppContext.chainId != null && config.targetNetworks[ethersAppContext.chainId] - ? config.targetNetworks[ethersAppContext.chainId] - : Object.values(config.targetNetworks)[0]; - - return { - currentProvider: ethersAppContext.provider ?? config.localProvider, - mainnetAdaptor: mainnetAdaptor, - localAdaptor: localAdaptor, - currentTargetNetwork: currentTargetNetwork, - targetNetworks: config.targetNetworks, - createLoginConnector: createLoginConnector, - }; -}; diff --git a/packages/common/src/components/index.ts b/packages/common/src/components/index.ts deleted file mode 100644 index c71aeee4..00000000 --- a/packages/common/src/components/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './ErrorFallback'; -export * from './FaucetHintButton'; -export * from './Ramp'; -export * from './ThemeSwitcher'; -export * from './hooks'; diff --git a/packages/common/src/config/appContracts.config.ts b/packages/common/src/config/appContracts.config.ts deleted file mode 100644 index fe31869c..00000000 --- a/packages/common/src/config/appContracts.config.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-function-return-type */ -import { - createConnectorForExternalAbi, - createConnectorForExternalContract, - createConnectorForFoundryContract, - createConnectorForHardhatContract, -} from 'eth-hooks/context'; -import { invariant } from 'ts-invariant'; - -import { externalContractsAddressMap } from './externalContracts.config'; - -import * as toolkitContracts from '~common/generated/contract-types/'; -import * as externalContracts from '~common/generated/external-contracts/esm/types'; -import foundryDeployedContractsJson from '~common/generated/foundry_contracts.json'; -import hardhatDeployedContractsJson from '~common/generated/hardhat_contracts.json'; -import { scaffoldConfig } from '~common/scaffold.config'; - -/** - * ⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️ - * ### Instructions - * 1. edit externalContracts.config.ts to add your external contract addresses. - * 2. edit `appContractsConfig` function below and add them to the list - * 3. run `yarn contracts:build` to generate types for contracts - * 4. run `yarn deploy` to generate hardhat_contracts.json - * - * ### Summary - * - called by useAppContracts - * @returns - */ -export const appContractsConfig = () => { - try { - const result = { - // -------------------------------------------------- - // 🙋🏽‍♂️ Contracts examples either using hardhat or foundry - // -------------------------------------------------- - YourContract: - scaffoldConfig.build.solidityToolkit === 'hardhat' - ? createConnectorForHardhatContract( - 'YourContract', - toolkitContracts.YourContract__factory, - hardhatDeployedContractsJson - ) - : createConnectorForFoundryContract( - 'YourContract', - toolkitContracts.YourContract__factory, - foundryDeployedContractsJson - ), - - YourNFT: - scaffoldConfig.build.solidityToolkit === 'hardhat' - ? createConnectorForHardhatContract( - 'YourNFT', - toolkitContracts.YourNFT__factory, - hardhatDeployedContractsJson - ) - : createConnectorForFoundryContract( - 'YourNFT', - toolkitContracts.YourNFT__factory, - foundryDeployedContractsJson - ), - - // -------------------------------------------------- - // 🙋🏽‍♂️ Add your external contracts here, make sure to define the address in `externalContractsConfig.ts`Í - // -------------------------------------------------- - DAI: createConnectorForExternalContract('DAI', externalContracts.DAI__factory, externalContractsAddressMap), - - // -------------------------------------------------- - // 🙋🏽‍♂️ Add your external abi here (unverified contracts)` - // -------------------------------------------------- - YourContractFromAbi: createConnectorForExternalAbi( - 'YourContract', - { - [1235]: { - address: 'xxx', - }, - }, - toolkitContracts.YourContract__factory.abi - // optional if you have a connect function: externalContracts.YourContract__factory.connect - ), - } as const; - - return result; - } catch (e) { - invariant.error( - '❌ appContractsConfig: ERROR with loading contracts please run `yarn contracts:build or yarn contracts:rebuild`. Then run `yarn deploy`!' - ); - invariant.error(e); - throw e; - } -}; diff --git a/packages/common/src/config/externalContracts.config.ts b/packages/common/src/config/externalContracts.config.ts deleted file mode 100644 index 1f941f91..00000000 --- a/packages/common/src/config/externalContracts.config.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { NetworkID } from '@dethcrypto/eth-sdk/dist/abi-management/networks'; -import { TExternalContractsAddressMap } from 'eth-hooks/models'; - -/** - * ⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️⛳️ - * #### Instructions - * - Add your contracts to the list here - * - The format is described by {@link TExternalContractsAddressMap} - * - * ### Summary - * The list of external contracts use by the app. - * it is used to generate the type definitions for the external contracts by `yarn contracts:build` - * provide the name and address of the external contract and the definition will be generated - */ -export const externalContractsAddressMap: TExternalContractsAddressMap = { - [NetworkID.MAINNET]: { - DAI: '0x6b175474e89094c44da98b954eedeac495271d0f', - }, - // [NetworkID.POLYGON]: { - // DAI: '0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063', - // }, -}; diff --git a/packages/common/src/config/index.ts b/packages/common/src/config/index.ts deleted file mode 100644 index ac90a407..00000000 --- a/packages/common/src/config/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './appContracts.config'; -export * from './externalContracts.config'; -export * from './web3Modal.config'; diff --git a/packages/common/src/config/web3Modal.config.ts b/packages/common/src/config/web3Modal.config.ts deleted file mode 100644 index e9a5406f..00000000 --- a/packages/common/src/config/web3Modal.config.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { ICoreOptions } from 'web3modal'; - -import { networkDefinitions } from '~common/constants/networkDefinitions'; - -export const customWeb3ModalProviders = { - coinbaseKey: 'custom-walletlink', - localhostKey: 'custom-localhost', -} as const; - -export const getWeb3ModalConfig = async ( - hasLocalProvider: boolean, - config: { infuraId: string } -): Promise> => { - const providerOptions: Record = {}; - - // === PORTIS - try { - const Portis = (await import('@portis/web3')).default; - providerOptions.portis = { - display: { - logo: 'https://user-images.githubusercontent.com/9419140/128913641-d025bc0c-e059-42de-a57b-422f196867ce.png', - name: 'Portis', - description: 'Connect to Portis App', - }, - package: Portis, - options: { - id: '6255fb2b-58c8-433b-a2c9-62098c05ddc9', - }, - }; - } catch (e) { - console.log('Failed to load config for web3 connector Portis: ', e); - } - - // === FORTMATIC - try { - const Fortmatic = (await import('fortmatic')).default; - providerOptions.fortmatic = { - package: Fortmatic, - options: { - key: 'pk_live_5A7C91B2FC585A17', - }, - }; - } catch (e) { - console.log('Failed to load config for web3 connector Fortmatic: ', e); - } - - // === COINBASE WALLETLINK - try { - const { CoinbaseWalletSDK: WalletLink } = await import('@coinbase/wallet-sdk'); - - // note: ⚠️ meta mask and coinbase wallets may clash. - // you might need to check this: https://github.com/Web3Modal/web3modal/issues/316 - - // Coinbase walletLink init - const walletLink = new WalletLink({ - appName: 'coinbase', - }); - // WalletLink provider - const walletLinkProvider = walletLink.makeWeb3Provider(`https://mainnet.infura.io/v3/${config.infuraId}`, 1); - - const coinbaseWalletLink = { - display: { - logo: 'https://play-lh.googleusercontent.com/PjoJoG27miSglVBXoXrxBSLveV6e3EeBPpNY55aiUUBM9Q1RCETKCOqdOkX2ZydqVf0', - name: 'Coinbase', - description: 'Connect to your Coinbase Wallet (not coinbase.com)', - }, - package: walletLinkProvider, - connector: async (provider: any, _options: any): Promise => { - await provider.enable(); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return provider; - }, - }; - providerOptions[customWeb3ModalProviders.coinbaseKey] = coinbaseWalletLink; - } catch (e) { - console.log('Failed to load config for web3 connector Coinbase WalletLink: ', e); - } - - // === WALLETCONNECT - try { - const WalletConnectProvider = (await import('@walletconnect/ethereum-provider')).default; - const walletConnectEthereum = { - package: WalletConnectProvider, - options: { - bridge: 'https://polygon.bridge.walletconnect.org', - infuraId: config.infuraId, - rpc: { - 1: `https://mainnet.infura.io/v3/${config.infuraId}`, - 42: `https://kovan.infura.io/v3/${config.infuraId}`, - 100: 'https://dai.poa.network', - }, - }, - }; - providerOptions.walletconnect = walletConnectEthereum; - } catch (e) { - console.log('Failed to load config for web3 connector WalletConnect: ', e); - } - - // === AUTHEREUM - try { - const Authereum = (await import('authereum')).default; - providerOptions.authereum = { - package: Authereum, - }; - } catch (e) { - console.log('Failed to load config for web3 connector Authereum: ', e); - } - - // === LOCALHOST STATIC - try { - if (hasLocalProvider) { - const { ConnectToStaticJsonRpcProvider } = await import('eth-hooks/context'); - const { StaticJsonRpcProvider } = await import('@ethersproject/providers'); - const localhostStaticConnector = { - display: { - logo: 'https://avatars.githubusercontent.com/u/56928858?s=200&v=4', - name: 'BurnerWallet', - description: '🔥 Connect to localhost with a burner wallet 🔥', - }, - package: StaticJsonRpcProvider, - connector: ConnectToStaticJsonRpcProvider, - options: { - chainId: networkDefinitions.localhost.chainId, - rpc: { - [networkDefinitions.localhost.chainId]: networkDefinitions.localhost.rpcUrl, - }, - }, - }; - providerOptions[customWeb3ModalProviders.localhostKey] = localhostStaticConnector; - } - } catch (e) { - console.log('Failed to load config for Localhost Static Connector: ', e); - } - - // network: 'mainnet', // Optional. If using WalletConnect on xDai, change network to "xdai" and add RPC info below for xDai chain. - - // const torus = { - // package: Torus, - // options: { - // networkParams: { - // host: 'https://localhost:8545', - // chainId: 1337, - // networkId: 1337, // optional - // }, - // config: { - // buildEnv: 'development', - // }, - // }, - // }; - - return { - cacheProvider: true, - theme: 'light', - providerOptions, - }; -}; diff --git a/packages/common/src/constants/addresses.ts b/packages/common/src/constants/addresses.ts deleted file mode 100644 index d6835032..00000000 --- a/packages/common/src/constants/addresses.ts +++ /dev/null @@ -1,2 +0,0 @@ -// EXTERNAL CONTRACTS -export const DAI_ADDRESS = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; // dai-mainnet diff --git a/packages/common/src/constants/hardhatNamedAccounts.ts b/packages/common/src/constants/hardhatNamedAccounts.ts deleted file mode 100644 index 12b5fb32..00000000 --- a/packages/common/src/constants/hardhatNamedAccounts.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { TNetworkNamesList } from '~common/models/scaffoldConfigTypes'; - -type TChain = TNetworkNamesList | number; -type TAccountName = 'deployer' | 'user1' | 'user2' | 'user3' | 'user4' | 'user5' | 'governance'; - -/** - * The default account to use for hardhat. For example 0 will take by default take the first account of hardhat - */ -type TDefaultAccount = { - ['default']: number | string; -}; - -/** - * Named accounts to be used by hardaht. See docs: https://github.com/wighawag/hardhat-deploy#1-namedaccounts-ability-to-name-addresses - * - * the values are account addresses, or account number in hardhat - */ -export const hardhatNamedAccounts: { - [name in TAccountName]: Readonly & TDefaultAccount>; -} = { - deployer: { - default: 0, // here this will by default take the first account as deployer - 1: 0, // similarly on mainnet it will take the first account as deployer. Note though that depending on how hardhat network are configured, the account 0 on one network can be different than on another - 4: '0xA296a3d5F026953e17F472B497eC29a5631FB51B', // but for rinkeby it will be a specific address - goerli: '0x84b9514E013710b9dD0811c9Fe46b837a4A0d8E0', // it can also specify a specific netwotk name (specified in hardhat.config.js) - }, - user1: { - default: 1, - }, - user2: { - default: 2, - }, - user3: { - default: 3, - }, - user4: { - default: 4, - }, - user5: { - default: 5, - }, - governance: { - default: 10, - }, -} as const; diff --git a/packages/common/src/constants/index.ts b/packages/common/src/constants/index.ts deleted file mode 100644 index a8b2499c..00000000 --- a/packages/common/src/constants/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './addresses'; -export * from './hardhatNamedAccounts'; -export * from './networkDefinitions'; diff --git a/packages/common/src/constants/networkDefinitions.ts b/packages/common/src/constants/networkDefinitions.ts deleted file mode 100644 index f0fbd870..00000000 --- a/packages/common/src/constants/networkDefinitions.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { TNetworkInfo } from 'eth-hooks/models'; - -import { TNetworkNamesList } from '~common/models'; - -const INFURA_ID = process.env.VITE_RPC_MAINNET_INFURA; - -let hostname = 'localhost'; -if (typeof window !== 'undefined' && window != null) { - hostname = window?.location?.hostname ?? 'localhost'; -} - -export type TNetworkDefinition = TNetworkInfo & { - color: string; -}; - -export const networkDefinitions: Record = { - localhost: { - name: 'localhost', - color: '#666666', - chainId: 31337, - blockExplorer: '', - rpcUrl: 'http://' + hostname + ':8545', - }, - mainnet: { - name: 'mainnet', - color: '#ff8b9e', - chainId: 1, - rpcUrl: `https://mainnet.infura.io/v3/${INFURA_ID}`, - blockExplorer: 'https://etherscan.io/', - }, - kovan: { - name: 'kovan', - color: '#7003DD', - chainId: 42, - rpcUrl: `https://kovan.infura.io/v3/${INFURA_ID}`, - blockExplorer: 'https://kovan.etherscan.io/', - faucet: 'https://gitter.im/kovan-testnet/faucet', // https://faucet.kovan.network/ - }, - rinkeby: { - name: 'rinkeby', - color: '#e0d068', - chainId: 4, - rpcUrl: `https://rinkeby.infura.io/v3/${INFURA_ID}`, - faucet: 'https://faucet.rinkeby.io/', - blockExplorer: 'https://rinkeby.etherscan.io/', - }, - ropsten: { - name: 'ropsten', - color: '#F60D09', - chainId: 3, - faucet: 'https://faucet.ropsten.be/', - blockExplorer: 'https://ropsten.etherscan.io/', - rpcUrl: `https://ropsten.infura.io/v3/${INFURA_ID}`, - }, - goerli: { - name: 'goerli', - color: '#0975F6', - chainId: 5, - faucet: 'https://goerli-faucet.slock.it/', - blockExplorer: 'https://goerli.etherscan.io/', - rpcUrl: `https://goerli.infura.io/v3/${INFURA_ID}`, - }, - xdai: { - name: 'xdai', - color: '#48a9a6', - chainId: 100, - price: 1, - gasPrice: 1200000000, - rpcUrl: 'https://dai.poa.network', - faucet: 'https://xdai-faucet.top/', - blockExplorer: 'https://blockscout.com/poa/xdai/', - }, - polygon: { - name: 'polygon', - color: '#2bbdf7', - chainId: 137, - price: 1, - gasPrice: 3500000000, - rpcUrl: 'https://matic-mainnet.chainstacklabs.com', - faucet: 'https://faucet.matic.network', - blockExplorer: 'https://polygonscan.com', - }, - mumbai: { - name: 'mumbai', - color: '#92D9FA', - chainId: 80001, - price: 1, - gasPrice: 2000000000, - rpcUrl: 'https://matic-mumbai.chainstacklabs.com', - faucet: 'https://faucet.matic.network', - blockExplorer: 'https://mumbai.polygonscan.com/', - }, - rinkebyArbitrum: { - name: 'Arbitrum Testnet', - color: '#50a0ea', - chainId: 421611, - blockExplorer: 'https://rinkeby-explorer.arbitrum.io/#/', - rpcUrl: `https://rinkeby.arbitrum.io/rpc`, - }, - arbitrum: { - name: 'Arbitrum', - color: '#50a0ea', - chainId: 42161, - blockExplorer: 'https://explorer.arbitrum.io/#/', - rpcUrl: `https://arb1.arbitrum.io/rpc`, - gasPrice: 0, - }, - kovanOptimism: { - name: 'kovanOptimism', - color: '#f01a37', - chainId: 69, - blockExplorer: 'https://kovan-optimistic.etherscan.io/', - rpcUrl: `https://kovan.optimism.io`, - gasPrice: 0, - }, - optimism: { - name: 'optimism', - color: '#f01a37', - chainId: 10, - blockExplorer: 'https://optimistic.etherscan.io/', - rpcUrl: `https://mainnet.optimism.io`, - }, - fujiAvalanche: { - name: 'fujiAvalanche', - color: '#666666', - chainId: 43113, - blockExplorer: 'https://cchain.explorer.avax-test.network/', - rpcUrl: `https://api.avax-test.network/ext/bc/C/rpc`, - gasPrice: 225000000000, - }, - avalanche: { - name: 'avalanche', - color: '#666666', - chainId: 43114, - blockExplorer: 'https://cchain.explorer.avax.network/', - rpcUrl: `https://api.avax.network/ext/bc/C/rpc`, - gasPrice: 225000000000, - }, - fantom: { - name: 'fantom', - color: '#1969ff', - chainId: 250, - blockExplorer: 'https://ftmscan.com/', - rpcUrl: `https://rpcapi.fantom.network`, - gasPrice: 1000000000, - }, - testnetFantom: { - name: 'testnetFantom', - color: '#1969ff', - chainId: 4002, - blockExplorer: 'https://testnet.ftmscan.com/', - rpcUrl: `https://rpc.testnet.fantom.network`, - gasPrice: 1000000000, - faucet: 'https://faucet.fantom.network/', - }, -} as const; diff --git a/packages/common/src/functions/contractsByNetworkName.ts b/packages/common/src/functions/contractsByNetworkName.ts deleted file mode 100644 index b74fbbdf..00000000 --- a/packages/common/src/functions/contractsByNetworkName.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { networkIDtoSymbol } from '@dethcrypto/eth-sdk/dist/abi-management/networks'; - -/* the following import should be relative due to eth-sdk limitations */ -import { externalContractsAddressMap } from '../config/externalContracts.config'; - -/** - * used by eth-sdk and `yarn contracts:build` - */ -export const contractsByNetworkName: Record = {}; -Object.keys(externalContractsAddressMap) - .map(Number) - .forEach((chainId) => { - const networkName = networkIDtoSymbol[chainId as keyof typeof networkIDtoSymbol]; - contractsByNetworkName[networkName] = externalContractsAddressMap[chainId]; - }); diff --git a/packages/common/src/functions/getNetworkInfo.ts b/packages/common/src/functions/getNetworkInfo.ts deleted file mode 100644 index 76cd0608..00000000 --- a/packages/common/src/functions/getNetworkInfo.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { getNetwork } from '@ethersproject/networks'; - -import { networkDefinitions, TNetworkDefinition } from '~common/constants'; -import { TNetworkNamesList } from '~common/models'; - -export const getNetworkInfo = (chainId: number | undefined): TNetworkDefinition | undefined => { - if (!chainId) return; - - for (const n in networkDefinitions) { - const names = n as TNetworkNamesList; - if (networkDefinitions[names].chainId === chainId) { - return networkDefinitions[names]; - } - } - - const network = getNetwork(chainId) ?? {}; - // @ts-expect-error - const rpcUrl: string = network?._defaultProvider?.connection?.rpcUrl ?? ''; - return { ...network, blockExplorer: '', color: '#666666', rpcUrl }; -}; diff --git a/packages/common/src/functions/getNetworks.ts b/packages/common/src/functions/getNetworks.ts deleted file mode 100644 index 35e1930c..00000000 --- a/packages/common/src/functions/getNetworks.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { TNetworkInfo } from 'eth-hooks/models'; - -import { networkDefinitions, TNetworkDefinition } from '~common/constants'; -import { TNetworkNamesList } from '~common/models'; - -export const getNetworks = (additionalFields: Record): Record => { - const result: Record = { ...networkDefinitions }; - for (const n in networkDefinitions) { - const name = n as TNetworkNamesList; - result[name] = { url: networkDefinitions[name].rpcUrl, ...networkDefinitions[name], ...additionalFields }; - } - - return result; -}; diff --git a/packages/common/src/functions/index.ts b/packages/common/src/functions/index.ts deleted file mode 100644 index dc8cf398..00000000 --- a/packages/common/src/functions/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './contractsByNetworkName'; -export * from './getNetworkInfo'; -export * from './getNetworks'; diff --git a/packages/common/src/functions/validateBroadcastCollection.ts b/packages/common/src/functions/validateBroadcastCollection.ts deleted file mode 100644 index 785011a7..00000000 --- a/packages/common/src/functions/validateBroadcastCollection.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { forgeDeploymentBroadcastCollectionSchema, TForgeDeploymentBroadcastCollection } from 'eth-hooks/models'; - -export const validateBroadcastFile = (json: Record): TForgeDeploymentBroadcastCollection => { - const result = forgeDeploymentBroadcastCollectionSchema.parse(json); - return result; -}; diff --git a/packages/common/src/helpers/__global.ts b/packages/common/src/helpers/__global.ts deleted file mode 100644 index d635388b..00000000 --- a/packages/common/src/helpers/__global.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import * as nodeBuffer from 'buffer'; -import * as nodeProcess from 'process'; -import * as util from 'util'; - -import 'eth-hooks/helpers/__global'; - -// (window as any).global = window; -// const global = window; - -if (!global.hasOwnProperty('Buffer')) { - (global as any).Buffer = nodeBuffer.Buffer; -} - -(global as any).process = nodeProcess; - -(global as any).util = util; - -export {}; diff --git a/packages/common/src/helpers/types/fileTypes.d.ts b/packages/common/src/helpers/types/fileTypes.d.ts deleted file mode 100644 index c50f1e24..00000000 --- a/packages/common/src/helpers/types/fileTypes.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* eslint @typescript-eslint/no-explicit-any: 0 */ -/* Use this file to declare any custom file extensions for importing */ -/* Use this folder to also add/extend a package d.ts file, if needed. */ - -/* CSS MODULES */ -declare module '*.module.css' { - const classes: { [key: string]: string }; - export default classes; -} -declare module '*.module.scss' { - const classes: { [key: string]: string }; - export default classes; -} -declare module '*.module.sass' { - const classes: { [key: string]: string }; - export default classes; -} -declare module '*.module.less' { - const classes: { [key: string]: string }; - export default classes; -} -declare module '*.module.styl' { - const classes: { [key: string]: string }; - export default classes; -} - -/* CSS */ -declare module '*.css'; -declare module '*.scss'; -declare module '*.sass'; -declare module '*.less'; -declare module '*.styl'; - -/* IMAGES */ -declare module '*.svg' { - const ref: string; - export default ref; -} -declare module '*.bmp' { - const ref: string; - export default ref; -} -declare module '*.gif' { - const ref: string; - export default ref; -} -declare module '*.jpg' { - const ref: string; - export default ref; -} -declare module '*.jpeg' { - const ref: string; - export default ref; -} -declare module '*.png' { - const ref: string; - export default ref; -} diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts deleted file mode 100644 index 18b37136..00000000 --- a/packages/common/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export const packageName = 'common'; diff --git a/packages/common/src/models/IScaffoldAppProviders.ts b/packages/common/src/models/IScaffoldAppProviders.ts deleted file mode 100644 index c667679d..00000000 --- a/packages/common/src/models/IScaffoldAppProviders.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { TCreateEthersModalConnector, TEthersAdaptor, TEthersProvider } from 'eth-hooks/models'; - -import { TNetworkDefinition } from '~common/constants'; - -export interface IScaffoldAppProviders { - currentProvider: TEthersProvider | undefined; - currentTargetNetwork: TNetworkDefinition; - targetNetworks: { [chainId: number]: TNetworkDefinition }; - mainnetAdaptor: TEthersAdaptor | undefined; - localAdaptor: TEthersAdaptor | undefined; - createLoginConnector: TCreateEthersModalConnector; -} diff --git a/packages/common/src/models/TForgeBroadcast.ts b/packages/common/src/models/TForgeBroadcast.ts deleted file mode 100644 index ca20b279..00000000 --- a/packages/common/src/models/TForgeBroadcast.ts +++ /dev/null @@ -1,39 +0,0 @@ -import z from 'zod'; - -export const forgeTransactionDataSchema = z.object({ - type: z.string(), - from: z.string(), - gas: z.string(), - value: z.string(), - data: z.string(), - nonce: z.string(), - accessList: z.array(z.string()), -}); - -export const forgeTransactionSchema = z.object({ - hash: z.string(), - transactionType: z.enum(['CREATE']), - contractName: z.string(), - contractAddress: z.string(), - function: z.string(), - arguments: z.string(), - transaction: forgeTransactionDataSchema, -}); - -export const forgeBroadcastSchema = z.object({ - transactions: z.array(forgeTransactionSchema), - chainId: z.string(), -}); - -export const TForgeBoradcastCollection = z.record( - z.number({ description: 'chainId' }), - z.object({ - transactions: z.array(forgeTransactionSchema), - }) -); - -export type TForgeTransactionData = z.infer; - -export type TForgeTransaction = z.infer; - -export type TForgeBroadcast = z.infer; diff --git a/packages/common/src/models/TScaffoldConfig.ts b/packages/common/src/models/TScaffoldConfig.ts deleted file mode 100644 index 23e0a3af..00000000 --- a/packages/common/src/models/TScaffoldConfig.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { z } from 'zod'; - -import { solidityToolkits, NetworkNamesList, reactBuilds } from '~common/models'; - -export const scaffoldConfigSchema = z.object({ - build: z.object({ - solidityToolkit: z.enum(solidityToolkits), - reactBuild: z.enum(reactBuilds), - }), - runtime: z.object({ - /** - * The networks the app will be available for - */ - availableNetworks: z.enum(NetworkNamesList).array(), - /** - * The target network to use for deployment, compilation - * The target network should be part of the availableNetworks list - */ - targetNetwork: z.enum(NetworkNamesList).default('localhost'), - networkConfig: z - .object({ - rpcMainnetInfuraUrl: z.string().default('https://mainnet.infura.io/v3'), - }) - .default({}), - buidlGuidl: z - .object({ - rpcMainnet: z.string().default('https://rpc.scaffoldeth.io:48544'), - infuraId: z.string().default('3ccea23c26224daf802cf31e4699d15e'), - }) - .default({}), - }), -}); - -export type TScaffoldConfig = z.infer; diff --git a/packages/common/src/models/index.ts b/packages/common/src/models/index.ts deleted file mode 100644 index 5e1a39d0..00000000 --- a/packages/common/src/models/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './IScaffoldAppProviders'; -export * from './scaffoldConfigTypes'; -export * from './TScaffoldConfig'; diff --git a/packages/common/src/models/scaffoldConfigTypes.ts b/packages/common/src/models/scaffoldConfigTypes.ts deleted file mode 100644 index ac1f5bc2..00000000 --- a/packages/common/src/models/scaffoldConfigTypes.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const NetworkNamesList = [ - 'localhost', - 'mainnet', - 'kovan', - 'rinkeby', - 'ropsten', - 'goerli', - 'xdai', - 'polygon', - 'mumbai', - 'rinkebyArbitrum', - 'arbitrum', - 'kovanOptimism', - 'optimism', - 'fujiAvalanche', - 'avalanche', - 'testnetFantom', - 'fantom', -] as const; - -export type TNetworkNamesList = typeof NetworkNamesList[number]; -export type TNetworkNames = { - [key in TNetworkNamesList]: key; -}; - -export const solidityToolkits = ['hardhat', 'foundry'] as const; -export type TSolidityToolkits = typeof solidityToolkits[number]; - -export const reactBuilds = ['vite', 'nextjs'] as const; -export type TReactBuilds = typeof reactBuilds[number]; diff --git a/packages/common/src/scaffold.config.ts b/packages/common/src/scaffold.config.ts deleted file mode 100644 index 07016a2d..00000000 --- a/packages/common/src/scaffold.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { invariant } from 'ts-invariant'; - -import json from './scaffold.config.json'; - -import { scaffoldConfigSchema, TScaffoldConfig } from '~common/models'; - -export const validatedScaffoldConfigSchema = scaffoldConfigSchema.refine((data) => { - // additional validation - if (!data?.runtime?.availableNetworks?.find((f) => f === data.runtime.targetNetwork)) { - invariant.error(`Default network ${data.runtime.targetNetwork} is not in the target networks list`); - return false; - } - return true; -}, `defaultNetwork must be in the targetNetworks list`); - -/** - * Use this for your app - */ -export const scaffoldConfig = validatedScaffoldConfigSchema.parse(json); - -// this logic is a bit redundant, as it has to work with esm, commonjs and hardhat - -/** - * use this for hardhat and node commonjs - */ -let configForHardhat: TScaffoldConfig = scaffoldConfig; -export const loadScaffoldConfig = async (): Promise => { - const data = await import('~common/scaffold.config.json'); - configForHardhat = validatedScaffoldConfigSchema.parse(data); - - console.log('...done loading scaffold config'); - return scaffoldConfig; -}; - -/** - * use this for hardhat - */ -export default configForHardhat; diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json deleted file mode 100644 index 372d9682..00000000 --- a/packages/common/tsconfig.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "lib": ["DOM", "DOM.Iterable", "ESNext", "ES2017"], - "sourceMap": true, - // "inlineSources": true, - "allowJs": false, - "declarationMap": true, - "declaration": true, - "esModuleInterop": true, - "skipLibCheck": true, - "composite": true, - "skipDefaultLibCheck": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "esnext", - "moduleResolution": "Node", - "incremental": true, - "resolveJsonModule": true, - "isolatedModules": true, - "rootDir": ".", - "baseUrl": ".", - "outDir": "dist", - "jsx": "react-jsxdev", - "jsxImportSource": "@emotion/react", - "paths": { - "~common/*": ["./src/*"] - } - }, - "include": ["src", "src/**/*.json"], - "exclude": [ - "**/node_modules", - ".husky", - "**/*.css", - "./tailwind.config.js", - "node_modules", - "**/.yalc/**/*", - ".yalc/**/*" - ] -}