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

Move horizon handling to networker #1255

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion i18n/locales/en/generic.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"cosigner-lacking-key": "Cannot add key pair as co-signer of an account, since no public key for the account to co-sign has been provided",
"expected-json-response-error": "Expected {{url}} to return a JSON response. Content type was {{contentType}} instead.",
"existing-account-error": "An account with that name does already exist.",
"fetch-account-data-error": "Cannot fetch account data of {{account}} from {{horizon}}",
"fetch-account-data-error": "Cannot fetch account data of {{account}}",
"fetch-signature-requests-error": "Fetching signature requests failed: {{response}} \nService: {{service}}",
"fetch-web-auth-challenge-error": "Cannot fetch web auth challenge",
"http-request-error": "HTTP fetch failed: {{response}} \nService: {{service}}",
Expand Down
4 changes: 2 additions & 2 deletions i18n/locales/es/generic.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"bio-auth-test-canceled": "Autenticación biométrica anulada",
"expected-json-response-error": "Se esperaba que {{url}} responda en formato JSON. El tipo de contenido fue {{contentType}}.",
"existing-account-error": "Ya existe otra cuenta con el mismo nombre.",
"fetch-account-data-error": "Imposible recuperar los datos de la cuenta de {{account}} desde {{horizon}}",
"fetch-account-data-error": "Imposible recuperar los datos de la cuenta de {{account}}",
"fetch-web-auth-challenge-error": "Error al obtener el desafío de autenticación",
"fetch-signature-requests-error": "Fallaron las solicitudes de recuperar firmas: {{response}} \nServicio: {{service}}",
"invariant-violation-error": "Violación invariante: {{message}}",
Expand Down Expand Up @@ -96,4 +96,4 @@
"user-interface": {
"copied-to-clipboard": "Copiado a Portapapeles."
}
}
}
2 changes: 1 addition & 1 deletion i18n/locales/it/generic.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"bio-auth-test-canceled": "Autenticazione biometrica annullata",
"expected-json-response-error": "Previsto che {{url}} restituisse una risposta JSON. Il tipo di contenuto era invece {{contentType}}.",
"existing-account-error": "Esiste già un account con quel nome.",
"fetch-account-data-error": "Impossibile recuperare i dati dell'account di {{account}} da {{horizon}}",
"fetch-account-data-error": "Impossibile recuperare i dati dell'account di {{account}}",
"fetch-signature-requests-error": "Recupero delle richieste di firma non riuscito: {{response}} \nService: {{service}}",
"invariant-violation-error": "Violazione invariante: {{message}}",
"low-reserve-order-error": "Impossibile effettuare l'ordine perché il saldo XLM spendibile è troppo basso.",
Expand Down
4 changes: 2 additions & 2 deletions src/Account/components/AccountTransactions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import UpdateIcon from "@material-ui/icons/Update"
import { Account } from "~App/contexts/accounts"
import { SettingsContext } from "~App/contexts/settings"
import { SignatureDelegationContext } from "~App/contexts/signatureDelegation"
import { useHorizonURLs } from "~Generic/hooks/stellar"
import {
useLiveRecentTransactions,
useLiveAccountData,
Expand All @@ -17,6 +16,7 @@ import { useLoadingState } from "~Generic/hooks/util"
import * as routes from "~App/routes"
import MainSelectionButton from "~Generic/components/MainSelectionButton"
import { VerticalLayout } from "~Layout/components/Box"
import { getHorizonURLs } from "~Workers/net-worker/stellar-network"
import FriendbotButton from "./FriendbotButton"
import OfferList from "./OfferList"
import { InteractiveSignatureRequestList } from "./SignatureRequestList"
Expand Down Expand Up @@ -69,7 +69,7 @@ function AccountTransactions(props: { account: Account }) {
const { account } = props
const { t } = useTranslation()
const accountData = useLiveAccountData(account.accountID, account.testnet)
const horizonURLs = useHorizonURLs(account.testnet)
const horizonURLs = getHorizonURLs(account.testnet)
const isSmallScreen = useIsMobile()
const [moreTxsLoadingState, handleMoreTxsFetch] = useLoadingState()
const recentTxs = useLiveRecentTransactions(account.accountID, account.testnet)
Expand Down
11 changes: 4 additions & 7 deletions src/Account/components/OfferList.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BigNumber from "big.js"
import React from "react"
import { Trans, useTranslation } from "react-i18next"
import { Operation, Server, ServerApi, Transaction } from "stellar-sdk"
import { Operation, ServerApi, Transaction } from "stellar-sdk"
import ExpansionPanel from "@material-ui/core/ExpansionPanel"
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails"
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary"
Expand All @@ -17,7 +17,6 @@ import { Account } from "~App/contexts/accounts"
import { breakpoints } from "~App/theme"
import { trackError } from "~App/contexts/notifications"
import { ActionButton } from "~Generic/components/DialogActions"
import { useHorizon } from "~Generic/hooks/stellar"
import { useLoadingState } from "~Generic/hooks/util"
import { useLiveAccountData, useLiveAccountOffers, useOlderOffers } from "~Generic/hooks/stellar-subscriptions"
import { useIsMobile } from "~Generic/hooks/userinterface"
Expand All @@ -30,7 +29,6 @@ import TransactionSender from "~Transaction/components/TransactionSender"
import { SingleBalance } from "./AccountBalances"

function createDismissalTransaction(
horizon: Server,
account: Account,
accountData: AccountData,
offer: ServerApi.OfferRecord
Expand All @@ -49,7 +47,7 @@ function createDismissalTransaction(
selling
})
],
{ accountData, horizon, walletAccount: account }
{ accountData, walletAccount: account }
)
} else {
return createTransaction(
Expand All @@ -62,7 +60,7 @@ function createDismissalTransaction(
selling
})
],
{ accountData, horizon, walletAccount: account }
{ accountData, walletAccount: account }
)
}
}
Expand Down Expand Up @@ -216,7 +214,6 @@ const useStyles = makeStyles({
function OfferList(props: Props & { sendTransaction: (tx: Transaction) => Promise<void> }) {
const accountData = useLiveAccountData(props.account.accountID, props.account.testnet)
const classes = useStyles()
const horizon = useHorizon(props.account.testnet)
const offerHistory = useLiveAccountOffers(props.account.publicKey, props.account.testnet)
const [moreTxsLoadingState, handleMoreTxsFetch] = useLoadingState()
const fetchMoreOffers = useOlderOffers(props.account.publicKey, props.account.testnet)
Expand All @@ -230,7 +227,7 @@ function OfferList(props: Props & { sendTransaction: (tx: Transaction) => Promis

const onCancel = async (offer: ServerApi.OfferRecord) => {
try {
const tx = await createDismissalTransaction(horizon, props.account, accountData, offer)
const tx = await createDismissalTransaction(props.account, accountData, offer)
await props.sendTransaction(tx)
} catch (error) {
trackError(error)
Expand Down
5 changes: 3 additions & 2 deletions src/Account/components/TransactionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { matchesRoute } from "~Generic/lib/routes"
import MemoMessage from "~Transaction/components/MemoMessage"
import TransactionReviewDialog from "~TransactionReview/components/TransactionReviewDialog"
import { useOperationTitle } from "~TransactionReview/components/Operations"
import { getNetwork } from "~Workers/net-worker/stellar-network"
import { SingleBalance } from "./AccountBalances"

const dedupe = <T extends any>(array: T[]): T[] => Array.from(new Set(array))
Expand Down Expand Up @@ -405,7 +406,7 @@ export const TransactionListItem = React.memo(function TransactionListItem(props

const { onOpenTransaction } = props
const restoredTransaction = React.useMemo(
() => TransactionBuilder.fromXDR(props.transactionEnvelopeXdr, props.testnet ? Networks.TESTNET : Networks.PUBLIC),
() => TransactionBuilder.fromXDR(props.transactionEnvelopeXdr, getNetwork(props.testnet)),
[props.testnet, props.transactionEnvelopeXdr]
)

Expand Down Expand Up @@ -506,7 +507,7 @@ function TransactionList(props: TransactionListProps) {
return null
}

const network = props.account.testnet ? Networks.TESTNET : Networks.PUBLIC
const network = getNetwork(props.account.testnet)
const txResponse = props.transactions.find(recentTx => recentTx.hash === openedTxHash)

let tx = txResponse ? TransactionBuilder.fromXDR(txResponse.envelope_xdr, network) : null
Expand Down
6 changes: 2 additions & 4 deletions src/AccountSettings/components/AccountDeletionDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react"
import { useTranslation } from "react-i18next"
import { Operation, Transaction, Server } from "stellar-sdk"
import { Operation, Transaction } from "stellar-sdk"
import DialogContent from "@material-ui/core/DialogContent"
import DialogContentText from "@material-ui/core/DialogContentText"
import Switch from "@material-ui/core/Switch"
Expand Down Expand Up @@ -90,15 +90,13 @@ interface Warning {

interface AccountDeletionDialogProps {
account: Account
horizon: Server
onClose: () => void
onDelete: () => void
sendTransaction: (transaction: Transaction) => void
}

function AccountDeletionDialog(props: AccountDeletionDialogProps) {
const accountData = useLiveAccountData(props.account.accountID, props.account.testnet)
const horizon = props.horizon

const { accounts } = React.useContext(AccountsContext)
const [mergeAccountEnabled, setMergeAccountEnabled] = React.useState(false)
Expand Down Expand Up @@ -126,7 +124,7 @@ function AccountDeletionDialog(props: AccountDeletionDialogProps) {
destination: selectedMergeAccount.publicKey
})
],
{ accountData, horizon, walletAccount: props.account }
{ accountData, walletAccount: props.account }
)

await props.sendTransaction(transaction)
Expand Down
21 changes: 9 additions & 12 deletions src/App/bootstrap/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,17 @@ import { CachingProviders } from "../contexts/caches"
import { NotificationsProvider } from "../contexts/notifications"
import { SettingsProvider } from "../contexts/settings"
import { SignatureDelegationProvider } from "../contexts/signatureDelegation"
import { StellarProvider } from "../contexts/stellar"

export function ContextProviders(props: { children: React.ReactNode }) {
return (
<StellarProvider>
<AccountsProvider>
<SettingsProvider>
<CachingProviders>
<NotificationsProvider>
<SignatureDelegationProvider>{props.children}</SignatureDelegationProvider>
</NotificationsProvider>
</CachingProviders>
</SettingsProvider>
</AccountsProvider>
</StellarProvider>
<AccountsProvider>
<SettingsProvider>
<CachingProviders>
<NotificationsProvider>
<SignatureDelegationProvider>{props.children}</SignatureDelegationProvider>
</NotificationsProvider>
</CachingProviders>
</SettingsProvider>
</AccountsProvider>
)
}
20 changes: 5 additions & 15 deletions src/App/components/DesktopNotifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { TFunction } from "i18next"
import React from "react"
import { useTranslation } from "react-i18next"
import { Asset, Horizon, ServerApi } from "stellar-sdk"
import { useHorizonURLs } from "~Generic/hooks/stellar"
import { useLiveAccountEffects } from "~Generic/hooks/stellar-subscriptions"
import { useRouter } from "~Generic/hooks/userinterface"
import { useSingleton } from "~Generic/hooks/util"
Expand All @@ -12,6 +11,7 @@ import { MultisigTransactionResponse } from "~Generic/lib/multisig-service"
import { showNotification } from "~Platform/notifications"
import { formatBalance } from "~Generic/lib/balances"
import { OfferDetailsString } from "~TransactionReview/components/Operations"
import { getNetwork } from "~Workers/net-worker/stellar-network"
import { NetWorker } from "~Workers/worker-controller"
import { Account, AccountsContext } from "../contexts/accounts"
import { trackError } from "../contexts/notifications"
Expand Down Expand Up @@ -39,13 +39,7 @@ const isTradeEffect = (effect: ServerApi.EffectRecord): effect is TradeEffect =>
const isPaymentEffect = (effect: ServerApi.EffectRecord) =>
effect.type === "account_credited" || effect.type === "account_debited"

function createEffectHandlers(
router: ReturnType<typeof useRouter>,
netWorker: NetWorker,
mainnetHorizonURLs: string[],
testnetHorizonURLs: string[],
t: TFunction
) {
function createEffectHandlers(router: ReturnType<typeof useRouter>, netWorker: NetWorker, t: TFunction) {
return {
async handleTradeEffect(account: Account, effect: TradeEffect) {
const buying =
Expand All @@ -57,8 +51,8 @@ function createEffectHandlers(
? new Asset(effect.sold_asset_code, effect.sold_asset_issuer)
: Asset.native()

const horizonURL = account.testnet ? testnetHorizonURLs : mainnetHorizonURLs
const openOffers = await netWorker.fetchAccountOpenOrders(horizonURL, account.accountID)
const network = getNetwork(account.testnet)
const openOffers = await netWorker.fetchAccountOpenOrders(account.accountID, network)

const orderOnlyPartiallyExecuted = openOffers._embedded.records.find(
offer => String(offer.id) === String(effect.offer_id)
Expand Down Expand Up @@ -107,15 +101,11 @@ function DesktopNotifications() {
const { accounts } = React.useContext(AccountsContext)
const { subscribeToNewSignatureRequests } = React.useContext(SignatureDelegationContext)

const mainnetHorizonURLs = useHorizonURLs(false)
const testnetHorizonURLs = useHorizonURLs(true)
const netWorker = useNetWorker()
const router = useRouter()
const { t } = useTranslation()

const effectHandlers = useSingleton(() =>
createEffectHandlers(router, netWorker, mainnetHorizonURLs, testnetHorizonURLs, t)
)
const effectHandlers = useSingleton(() => createEffectHandlers(router, netWorker, t))

const handleNewSignatureRequest = React.useCallback(
(signatureRequest: MultisigTransactionResponse) => {
Expand Down
100 changes: 0 additions & 100 deletions src/App/contexts/stellar.tsx

This file was deleted.

5 changes: 3 additions & 2 deletions src/App/cordova/keystore.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { KeyStore } from "key-store"
import { Transaction, Keypair, Networks } from "stellar-sdk"
import { Transaction, Keypair } from "stellar-sdk"
import { Messages } from "~shared/ipc"
import { getNetwork } from "~Workers/net-worker/stellar-network"
import { WrongPasswordError } from "~Generic/lib/errors"
import { CommandHandlers, expose } from "./ipc"

Expand Down Expand Up @@ -88,7 +89,7 @@ async function respondWithSignedTransaction(
) {
try {
const account = keyStore.getPublicKeyData(internalAccountID)
const networkPassphrase = account.testnet ? Networks.TESTNET : Networks.PUBLIC
const networkPassphrase = getNetwork(account.testnet)
const transaction = new Transaction(transactionXDR, networkPassphrase)

const privateKey = keyStore.getPrivateKeyData(internalAccountID, password).privateKey
Expand Down
Loading