-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathuniV2Utils.ts
More file actions
248 lines (233 loc) · 7.44 KB
/
uniV2Utils.ts
File metadata and controls
248 lines (233 loc) · 7.44 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import { mul, sub } from 'biggystring'
import {
EdgeSwapQuote,
EdgeSwapRequest,
EdgeSwapResult,
EdgeTransaction
} from 'edge-core-js/types'
import { BigNumber, Contract, ethers, PopulatedTransaction } from 'ethers'
import { round } from '../../../util/biggystringplus'
import { fixRequest } from '../../../util/utils'
import { getMetaTokenAddress } from '../defiUtils'
import { makeErc20Contract, makeWrappedFtmContract } from './uniV2Contracts'
/**
* Get the output swap amounts based on the requested input amount.
* Call the router contract to calculate amounts and check if the swap path is
* supported.
*/
export const getSwapAmounts = async (
router: Contract,
quoteFor: string,
nativeAmount: string,
fromTokenAddress: string,
toTokenAddress: string,
isWrappingSwap: boolean
): Promise<{ amountToSwap: string; expectedAmountOut: string }> => {
const path = [fromTokenAddress, toTokenAddress]
const [amountToSwap, expectedAmountOut] = (isWrappingSwap
? [nativeAmount, nativeAmount]
: quoteFor === 'to'
? await router.getAmountsIn(nativeAmount, path)
: quoteFor === 'from'
? await router.getAmountsOut(nativeAmount, path)
: []
).map(String)
if (amountToSwap == null || expectedAmountOut == null)
throw new Error(`Failed to calculate amounts`)
return { amountToSwap, expectedAmountOut }
}
/**
* Get smart contract transaction(s) necessary to swap based on swap params
*/
export const getSwapTransactions = async (
provider: ethers.providers.Provider,
rawRequest: EdgeSwapRequest,
router: Contract,
amountToSwap: string,
expectedAmountOut: string,
toAddress: string,
slippage: string,
deadline: number
): Promise<PopulatedTransaction[]> => {
const swapRequest = fixRequest(rawRequest)
const { fromWallet, fromCurrencyCode, toCurrencyCode } = swapRequest
const {
currencyCode: nativeCurrencyCode,
metaTokens
} = fromWallet.currencyInfo
// TODO: Use our new denom implementation to get native amounts
const wrappedCurrencyCode = `W${nativeCurrencyCode}`
const isFromNativeCurrency = fromCurrencyCode === nativeCurrencyCode
const isToNativeCurrency = toCurrencyCode === nativeCurrencyCode
const isFromWrappedCurrency = fromCurrencyCode === wrappedCurrencyCode
const isToWrappedCurrency = toCurrencyCode === wrappedCurrencyCode
const fromTokenAddress = getMetaTokenAddress(
metaTokens,
isFromNativeCurrency ? wrappedCurrencyCode : fromCurrencyCode
)
const toTokenAddress = getMetaTokenAddress(
metaTokens,
isToNativeCurrency ? wrappedCurrencyCode : toCurrencyCode
)
// Determine router method name and params
if (isFromNativeCurrency && isToNativeCurrency)
throw new Error('Invalid swap: Cannot swap to the same native currency')
const path = [fromTokenAddress, toTokenAddress]
const gasPrice = await provider.getGasPrice()
const addressToApproveTx = async (
tokenAddress: string,
contractAddress: string
): Promise<ethers.PopulatedTransaction> => {
const tokenContract = makeErc20Contract(provider, tokenAddress)
const promise = tokenContract.populateTransaction.approve(
contractAddress,
BigNumber.from(amountToSwap),
{ gasLimit: '60000', gasPrice }
)
return await promise
}
const txPromises: Array<Promise<PopulatedTransaction>> = []
// Deposit native currency for wrapped token
if (isFromNativeCurrency && isToWrappedCurrency) {
txPromises.push(
...[
makeWrappedFtmContract(provider).populateTransaction.deposit({
gasLimit: '51000',
gasPrice,
value: amountToSwap
})
]
)
}
// Withdraw wrapped token for native currency
else if (isFromWrappedCurrency && isToNativeCurrency) {
txPromises.push(
// Deposit Tx
makeWrappedFtmContract(provider).populateTransaction.withdraw(
amountToSwap,
{
gasLimit: '51000',
gasPrice
}
)
)
}
// Swap native currency for token
else {
const slippageMultiplier = sub('1', slippage)
if (isFromNativeCurrency && !isToNativeCurrency) {
txPromises.push(
// Swap Tx
router.populateTransaction.swapExactETHForTokens(
round(mul(expectedAmountOut, slippageMultiplier)),
path,
toAddress,
deadline,
{ gasLimit: '250000', gasPrice, value: amountToSwap }
)
)
}
// Swap token for native currency
else if (!isFromNativeCurrency && isToNativeCurrency) {
txPromises.push(
// Approve TX
addressToApproveTx(path[0], router.address),
// Swap Tx
router.populateTransaction.swapExactTokensForETH(
amountToSwap,
round(mul(expectedAmountOut, slippageMultiplier)),
path,
toAddress,
deadline,
{ gasLimit: '250000', gasPrice }
)
)
}
// Swap token for token
else if (!isFromNativeCurrency && !isToNativeCurrency) {
txPromises.push(
// Approve TX
addressToApproveTx(path[0], router.address),
// Swap Tx
router.populateTransaction.swapExactTokensForTokens(
amountToSwap,
round(mul(expectedAmountOut, slippageMultiplier)),
path,
toAddress,
deadline,
{ gasLimit: '600000', gasPrice }
)
)
} else {
throw new Error('Unhandled swap type')
}
}
return await Promise.all(txPromises)
}
/**
* Generate the quote with approve() method
* */
export function makeUniV2EdgeSwapQuote(
request: EdgeSwapRequest,
fromNativeAmount: string,
toNativeAmount: string,
txs: EdgeTransaction[],
pluginId: string,
displayName: string,
isEstimate: boolean = false,
expirationDate?: Date
): EdgeSwapQuote {
const { fromWallet } = request
const swapTx = txs[txs.length - 1]
const out: EdgeSwapQuote = {
request,
fromNativeAmount,
toNativeAmount,
networkFee: {
currencyCode: fromWallet.currencyInfo.currencyCode,
nativeAmount:
swapTx.parentNetworkFee != null
? swapTx.parentNetworkFee
: swapTx.networkFee
},
pluginId,
expirationDate,
isEstimate,
async approve(opts): Promise<EdgeSwapResult> {
let swapTx
let index = 0
for (let i = 0; i < txs.length; i++) {
const tx = txs[i]
if (txs.length > 1 && i === 0) {
// This is an approval transaction. Tag with some unfortunately non-translatable data but better than nothing
tx.metadata = {
name: displayName,
category: 'expense:Token Approval'
}
} else {
// This is the swap transaction
tx.metadata = { ...opts?.metadata, ...tx.metadata }
}
// for (const tx of txs) {
const signedTransaction = await fromWallet.signTx(tx)
// NOTE: The swap transaction will always be the last one
swapTx = await fromWallet.broadcastTx(signedTransaction)
const lastTransactionIndex = txs.length - 1
// if it's the last transaction of the array then assign `nativeAmount` data
// (after signing and broadcasting) for metadata purposes
if (index === lastTransactionIndex) {
tx.nativeAmount = `-${fromNativeAmount}`
}
await fromWallet.saveTx(signedTransaction)
index++
}
if (swapTx == null) throw new Error(`No ${pluginId} swapTx generated.`)
return {
transaction: swapTx,
orderId: swapTx.txid
}
},
async close() {}
}
return out
}