Skip to content

Commit

Permalink
Merge pull request #135 from palladians/feat/improved-vault
Browse files Browse the repository at this point in the history
Vault 3.0
  • Loading branch information
teddyjfpender authored Jan 23, 2024
2 parents 0b8689a + a987dce commit 268ab5d
Show file tree
Hide file tree
Showing 77 changed files with 1,152 additions and 833 deletions.
22 changes: 8 additions & 14 deletions packages/features/src/common/hooks/use-account.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Mina } from '@palladxyz/mina-core'
import { getSessionPersistence } from '@palladxyz/persistence'
import { useVault } from '@palladxyz/vault'
import easyMeshGradient from 'easy-mesh-gradient'
Expand All @@ -14,34 +13,28 @@ export const useAccount = () => {
const navigate = useNavigate()
const { toast } = useToast()
const currentWallet = useVault((state) => state.getCurrentWallet())
const getAccountInfo = useVault((state) => state.getAccountInfo)
const getAccountsInfo = useVault((state) => state.getAccountsInfo)
const restartWallet = useVault((state) => state.restartWallet)
const _syncWallet = useVault((state) => state._syncWallet)
const network = useAppStore((state) => state.network)
const setVaultStateUninitialized = useAppStore(
(state) => state.setVaultStateUninitialized
)
const fetchWallet = async () => {
await _syncWallet(network, currentWallet?.credential.credential)
return getAccountInfo(network, publicKey)
await _syncWallet()
return getAccountsInfo(network, publicKey) // TODO: replace with getBalance
}
const { publicKey } = currentWallet.accountInfo
const publicKey = currentWallet.credential.credential?.address as string
const swr = useSWR(
publicKey
? [
publicKey,
'account',
Mina.Networks[network.toUpperCase() as keyof typeof Mina.Networks]
]
: null,
publicKey ? [publicKey, 'account', network] : null,
async () => await fetchWallet(),
{
refreshInterval: 30000
}
)
const rawMinaBalance = swr.isLoading
? 0
: swr.data?.accountInfo?.balance?.total ?? 0
: swr.data?.accountInfo['MINA']?.balance?.total ?? 0 // TODO: remove hardcoded 'MINA'
const minaBalance =
rawMinaBalance && BigInt(rawMinaBalance) / BigInt(1_000_000_000)
const gradientBackground = useMemo(
Expand All @@ -54,7 +47,8 @@ export const useAccount = () => {
[publicKey]
)
const stakeDelegated =
currentWallet.accountInfo.publicKey !== currentWallet.accountInfo.delegate
currentWallet.accountInfo['MINA'].publicKey !==
currentWallet.accountInfo['MINA'].delegate
const copyWalletAddress = async () => {
await navigator.clipboard.writeText(publicKey ?? '')
toast({
Expand Down
13 changes: 3 additions & 10 deletions packages/features/src/common/hooks/use-transaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Mina } from '@palladxyz/mina-core'
import { useVault } from '@palladxyz/vault'
import useSWR from 'swr'

Expand All @@ -8,20 +7,14 @@ export const useTransaction = ({ hash }: { hash: string }) => {
const currentWallet = useVault((state) => state.getCurrentWallet())
const _syncTransactions = useVault((state) => state._syncTransactions)
const getTransaction = useVault((state) => state.getTransaction)
const { publicKey } = currentWallet.accountInfo
const publicKey = currentWallet.credential.credential?.address as string
const network = useAppStore((state) => state.network)
const syncAndGetTransaction = async () => {
await _syncTransactions(network, currentWallet?.credential.credential)
return getTransaction(network, publicKey, hash)
return getTransaction(network, publicKey, hash, 'MINA') // TODO: remove hardcoded 'MINA'
}
return useSWR(
publicKey
? [
'transaction',
hash,
Mina.Networks[network.toUpperCase() as keyof typeof Mina.Networks]
]
: null,
publicKey ? ['transaction', hash, network] : null,
async () => await syncAndGetTransaction()
)
}
13 changes: 3 additions & 10 deletions packages/features/src/common/hooks/use-transactions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Mina } from '@palladxyz/mina-core'
import { useVault } from '@palladxyz/vault'
import useSWR from 'swr'

Expand All @@ -7,16 +6,10 @@ import { useAppStore } from '../store/app'
export const useTransactions = () => {
const currentWallet = useVault((state) => state.getCurrentWallet())
const getTransactions = useVault((state) => state.getTransactions)
const { publicKey } = currentWallet.accountInfo
const publicKey = currentWallet.credential.credential?.address as string
const network = useAppStore((state) => state.network)
return useSWR(
publicKey
? [
publicKey,
'transactions',
Mina.Networks[network.toUpperCase() as keyof typeof Mina.Networks]
]
: null,
async () => await getTransactions(network, publicKey)
publicKey ? [publicKey, 'transactions', network] : null,
async () => await getTransactions(network, publicKey, 'MINA') // TODO: remove hardcoded 'MINA'
)
}
1 change: 1 addition & 0 deletions packages/features/src/common/lib/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const TransactionFee = {
fast: 0.2
} as Record<string, number>

// TODO: this should be with vite or obtained via a provider
export const MinaChainId = {
Mainnet: '5f704cc0c82e0ed70e873f0893d7e06f148524e3f0bdae2afb02e7819a0c24d1',
Devnet: 'b6ee40d336f4cc3f33c1cc04dee7618eb8e556664c2b2d82ad4676b512a82418',
Expand Down
22 changes: 7 additions & 15 deletions packages/features/src/common/store/app.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { Mina } from '@palladxyz/mina-core'
import { Multichain } from '@palladxyz/multi-chain-core'
import { getLocalPersistence } from '@palladxyz/persistence'
import { DEFAULT_NETWORK } from '@palladxyz/vault'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'

import { VaultState } from '../lib/const'

const VITE_APP_DEFAULT_NETWORK =
import.meta.env.VITE_APP_DEFAULT_NETWORK || 'Mainnet'

// TODO: Make network a generic type that can support networks other than just Mina
type AppState = {
network: Multichain.MultiChainNetworks
network: string
vaultState: VaultState
shareData: boolean
}
Expand All @@ -21,7 +17,7 @@ type AppQueries = {
}

type AppMutators = {
setNetwork: (network: Multichain.MultiChainNetworks) => void
setNetwork: (network: string) => void
setVaultState: (vaultState: VaultState) => void
setVaultStateInitialized: () => void
setVaultStateUninitialized: () => void
Expand All @@ -30,12 +26,9 @@ type AppMutators = {

type AppStore = AppState & AppMutators & AppQueries

// TODO: figure out how to use Multichain.MultiChainNetworks -- investigate need for
// MultiChainNetworksEnum
const defaultNetwork =
Mina.Networks[
VITE_APP_DEFAULT_NETWORK.toUpperCase() as keyof typeof Mina.Networks
]
// TODO: this should be with vite
// const VITE_APP_DEFAULT_NETWORK = import.meta.env.VITE_APP_DEFAULT_NETWORK || 'Mainnet'
const defaultNetwork = DEFAULT_NETWORK

export const useAppStore = create<AppStore>()(
persist(
Expand All @@ -49,8 +42,7 @@ export const useAppStore = create<AppStore>()(
},
setNetwork(network) {
return set({
network:
Mina.Networks[network.toUpperCase() as keyof typeof Mina.Networks]
network: network
})
},
setShareData(shareData) {
Expand Down
1 change: 1 addition & 0 deletions packages/features/src/onboarding/views/create-wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { WalletInfoForm } from '../components/wallet-info-form'
export const CreateWalletView = () => {
const navigate = useNavigate()
const { setMnemonic, setWalletName, setSpendingPassword } =
// TODO: fix this useOnboardingStore it is deprecated
useOnboardingStore(
(state) => ({
setSpendingPassword: state.setSpendingPassword,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import {
MinaSpecificArgs,
Network
} from '@palladxyz/key-management'
import { Mina } from '@palladxyz/mina-core'
import { getSessionPersistence } from '@palladxyz/persistence'
import { KeyAgents, useVault } from '@palladxyz/vault'
import { DEFAULT_NETWORK, KeyAgents, useVault } from '@palladxyz/vault'
import { Loader2Icon } from 'lucide-react'
import { useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
Expand Down Expand Up @@ -69,14 +68,14 @@ export const MnemonicConfirmationView = () => {
await restoreWallet(
new MinaPayload(),
restoreArgs,
Mina.Networks.BERKELEY,
DEFAULT_NETWORK,
{
mnemonicWords: mnemonic.split(' '),
getPassphrase: async () => Buffer.from(spendingPassword)
},
walletName,
KeyAgents.InMemory,
'Test'
'Test' // TODO: make this a configurable credential name or random if not provided
)
track({ event: 'wallet_created' })
setVaultStateInitialized()
Expand Down
10 changes: 5 additions & 5 deletions packages/features/src/onboarding/views/mnemonic-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import {
validateMnemonic,
wordlist
} from '@palladxyz/key-management'
import { Mina } from '@palladxyz/mina-core'
import { getSessionPersistence } from '@palladxyz/persistence'
import { KeyAgents, useVault } from '@palladxyz/vault'
import { DEFAULT_NETWORK, KeyAgents, useVault } from '@palladxyz/vault'
import { Loader2Icon } from 'lucide-react'
import { useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
Expand Down Expand Up @@ -41,6 +40,7 @@ export const MnemonicInputView = () => {
const restoreWallet = useVault((state) => state.restoreWallet)
const navigate = useNavigate()
const { walletName, spendingPassword } = useOnboardingStore(
// TODO: fix this useOnboardingStore it is deprecated
(state) => ({
spendingPassword: state.spendingPassword,
walletName: state.walletName
Expand All @@ -64,21 +64,21 @@ export const MnemonicInputView = () => {
network: Network.Mina,
accountIndex: 0,
addressIndex: 0,
networkType: 'testnet' // TODO: make this configurable
networkType: 'testnet' // TODO: make this configurable if the user restores to mainnet it needs to be 'mainnet
}
try {
setRestoring(true)
await restoreWallet(
new MinaPayload(),
restoreArgs,
Mina.Networks.BERKELEY,
DEFAULT_NETWORK,
{
mnemonicWords: data.mnemonic,
getPassphrase: async () => Buffer.from(spendingPassword)
},
walletName,
KeyAgents.InMemory,
'Test'
'Test' // TODO: make this a configurable credential name or random if not provided
)
track({ event: 'wallet_restored' })
setVaultStateInitialized()
Expand Down
2 changes: 1 addition & 1 deletion packages/features/src/onboarding/views/start.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export const StartView = () => {
<div className="flex flex-1 flex-col items-center justify-center gap-8 p-4 text-center">
<img src="/intro.png" className="w-[220px]" />
<p className="leading-7 text-muted-foreground">
Your gateway to Minaverse.
Your gateway to the Minaverse.
</p>
</div>
</WizardLayout>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { GroupedCredentials } from '@palladxyz/key-management'
import { Mina } from '@palladxyz/mina-core'
import { Multichain } from '@palladxyz/multi-chain-core'
import { useVault } from '@palladxyz/vault'
Expand Down Expand Up @@ -28,11 +27,13 @@ import { cn } from '@/lib/utils'
import { ConfirmTransactionSchema } from './confirm-transaction-form.schema'

type ConfirmTransactionData = z.infer<typeof ConfirmTransactionSchema>

// TODO: Refactor to not use multichain package and use new signing args
export const ConfirmTransactionForm = () => {
const { track } = useAnalytics()
const [submitting, setSubmitting] = useState(false)
const navigate = useNavigate()
// can use
// const request = useVault((state) => state.request) for signing
const sign = useVault((state) => state.sign)
const submitTx = useVault((state) => state.submitTx)
const constructTx = useVault((state) => state.constructTx)
Expand Down Expand Up @@ -68,7 +69,7 @@ export const ConfirmTransactionForm = () => {
validUntil: '4294967295',
fee,
amount,
nonce: currentWallet.accountInfo.inferredNonce,
nonce: currentWallet.accountInfo['MINA'].inferredNonce, // TODO: remove hardcoded 'MINA'
type: 'payment'
}
const constructedTx = await constructTx(
Expand All @@ -91,6 +92,7 @@ export const ConfirmTransactionForm = () => {
}
}
if (!signedTx) return
// TODO: Make a util for this
const submitTxArgs = {
signedTransaction: signedTx as unknown as SignedLegacy<Payment>,
kind:
Expand All @@ -117,10 +119,7 @@ export const ConfirmTransactionForm = () => {
hash,
expireAt: addHours(new Date(), 8).toISOString()
})
await syncWallet(
Mina.Networks.BERKELEY,
currentWallet.credential.credential as GroupedCredentials
)
await syncWallet()
track({
event: kind === 'staking' ? 'portfolio_delegated' : 'transaction_sent',
metadata: {
Expand Down
4 changes: 2 additions & 2 deletions packages/features/src/send/components/send-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export const SendForm = () => {
}, [])
if (accountLoading) return null
const totalBalance =
accountData?.accountInfo.balance.total &&
accountData?.accountInfo.balance.total / 1_000_000_000
accountData?.accountInfo['MINA'].balance.total &&
accountData?.accountInfo['MINA'].balance.total / 1_000_000_000
const setMaxAmount = async () => {
const { fee } = getValues()
const currentFee = TransactionFee[fee]
Expand Down
2 changes: 1 addition & 1 deletion packages/features/src/send/views/transaction-summary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const TransactionSummaryView = () => {
)}
<MetaField label="Fee" value={`${outgoingTransaction.fee} MINA`} />
{outgoingTransaction?.amount && (
<MetaField label="Total" value={`${total} MINA`} />
<MetaField label="Total" value={`${total} MINA`} /> // TODO: this will not always be 'MINA'
)}
</Card>
<ConfirmTransactionForm />
Expand Down
2 changes: 1 addition & 1 deletion packages/features/src/staking/views/staking-overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const StakingOverviewView = () => {
<MetaField
label="Block Producer"
value={truncateString({
value: accountInfo.delegate,
value: accountInfo['MINA'].delegate,
endCharCount: 8,
firstCharCount: 8
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { structurizeTransactions } from '../utils/structurize-transactions'
import { TxTile } from './tx-tile'

interface TransactionsListProps {
// TODO: Refactor to not use multichain package and use new signing args
transactions: Multichain.MultiChainTransactionBody[]
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { TxKind, TxSide } from '@/common/types'

interface TxSideIndicatorProps {
side: TxSide
// TODO: consider how to make this with Multichain
kind: Mina.TransactionKind
from: string
to: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const structurizeTransaction = ({
tx,
walletPublicKey
}: {
// TODO: remove the multichain package from this file
tx: Multichain.MultiChainTransactionBody
walletPublicKey: string
}) => ({
Expand Down
3 changes: 3 additions & 0 deletions packages/mina-core/src/Providers/UnifiedProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
TransactionsByAddressesArgs,
TransactionsByIdsArgs
} from './ChainHistoryProvider'
import { DaemonStatus } from './daemon-status-provider'
import { HealthCheckResponse } from './Provider'
import { TxStatus, TxStatusArgs } from './TxStatusProvider'
import { SubmitTxArgs, SubmitTxResult } from './TxSubmitProvider'
Expand Down Expand Up @@ -36,6 +37,8 @@ export interface UnifiedMinaProviderType {
args: TransactionsByIdsArgs
): Promise<TransactionBody[] | undefined>

getDaemonStatus?(): Promise<DaemonStatus>

// healthCheck
healthCheck?(): Promise<HealthCheckResponse>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './types'
Loading

0 comments on commit 268ab5d

Please sign in to comment.