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

Typed state #1648

Merged
merged 31 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
f5dd79b
start migrating types to use zod for parsing and defaults
mholtzman Aug 10, 2023
224a709
finish basic state loading, add some tests
mholtzman Aug 11, 2023
80c05e8
use current base state when state is corrupted
mholtzman Aug 11, 2023
71ad23c
fix tests
mholtzman Aug 11, 2023
9487fc3
fix gas for tests
mholtzman Aug 11, 2023
7f5b984
update legacy migrations to be more resilient
mholtzman Aug 11, 2023
db635c9
add test migration files
mholtzman Aug 14, 2023
b22aac7
update migration 38
mholtzman Aug 17, 2023
b9a6a3b
update tests
mholtzman Aug 17, 2023
e0cb39a
continue updating schemas
mholtzman Aug 18, 2023
cba9285
add dapp schema
mholtzman Aug 18, 2023
044ff9e
add more types
mholtzman Aug 18, 2023
7fdbb44
initial working version
mholtzman Aug 19, 2023
c221f9a
fix some tests
mholtzman Aug 19, 2023
bfa5cdc
finish tokens schema
mholtzman Aug 21, 2023
68de36e
finish updating migrations
mholtzman Aug 21, 2023
415f70e
add settings for panel and selected
mholtzman Aug 24, 2023
1762c5b
update most of state not to persist
mholtzman Aug 24, 2023
37871af
allow chain metadata with no native currency rate data
mholtzman Aug 24, 2023
7463625
update types to support migration from v0.4.4
mholtzman Aug 25, 2023
baed743
fix typo
mholtzman Aug 29, 2023
363b5e2
add last migration test
mholtzman Aug 29, 2023
ec97b42
fix test
mholtzman Aug 29, 2023
8b6b8ae
dont persist signers
mholtzman Aug 30, 2023
9553fe1
update test
mholtzman Aug 30, 2023
db69bda
fix test
mholtzman Aug 30, 2023
210edae
final changes
mholtzman Aug 31, 2023
af7b254
update version
mholtzman Aug 31, 2023
bbb40ca
remove no check and add any to legacy migrations
mholtzman Aug 31, 2023
7ab747b
skip test
mholtzman Aug 31, 2023
7b460c3
cleanup
mholtzman Aug 31, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class TxFee extends React.Component {
const serializedTransaction = utils.serializeTransaction(tx)

// Get current Ethereum gas price
const ethBaseFee = this.store('main.networksMeta.ethereum', 1, 'gas.price.fees.nextBaseFee')
const ethBaseFee = this.store('main.networksMeta.ethereum', 1, 'gas.fees.nextBaseFee')
const l1DataFee = calculateOptimismL1DataFee(serializedTransaction, ethBaseFee)

// Compute the L2 execution fee
Expand Down
2 changes: 1 addition & 1 deletion main/accounts/Account/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { isTransactionRequest, isTypedMessageSignatureRequest } from '../../../r
import Erc20Contract from '../../contracts/erc20'

import type { PermitSignatureRequest, TypedMessage } from '../types'
import type { Account, Permission, Signer } from '../../store/state'
import type { Account, Permission, Signer } from '../../store/state/types'

const nebula = nebulaApi()

Expand Down
4 changes: 2 additions & 2 deletions main/accounts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { accountNS } from '../../resources/domain/account'
import { getMaxTotalFee } from '../../resources/gas'

import type { Chain } from '../chains'
import type { Account, AccountMetadata, Gas } from '../store/state'
import type { Account, AccountMetadata, Gas } from '../store/state/types'

function notify(title: string, body: string, action: (event: Electron.Event) => void) {
const notification = new Notification({ title, body })
Expand Down Expand Up @@ -553,7 +553,7 @@ export class Accounts extends EventEmitter {
const gas = store('main.networksMeta', chain.type, chain.id, 'gas') as Gas

if (usesBaseFee(tx)) {
const { maxBaseFeePerGas, maxPriorityFeePerGas } = gas.price.fees || {}
const { maxBaseFeePerGas, maxPriorityFeePerGas } = gas.fees || {}

if (maxPriorityFeePerGas && maxBaseFeePerGas) {
this.setPriorityFee(maxPriorityFeePerGas, id, false)
Expand Down
2 changes: 1 addition & 1 deletion main/accounts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { Chain } from '../chains'
import type { TransactionData } from '../../resources/domain/transaction'
import type { Action } from '../transaction/actions'
import type { TokenData } from '../contracts/erc20'
import type { Token } from '../store/state'
import type { Token } from '../store/state/types'

export enum ReplacementType {
Speed = 'speed',
Expand Down
2 changes: 0 additions & 2 deletions main/api/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { updateOrigin, isTrusted, parseOrigin } from './origins'
import validPayload from './validPayload'
import protectedMethods from './protectedMethods'

import type { Permission } from '../store/state'

const logTraffic = process.env.LOG_TRAFFIC

interface PendingRequest {
Expand Down
2 changes: 1 addition & 1 deletion main/api/origins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import queryString from 'query-string'
import accounts, { AccessRequest } from '../accounts'
import store from '../store'

import type { Permission } from '../store/state'
import type { Permission } from '../store/state/types'

const dev = process.env.NODE_ENV === 'development'

Expand Down
2 changes: 1 addition & 1 deletion main/chains/gas/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { intToHex } from '@ethereumjs/util'
import { chainUsesOptimismFees } from '../../../resources/utils/chains'

import type { GasFees } from '../../store/state'
import type { GasFees } from '../../store/state/types'

interface GasCalculator {
calculateGas: (blocks: Block[]) => GasFees
Expand Down
2 changes: 1 addition & 1 deletion main/contracts/deployments/ens/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {

import type { JsonFragment } from '@ethersproject/abi'
import type { DecodableContract } from '../../../transaction/actions'
import type { InventoryCollection } from '../../../store/state'
import type { InventoryCollection } from '../../../store/state/types'

// TODO: fix typing on contract types
type EnsContract = DecodableContract<unknown>
Expand Down
2 changes: 1 addition & 1 deletion main/dapps/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import server from './server'
import extractColors from '../windows/extractColors'
import { dappPathExists, getDappCacheDir, isDappVerified } from './verify'

import type { Dapp } from '../store/state'
import type { Dapp } from '../store/state/types'

const nebula = nebulaApi()

Expand Down
2 changes: 1 addition & 1 deletion main/externalData/balances/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { EventEmitter } from 'stream'
import { toTokenId } from '../../../resources/domain/balance'

import type { CurrencyBalance } from './scan'
import type { Token, TokenBalance } from '../../store/state'
import type { Token, TokenBalance } from '../../store/state/types'

const BOOTSTRAP_TIMEOUT_SECONDS = 20

Expand Down
7 changes: 3 additions & 4 deletions main/externalData/balances/processor/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import log from 'electron-log'

import { isEqual } from 'lodash'

import surface from '../../surface'
import { storeApi } from '../../storeApi'
import { isNativeCurrency, toTokenId } from '../../../../resources/domain/balance'

import type { Token, TokenBalance } from '../../../store/state'
import { NATIVE_CURRENCY } from '../../../../resources/constants'

import type { Token, TokenBalance } from '../../../store/state/types'

type UpdatedBalance = TokenBalance & { hideByDefault?: boolean }

const toExpiryWindow = {
Expand Down Expand Up @@ -136,7 +136,6 @@ export function handleBalanceUpdate(
const withLocalData = mergeCustomAndNative(balances, chains)

const changedBalances = getChangedBalances(address, withLocalData)

if (changedBalances.length) {
storeApi.setBalances(address, changedBalances)
const { toAdd, toRemove } = splitTokenBalances(changedBalances)
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/balances/reducers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Token } from '../../store/state'
import type { Token } from '../../store/state/types'

export interface TokensByChain {
[chainId: number]: Token[]
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/balances/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { groupByChain, TokensByChain } from './reducers'

import type { BytesLike } from '@ethersproject/bytes'
import type EthereumProvider from 'ethereum-provider'
import type { Balance, Token, TokenBalance } from '../../store/state'
import type { Balance, Token, TokenBalance } from '../../store/state/types'

const erc20Interface = new Interface(erc20TokenAbi)

Expand Down
6 changes: 4 additions & 2 deletions main/externalData/balances/scanner/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import log from 'electron-log'

import BalancesWorkerController from '../controller'
import { storeApi } from '../../storeApi'
import { NATIVE_CURRENCY } from '../../../../resources/constants'
import { toTokenId } from '../../../../resources/domain/balance'
import BalancesWorkerController from '../controller'
import { handleBalanceUpdate } from '../processor'
import { CurrencyBalance } from '../scan'
import { Token, TokenBalance, WithTokenId } from '../../../store/state'

import type { Token, TokenBalance, WithTokenId } from '../../../store/state/types'

const RESTART_WAIT = 5 // seconds

Expand Down
6 changes: 3 additions & 3 deletions main/externalData/balances/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ log.transports.file.level = ['development', 'test'].includes(process.env.NODE_EN
? false
: 'verbose'

import { supportsChain as chainSupportsScan } from '../../multicall'
import balancesLoader, { BalanceLoader } from './scan'
import TokenLoader from '../inventory/tokens'
import balancesLoader, { BalanceLoader } from './scan'
import { supportsChain as chainSupportsScan } from '../../multicall'
import { toTokenId } from '../../../resources/domain/balance'

import type { Token } from '../../store/state'
import type { Token } from '../../store/state/types'

interface ExternalDataWorkerMessage {
command: string
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
createTrayObserver
} from './observers'

import type { Token } from '../store/state'
import type { Token } from '../store/state/types'

export interface DataScanner {
close: () => void
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/inventory/processor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import log from 'electron-log'

import { storeApi } from '../../storeApi'

import type { Inventory, InventoryAsset } from '../../../store/state'
import type { Inventory, InventoryAsset } from '../../../store/state/types'

export const updateCollections = (account: string, inventory: Inventory) => {
const existingInventory = storeApi.getInventory(account)
Expand Down
28 changes: 25 additions & 3 deletions main/externalData/inventory/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ import ethProvider from 'eth-provider'
import nebulaApi from '../../nebula'
import defaultTokenList from './default-tokens.json'

import type { Token } from '../../store/state'
import type { Token } from '../../store/state/types'

const TOKENS_ENS_DOMAIN = 'tokens.frame.eth'

type ListedToken = {
chainId: number
address: string
decimals: number
symbol: string
name: string
logoURI?: string
}

interface TokenSpec extends Token {
extensions?: {
omit?: boolean
Expand All @@ -19,6 +28,19 @@ function isBlacklisted(token: TokenSpec) {
return token.extensions?.omit
}

function convertLogoToMedia(listedToken: ListedToken): TokenSpec {
const { logoURI, ...token } = listedToken
return {
...token,
hideByDefault: false,
media: {
source: logoURI || '',
cdn: {},
format: !!logoURI ? 'image' : ''
}
}
}

export default class TokenLoader {
private tokens: TokenSpec[] = defaultTokenList.tokens as TokenSpec[]
private nextLoad?: NodeJS.Timeout | null
Expand All @@ -34,7 +56,7 @@ export default class TokenLoader {
try {
const updatedTokens = await this.fetchTokenList(timeout)
log.info(`Fetched ${updatedTokens.length} tokens`)
this.tokens = updatedTokens
this.tokens = updatedTokens.map(convertLogoToMedia)
log.info(`Updated token list to contain ${this.tokens.length} tokens`)

this.nextLoad = setTimeout(() => this.loadTokenList(), 10 * 60_000)
Expand All @@ -48,7 +70,7 @@ export default class TokenLoader {
log.verbose(`Fetching tokens from ${TOKENS_ENS_DOMAIN}`)

let timeoutHandle: NodeJS.Timeout | undefined
const requestTimeout = new Promise<TokenSpec[]>((resolve, reject) => {
const requestTimeout = new Promise<ListedToken[]>((resolve, reject) => {
timeoutHandle = setTimeout(() => {
reject(`Timeout fetching token list from ${TOKENS_ENS_DOMAIN}`)
}, timeout)
Expand Down
3 changes: 1 addition & 2 deletions main/externalData/observers/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import deepEqual from 'deep-equal'

import store from '../../store'
import { arraysEqual } from '../../../resources/utils'
import { storeApi } from '../storeApi'

import type { Token } from '../../store/state'
import type { Token } from '../../store/state/types'

interface ActiveAddressChangedHandler {
addressChanged: (address: Address) => void
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/rates/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { storeApi } from '../storeApi'
import { toTokenId } from '../../../resources/domain/balance'

import type { AssetId } from '@framelabs/pylon-client/dist/assetId'
import type { Rate, WithTokenId } from '../../store/state'
import type { Rate, WithTokenId } from '../../store/state/types'

type RateUpdate = {
id: AssetId
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/rates/subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { storeApi } from '../storeApi'
import { toTokenId } from '../../../resources/domain/balance'

import type { AssetId } from '@framelabs/pylon-client/dist/assetId'
import type { Chain, Rate, Token, WithTokenId } from '../../store/state'
import type { Chain, Rate, Token, WithTokenId } from '../../store/state/types'

const NO_RATE_DATA = {}
const RATES_LOADED_TIMEOUT = 2000 // 2 seconds
Expand Down
2 changes: 1 addition & 1 deletion main/externalData/storeApi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import store from '../store'
import { NATIVE_CURRENCY } from '../../resources/constants'

import type { Chain, Token, Rate, Inventory, InventoryAsset, TokenBalance } from '../store/state'
import type { Chain, Token, Rate, InventoryAsset, Inventory, TokenBalance } from '../store/state/types'

export const storeApi = {
// Accounts
Expand Down
8 changes: 7 additions & 1 deletion main/externalData/surface/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import Networks from './networks'
import { handleBalanceUpdate } from '../balances/processor'
import { updateCollections, updateItems } from '../inventory/processor'

import type { Inventory, InventoryAsset, Media, TokenBalance } from '../../store/state'
import type {
Inventory,
InventoryAsset,
InventoryCollection,
Media,
TokenBalance
} from '../../store/state/types'

type Subscription = Unsubscribable & { unsubscribables: Unsubscribable[]; collectionItems: CollectionItem[] }

Expand Down
3 changes: 1 addition & 2 deletions main/provider/assets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import store from '../../store'
import { NATIVE_CURRENCY } from '../../../resources/constants'
import { toTokenId } from '../../../resources/domain/balance'

import type { NativeCurrency, Rate, AssetPreferences } from '../../store/state'
import type { TokenBalance } from '../../store/state/types/token'
import type { NativeCurrency, Rate, AssetPreferences, TokenBalance } from '../../store/state/types'

interface AssetsChangedHandler {
assetsChanged: (address: Address, assets: RPC.GetAssets.Assets) => void
Expand Down
5 changes: 2 additions & 3 deletions main/provider/chains/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import deepEqual from 'deep-equal'

import { Colorway, getColor } from '../../../resources/colors'
import store from '../../store'
import { Colorway, getColor } from '../../../resources/colors'

import type { Chain, Origin } from '../../store/state'
import type { ChainMetadata } from '../../store/state/types/chainMeta'
import type { Chain, ChainMetadata, Origin } from '../../store/state/types'

// typed access to state
const storeApi = {
Expand Down
2 changes: 1 addition & 1 deletion main/provider/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import protectedMethods from '../api/protectedMethods'
import { usesBaseFee, TransactionData, GasFeesSource } from '../../resources/domain/transaction'
import { getAddress } from '../../resources/utils'

import type { Chain, Permission } from '../store/state'
import type { Chain } from '../store/state/types'

const permission = (date: number, method: string) => ({ parentCapability: method, date })

Expand Down
2 changes: 1 addition & 1 deletion main/provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ import * as sigParser from '../signatures'
import { hasAddress } from '../../resources/domain/account'
import { mapRequest } from '../requests'

import type { Origin, Token } from '../store/state'
import type { Origin, Token } from '../store/state/types'

interface RequiredApproval {
type: ApprovalType
Expand Down
3 changes: 2 additions & 1 deletion main/provider/subscriptions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { v5 as uuid } from 'uuid'

import store from '../store'

import type { Permission } from '../store/state'
import type { Permission } from '../store/state/types'

const trustedOriginIds = ['frame-extension', 'frame-internal'].map((origin) => uuid(origin, uuid.DNS))
const isTrustedOrigin = (originId: string) => trustedOriginIds.includes(originId)
Expand Down
2 changes: 1 addition & 1 deletion main/signers/hot/HotSigner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { stringToKey } from '../../../crypt'
import Signer from '../../Signer'
import store from '../../../store'

import type { HotSignerType } from '../../../store/state'
import type { HotSignerType } from '../../../store/state/types'
import type { TransactionData } from '../../../../resources/domain/transaction'
import type { TypedMessage } from '../../../accounts/types'
import type {
Expand Down
2 changes: 1 addition & 1 deletion main/signers/hot/HotSigner/worker/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import SeedSignerWorker from '../../SeedSigner/worker'
import launchController from './controller'

import type { WorkerRPCMessage, WorkerTokenMessage } from '../types'
import type { HotSignerType } from '../../../../store/state'
import type { HotSignerType } from '../../../../store/state/types'

const signerType = process.argv[2] as HotSignerType
let worker
Expand Down
2 changes: 1 addition & 1 deletion main/signers/hot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import RingSigner, { RingSignerData } from './RingSigner'

import type { Signers } from '..'
import type Signer from '../Signer'
import type { HotSignerType } from '../../store/state'
import type { HotSignerType } from '../../store/state/types'

export interface HotSignerData {
type: HotSignerType
Expand Down
4 changes: 1 addition & 3 deletions main/store/actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ module.exports = {
u('main.privacy.errorReporting', () => enable)
},
setGasFees: (u, netType, netId, fees) => {
u('main.networksMeta', netType, netId, 'gas.price.fees', () => fees)
u('main.networksMeta', netType, netId, 'gas.fees', () => fees)
},
setGasPrices: (u, netType, netId, prices) => {
u('main.networksMeta', netType, netId, 'gas.price.levels', () => prices)
Expand All @@ -293,8 +293,6 @@ module.exports = {
u('main.networksMeta', netType, netId, 'gas.price.selected', () => level)
if (level === 'custom') {
u('main.networksMeta', netType, netId, 'gas.price.levels.custom', () => price)
} else {
u('main.networksMeta', netType, netId, 'gas.price.lastLevel', () => level)
}
},
setNativeCurrencyData: (u, netType, netId, currency) => {
Expand Down
Loading