Skip to content

Commit

Permalink
fix(earn): approve standby tx handling for swap-deposit (#6055)
Browse files Browse the repository at this point in the history
### Description

Use the fromToken instead of the depositToken to identify approve tx
(works for both deposit and swap-deposit)

### Test plan

Unit tests, manually doing swap deposit from ERC-20 token

### Related issues

- N/A

### Backwards compatibility

Yes

### Network scalability

If a new NetworkId and/or Network are added in the future, the changes
in this PR will:

- [x] Continue to work without code changes, OR trigger a compilation
error (guaranteeing we find it when a new network is added)
  • Loading branch information
satish-ravi authored Sep 19, 2024
1 parent 21f4de3 commit 4727655
Show file tree
Hide file tree
Showing 2 changed files with 231 additions and 16 deletions.
211 changes: 208 additions & 3 deletions src/earn/saga.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import networkConfig from 'src/web3/networkConfig'
import { createMockStore } from 'test/utils'
import {
mockAaveArbUsdcTokenId,
mockArbArbAddress,
mockArbArbTokenId,
mockArbUsdcTokenId,
mockEarnPositions,
Expand Down Expand Up @@ -117,9 +118,11 @@ describe('depositSubmitSaga', () => {
mockStandbyHandler(standbyHandlers[0]('0x2'))
return ['0x2']
} else {
mockStandbyHandler(standbyHandlers[0]('0x1'))
mockStandbyHandler(standbyHandlers[1]('0x2'))
return ['0x1', '0x2']
return (txs as any[]).map((_tx, i) => {
const hash = `0x${i + 1}`
mockStandbyHandler(standbyHandlers[i](`0x${i + 1}`))
return hash
})
}
}),
],
Expand All @@ -131,6 +134,10 @@ describe('depositSubmitSaga', () => {
call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x2' }),
mockTxReceipt2,
],
[
call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x3' }),
mockTxReceipt2,
],
]

