Skip to content

Commit

Permalink
Fix scripts and circular dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
shanejearley committed May 16, 2023
1 parent fffcf5e commit 9a3115b
Show file tree
Hide file tree
Showing 49 changed files with 4,202 additions and 4,131 deletions.
2 changes: 1 addition & 1 deletion apps/landing/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { fileURLToPath } from 'url'
import * as path from 'path'

export default defineConfig({
server: { port: 3000 },
server: { port: 3001 },
plugins: [
vue({ include: [/\.vue$/] })
],
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/composables/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import useEnvironment from '@/composables/environment'
import { LoginCredentials, ProviderString } from '@casimir/types'
import { LoginCredentials } from '@casimir/types'
import { ProviderString } from '@casimir/types'

const { usersBaseURL } = useEnvironment()

Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ref } from 'vue'
import { ethers } from 'ethers'
import { BrowserProviders, EthersProvider, MessageInit, TransactionInit } from '@/interfaces/index'
import { Currency, ProviderString } from '@casimir/types'
import { BrowserProviders, Currency, EthersProvider, MessageInit, ProviderString, TransactionInit } from '@casimir/types'
import useAuth from '@/composables/auth'

const { getMessage, login } = useAuth()
Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/composables/ledger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { BitcoinLedgerSigner, EthersLedgerSigner } from '@casimir/wallets'
import { ethers } from 'ethers'
import { MessageInit, TransactionInit } from '@/interfaces/index'
import { Currency, ProviderString } from '@casimir/types'
import { Currency, MessageInit, ProviderString, TransactionInit } from '@casimir/types'
import useEnvironment from '@/composables/environment'
import useEthers from '@/composables/ethers'
import useAuth from '@/composables/auth'
Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/composables/solana.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import {
SystemProgram,
PublicKey
} from '@solana/web3.js'
import { BrowserProviders, MessageInit, TransactionInit } from '@/interfaces/index'
import { ProviderString } from '@casimir/types'
import { BrowserProviders, MessageInit, ProviderString, TransactionInit } from '@casimir/types'

export default function useSolana() {
const solanaProviderList = ['Phantom']
Expand Down
14 changes: 5 additions & 9 deletions apps/web/src/composables/ssv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import useLedger from './ledger'
import useTrezor from './trezor'
import useWalletConnect from './walletConnect'
import { Account, Pool, ProviderString } from '@casimir/types'
import { ReadyOrStakeString } from '../interfaces'
import { ReadyOrStakeString } from '@/interfaces/ReadyOrStakeString'

/** Manager contract */
let manager: CasimirManager
Expand Down Expand Up @@ -46,21 +46,17 @@ export default function useSSV() {
let signer = signerCreator(walletProvider)
if (isWalletConnectSigner(signer)) signer = await signer
const managerSigner = manager.connect(signer as ethers.Signer)
const fees = await managerSigner.getFees()
const { LINK, SSV } = fees
const feesTotalPercent = LINK + SSV
const depositAmount = parseFloat(amount) * ((100 + feesTotalPercent) / 100)
const fees = await managerSigner.getFeePercent()
const depositAmount = parseFloat(amount) * ((100 + fees) / 100)
const value = ethers.utils.parseEther(depositAmount.toString())
const result = await managerSigner.depositStake({ value, type: 0 })
return await result.wait()
}

async function getDepositFees() {
const provider = new ethers.providers.JsonRpcProvider(ethereumURL)
const fees = await manager.connect(provider).getFees()
const { LINK, SSV } = fees
const feesTotalPercent = LINK + SSV
const feesRounded = Math.round(feesTotalPercent * 100) / 100
const fees = await manager.connect(provider).getFeePercent()
const feesRounded = Math.round(fees * 100) / 100
return feesRounded
}

Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/composables/trezor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { EthersTrezorSigner } from '@casimir/wallets'
import useEthers from '@/composables/ethers'
import useEnvironment from '@/composables/environment'
import { ethers } from 'ethers'
import { MessageInit, TransactionInit } from '@/interfaces/index'
import { MessageInit, TransactionInit } from '@casimir/types'

const trezorPath = 'm/44\'/60\'/0\'/0/0'

Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/composables/users.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { onMounted, ref } from 'vue'
import { ref } from 'vue'
import { AddAccountOptions, ProviderString, RemoveAccountOptions, UserWithAccounts } from '@casimir/types'
import { ethers } from 'ethers'
import useEnvironment from '@/composables/environment'
Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/composables/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import useEthers from '@/composables/ethers'
import useWalletConnect from '@/composables/walletConnect'
import useSolana from '@/composables/solana'
import useUsers from '@/composables/users'
import { Account, ProviderString, Currency } from '@casimir/types'
import { MessageInit, TransactionInit } from '@/interfaces/index'
import { Account, Currency, MessageInit, ProviderString, TransactionInit } from '@casimir/types'
import * as Session from 'supertokens-web-js/recipe/session'
import router from './router'

Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/composables/walletConnect.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ethers } from 'ethers'
import WalletConnectProvider from '@walletconnect/web3-provider'
import { MessageInit, TransactionInit } from '@/interfaces/index'
import { MessageInit, TransactionInit } from '@casimir/types'
import useEnvironment from '@/composables/environment'
import useEthers from '@/composables/ethers'

Expand Down
12 changes: 0 additions & 12 deletions apps/web/src/interfaces/User.ts

This file was deleted.

15 changes: 0 additions & 15 deletions apps/web/src/interfaces/index.ts

This file was deleted.

2 changes: 1 addition & 1 deletion apps/web/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@
"./node_modules/@types"
]
},
"include": ["./src/**/*.ts", "./src/**/*.vue"]
"include": ["./src/**/*.ts", "./src/**/*.vue", "../../common/types/src/interfaces/BrowserProviders.ts", "../../common/types/src/interfaces/EthersProvider.ts", "../../common/types/src/interfaces/MessageInit.ts", "../../common/types/src/interfaces/TransactionInit.ts", "../../common/types/src/interfaces/UserWithProviders.ts"]
}
10 changes: 4 additions & 6 deletions apps/web/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import vue from '@vitejs/plugin-vue'
import { UserConfig } from 'vite'
import { defineConfig } from 'vite'
import { fileURLToPath } from 'url'
import * as path from 'path'
import NodeGlobalsPolyfillPlugin from '@esbuild-plugins/node-globals-polyfill'
import inject from '@rollup/plugin-inject'
import nodePolyFills from 'rollup-plugin-node-polyfills'

