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

Feature/sessions #271

Merged
merged 10 commits into from
Mar 2, 2023
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"buffer": "^6.0.3",
"d3": "^7.8.1",
"ethers": "^5.7.2",
"supertokens-web-js": "^0.5.0",
"util": "^0.12.5",
"vue": "^3.2.25",
"vue-router": "^4.0.15",
Expand Down
24 changes: 14 additions & 10 deletions apps/web/src/components/Wallet.vue
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
<template>
<div>
<button @click="getCurrentBalance()">
Get Balance New
</button>
<button @click="getUserBalance(selectedAddress)">
Get Balance Old
</button>
<div class="network-div">
<div class="flex">
<button @click="getCurrentBalance()">
Get Balance New
</button>
<button @click="getUserBalance(selectedAddress)">
Get Balance Old
</button>
</div>
<div class="network-div w-100 mx-8">
Choose Network
<div class="choose-network">
<div class="choose-network flex">
<button
@click="switchNetwork('5')"
>
Expand All @@ -30,6 +32,9 @@
<button @click="setPrimaryWalletAccount()">
Set Primary Account
</button>
<button @click="logout">
logout
</button>
</div>
<div>
<button
Expand Down Expand Up @@ -177,7 +182,6 @@
<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import useWallet from '@/composables/wallet'
import useUsers from '@/composables/users'

const message = ref('')
const signedMessage = ref('')
Expand All @@ -200,12 +204,12 @@ const {
selectedProvider,
selectedAddress,
primaryAddress,
selectedCurrency,
toAddress,
amount,
amountToStake,
pools,
connectWallet,
logout,
setPrimaryWalletAccount,
sendTransaction,
signMessage,
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/composables/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function useAuth() {
},
body: JSON.stringify(signupCredentials)
}
return await fetch(`${usersBaseURL}/signupLogin`, requestOptions)
return await fetch(`${usersBaseURL}/auth/signupLogin`, requestOptions)
}

async function signUpAuth(signupCredentials: SignupLoginCredentials) {
Expand Down
5 changes: 1 addition & 4 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,7 @@ export default function useEthers() {
signedMessage: signature,
currency
})
console.log('response in signupLoginWithEthers in ethers.ts :>> ', response)
const json = await response.json()
console.log('json in signupLoginWithEthers in ethers.ts :>> ', json)
return json
return await response.json()
}

async function getEthersBrowserProviderSelectedCurrency(providerString: ProviderString) {
Expand Down
41 changes: 27 additions & 14 deletions apps/web/src/composables/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ const user = ref<User | null>(null)
export default function useUsers () {
const { ssvManager } = useSSV()

async function getUser() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
const response = await fetch(`${usersBaseURL}/user`, requestOptions)
const { data } = await response.json()
user.value = data
return data
}

// Todo filter for events for user addresses
function subscribeToUserEvents() {
const { getUserBalance, getUserPools } = useWallet()
Expand All @@ -36,15 +49,15 @@ export default function useUsers () {
})
}

onMounted(async () => {
const { getUserBalance, getUserPools } = useWallet()
// Just get pools for primary account for demo
user.value.balance = ethers.utils.formatEther(await getUserBalance(user.value.id))
user.value.pools = await getUserPools(user.value.id)
subscribeToUserEvents()
})
// onMounted(async () => {
// const { getUserBalance, getUserPools } = useWallet()
// // Just get pools for primary account for demo
// user.value.balance = ethers.utils.formatEther(await getUserBalance(user.value.id))
// user.value.pools = await getUserPools(user.value.id)
// subscribeToUserEvents()
// })

