Skip to content

Commit

Permalink
Merge branch 'main' into add-alchemy
Browse files Browse the repository at this point in the history
  • Loading branch information
jagodarybacka authored Nov 17, 2023
2 parents d50e061 + 03bc18d commit f08c2d2
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 99 deletions.
3 changes: 1 addition & 2 deletions background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ import { selectActivitesHashesForEnrichment } from "./redux-slices/selectors"
import { getActivityDetails } from "./redux-slices/utils/activities-utils"
import { getRelevantTransactionAddresses } from "./services/enrichment/utils"
import { AccountSignerWithId } from "./signing"
import { AnalyticsPreferences } from "./services/preferences/types"
import {
AnyAssetMetadata,
assetAmountToDesiredDecimals,
Expand Down Expand Up @@ -197,7 +196,7 @@ import {
} from "./services/internal-signer"
import { getPricePoint, getTokenPrices } from "./lib/prices"
import { makeFlashbotsProviderCreator } from "./services/chain/serial-fallback-provider"
import { DismissableItem } from "./services/preferences"
import { AnalyticsPreferences, DismissableItem } from "./services/preferences"
import { newPricePoints } from "./redux-slices/prices"

// This sanitizer runs on store and action data before serializing for remote
Expand Down
3 changes: 1 addition & 2 deletions background/redux-slices/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { AddressOnNetwork } from "../accounts"
import { ETHEREUM } from "../constants"
import { AnalyticsEvent, OneTimeAnalyticsEvent } from "../lib/posthog"
import { EVMNetwork } from "../networks"
import { DismissableItem } from "../services/preferences"
import { AnalyticsPreferences } from "../services/preferences/types"
import { AnalyticsPreferences, DismissableItem } from "../services/preferences"
import { AccountSignerWithId } from "../signing"
import { AccountSignerSettings } from "../ui"
import { AccountState, addAddressNetwork } from "./accounts"
Expand Down
1 change: 1 addition & 0 deletions background/services/chain/serial-fallback-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const ALCHEMY_RPC_METHOD_PROVIDER_ROUTING = {
"eth_sendRawTransaction", // broadcast should always go to alchemy
"eth_subscribe", // generic http providers do not support this, but dapps need this
"eth_estimateGas", // just want to be safe, when setting up a transaction
"eth_getLogs", // to avoid eth_getLogs block range limitations
],
[OPTIMISM.chainID]: [
"eth_call", // this is causing issues on optimism with ankr and is used heavily by uniswap
Expand Down
54 changes: 31 additions & 23 deletions background/services/preferences/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { AddressOnNetwork } from "../../accounts"
import DEFAULT_PREFERENCES, { DEFAULT_AUTOLOCK_INTERVAL } from "./defaults"
import { AccountSignerSettings } from "../../ui"
import { AccountSignerWithId } from "../../signing"
import { AnalyticsPreferences } from "./types"
import { NETWORK_BY_CHAIN_ID } from "../../constants"
import { UNIXTime } from "../../types"

Expand Down Expand Up @@ -45,21 +44,25 @@ const getNewUrlsForTokenList = (
return newURLs
}

// The idea is to use this interface to describe the data structure stored in indexedDb
// In the future this might also have a runtime type check capability, but it's good enough for now.
// NOTE: Check if can be merged with preferences/types.ts
export type TokenListPreferences = {
autoUpdate: boolean
urls: string[]
}

export type AnalyticsPreferences = {
isEnabled: boolean
hasDefaultOnBeenTurnedOn: boolean
}

export type Preferences = {
id?: number
savedAt: number
tokenLists: { autoUpdate: boolean; urls: string[] }
tokenLists: TokenListPreferences
currency: FiatCurrency
defaultWallet: boolean
currentAddress?: string
selectedAccount: AddressOnNetwork
analytics: {
isEnabled: boolean
hasDefaultOnBeenTurnedOn: boolean
}
accountSignersSettings: AccountSignerSettings[]
analytics: AnalyticsPreferences
autoLockInterval: UNIXTime
}

Expand Down Expand Up @@ -143,19 +146,21 @@ export class PreferenceDatabase extends Dexie {
tx
.table("preferences")
.toCollection()
.modify((storedPreferences: Preferences) => {
if (storedPreferences.currentAddress) {
// eslint-disable-next-line no-param-reassign
storedPreferences.selectedAccount = {
network: DEFAULT_PREFERENCES.selectedAccount.network,
address: storedPreferences.currentAddress,
.modify(
(storedPreferences: Preferences & { currentAddress?: string }) => {
if (storedPreferences.currentAddress) {
// eslint-disable-next-line no-param-reassign
storedPreferences.selectedAccount = {
network: DEFAULT_PREFERENCES.selectedAccount.network,
address: storedPreferences.currentAddress,
}
} else {
// eslint-disable-next-line no-param-reassign
storedPreferences.selectedAccount =
DEFAULT_PREFERENCES.selectedAccount
}
} else {
// eslint-disable-next-line no-param-reassign
storedPreferences.selectedAccount =
DEFAULT_PREFERENCES.selectedAccount
}
}),
},
),
)

// Add the new default token list
Expand Down Expand Up @@ -424,7 +429,10 @@ export class PreferenceDatabase extends Dexie {
this.on("populate", (tx: Transaction) => {
// This could be tx.preferences but the typing for populate
// is not generic so it does not know about the preferences table
tx.table("preferences").add(DEFAULT_PREFERENCES)
tx.table<Preferences, string>("preferences").add({
savedAt: Date.now(),
...DEFAULT_PREFERENCES,
})
})
}

Expand Down
3 changes: 1 addition & 2 deletions background/services/preferences/defaults.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { ETHEREUM, MINUTE, USD } from "../../constants"
import { storageGatewayURL } from "../../lib/storage-gateway"
import { Preferences } from "./types"

export const DEFAULT_AUTOLOCK_INTERVAL = 60 * MINUTE

const defaultPreferences: Preferences = {
const defaultPreferences = {
tokenLists: {
autoUpdate: false,
urls: [
Expand Down
17 changes: 13 additions & 4 deletions background/services/preferences/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import { ServiceLifecycleEvents, ServiceCreatorFunction } from "../types"

import {
AnalyticsPreferences,
Preferences,
Preferences as DbPreferences,
TokenListPreferences,
} from "./types"
import { DismissableItem, getOrCreateDB, PreferenceDatabase } from "./db"
DismissableItem,
getOrCreateDB,
PreferenceDatabase,
} from "./db"
import BaseService from "../base"
import { normalizeEVMAddress } from "../../lib/utils"
import { ETHEREUM, OPTIMISM, ARBITRUM_ONE } from "../../constants"
Expand All @@ -16,7 +18,14 @@ import { HexString, UNIXTime } from "../../types"
import { AccountSignerSettings } from "../../ui"
import { AccountSignerWithId } from "../../signing"

export { ManuallyDismissableItem, SingleShotItem, DismissableItem } from "./db"
export {
AnalyticsPreferences,
ManuallyDismissableItem,
SingleShotItem,
DismissableItem,
} from "./db"

export type Preferences = Omit<DbPreferences, "id" | "savedAt">

type AddressBookEntry = {
network: EVMNetwork
Expand Down
24 changes: 0 additions & 24 deletions background/services/preferences/types.ts

This file was deleted.

45 changes: 4 additions & 41 deletions ui/components/DAppConnection/DAppConnection.tsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,15 @@
import { PermissionRequest } from "@tallyho/provider-bridge-shared"
import { selectAllowedPages } from "@tallyho/tally-background/redux-slices/selectors"
import { browser } from "@tallyho/tally-background"
import React, { ReactElement, useCallback, useEffect, useState } from "react"
import { useBackgroundSelector } from "../../hooks"
import React, { ReactElement } from "react"
import ActiveDAppConnection from "./ActiveDAppConnection"
import DAppConnectionDefaultToggle from "./DAppConnectionDefaultToggle"
import { useDappPermission } from "../../hooks/dapp-hooks"

export default function DAppConnection(): ReactElement {
const [isConnectedToDApp, setIsConnectedToDApp] = useState(false)
const [currentPermission, setCurrentPermission] = useState<
PermissionRequest | undefined
>(undefined)

const allowedPages = useBackgroundSelector(selectAllowedPages)

const initPermissionAndOrigin = useCallback(async () => {
const { url } = await browser.tabs
.query({
active: true,
lastFocusedWindow: true,
})
.then((tabs) =>
tabs[0] ? tabs[0] : { url: "", favIconUrl: "", title: "" },
)
if (!url) return

const { origin } = new URL(url)

const allowPermission = allowedPages.find(
(permission) => permission.origin === origin,
)

if (allowPermission) {
setCurrentPermission(allowPermission)
setIsConnectedToDApp(true)
} else {
setIsConnectedToDApp(false)
}
}, [allowedPages, setCurrentPermission])

useEffect(() => {
initPermissionAndOrigin()
}, [initPermissionAndOrigin])
const { isConnected, currentPermission, allowedPages } = useDappPermission()

return (
<section>
<ActiveDAppConnection
isConnectedToDApp={isConnectedToDApp}
isConnectedToDApp={isConnected}
currentPermission={currentPermission}
allowedPages={allowedPages}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ import SharedAddress from "../../../../Shared/SharedAddress"
import { TransactionSignatureSummaryProps } from "./TransactionSignatureSummaryProps"
import TransactionSignatureSummaryBody from "./TransactionSignatureSummaryBody"
import SharedSkeletonLoader from "../../../../Shared/SharedSkeletonLoader"
import { useDappPermission } from "../../../../../hooks/dapp-hooks"

export default function SpendApprovalSummary({
transactionRequest,
annotation,
}: TransactionSignatureSummaryProps<AssetApproval>): ReactElement {
const { currentPermission } = useDappPermission()
const dappFavicon = currentPermission?.faviconUrl

const { t } = useTranslation("translation", {
keyPrefix: "signTransaction.spendApproval",
})
Expand Down Expand Up @@ -240,7 +244,8 @@ export default function SpendApprovalSummary({
<style jsx>
{`
.site_icon {
background: url("./images/dapp_favicon_default@2x.png");
background: url(${dappFavicon ??
"./images/dapp_favicon_default@2x.png"});
background-size: cover;
width: 48px;
height: 48px;
Expand Down
54 changes: 54 additions & 0 deletions ui/hooks/dapp-hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { PermissionRequest } from "@tallyho/provider-bridge-shared"
import { useCallback, useEffect, useState } from "react"
import { browser } from "@tallyho/tally-background"
import { selectAllowedPages } from "@tallyho/tally-background/redux-slices/selectors"
import { useBackgroundSelector } from "./redux-hooks"

// eslint-disable-next-line import/prefer-default-export
export function useDappPermission(): {
isConnected: boolean
currentPermission: PermissionRequest | undefined
allowedPages: PermissionRequest[]
} {
const [isConnected, setisConnected] = useState(false)
const [currentPermission, setCurrentPermission] = useState<
PermissionRequest | undefined
>(undefined)

const allowedPages = useBackgroundSelector(selectAllowedPages)

const initPermissionAndOrigin = useCallback(async () => {
const { url } = await browser.tabs
.query({
active: true,
})
.then((tabs) =>
tabs[0] ? tabs[0] : { url: "", favIconUrl: "", title: "" },
)

if (!url) return

const { origin } = new URL(url)

const allowPermission = allowedPages.find(
(permission) => permission.origin === origin,
)

if (allowPermission) {
setCurrentPermission(allowPermission)
setisConnected(true)
} else {
setisConnected(false)
}
}, [allowedPages, setCurrentPermission])

useEffect(() => {
initPermissionAndOrigin()
}, [initPermissionAndOrigin])

return {
isConnected,
currentPermission,
allowedPages,
}
}

0 comments on commit f08c2d2

Please sign in to comment.