const config: UserConfig = {
server: { port: 3000 },
export default defineConfig({
server: { port: 3001 },
plugins: [
vue({ include: [/\.vue$/] }),
nodePolyFills(),
Expand Down Expand Up @@ -53,6 +53,4 @@ const config: UserConfig = {
]
},
envPrefix: 'PUBLIC_'
} as UserConfig

export default config
})
4 changes: 2 additions & 2 deletions common/data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"build": "echo '@casimir/data build not specified. Disregard this warning and any listed errors above if @casimir/types is not needed for the current project build.' && exit 0",
"clean": "ts-node --transpile-only scripts/clean.ts",
"configure:python": "poetry install && poetry run ipython kernel install --user --name=casimir-data",
"dev": "ts-node --transpile-only scripts/postgres.ts --tables \"$npm_config_tables\"",
"watch": "ts-node-dev --watch src --respawn --transpile-only scripts/postgres.ts --tables \"$npm_config_tables\"",
"dev": "ts-node --transpile-only scripts/dev.ts --tables \"$npm_config_tables\"",
"watch": "ts-node-dev --watch src --respawn --transpile-only scripts/dev.ts --tables \"$npm_config_tables\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
Expand Down
19 changes: 3 additions & 16 deletions common/data/scripts/clean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,9 @@ import { run } from '@casimir/helpers'
const resourcePath = './scripts'

/**
* Clean Docker containers, Postgres data, and SQL schema files.
* Clean up resources
*/
void async function () {
console.log(`Cleaning up Docker containers, Postgres data, and SQL schema files from ${resourcePath}/.out`)

/** Stop postgres database */
const stackName = 'casimir-data'
const containerName = `${stackName}-postgres-1`
const container = await run(`docker ps -q --filter name=${containerName}`)
if (container) {
await run(`docker compose -p ${stackName} -f ${resourcePath}/docker-compose.yaml down`)
}

/** Clear output directory for pgdata and sql */
const outDir = `${resourcePath}/.out`
await run(`npx rimraf ${outDir}`)

console.log('🐘 Database resources cleaned')
await run(`rm -rf ${resourcePath}/.out`)
await run(`docker compose -p casimir-data -f ${resourcePath}/docker-compose.yaml down`)
}()
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import minimist from 'minimist'
import fs from 'fs'
import { run } from '@casimir/helpers'
import { run, runSync } from '@casimir/helpers'
import { JsonSchema, Schema, accountSchema, nonceSchema, userSchema } from '@casimir/data'