async function addAccount(provider: ProviderString, address: string, currency: Currency) {
async function addAccount(provider: ProviderString, address: string, currency: Currency): Promise<{ error: boolean, message: string, data: User | null }> {
address = address.toLowerCase()
const account = user.value?.accounts?.find((account: Account) => {
const accountAddress = account.address.toLowerCase()
Expand All @@ -57,7 +70,6 @@ export default function useUsers () {
return isEqual
}) as Account
if (account) {
alert(`Account already exists on user: ${account}`)
return { error: false, message: `Account already exists on user: ${account}`, data: user.value }
} else {
const accountToAdd = {
Expand All @@ -78,11 +90,11 @@ export default function useUsers () {
account: accountToAdd
})
}
const response = await fetch(`${usersBaseURL}/users/add-sub-account`, requestOptions)
const json = await response.json()
return json
const response = await fetch(`${usersBaseURL}/user/add-sub-account`, requestOptions)
const { data: userAccount } = await response.json()
user.value = userAccount
return { error: false, message: `Account added to user: ${userAccount}`, data: userAccount }
}

}

// TODO: Refactor this next. 2/14
Expand All @@ -100,7 +112,7 @@ export default function useUsers () {
currency
})
}
return await fetch(`${usersBaseURL}/users/remove-sub-account`, requestOptions)
return await fetch(`${usersBaseURL}/user/remove-sub-account`, requestOptions)
}

