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

feat(earn): add function for preparing supply transaction #5405

Merged
merged 5 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
148 changes: 148 additions & 0 deletions src/earn/prepareTransactions.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import BigNumber from 'bignumber.js'
import aavePool from 'src/abis/AavePoolV3'
import erc20 from 'src/abis/IERC20'
import { prepareSupplyTransactions } from 'src/earn/prepareTransactions'
import { TokenBalance } from 'src/tokens/slice'
import { Network, NetworkId } from 'src/transactions/types'
import { publicClient } from 'src/viem'
import { prepareTransactions } from 'src/viem/prepareTransactions'
import { encodeFunctionData } from 'viem'

const mockFeeCurrency: TokenBalance = {
address: null,
balance: new BigNumber(100), // 10k units, 100.0 decimals
decimals: 2,
priceUsd: null,
lastKnownPriceUsd: null,
tokenId: 'arbitrum-sepolia:native',
symbol: 'FEE1',
name: 'Fee token 1',
networkId: NetworkId['arbitrum-sepolia'],
isNative: true,
}

const mockToken: TokenBalance = {
address: '0xusdc',
balance: new BigNumber(10),
decimals: 6,
priceUsd: null,
lastKnownPriceUsd: null,
tokenId: 'arbitrum-sepolia:0xusdc',
symbol: 'USDC',
name: 'USD Coin',
networkId: NetworkId['arbitrum-sepolia'],
}

jest.mock('src/viem/prepareTransactions')
jest.mock('viem', () => ({
...jest.requireActual('viem'),
encodeFunctionData: jest.fn(),
}))

describe('prepareTransactions', () => {
beforeEach(() => {
jest.clearAllMocks()
jest.mocked(prepareTransactions).mockImplementation(async ({ baseTransactions }) => ({
transactions: baseTransactions,
type: 'possible',
feeCurrency: mockFeeCurrency,
}))
jest.mocked(encodeFunctionData).mockReturnValue('0xencodedData')
})

describe('prepareSupplyTransactions', () => {
it('prepares transactions with approve and supply if not already approved', async () => {
jest.spyOn(publicClient[Network.Arbitrum], 'readContract').mockResolvedValue(BigInt(0))

const result = await prepareSupplyTransactions({
amount: '5',
token: mockToken,
walletAddress: '0x1234',
feeCurrencies: [mockFeeCurrency],
poolContractAddress: '0x5678',
})

const expectedTransactions = [
{
from: '0x1234',
to: '0xusdc',
data: '0xencodedData',
},
{
from: '0x1234',
to: '0x5678',
data: '0xencodedData',
},
]
expect(result).toEqual({
type: 'possible',
feeCurrency: mockFeeCurrency,
transactions: expectedTransactions,
})
expect(publicClient[Network.Arbitrum].readContract).toHaveBeenCalledWith({
address: '0xusdc',
abi: erc20.abi,
functionName: 'allowance',
args: ['0x1234', '0xusdc'],
})
expect(encodeFunctionData).toHaveBeenNthCalledWith(1, {
abi: erc20.abi,
functionName: 'approve',
args: ['0x5678', BigInt(5e6)],
})
expect(encodeFunctionData).toHaveBeenNthCalledWith(2, {
abi: aavePool,
functionName: 'supply',
args: ['0xusdc', BigInt(5e6), '0x1234', 0],
})
expect(prepareTransactions).toHaveBeenCalledWith({
baseTransactions: expectedTransactions,
feeCurrencies: [mockFeeCurrency],
spendToken: mockToken,
spendTokenAmount: new BigNumber(5),
})
})

it('prepares transactions with supply if already approved', async () => {
jest.spyOn(publicClient[Network.Arbitrum], 'readContract').mockResolvedValue(BigInt(5e6))

const result = await prepareSupplyTransactions({
amount: '5',
token: mockToken,
walletAddress: '0x1234',
feeCurrencies: [mockFeeCurrency],
poolContractAddress: '0x5678',
})

const expectedTransactions = [
{
from: '0x1234',
to: '0x5678',
data: '0xencodedData',
},
]
expect(result).toEqual({
type: 'possible',
feeCurrency: mockFeeCurrency,
transactions: expectedTransactions,
})
expect(publicClient[Network.Arbitrum].readContract).toHaveBeenCalledWith({
address: '0xusdc',
abi: erc20.abi,
functionName: 'allowance',
args: ['0x1234', '0xusdc'],
})
expect(encodeFunctionData).toHaveBeenNthCalledWith(1, {
abi: aavePool,
functionName: 'supply',
args: ['0xusdc', BigInt(5e6), '0x1234', 0],
})
expect(prepareTransactions).toHaveBeenCalledWith({
baseTransactions: expectedTransactions,
feeCurrencies: [mockFeeCurrency],
spendToken: mockToken,
spendTokenAmount: new BigNumber(5),
})
})
})
})
75 changes: 75 additions & 0 deletions src/earn/prepareTransactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import BigNumber from 'bignumber.js'
import aavePool from 'src/abis/AavePoolV3'
import erc20 from 'src/abis/IERC20'
import { TokenBalance } from 'src/tokens/slice'
import { publicClient } from 'src/viem'
import { TransactionRequest, prepareTransactions } from 'src/viem/prepareTransactions'
import { networkIdToNetwork } from 'src/web3/networkConfig'
import { Address, encodeFunctionData, parseUnits } from 'viem'

export async function prepareSupplyTransactions({
amount,
token,
walletAddress,
feeCurrencies,
poolContractAddress,
}: {
amount: string
token: TokenBalance
walletAddress: Address
feeCurrencies: TokenBalance[]
poolContractAddress: Address
}) {
const baseTransactions: TransactionRequest[] = []

// amount in smallest unit
const amountToSupply = parseUnits(amount, token.decimals)

if (!token.address) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i've been nagging people to use the viem type guard in places like this:

if (!token.address || !isAddress(token.address) {

// should never happen
throw new Error('Cannot use a token without address')

Check warning on line 30 in src/earn/prepareTransactions.ts

View check run for this annotation

Codecov / codecov/patch

src/earn/prepareTransactions.ts#L30

Added line #L30 was not covered by tests
satish-ravi marked this conversation as resolved.
Show resolved Hide resolved
}

const approvedAllowanceForSpender = await publicClient[
networkIdToNetwork[token.networkId]
].readContract({
address: token.address as Address,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...then you can drop the type assertions and maybe feel good about that.

abi: erc20.abi,
functionName: 'allowance',
args: [walletAddress, token.address as Address],
})

if (approvedAllowanceForSpender < amountToSupply) {
MuckT marked this conversation as resolved.
Show resolved Hide resolved
const data = encodeFunctionData({
abi: erc20.abi,
functionName: 'approve',
args: [poolContractAddress, amountToSupply],
})

const approveTx: TransactionRequest = {
from: walletAddress,
to: token.address as Address,
data,
}
baseTransactions.push(approveTx)
}

const supplyTx: TransactionRequest = {
from: walletAddress,
to: poolContractAddress,
data: encodeFunctionData({
abi: aavePool,
functionName: 'supply',
args: [token.address as Address, amountToSupply, walletAddress, 0],
}),
}

baseTransactions.push(supplyTx)

return prepareTransactions({
feeCurrencies,
baseTransactions,
spendToken: token,
spendTokenAmount: new BigNumber(amount),
})
}
Loading