Skip to content
This repository has been archived by the owner on Oct 10, 2023. It is now read-only.

Handle Ledger LTC txs #2119

Merged
merged 8 commits into from
Mar 5, 2022
Merged
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
"@xchainjs/xchain-crypto": "^0.2.6",
"@xchainjs/xchain-doge": "^0.1.2",
"@xchainjs/xchain-ethereum": "^0.23.3",
"@xchainjs/xchain-litecoin": "^0.7.2",
"@xchainjs/xchain-litecoin": "^0.8.0-alpha.1",
"@xchainjs/xchain-terra": "^0.1.0-alpha.2",
"@xchainjs/xchain-thorchain": "^0.22.2",
"@xchainjs/xchain-util": "^0.6.0",
Expand Down
3 changes: 2 additions & 1 deletion src/main/api/ledger/bitcoin/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import { BaseAmount } from '@xchainjs/xchain-util'
import * as Bitcoin from 'bitcoinjs-lib'
import * as E from 'fp-ts/lib/Either'

import { getSochainUrl } from '../../../../shared/api/sochain'
import { LedgerError, LedgerErrorId, Network } from '../../../../shared/api/types'
import { getHaskoinApiUrl, getSochainUrl } from '../../../../shared/bitcoin/client'
import { getHaskoinApiUrl } from '../../../../shared/bitcoin/client'
import { toClientNetwork } from '../../../../shared/utils/client'
import { isError } from '../../../../shared/utils/guard'
import { getDerivationPath } from './common'
Expand Down
104 changes: 104 additions & 0 deletions src/main/api/ledger/litecoin/transaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import AppBTC from '@ledgerhq/hw-app-btc'
import { Transaction } from '@ledgerhq/hw-app-btc/lib/types'
import Transport from '@ledgerhq/hw-transport'
import { Address, FeeRate, TxHash } from '@xchainjs/xchain-client'
import { broadcastTx, buildTx } from '@xchainjs/xchain-litecoin'
import { BaseAmount } from '@xchainjs/xchain-util'
import * as Bitcoin from 'bitcoinjs-lib'
import * as E from 'fp-ts/lib/Either'

import { getSochainUrl } from '../../../../shared/api/sochain'
import { LedgerError, LedgerErrorId, Network } from '../../../../shared/api/types'
import { getNodeAuth, getNodeUrl } from '../../../../shared/litecoin/client'
import { toClientNetwork } from '../../../../shared/utils/client'
import { isError } from '../../../../shared/utils/guard'
import { getDerivationPath } from './common'

/**
* Sends LTC tx using Ledger
*/
export const send = async ({
transport,
network,
sender,
recipient,
amount,
feeRate,
memo,
walletIndex
}: {
transport: Transport
network: Network
sender?: Address
recipient: Address
amount: BaseAmount
feeRate: FeeRate
memo?: string
walletIndex: number
}): Promise<E.Either<LedgerError, TxHash>> => {
if (!sender) {
return E.left({
errorId: LedgerErrorId.GET_ADDRESS_FAILED,
msg: `Getting sender address using Ledger failed`
})
}

try {
const app = new AppBTC(transport)
const clientNetwork = toClientNetwork(network)
const derivePath = getDerivationPath(walletIndex, clientNetwork)

const { psbt, utxos } = await buildTx({
amount,
recipient,
memo,
feeRate,
sender,
network: clientNetwork,
sochainUrl: getSochainUrl(),
withTxHex: true
})

const inputs: Array<[Transaction, number, string | null, number | null]> = utxos.map(({ txHex, hash, index }) => {
if (!txHex) {
throw Error(`Missing 'txHex' for UTXO (txHash ${hash})`)
}
const utxoTx = Bitcoin.Transaction.fromHex(txHex)
const splittedTx = app.splitTransaction(txHex, utxoTx.hasWitnesses())
return [splittedTx, index, null, null]
})

const associatedKeysets: string[] = inputs.map((_) => derivePath)

const newTxHex = psbt.data.globalMap.unsignedTx.toBuffer().toString('hex')
const newTx: Transaction = app.splitTransaction(newTxHex, true)

const outputScriptHex = app.serializeTransactionOutputs(newTx).toString('hex')

const txHex = await app.createPaymentTransactionNew({
inputs,
associatedKeysets,
outputScriptHex,
segwit: true,
useTrustedInputForSegwit: true,
additionals: ['bech32']
})

const nodeUrl = getNodeUrl(network)
const auth = getNodeAuth()
const txHash = await broadcastTx({ txHex, nodeUrl, auth })

if (!txHash) {
return E.left({
errorId: LedgerErrorId.INVALID_RESPONSE,
msg: `Post request to send LTC transaction using Ledger failed`
})
}
return E.right(txHash)
} catch (error) {
return E.left({
errorId: LedgerErrorId.SEND_TX_FAILED,
msg: isError(error) ? error?.message ?? error.toString() : `${error}`
})
}
}
15 changes: 14 additions & 1 deletion src/main/api/ledger/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import TransportNodeHidSingleton from '@ledgerhq/hw-transport-node-hid-singleton'
import { TxHash } from '@xchainjs/xchain-client'
import { BNBChain, BTCChain, THORChain } from '@xchainjs/xchain-util'
import { BNBChain, BTCChain, LTCChain, THORChain } from '@xchainjs/xchain-util'
import * as E from 'fp-ts/Either'