async function getMessage(address: string) {
Expand Down Expand Up @@ -131,6 +143,7 @@ export default function useUsers () {

return {
user,
getUser,
addAccount,
removeAccount,
getMessage,
Expand Down
67 changes: 41 additions & 26 deletions apps/web/src/composables/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ import { TransactionInit } from '@/interfaces/TransactionInit'
import { MessageInit } from '@/interfaces/MessageInit'
import { Pool } from '@casimir/types/src/interfaces/Pool'
import { Currency } from '@casimir/types'
import * as Session from 'supertokens-web-js/recipe/session'

// Test ethereum send to address : 0xD4e5faa8aD7d499Aa03BDDE2a3116E66bc8F8203
// Test ethereum send to address : 0xd557a5745d4560B24D36A68b52351ffF9c86A212
// Test solana address: 7aVow9eVQjwn7Y4y7tAbPM1pfrE1TzjmJhxcRt8QwX5F
// Test iotex send to address: acc://06da5e904240736b1e21ca6dbbd5f619860803af04ff3d54/acme
// Test bitcoin send to address : 2N3Petr4LMH9tRneZCYME9mu33gR5hExvds
const loggedIn = ref(false)
const selectedProvider = ref<ProviderString>('')
const selectedAddress = ref<string>('')
Expand All @@ -23,22 +29,17 @@ const toAddress = ref<string>('2N3Petr4LMH9tRneZCYME9mu33gR5hExvds')
const amount = ref<string>('0.000001')
const amountToStake = ref<string>('0.0')
const pools = ref<Pool[]>([])
// Test ethereum send to address : 0xD4e5faa8aD7d499Aa03BDDE2a3116E66bc8F8203
// Test ethereum send to address : 0xd557a5745d4560B24D36A68b52351ffF9c86A212
// Test solana address: 7aVow9eVQjwn7Y4y7tAbPM1pfrE1TzjmJhxcRt8QwX5F
// Test iotex send to address: acc://06da5e904240736b1e21ca6dbbd5f619860803af04ff3d54/acme
// Test bitcoin send to address : 2N3Petr4LMH9tRneZCYME9mu33gR5hExvds
const session = ref<boolean>(false)

export default function useWallet() {
const { ethereumURL } = useEnvironment()
const { ssvManager, getSSVFeePercent } = useSSV()
const { ethersProviderList, getEthersBrowserSigner, getEthersAddress, getEthersBalance, sendEthersTransaction, signEthersMessage, signupLoginWithEthers, getEthersBrowserProviderSelectedCurrency, switchEthersNetwork } = useEthers()
const { solanaProviderList, getSolanaAddress, sendSolanaTransaction, signSolanaMessage } = useSolana()
// const { getIoPayAddress, sendIoPayTransaction, signIoPayMessage } = useIoPay()
const { getBitcoinLedgerAddress, getEthersLedgerAddress, getEthersLedgerSigner, sendLedgerTransaction, signLedgerMessage } = useLedger()
const { getTrezorAddress, getEthersTrezorSigner, sendTrezorTransaction, signTrezorMessage } = useTrezor()
const { isWalletConnectSigner, getWalletConnectAddress, getEthersWalletConnectSigner, sendWalletConnectTransaction, signWalletConnectMessage } = useWalletConnect()
const { user, addAccount, removeAccount, updatePrimaryAddress } = useUsers()
const { user, getUser, addAccount, removeAccount, updatePrimaryAddress } = useUsers()
const getLedgerAddress = {
'BTC': getBitcoinLedgerAddress,
'ETH': getEthersLedgerAddress,
Expand Down Expand Up @@ -66,50 +67,52 @@ export default function useWallet() {
selectedProvider.value = provider
}

const setSelectedAccount = (address: string) => {
const setSelectedAddress = (address: string) => {
selectedAddress.value = address
}

const setSelectedCurrency = (currency: Currency) => {
selectedCurrency.value = currency
}

async function getUserAccount() {
session.value = await Session.doesSessionExist()
if (session.value) {
await getUser()
}
}

async function connectWallet(provider: ProviderString, currency?: Currency) {
try {
// Login (retrieve accounts) / sign up OR add account
if (!selectedAddress.value) {
try { // Sign Up or Login
if (!loggedIn.value) {
const connectedAddress = await getConnectedAddress(provider, currency)
const connectedCurrency = await detectCurrency(provider) as Currency
const response = await signupOrLogin(provider, connectedAddress, connectedCurrency)
if (!response.error) {
if (!response?.error) {
await getUserAccount()
setSelectedProvider(provider)
setSelectedAccount(connectedAddress)
setSelectedAddress(connectedAddress)
setSelectedCurrency(connectedCurrency)
loggedIn.value = true
user.value = response.data
primaryAddress.value = response.data.address
return response
primaryAddress.value = user.value?.address as string
}
} else {
// Add account if already logged in / signed up
const connectedAddress = await getConnectedAddress(provider, currency)
} else { // Add account
console.log('already logged in!')
const connectedAddress = await getConnectedAddress(provider, currency) // TODO: Remove currency from here? Maybe not.
const connectedCurrency = await detectCurrency(provider) as Currency
const response = await addAccount(provider, connectedAddress, connectedCurrency)
console.log('add account response in connectWallet in wallet.ts:>> ', response)
if (!response?.error) {
setSelectedProvider(provider)
setSelectedAccount(connectedAddress)
setSelectedAddress(connectedAddress)
setSelectedCurrency(connectedCurrency)
loggedIn.value = true
user.value = response.data
primaryAddress.value = response.data.address
primaryAddress.value = response.data?.address as string
}
}
console.log('user.value on connect wallet :>> ', user.value)
} catch (error) {
console.error(error)
}
}

async function getConnectedAddress(provider: ProviderString, currency?: Currency) {
try {
let address
Expand Down Expand Up @@ -150,6 +153,17 @@ export default function useWallet() {
}
}

async function logout() {
await Session.signOut()
loggedIn.value = false
setSelectedAddress('')
setSelectedProvider('')
setSelectedCurrency('')
primaryAddress.value = ''
user.value = null
console.log('user.value on logout :>> ', user.value)
}

async function setPrimaryWalletAccount() {
if (!loggedIn.value) {
alert('Please login first')
Expand All @@ -176,7 +190,7 @@ export default function useWallet() {
const result = await removeAccount(selectedProvider.value, selectedAddress.value, selectedCurrency.value)
const json = await result.json()
if (!json.error) {
setSelectedAccount(json.data.address)
setSelectedAddress(json.data.address)
json.data.accounts.forEach((account: Account) => {
if (account.address === selectedAddress.value) {
setSelectedProvider(account.walletProvider as ProviderString)
Expand Down Expand Up @@ -366,6 +380,7 @@ export default function useWallet() {
amountToStake,
pools,
connectWallet,
logout,
setPrimaryWalletAccount,
removeConnectedAccount,
detectCurrency,
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import App from '@/App.vue'
import '@/index.css'
import router from '@/composables/router'

import SuperTokens from 'supertokens-web-js'
import { SuperTokensWebJSConfig } from './sessions.config'

SuperTokens.init(SuperTokensWebJSConfig)

console.log('Creating app...', import.meta.env)
console.log('Local mocking is', import.meta.env.PUBLIC_MOCK_ENABLED ? 'enabled' : 'disabled')

Expand Down
13 changes: 13 additions & 0 deletions apps/web/src/sessions.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Session from 'supertokens-web-js/recipe/session'
import useEnvironment from '@/composables/environment'

const { usersBaseURL } = useEnvironment()

export const SuperTokensWebJSConfig = {
appInfo: {
apiDomain: usersBaseURL,
appName: 'Casimir',
// apiBasePath: '/',
},
recipeList: [Session.init()],
}
Loading