Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update/db schema #320

Merged
merged 6 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 4 additions & 68 deletions apps/web/src/composables/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,71 +11,6 @@ const { usersBaseURL, ethereumURL } = useEnvironment()
// 0xd557a5745d4560B24D36A68b52351ffF9c86A212
const session = ref<boolean>(false)
const user = ref<UserWithAccounts>()
// const user = ref(
// {
// address: '0xd557a5745d4560B24D36A68b52351ffF9c86A212'.toLowerCase(),
// accounts: [
// {
// address: '0xd557a5745d4560B24D36A68b52351ffF9c86A212'.toLowerCase(),
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'MetaMask'
// },
// {
// address: '0x1dc336d94890b10e1a47b6e34cdee1009ee7b942'.toLowerCase(),
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'CoinbaseWallet'
// },
// {
// address: '0x1dc336d94890b10e1a47b6e34cdee1009ee7b942'.toLowerCase(),
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'CoinbaseWallet'
// },
// {
// address: '0x1dc336d94890b10e1a47b6e34cdee1009ee7b942'.toLowerCase(),
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'CoinbaseWallet'
// },
// {
// address: '0x8222Ef172A2117D1C4739E35234E097630D94376'.toLowerCase(),
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'Ledger'
// },
// {
// address: '0x8222Ef172A2117D1C4739E35234E097630D94377'.toLowerCase(), // Fake address
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'Trezor'
// },
// {
// address: '0x8222Ef172A2117D1C4739E35234E097630D94378'.toLowerCase(), // Fake address
// currency: 'ETH',
// balance: '1000000000000000000',
// balanceSnapshots: [{ date: '2023-02-06', balance: '1000000000000000000' }, { date: '2023-02-05', balance: '100000000000000000' }],
// roi: 0.25,
// walletProvider: 'WalletConnect'
// },
// ],
// nonce: '1234567890',
// pools: []
// }
// )
const { casimirManager, getPools } = useSSV()

export default function useUsers () {
Expand Down Expand Up @@ -190,15 +125,16 @@ export default function useUsers () {
})
}

async function updatePrimaryAddress(primaryAddress: string, updatedProvider: ProviderString, updatedAddress: string) {
async function updatePrimaryAddress(updatedAddress: string) {
const userId = user?.value?.id
const requestOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ primaryAddress, updatedProvider, updatedAddress })
body: JSON.stringify({ userId, updatedAddress })
}
return await fetch(`${usersBaseURL}/users/update-primary-account`, requestOptions)
return await fetch(`${usersBaseURL}/user/update-primary-account`, requestOptions)
}

