Skip to content

Commit

Permalink
chore: use api endpoints for swap logic (brave#21454)
Browse files Browse the repository at this point in the history
* chore: use api endpoints for swap logic

* chore: move sendSolanaSerializedTransaction to a mutation
  • Loading branch information
josheleonard authored Dec 29, 2023
1 parent 67c3a5f commit 6e1a0a2
Show file tree
Hide file tree
Showing 7 changed files with 207 additions and 94 deletions.
33 changes: 1 addition & 32 deletions components/brave_wallet_ui/common/async/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ import { mapLimit } from 'async'
import {
HardwareWalletConnectOpts //
} from '../../components/desktop/popup-modals/add-account-modal/hardware-wallet-connect/types'
import {
BraveWallet,
SolanaSerializedTransactionParams
} from '../../constants/types'
import { BraveWallet } from '../../constants/types'
import * as WalletActions from '../actions/wallet_actions'

// Utils
Expand Down Expand Up @@ -49,7 +46,6 @@ import {
isIpfs,
stripERC20TokenImageURL
} from '../../utils/string-utils'
import { toTxDataUnion } from '../../utils/tx-utils'

export const onConnectHardwareWallet = (
opts: HardwareWalletConnectOpts
Expand Down Expand Up @@ -178,33 +174,6 @@ export function refreshVisibleTokenInfo(
}
}

export async function sendSolanaSerializedTransaction(
payload: SolanaSerializedTransactionParams
) {
const { solanaTxManagerProxy, txService } = getAPIProxy()
const result =
await solanaTxManagerProxy.makeTxDataFromBase64EncodedTransaction(
payload.encodedTransaction,
payload.txType,
payload.sendOptions || null
)
if (result.error !== BraveWallet.ProviderError.kSuccess) {
console.error(`Failed to sign Solana message: ${result.errorMessage}`)
return { success: false, errorMessage: result.errorMessage, txMetaId: '' }
}

return await txService.addUnapprovedTransaction(
toTxDataUnion({ solanaTxData: result.txData ?? undefined }),
payload.chainId,
payload.accountId
)
}

export function getSwapService() {
const { swapService } = getAPIProxy()
return swapService
}

export async function getNFTMetadata(token: BraveWallet.BlockchainToken) {
const { jsonRpcService } = getAPIProxy()
if (token.coin === BraveWallet.CoinType.ETH) {
Expand Down
7 changes: 7 additions & 0 deletions components/brave_wallet_ui/common/slices/api.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { tokenBalancesEndpoints } from './endpoints/token_balances.endpoints'
import { fiatCurrencyEndpoints } from './endpoints/fiat_currency.endpoints'
import { sitePermissionEndpoints } from './endpoints/site_permissions.endpoints'
import { transactionEndpoints } from './endpoints/transaction.endpoints'
import { swapEndpoints } from './endpoints/swap.endpoints'

export function createWalletApi() {
// base to add endpoints to
Expand Down Expand Up @@ -146,6 +147,8 @@ export function createWalletApi() {
.injectEndpoints({ endpoints: fiatCurrencyEndpoints })
// Site permission (connected accounts) endpoints
.injectEndpoints({ endpoints: sitePermissionEndpoints })
// Brave Swap endpoints
.injectEndpoints({ endpoints: swapEndpoints })
)
}

Expand All @@ -171,7 +174,10 @@ export const {
useConnectToSiteMutation,
useCreateWalletMutation,
useEnableEnsOffchainLookupMutation,
useGenerateBraveSwapFeeMutation,
useGenerateReceiveAddressMutation,
useGenerateSwapQuoteMutation,
useGenerateSwapTransactionMutation,
useGetAccountInfosRegistryQuery,
useGetAccountTokenCurrentBalanceQuery,
useGetActiveOriginConnectedAccountIdsQuery,
Expand Down Expand Up @@ -290,6 +296,7 @@ export const {
useSendETHFilForwarderTransferMutation,
useSendEvmTransactionMutation,
useSendFilTransactionMutation,
useSendSolanaSerializedTransactionMutation,
useSendSolTransactionMutation,
useSendSPLTransferMutation,
useSendZecTransactionMutation,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright (c) 2023 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

// types
import { BraveWallet } from '../../../constants/types'
import { WalletApiEndpointBuilderParams } from '../api-base.slice'

// utils
import { handleEndpointError } from '../../../utils/api-utils'

export const swapEndpoints = ({
mutation,
query
}: WalletApiEndpointBuilderParams) => {
return {
generateBraveSwapFee: mutation<
{
response: BraveWallet.BraveSwapFeeResponse | null
errorString: string
},
BraveWallet.BraveSwapFeeParams
>({
queryFn: async (params, { endpoint }, extraOptions, baseQuery) => {
const { swapService } = baseQuery(undefined).data
try {
const result = await swapService.getBraveFee(params)
return {
data: result
}
} catch (error) {
return handleEndpointError(
endpoint,
'Unable to fetch Brave Swap fee',
error
)
}
}
}),

generateSwapQuote: mutation<
{
response: BraveWallet.SwapQuoteUnion | null
error: BraveWallet.SwapErrorUnion | null
errorString: string
},
BraveWallet.SwapQuoteParams
>({
queryFn: async (params, { endpoint }, extraOptions, baseQuery) => {
const { swapService } = baseQuery(undefined).data
try {
const result = await swapService.getQuote(params)
return {
data: result
}
} catch (error) {
return handleEndpointError(
endpoint,
'Unable to generate Brave Swap quote',
error
)
}
}
}),

generateSwapTransaction: mutation<
{
response: BraveWallet.SwapTransactionUnion | null
error: BraveWallet.SwapErrorUnion | null
errorString: string
},
BraveWallet.SwapTransactionParamsUnion
>({
queryFn: async (params, { endpoint }, extraOptions, baseQuery) => {
const { swapService } = baseQuery(undefined).data
try {
const result = await swapService.getTransaction(params)
return {
data: result
}
} catch (error) {
return handleEndpointError(
endpoint,
'Unable to generate Brave Swap transaction',
error
)
}
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,59 @@ export const transactionEndpoints = ({
})
}),

sendSolanaSerializedTransaction: mutation<
boolean, // success,
{
encodedTransaction: string
chainId: string
accountId: BraveWallet.AccountId
txType: BraveWallet.TransactionType
sendOptions?: BraveWallet.SolanaSendTransactionOptions
}
>({
queryFn: async (payload, { endpoint }, extraOptions, baseQuery) => {
try {
const { data: api } = baseQuery(undefined)
const { solanaTxManagerProxy, txService } = api
const result =
await solanaTxManagerProxy.makeTxDataFromBase64EncodedTransaction(
payload.encodedTransaction,
payload.txType,
payload.sendOptions || null
)

if (result.error !== BraveWallet.ProviderError.kSuccess) {
throw new Error(
`Failed to sign Solana message: ${result.errorMessage}`
)
}

const { errorMessage, success } =
await txService.addUnapprovedTransaction(
toTxDataUnion({ solanaTxData: result.txData ?? undefined }),
payload.chainId,
payload.accountId
)

if (!success) {
throw new Error(
`Error creating Solana transaction: ${errorMessage}`
)
}

return {
data: success
}
} catch (error) {
return handleEndpointError(
endpoint,
'Failed to send Solana serialized transaction',
error
)
}
}
}),

// BTC
sendBtcTransaction: mutation<
{ success: boolean },
Expand Down
8 changes: 0 additions & 8 deletions components/brave_wallet_ui/constants/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,14 +344,6 @@ export interface SPLTransferFromParams extends BaseTransactionParams {
splTokenMintAddress: string
}

export interface SolanaSerializedTransactionParams {
encodedTransaction: string
chainId: string
accountId: BraveWallet.AccountId
txType: BraveWallet.TransactionType
sendOptions?: BraveWallet.SolanaSendTransactionOptions
}

export interface SendEthTransactionParams extends BaseEthTransactionParams {
data?: number[]
}
Expand Down
Loading

0 comments on commit 6e1a0a2

Please sign in to comment.