/** Resource path from package caller */
Expand Down Expand Up @@ -48,9 +48,9 @@ void async function () {
if (!container) {
/** Start local database */
await run(`docker compose -p ${stackName} -f ${resourcePath}/docker-compose.yaml up -d`)
console.log('🐘 Database started')
console.log('🐘 Database resources started')
} else {
await run(`docker exec ${containerName} psql -U postgres -d postgres -f /docker-entrypoint-initdb.d/schema.sql`)
console.log('🐘 Database synced')
console.log('🐘 Database resources synced')
}
}()
2 changes: 1 addition & 1 deletion common/data/src/providers/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class Postgres {
*/
constructor(config?: PoolConfig) {
this.pool = new Pool(config)
process.on('exit', () => this.close())
process.on('SIGINT', () => this.close())
}

/**
Expand Down
44 changes: 26 additions & 18 deletions common/helpers/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { spawn, execSync } from 'child_process'
import { exec, execSync } from 'child_process'
import { fromIni } from '@aws-sdk/credential-providers'
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager'
import { ethers } from 'ethers'
Expand Down Expand Up @@ -95,17 +95,16 @@ export function kebabCase(string: string): string {
}

/**
* Run any shell command with a spawned child process and return a promise
* @param fullCommand - The full command to run
* Run any shell command in a child process and return a promise
* @param command - The full command to run
* @returns A promise that resolves when the command exits
*/
export async function run(fullCommand: string) {
const [command, ...args] = fullCommand.split(' ')
const child = spawn(command, args)
export async function run(command: string) {
const child = exec(command)
let data = ''
return new Promise((resolve, reject) => {
child.on('error', reject)
child.stdout.on('data', chunk => {
child.stdout?.on('data', chunk => {
process.stdout.write(chunk.toString())
data += chunk.toString()
})
Expand All @@ -114,51 +113,60 @@ export async function run(fullCommand: string) {
}

/**
* Retry run any shell command with a spawned child process and return a promise
* @param fullCommand - The full command to run
* Retry run any shell command in a child process and return a promise
* @param command - The full command to run
* @param retriesLeft - Number of retries left (default: 5)
* @returns A promise that resolves when the command exits
*/
export async function retryRun(fullCommand: string, retriesLeft: number | undefined = 25): Promise<unknown> {
export async function runRetry(command: string, retriesLeft: number | undefined = 25): Promise<unknown> {
if (retriesLeft === 0) {
throw new Error('Command failed after maximum retries')
}

try {
return await run(fullCommand)
return await run(command)
} catch (error) {
await new Promise(resolve => setTimeout(resolve, 5000))
console.log('Retrying command', fullCommand)
return await retryRun(fullCommand, retriesLeft - 1)
console.log('Retrying command', command)
return await runRetry(command, retriesLeft - 1)
}
}

/**
* Run any shell command synchronously in a child process
* @param command - The full command to run
* @returns The output of the command
*/
export function runSync(command: string) {
return execSync(command).toString()
}

/**
* Retry a fetch request.
* @param {RequestInfo} info - URL string or request object
* @param {RequestInit} init - Request init options
* @param {number | undefined} retriesLeft - Number of retries left (default: 5)
* @returns {Promise<Response>} Response
* @example
* const response = await retryFetch('https://example.com')
* const response = await fetchRetry('https://example.com')
*/
export async function retryFetch(info: RequestInfo, init?: RequestInit, retriesLeft: number | undefined = 25): Promise<Response> {
export async function fetchRetry(info: RequestInfo, init?: RequestInit, retriesLeft: number | undefined = 25): Promise<Response> {
if (retriesLeft === 0) {
throw new Error('API request failed after maximum retries')
}

try {
const response = await fetch(info, init)
const response = await fetch(info, init)
if (response.status !== 200) {
await new Promise(resolve => setTimeout(resolve, 5000))
console.log('Retrying fetch request to', info, init)
return await retryFetch(info, init || {}, retriesLeft - 1)
return await fetchRetry(info, init || {}, retriesLeft - 1)
}
return response
} catch (error) {
await new Promise(resolve => setTimeout(resolve, 5000))
console.log('Retrying fetch request to', info, init)
return await retryFetch(info, init || {}, retriesLeft - 1)
return await fetchRetry(info, init || {}, retriesLeft - 1)
}
}

Expand Down
12 changes: 10 additions & 2 deletions common/types/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,45 @@
import { Account } from './interfaces/Account'
import { AddAccountOptions } from './interfaces/AddAccountOptions'
import { BalanceSnapshot } from './interfaces/BalanceSnapshot'
import { BrowserProviders } from './interfaces/BrowserProviders'
import { ContractArgs } from './interfaces/ContractArgs'
import { ContractConfig } from './interfaces/ContractConfig'
import { Currency } from './interfaces/Currency'
import { DeploymentConfig } from './interfaces/DeploymentConfig'
import { EthersProvider } from './interfaces/EthersProvider'
import { Event } from './interfaces/Event'
import { LoginCredentials } from './interfaces/LoginCredentials'
import { MessageInit } from './interfaces/MessageInit'
import { Operator } from './interfaces/Operator'
import { Pool } from './interfaces/Pool'
import { ProviderString } from './interfaces/ProviderString'
import { RemoveAccountOptions } from './interfaces/RemoveAccountOptions'
import { TransactionInit } from './interfaces/TransactionInit'
import { User } from './interfaces/User'
import { UserWithAccounts } from './interfaces/UserWithAccounts'
import { UserAddedSuccess } from './interfaces/UserAddedSuccess'
import { UserWithAccounts } from './interfaces/UserWithAccounts'
import { Validator } from './interfaces/Validator'

export type {
Account,
AddAccountOptions,
BalanceSnapshot,
BrowserProviders,
ContractArgs,
ContractConfig,
Currency,
DeploymentConfig,
EthersProvider,
Event,
LoginCredentials,
MessageInit,
Operator,
Pool,
ProviderString,
RemoveAccountOptions,
TransactionInit,
User,
UserWithAccounts,
UserAddedSuccess,
UserWithAccounts,
Validator,
}
Loading

0 comments on commit 9a3115b

Please sign in to comment.