return {
Expand Down
12 changes: 6 additions & 6 deletions apps/web/src/composables/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export default function useWallet() {
// If account doesn't exist, add account using users api
console.log('adding sub account')
const account = {
userId: user?.value?.id,
address: connectedAddress.toLowerCase() as string,
currency: connectedCurrency,
ownerAddress: user?.value?.address.toLowerCase() as string,
Expand Down Expand Up @@ -206,13 +207,12 @@ export default function useWallet() {
}
}

// TODO: What is this used for?
// Do we need balance of active address only?
// Or do we need balance of all addresses in accounts associated with user?
// Is this calculated on front end or back end or both?
async function getUserBalance() {
if (ethersProviderList.includes(selectedProvider.value)){
const walletBalance = await getEthersBalance(selectedProvider.value, selectedAddress.value)
const walletBalance = await getEthersBalance(selectedAddress.value)
console.log('walletBalance in wei in wallet.ts :>> ', walletBalance)
return walletBalance
} else {
Expand Down Expand Up @@ -312,14 +312,14 @@ export default function useWallet() {
async function setPrimaryWalletAccount() {
if (!user?.value?.address) {
alert('Please login first')
}
return alert('Not yet implemented for this wallet provider')
if (ethersProviderList.includes(selectedProvider.value)) {
const result = await updatePrimaryAddress(primaryAddress.value, selectedProvider.value, selectedAddress.value)
} else if (ethersProviderList.includes(selectedProvider.value)) {
const result = await updatePrimaryAddress(selectedAddress.value)
const { data } = await result.json()
if (data) {
primaryAddress.value = data.address
}
} else {
return alert('Not yet implemented for this wallet provider')
}
}

Expand Down
7 changes: 4 additions & 3 deletions common/data/scripts/postgres.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import minimist from 'minimist'
import fs from 'fs'
import { run } from '@casimir/helpers'
import { JsonSchema, Schema, accountSchema, nonceSchema, userSchema } from '@casimir/data'
import { JsonSchema, Schema, accountSchema, nonceSchema, userSchema, usersAccountsSchema } from '@casimir/data'

/** Resource path from package caller */
const resourcePath = './scripts'
Expand All @@ -10,7 +10,8 @@ const resourcePath = './scripts'
const tableSchemas = {
accounts: accountSchema,
nonces: nonceSchema,
users: userSchema
users: userSchema,
users_accounts: usersAccountsSchema
}

/**
Expand All @@ -25,7 +26,7 @@ void async function () {
const argv = minimist(process.argv.slice(2))

/** Default to all tables */
const tables = argv.tables ? argv.tables.split(',') : ['accounts', 'nonces', 'users']
const tables = argv.tables ? argv.tables.split(',') : ['accounts', 'nonces', 'users', 'users_accounts']
let sqlSchema = '-- Generated by @casimir/data/scripts/postgres.ts\n\n'
for (const table of tables) {
const tableSchema = tableSchemas[table] as JsonSchema
Expand Down
2 changes: 2 additions & 0 deletions common/data/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import nonceSchema from './schemas/nonce.schema.json'
import userSchema from './schemas/user.schema.json'
import eventSchema from './schemas/event.schema.json'
import aggSchema from './schemas/agg.schema.json'
import usersAccountsSchema from './schemas/users_accounts.schema.json'
import operatorStore from './mock/operator.store.json'
import validatorStore from './mock/validator.store.json'
import accountStore from './mock/account.store.json'
Expand All @@ -15,6 +16,7 @@ export {
accountSchema,
nonceSchema,
userSchema,
usersAccountsSchema,
eventSchema,
aggSchema,
accountStore,
Expand Down
2 changes: 2 additions & 0 deletions common/data/src/interfaces/JsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ export interface JsonSchema {
description: string
}
},
uniqueFields?: string[],
composite_key?: string
}
13 changes: 10 additions & 3 deletions common/data/src/providers/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export class Schema {
* ```
*/
getPostgresTable(): string {
const compositeKey = this.jsonSchema.composite_key
const uniqueFields = this.jsonSchema.uniqueFields || []
const columns = Object.keys(this.jsonSchema.properties).map((name: string) => {
const property = this.jsonSchema.properties[name]
let type = {
Expand All @@ -70,7 +72,8 @@ export class Schema {
boolean: 'BOOLEAN',
object: 'JSON',
array: 'JSON',
null: 'VARCHAR'
null: 'VARCHAR',
serial: 'SERIAL'
}[property.type as JsonType] as PostgresType

if (name.endsWith('_at')) type = 'TIMESTAMP'
Expand All @@ -80,14 +83,18 @@ export class Schema {

const comment = property.description
if (comment.includes('PK')) column += ' PRIMARY KEY'

return column
})

/** Check for composite key property and add the primary key if so */
if (compositeKey) columns.push(`PRIMARY KEY (${compositeKey})`)

/** Make table name plural of schema objects (todo: check edge-cases) */
const tableName = this.getTitle().toLowerCase() + 's'
ccali11 marked this conversation as resolved.
Show resolved Hide resolved

return `CREATE TABLE ${tableName} (\n\t${columns.join(',\n\t')}\n);`
const queryString = uniqueFields.length > 0 ? `CREATE TABLE ${tableName} (\n\t${columns.join(',\n\t')}, \n\tUNIQUE (${uniqueFields.join(', ')}));` : `CREATE TABLE ${tableName} (\n\t${columns.join(',\n\t')}\n);`
return queryString
}

/**
Expand Down
22 changes: 17 additions & 5 deletions common/data/src/schemas/account.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"properties": {
"address": {
"type": "string",
"description": "The account address (PK)"
"description": "The account address"
},
"balance": {
"type": "number",
Expand All @@ -20,9 +20,9 @@
"type": "string",
"description": "The account creation date in ISO 8601 format"
},
"owner_address": {
"type": "string",
"description": "The account owner address"
"id": {
"type": "serial",
"description": "The account ID (PK)"
},
"snapshots": {
"type": "array",
Expand All @@ -49,15 +49,27 @@
"type": "string",
"description": "The account last update date in ISO 8601 format"
},
"user_id": {
"type": "integer",
"description": "The account user ID (FK)"
},
"wallet_provider": {
"type": "string",
"description": "The account wallet provider"
}
},
"uniqueFields": [
"address",
"user_id",
"wallet_provider"
],
"required": [
"id",
"address",
"created_at",
"currency",
"owner_address",
"updated_at",
"user_id",
"wallet_provider"
]
}
11 changes: 9 additions & 2 deletions common/data/src/schemas/user.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,25 @@
"properties": {
"address": {
"type": "string",
"description": "The user address (PK)"
"description": "The user address used to sign in"
},
"created_at": {
"type": "string",
"description": "The account creation date in ISO 8601 format"
},
"id": {
"type": "serial",
"description": "The user ID (PK)"
},
"updated_at": {
"type": "string",
"description": "The account last update date in ISO 8601 format"
}
},
"required": [
"address"
"address",
"created_at",
"id",
"updated_at"
]
}
27 changes: 27 additions & 0 deletions common/data/src/schemas/users_accounts.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"$id": "https://casimir.co/users_accounts.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User_Account",
ccali11 marked this conversation as resolved.
Show resolved Hide resolved
"type": "object",
"properties": {
"account_id": {
"type": "integer",
"description": "The unique identifier for an account (pk part 2) and the FK to the account table"
},
"created_at": {
"type": "string",
"description": "The date and time the user_account was created"
},
"user_id": {
"type": "integer",
"description": "The unique identifier for a user (pk part 1) and the FK to the user table"
}
},
"composite_key": "user_id, account_id",
"required": [
"account_id",
"created_at",
"user_id"
]
}

2 changes: 2 additions & 0 deletions common/types/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Account } from './interfaces/Account'
import { AccountWithStakingInfo } from './interfaces/AccountWithStakingInfo'
import { AddAccountOptions } from './interfaces/AddAccountOptions'
import { BalanceSnapshot } from './interfaces/BalanceSnapshot'
import { ContractArgs } from './interfaces/ContractArgs'
Expand All @@ -18,6 +19,7 @@ import { Validator } from './interfaces/Validator'

export type {
Account,
AccountWithStakingInfo,
AddAccountOptions,
BalanceSnapshot,
ContractArgs,
Expand Down
24 changes: 11 additions & 13 deletions common/types/src/interfaces/Account.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import { BalanceSnapshot, Currency, Pool, ProviderString } from '@casimir/types'

export interface Account {
/** Unique ID (only keeping the latest of each distinct address/currency pair per User to avoid double counting) */
/** The address of the current account */
address: string
/** The current balance */
balance?: string
/** Daily balance snapshots */
balanceSnapshots?: BalanceSnapshot[]
/** See Currency below */
currency: Currency
/** The user's current staking pools and details (this interface/logic is in the web app wallet composable, but it will be moved to the processor, see https://github.com/consensusnetworks/casimir/blob/master/apps/web/src/composables/wallet.ts#L146) */
pools?: Pool[]
/** The total amount of stake rewards available to withdraw (ignore for now, see note on Account.pools) */
rewards?: string
/** Return on investment rate (see https://github.com/consensusnetworks/casimir/issues/168#issuecomment-1314420917) */
roi?: number
/** The total amount currently staked (ignore for now, see note on Account.pools) */
stake?: string
/** ISO Timestamp of when user was created */
createdAt: string
/** The unique account id */
id: number
/** The account snapshots */
snapshots?: BalanceSnapshot[]
/** The account transactions */
// transactions?: Transaction[]
/** The user id associated with the account */
userId: string
/** The wallet provider which helps us show user breakdown and connect when signing or sending TXs */
walletProvider: ProviderString
/** The verified user owner address (only optional for compat, should be req) */
ownerAddress?: string
}
Loading