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

node: Use simulate + write contract pattern for approval tx #156

Merged
merged 2 commits into from
Jan 16, 2025
Merged
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
23 changes: 13 additions & 10 deletions packages/node/src/actions/executeDeposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import {
} from '@renegade-fi/core'
import { type createConfig, waitForTransactionReceipt } from '@wagmi/core'
import invariant from 'tiny-invariant'
import { type Address, type WalletClient, zeroAddress } from 'viem'
import { readErc20Allowance, writeErc20Approve } from '../generated.js'
import { type Address, type WalletClient, erc20Abi, zeroAddress } from 'viem'
import { signPermit2 } from '../utils/permit2.js'

export type ExecuteDepositParameters = {
Expand Down Expand Up @@ -57,29 +56,33 @@ export async function executeDeposit(
})

// Check Permit2 Allowance
const permit2Allowance = await readErc20Allowance(viemConfig, {
const permit2Allowance = await config.viemClient.readContract({
address: mint,
account: walletClient.account,
abi: erc20Abi,
functionName: 'allowance',
args: [walletClient.account.address, permit2Address],
chainId,
})

// If not enough allowance, approve max amount
if (permit2Allowance < amount) {
const nonce = await config.viemClient.getTransactionCount({
address: walletClient.account.address,
})
const hash = await writeErc20Approve(viemConfig, {
address: mint,
const { request } = await config.viemClient.simulateContract({
account: walletClient.account,
address: mint,
abi: erc20Abi,
functionName: 'approve',
args: [permit2Address, amount],
nonce,
}).catch(() => {
throw new Error('Error approving permit2 allowance: likely need gas.')
})

const hash = await walletClient.writeContract(request)
await waitForTransactionReceipt(viemConfig, {
hash,
confirmations: 1,
timeout: 5_000,
}).catch(() => {
// Attempt deposit even if receipt not found
})
}

Expand Down
Loading