const expectedAnalyticsProps = {
Expand Down Expand Up @@ -224,6 +231,10 @@ describe('depositSubmitSaga', () => {
beforeEach(() => {
jest.clearAllMocks()
jest.mocked(isGasSubsidizedForNetwork).mockReturnValue(false)
jest.mocked(decodeFunctionData).mockReturnValue({
functionName: 'approve',
args: ['0xspenderAddress', BigInt(1e8)],
})
})

it('sends approve and deposit transactions, navigates home and dispatches the success action (gas subsidy on)', async () => {
Expand Down Expand Up @@ -317,6 +328,200 @@ describe('depositSubmitSaga', () => {
expect(mockIsGasSubsidizedCheck).not.toHaveBeenCalledWith(true)
})

it('sends approve and swap-deposit transactions, navigates home and dispatches the success action (gas subsidy off)', async () => {
jest.mocked(decodeFunctionData).mockReturnValue({
functionName: 'approve',
args: ['0xspenderAddress', BigInt(5e19)],
})
await expectSaga(depositSubmitSaga, {
type: depositStart.type,
payload: {
amount: '100',
pool: mockEarnPositions[0],
preparedTransactions: [
{ ...serializableApproveTx, to: mockArbArbAddress as Address },
serializableDepositTx,
],
mode: 'swap-deposit',
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
},
})
.withState(createMockStore({ tokens: { tokenBalances: mockTokenBalances } }).getState())
.provide(sagaProviders)
.put(
depositSuccess({
tokenId: mockArbUsdcTokenId,
networkId: NetworkId['arbitrum-sepolia'],
transactionHash: '0x2',
})
)
.put(fetchTokenBalances({ showLoading: false }))
.call.like({ fn: sendPreparedTransactions })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x1' })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x2' })
.run()
expect(navigateHome).toHaveBeenCalled()
expect(decodeFunctionData).toHaveBeenCalledWith({
abi: erc20Abi,
data: serializableApproveTx.data,
})
expect(mockStandbyHandler).toHaveBeenCalledTimes(2)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(1, {
...expectedApproveStandbyTx,
approvedAmount: '50',
tokenId: mockArbArbTokenId,
})
expect(mockStandbyHandler).toHaveBeenNthCalledWith(2, expectedDepositStandbyTx)
expect(AppAnalytics.track).toHaveBeenCalledWith(EarnEvents.earn_deposit_submit_start, {
...expectedAnalyticsProps,
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
mode: 'swap-deposit',
})
expect(AppAnalytics.track).toHaveBeenCalledWith(EarnEvents.earn_deposit_submit_success, {
...expectedAnalyticsProps,
...expectedCumulativeGasAnalyticsProperties,
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
mode: 'swap-deposit',
})
expect(mockIsGasSubsidizedCheck).toHaveBeenCalledWith(false)
expect(mockIsGasSubsidizedCheck).not.toHaveBeenCalledWith(true)
})

it('sends only swap-deposit transaction, navigates home and dispatches the success action (gas subsidy on)', async () => {
jest.mocked(isGasSubsidizedForNetwork).mockReturnValue(true)
await expectSaga(depositSubmitSaga, {
type: depositStart.type,
payload: {
amount: '100',
pool: mockEarnPositions[0],
preparedTransactions: [serializableDepositTx],
mode: 'swap-deposit',
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
},
})
.withState(createMockStore({ tokens: { tokenBalances: mockTokenBalances } }).getState())
.provide(sagaProviders)
.put(
depositSuccess({
tokenId: mockArbUsdcTokenId,
networkId: NetworkId['arbitrum-sepolia'],
transactionHash: '0x2',
})
)
.put(fetchTokenBalances({ showLoading: false }))
.call.like({ fn: sendPreparedTransactions })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x2' })
.run()
expect(navigateHome).toHaveBeenCalled()
expect(decodeFunctionData).not.toHaveBeenCalled()
expect(mockStandbyHandler).toHaveBeenCalledTimes(1)
expect(mockStandbyHandler).toHaveBeenCalledWith(expectedDepositStandbyTx)
expect(AppAnalytics.track).toHaveBeenCalledWith(EarnEvents.earn_deposit_submit_start, {
...expectedAnalyticsProps,
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
mode: 'swap-deposit',
})
expect(AppAnalytics.track).toHaveBeenCalledWith(EarnEvents.earn_deposit_submit_success, {
...expectedAnalyticsProps,
...expectedDepositGasAnalyticsProperties,
gasFee: 0.00185837,
gasFeeUsd: 2.787555,
gasUsed: 371674,
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
mode: 'swap-deposit',
})
expect(mockIsGasSubsidizedCheck).toHaveBeenCalledWith(true)
expect(mockIsGasSubsidizedCheck).not.toHaveBeenCalledWith(false)
})

it('uses null standby transactions if there are more than two prepared transactions', async () => {
await expectSaga(depositSubmitSaga, {
type: depositStart.type,
payload: {
amount: '100',
pool: mockEarnPositions[0],
preparedTransactions: [
serializableApproveTx,
serializableDepositTx,
{ ...serializableDepositTx, to: '0xd' },
],
mode: 'deposit',
fromTokenAmount: '100',
fromTokenId: mockArbUsdcTokenId,
},
})
.withState(createMockStore({ tokens: { tokenBalances: mockTokenBalances } }).getState())
.provide(sagaProviders)
.put(
depositSuccess({
tokenId: mockArbUsdcTokenId,
networkId: NetworkId['arbitrum-sepolia'],
transactionHash: '0x3',
})
)
.put(fetchTokenBalances({ showLoading: false }))
.call.like({ fn: sendPreparedTransactions })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x1' })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x2' })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x3' })
.run()
expect(navigateHome).toHaveBeenCalled()
expect(decodeFunctionData).not.toHaveBeenCalled()
expect(mockStandbyHandler).toHaveBeenCalledTimes(3)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(1, null)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(2, null)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(3, null)
})

it('uses null standby transaction for approve if there are two prepared transactions and the first is not approve', async () => {
jest.mocked(decodeFunctionData).mockReturnValue({
functionName: 'not-approve',
args: ['0xspenderAddress', BigInt(5e19)],
})
await expectSaga(depositSubmitSaga, {
type: depositStart.type,
payload: {
amount: '100',
pool: mockEarnPositions[0],
preparedTransactions: [
{ ...serializableApproveTx, to: mockArbArbAddress as Address },
serializableDepositTx,
],
mode: 'swap-deposit',
fromTokenAmount: '50',
fromTokenId: mockArbArbTokenId,
},
})
.withState(createMockStore({ tokens: { tokenBalances: mockTokenBalances } }).getState())
.provide(sagaProviders)
.put(
depositSuccess({
tokenId: mockArbUsdcTokenId,
networkId: NetworkId['arbitrum-sepolia'],
transactionHash: '0x2',
})
)
.put(fetchTokenBalances({ showLoading: false }))
.call.like({ fn: sendPreparedTransactions })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x1' })
.call([publicClient[Network.Arbitrum], 'waitForTransactionReceipt'], { hash: '0x2' })
.run()
expect(navigateHome).toHaveBeenCalled()
expect(decodeFunctionData).toHaveBeenCalledWith({
abi: erc20Abi,
data: serializableApproveTx.data,
})
expect(mockStandbyHandler).toHaveBeenCalledTimes(2)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(1, null)
expect(mockStandbyHandler).toHaveBeenNthCalledWith(2, expectedDepositStandbyTx)
})

it('dispatches cancel action if pin input is cancelled and does not navigate home', async () => {
await expectSaga(depositSubmitSaga, {
type: depositStart.type,
Expand Down
36 changes: 23 additions & 13 deletions src/earn/saga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,25 +82,29 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
fromTokenAmount,
fromTokenId,
} = action.payload
const tokenId = pool.dataProps.depositTokenId
const depositTokenId = pool.dataProps.depositTokenId

const preparedTransactions = getPreparedTransactions(serializablePreparedTransactions)

const tokenInfo = yield* call(getTokenInfo, tokenId)
if (!tokenInfo) {
Logger.error(`${TAG}/depositSubmitSaga`, 'Token info not found for token id', tokenId)
const depositTokenInfo = yield* call(getTokenInfo, depositTokenId)
const fromTokenInfo = yield* call(getTokenInfo, fromTokenId)
if (!depositTokenInfo || !fromTokenInfo) {
Logger.error(
`${TAG}/depositSubmitSaga`,
`Token info not found for token ids ${depositTokenId} and/or ${fromTokenId}`
)
yield* put(depositError())
return
}

const tokensById = yield* select((state) =>
tokensByIdSelector(state, { networkIds: [tokenInfo.networkId], includePositionTokens: true })
tokensByIdSelector(state, { networkIds: [pool.networkId], includePositionTokens: true })
)

const trackedTxs: TrackedTx[] = []
const networkId = tokenInfo.networkId
const networkId = pool.networkId
const commonAnalyticsProps = {
depositTokenId: tokenId,
depositTokenId,
depositTokenAmount: amount,
networkId,
providerId: pool.appId,
Expand All @@ -115,7 +119,7 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
try {
Logger.debug(
`${TAG}/depositSubmitSaga`,
`Starting deposit for token ${tokenId}, total transactions: ${preparedTransactions.length}`
`Starting ${mode} with token ${fromTokenId}, total transactions: ${preparedTransactions.length}`
)

for (const tx of preparedTransactions) {
Expand All @@ -137,13 +141,13 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
})
if (
functionName === 'approve' &&
preparedTransactions[0].to === tokenInfo.address &&
preparedTransactions[0].to === fromTokenInfo.address &&
args
) {
Logger.debug(`${TAG}/depositSubmitSaga`, 'First transaction is an approval transaction')
const approvedAmountInSmallestUnit = args[1] as bigint
const approvedAmount = new BigNumber(approvedAmountInSmallestUnit.toString())
.shiftedBy(-tokenInfo.decimals)
.shiftedBy(-fromTokenInfo.decimals)
.toString()

const createApprovalStandbyTx = (
Expand All @@ -156,12 +160,18 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
networkId,
type: TokenTransactionTypeV2.Approval,
transactionHash,
tokenId,
tokenId: fromTokenId,
approvedAmount,
feeCurrencyId,
}
}
createDepositStandbyTxHandlers.push(createApprovalStandbyTx)
} else {
Logger.info(
TAG,
'First transaction is not an expected approval transaction, using empty standby handler'
)
createDepositStandbyTxHandlers.push(() => null)
}
}

Expand All @@ -180,7 +190,7 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
},
outAmount: {
value: amount,
tokenId,
tokenId: depositTokenId,
},
providerId: pool.appId,
transactionHash,
Expand Down Expand Up @@ -244,7 +254,7 @@ export function* depositSubmitSaga(action: PayloadAction<DepositInfo>) {
})
yield* put(
depositSuccess({
tokenId: tokenInfo.tokenId,
tokenId: depositTokenInfo.tokenId,
networkId,
transactionHash: txHashes[txHashes.length - 1],
})
Expand Down

0 comments on commit 4727655

Please sign in to comment.