import { IPCLedgerDepositTxParams, IPCLedgerSendTxParams } from '../../../shared/api/io'
import { LedgerError, LedgerErrorId } from '../../../shared/api/types'
import { isError } from '../../../shared/utils/guard'
import * as BNB from './binance/transaction'
import * as BTC from './bitcoin/transaction'
import * as LTC from './litecoin/transaction'
import * as THOR from './thorchain/transaction'

export const sendTx = async ({
Expand Down Expand Up @@ -59,6 +60,18 @@ export const sendTx = async ({
walletIndex
})
break
case LTCChain:
res = await LTC.send({
transport,
network,
sender,
recipient,
amount,
feeRate,
memo,
walletIndex
})
break
default:
res = E.left({
errorId: LedgerErrorId.NOT_IMPLEMENTED,
Expand Down
6 changes: 3 additions & 3 deletions src/renderer/components/swap/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
to1e8BaseAmount,
isChainAsset
} from '../../helpers/assetHelper'
import { getChainAsset, isBtcChain, isEthChain } from '../../helpers/chainHelper'
import { getChainAsset, isBtcChain, isEthChain, isLtcChain } from '../../helpers/chainHelper'
import { unionAssets } from '../../helpers/fp/array'
import { eqAsset, eqBaseAmount, eqOAsset, eqOApproveParams, eqAddress, eqOAddress } from '../../helpers/fp/eq'
import { sequenceSOption, sequenceTOption } from '../../helpers/fpHelpers'
Expand Down Expand Up @@ -373,7 +373,7 @@ export const Swap = ({
() =>
FP.pipe(
oSourceAsset,
O.map(({ chain }) => isBtcChain(chain) && useSourceAssetLedger),
O.map(({ chain }) => (isBtcChain(chain) || isLtcChain(chain)) && useSourceAssetLedger),
O.getOrElse(() => false)
),
[useSourceAssetLedger, oSourceAsset]
Expand Down Expand Up @@ -1358,7 +1358,7 @@ export const Swap = ({
from={oSourcePoolAsset}
to={oTargetPoolAsset}
disableSlippage={disableSlippage}
disableSlippageMsg={intl.formatMessage({ id: 'swap.slip.tolerance.btc-ledger-disabled.info' })}
disableSlippageMsg={intl.formatMessage({ id: 'swap.slip.tolerance.ledger-disabled.info' })}
/>
</Styled.CurrencyInfoContainer>

Expand Down
57 changes: 37 additions & 20 deletions src/renderer/components/wallet/txs/send/SendFormLTC.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
baseAmount,
baseToAsset,
bn,
formatAssetAmountCurrency
formatAssetAmountCurrency,
LTCChain
} from '@xchainjs/xchain-util'
import { Row, Form } from 'antd'
import { RadioChangeEvent } from 'antd/lib/radio'
Expand All @@ -21,6 +22,7 @@ import * as O from 'fp-ts/lib/Option'
import { useIntl } from 'react-intl'

import { Network } from '../../../../../shared/api/types'
import { isKeystoreWallet, isLedgerWallet } from '../../../../../shared/utils/guard'
import { WalletType } from '../../../../../shared/wallet/types'
import { ZERO_BASE_AMOUNT, ZERO_BN } from '../../../../const'
import { useSubscriptionState } from '../../../../hooks/useSubscriptionState'
Expand All @@ -30,7 +32,7 @@ import { AddressValidation, GetExplorerTxUrl, OpenExplorerTxUrl, WalletBalances
import { FeesWithRatesRD } from '../../../../services/litecoin/types'
import { ValidatePasswordHandler } from '../../../../services/wallet/types'
import { WalletBalance } from '../../../../services/wallet/types'
import { WalletPasswordConfirmationModal } from '../../../modal/confirmation'
import { LedgerConfirmationModal, WalletPasswordConfirmationModal } from '../../../modal/confirmation'
import * as StyledR from '../../../shared/form/Radio.styles'
import { MaxBalanceButton } from '../../../uielements/button/MaxBalanceButton'
import { UIFeesRD } from '../../../uielements/fees'
Expand Down Expand Up @@ -269,16 +271,10 @@ export const SendFormLTC: React.FC<Props> = (props): JSX.Element => {
[intl, maxAmount]
)

// State for visibility of Modal to confirm tx
const [showPwModal, setShowPwModal] = useState(false)

// Send tx start time
const [sendTxStartTime, setSendTxStartTime] = useState<number>(0)

const submitTx = useCallback(() => {
// close PW modal
setShowPwModal(false)

setSendTxStartTime(Date.now())

subscribeSendTxState(
Expand All @@ -305,19 +301,40 @@ export const SendFormLTC: React.FC<Props> = (props): JSX.Element => {
selectedFeeOption
])

const renderPwModal = useMemo(
() =>
showPwModal ? (
const [showConfirmationModal, setShowConfirmationModal] = useState(false)

const renderConfirmationModal = useMemo(() => {
const onSuccessHandler = () => {
setShowConfirmationModal(false)
submitTx()
}
const onCloseHandler = () => {
setShowConfirmationModal(false)
}

if (isLedgerWallet(walletType)) {
return (
<LedgerConfirmationModal
network={network}
onSuccess={onSuccessHandler}
onClose={onCloseHandler}
visible={showConfirmationModal}
chain={LTCChain}
description={intl.formatMessage({ id: 'wallet.ledger.confirm' })}
/>
)
} else if (isKeystoreWallet(walletType)) {
return (
<WalletPasswordConfirmationModal
onSuccess={submitTx}
onClose={() => setShowPwModal(false)}
onSuccess={onSuccessHandler}
onClose={onCloseHandler}
validatePassword$={validatePassword$}
/>
) : (
<></>
),
[submitTx, showPwModal, validatePassword$]
)
)
} else {
return null
}
}, [intl, network, submitTx, showConfirmationModal, validatePassword$, walletType])

const renderTxModal = useMemo(
() =>
Expand Down Expand Up @@ -405,7 +422,7 @@ export const SendFormLTC: React.FC<Props> = (props): JSX.Element => {
// Default value for RadioGroup of feeOptions
feeRate: DEFAULT_FEE_OPTION
}}
onFinish={() => setShowPwModal(true)}
onFinish={() => setShowConfirmationModal(true)}
labelCol={{ span: 24 }}>
<Styled.SubForm>
<Styled.CustomLabel size="big">
Expand Down Expand Up @@ -446,7 +463,7 @@ export const SendFormLTC: React.FC<Props> = (props): JSX.Element => {
</Styled.Form>
</Styled.Col>
</Row>
{renderPwModal}
{showConfirmationModal && renderConfirmationModal}
{renderTxModal}
</>
)
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,4 @@ export const ASYM_DEPOSIT_TOOL_URL: Record<Network, string> = {
}

// @asgdx-team: Extend list whenever another ledger app will be supported
export const SUPPORTED_LEDGER_APPS: Chain[] = [THORChain, BNBChain, BTCChain]
export const SUPPORTED_LEDGER_APPS: Chain[] = [THORChain, BNBChain, BTCChain, LTCChain]
17 changes: 15 additions & 2 deletions src/renderer/hooks/useLiquidityProviders.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from 'react'
import { useEffect, useMemo } from 'react'

import * as RD from '@devexperts/remote-data-ts'
import { Address } from '@xchainjs/xchain-client'
Expand All @@ -7,6 +7,7 @@ import * as A from 'fp-ts/lib/Array'
import * as FP from 'fp-ts/lib/function'
import * as O from 'fp-ts/lib/Option'
import { useObservableState } from 'observable-hooks'
import * as RxOp from 'rxjs/operators'

import { Network } from '../../shared/api/types'
import { useThorchainContext } from '../contexts/ThorchainContext'
Expand Down Expand Up @@ -36,7 +37,19 @@ export const useLiquidityProviders = ({
}) => {
const { getLiquidityProviders } = useThorchainContext()

const [providers] = useObservableState(() => getLiquidityProviders({ asset, network }), RD.initial)
const [providers, networkUpdated] = useObservableState<LiquidityProvidersRD, Network>(
(network$) =>
FP.pipe(
network$,
RxOp.distinctUntilChanged(),
RxOp.switchMap((network) => getLiquidityProviders({ asset, network }))
),
RD.initial
)

// `networkUpdated` needs to be called whenever network has been updated
// to update `useObservableState` properly to push latest `network` into `getLiquidityProviders`
useEffect(() => networkUpdated(network), [network, networkUpdated])

/**
* Gets liquidity provider data by given RUNE + asset address
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/i18n/de/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const swap: SwapMessages = {
'swap.slip.tolerance': 'Slippage-Toleranz',
'swap.slip.tolerance.info':
'Je höher die Prozentangabe, je höher akzeptierst Du ein Slippage. Mehr Slippage bedeutet zugleich ein größerer Spielraum zur Abdeckung der geschätzten Gebühren, um fehlgeschlagene Swaps zu vermeiden.',
'swap.slip.tolerance.btc-ledger-disabled.info':
'Das Auswählen der Slippage-Toleranz ist deaktiviert aufgrund technischer Probleme mit Ledger und BTC.',
'swap.slip.tolerance.ledger-disabled.info':
'Slippage-Toleranz ist deaktiviert aufgrund technischer Probleme mit Ledger.',
'swap.errors.amount.balanceShouldCoverChainFee':
'Transaktionsgebühr in Höhe von {fee} ist nicht über Dein Guthaben {balance} gedeckt.',
'swap.errors.amount.outputShouldCoverChainFee':
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/i18n/en/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const swap: SwapMessages = {
'swap.slip.tolerance': 'Slippage tolerance',
'swap.slip.tolerance.info':
'The higher the percentage, the more slippage you will accept. More slippage includes also a wider range for covering estimated fees to avoid aborted swaps.',
'swap.slip.tolerance.btc-ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger and BTC.',
'swap.slip.tolerance.ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger.',
'swap.errors.amount.balanceShouldCoverChainFee':
'Transaction fee {fee} needs to be covered by your balance (currently {balance}).',
'swap.errors.amount.outputShouldCoverChainFee':
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/i18n/fr/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const swap: SwapMessages = {
'swap.slip.tolerance': 'Tolérance de slippage',
'swap.slip.tolerance.info':
"Plus le pourcentage est élevé, plus vous acceptez de slippage. Ceci inclus également un écart plus important pour couvrir les frais estimés, afin d'éviter les échanges avortés.",
'swap.slip.tolerance.btc-ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger and BTC. - FR',
'swap.slip.tolerance.ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger. - FR',
'swap.errors.amount.balanceShouldCoverChainFee':
'{fee} de frais de transaction doivent être couverts par votre solde (actuellement {balance}).',
'swap.errors.amount.outputShouldCoverChainFee':
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/i18n/ru/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const swap: SwapMessages = {
'swap.slip.tolerance': 'Допуск по проскальзыванию',
'swap.slip.tolerance.info':
'Чем выше процент, тем большее проскальзывание вы допускаете. Большее проскальзывание включает также более широкий диапазон расчёта комиссий во избежание прерывания обмена.',
'swap.slip.tolerance.btc-ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger and BTC. - RU',
'swap.slip.tolerance.ledger-disabled.info':
'Selecting slippage tolerance has been disabled due technical issues with Ledger. - RU',
'swap.errors.amount.balanceShouldCoverChainFee':
'Комиссия транзакции {fee} дожна покрываться вашим балансом (сейчас {balance}).',
'swap.errors.amount.outputShouldCoverChainFee':
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/i18n/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ type SwapMessageKey =
| 'swap.slip.title'
| 'swap.slip.tolerance'
| 'swap.slip.tolerance.info'
| 'swap.slip.tolerance.btc-ledger-disabled.info'
| 'swap.slip.tolerance.ledger-disabled.info'
| 'swap.state.pending'
| 'swap.state.success'
| 'swap.state.error'
Expand Down
Loading