-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
114 lines (98 loc) · 3.21 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { BigNumber, ethers } from 'ethers'
import { AlphaRouter, SwapRoute } from '@uniswap/smart-order-router'
import { CurrencyAmount, TradeType } from '@uniswap/sdk-core'
import type { TransactionRequest } from '@ethersproject/abstract-provider/src.ts/index'
import { WETH, UNI } from './tokens'
import {
provider,
signer,
CHAIN_ID,
SWAP_ROUTER_ADDRESS,
SLIPPAGE_TOLERANCE,
DEADLINE,
} from './config'
const tokenFrom = WETH.token
const tokenFromContract = WETH.contract(provider)
const tokenTo = UNI.token
async function main() {
if (typeof process.argv[2] == 'undefined')
throw new Error(`Pass in the amount of ${tokenFrom.symbol} to swap.`)
const walletAddress = await signer.getAddress()
const amountIn = ethers.utils.parseUnits(process.argv[2], tokenFrom.decimals)
const balance = await tokenFromContract.balanceOf(walletAddress)
if (!(await WETH.walletHas(signer, amountIn)))
throw new Error(
`Not enough ${tokenFrom.symbol}. Needs ${amountIn}, but balance is ${balance}.`,
)
const router = new AlphaRouter({ chainId: CHAIN_ID, provider })
const route = await router.route(
CurrencyAmount.fromRawAmount(tokenFrom, amountIn.toString()),
tokenTo,
TradeType.EXACT_INPUT,
{
recipient: walletAddress,
slippageTolerance: SLIPPAGE_TOLERANCE,
deadline: DEADLINE,
},
)
console.log(
`Swapping ${amountIn} ${tokenFrom.symbol} for ${route?.quote.toFixed(
tokenTo.decimals,
)} ${tokenTo.symbol}.`,
)
const allowance: BigNumber = await tokenFromContract.allowance(
walletAddress,
SWAP_ROUTER_ADDRESS,
)
const buildSwapTransaction = (
walletAddress: string,
routerAddress: string,
route: SwapRoute | null,
) => {
return {
data: route?.methodParameters?.calldata,
to: routerAddress,
value: BigNumber.from(route?.methodParameters?.value),
from: walletAddress,
gasPrice: BigNumber.from(route?.gasPriceWei),
// gasLimit: BigNumber.from(route?.estimatedGasUsed).div(100).mul(115), // Add a 15% buffer on top.
gasLimit: BigNumber.from('200000'),
}
}
const swapTransaction = buildSwapTransaction(
walletAddress,
SWAP_ROUTER_ADDRESS,
route,
)
const attemptSwapTransaction = async (
signer: ethers.Wallet,
transaction: TransactionRequest,
) => {
const signerBalance = await signer.getBalance()
if (!signerBalance.gte(transaction.gasLimit || '0'))
throw new Error(`Not enough ETH to cover gas: ${transaction.gasLimit}`)
signer.sendTransaction(transaction).then((tx) => {
tx.wait().then((receipt) => {
console.log('Completed swap transaction:', receipt.transactionHash)
})
})
}
if (allowance.lt(amountIn)) {
console.log(`Requesting ${tokenFrom.symbol} approval…`)
const approvalTx = await tokenFromContract
.connect(signer)
.approve(
SWAP_ROUTER_ADDRESS,
ethers.utils.parseUnits(amountIn.mul(1000).toString(), 18),
)
approvalTx.wait(3).then(() => {
attemptSwapTransaction(signer, swapTransaction)
})
} else {
console.log(
`Sufficient ${tokenFrom.symbol} allowance, no need for approval.`,
)
attemptSwapTransaction(signer, swapTransaction)
}
}
main()