forked from balancer/balancer-sor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
184 lines (166 loc) · 5.53 KB
/
utils.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
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
import dotenv from 'dotenv';
dotenv.config();
import { BigNumber, formatFixed } from '@ethersproject/bignumber';
import { Wallet } from '@ethersproject/wallet';
import { Contract } from '@ethersproject/contracts';
import { AddressZero, MaxUint256 } from '@ethersproject/constants';
import { SOR, SwapInfo, SwapTypes } from '../../src';
import { vaultAddr } from './constants';
import erc20abi from '../abi/ERC20.json';
// Helper to check/set allowances for tokens being traded via vault
export async function handleAllowances(
wallet: Wallet,
tokenIn: string,
amount: BigNumber
): Promise<void> {
if (tokenIn !== AddressZero) {
// Vault needs approval for swapping non ETH
console.log('Checking vault allowance...');
const tokenInContract = new Contract(
tokenIn,
erc20abi,
wallet.provider
);
let allowance = await tokenInContract.allowance(
wallet.address,
vaultAddr
);
if (allowance.lt(amount)) {
console.log(
`Not Enough Allowance: ${allowance.toString()}. Approving vault now...`
);
const txApprove = await tokenInContract
.connect(wallet)
.approve(vaultAddr, MaxUint256);
await txApprove.wait();
console.log(`Allowance updated: ${txApprove.hash}`);
allowance = await tokenInContract.allowance(
wallet.address,
vaultAddr
);
}
console.log(`Allowance: ${allowance.toString()}`);
}
}
// Helper to set batchSwap limits
export function getLimits(
tokenIn: string,
tokenOut: string,
swapType: SwapTypes,
swapAmount: BigNumber,
returnAmount: BigNumber,
tokenAddresses: string[]
): string[] {
// Limits:
// +ve means max to send
// -ve mean min to receive
// For a multihop the intermediate tokens should be 0
// This is where slippage tolerance would be added
const limits: string[] = [];
const amountIn =
swapType === SwapTypes.SwapExactIn ? swapAmount : returnAmount;
const amountOut =
swapType === SwapTypes.SwapExactIn ? returnAmount : swapAmount;
tokenAddresses.forEach((token, i) => {
if (token.toLowerCase() === tokenIn.toLowerCase())
limits[i] = amountIn.toString();
else if (token.toLowerCase() === tokenOut.toLowerCase()) {
limits[i] = amountOut
.mul('990000000000000000') // 0.99
.div('1000000000000000000')
.mul(-1)
.toString()
.split('.')[0];
} else {
limits[i] = '0';
}
});
return limits;
}
// Build batchSwap tx data
export function buildTx(
wallet: Wallet,
swapInfo: SwapInfo,
swapType: SwapTypes
) {
const funds = {
sender: wallet.address,
recipient: wallet.address,
fromInternalBalance: false,
toInternalBalance: false,
};
const limits: string[] = getLimits(
swapInfo.tokenIn,
swapInfo.tokenOut,
swapType,
swapInfo.swapAmount,
swapInfo.returnAmount,
swapInfo.tokenAddresses
);
const overRides = {};
// overRides['gasLimit'] = '200000';
// overRides['gasPrice'] = '20000000000';
// ETH in swaps must send ETH value
if (swapInfo.tokenIn === AddressZero) {
overRides['value'] = swapInfo.swapAmount.toString();
}
const deadline = MaxUint256;
return {
funds,
limits,
overRides,
deadline,
};
}
// Helper to log output
export async function printOutput(
swapInfo: SwapInfo,
sor: SOR,
tokenIn: any,
tokenOut: any,
swapType: SwapTypes,
swapAmount: BigNumber,
gasPrice: BigNumber,
limits: string[]
): Promise<void> {
// Scale to human numbers
const amtInScaled =
swapType === SwapTypes.SwapExactIn
? formatFixed(swapAmount, tokenIn.decimals)
: formatFixed(swapInfo.returnAmount, tokenIn.decimals);
const amtOutScaled =
swapType === SwapTypes.SwapExactIn
? formatFixed(swapInfo.returnAmount, tokenOut.decimals)
: formatFixed(swapAmount, tokenOut.decimals);
const returnDecimals =
swapType === SwapTypes.SwapExactIn
? tokenOut.decimals
: tokenIn.decimals;
const returnWithFeesScaled = formatFixed(
swapInfo.returnAmountConsideringFees,
returnDecimals
);
const swapTypeStr =
swapType === SwapTypes.SwapExactIn ? 'SwapExactIn' : 'SwapExactOut';
// This calculates the cost to make a swap which is used as an input to sor to allow it to make gas efficient recommendations.
// Note - tokenOut for SwapExactIn, tokenIn for SwapExactOut
const outputToken = swapType === SwapTypes.SwapExactIn ? tokenOut : tokenIn;
const cost = await sor.getCostOfSwapInToken(
outputToken.address,
outputToken.decimals,
gasPrice,
BigNumber.from('35000')
);
const costToSwapScaled = formatFixed(cost, returnDecimals);
console.log(`Swaps:`);
console.log(swapInfo.swaps);
console.log(swapInfo.tokenAddresses);
console.log(limits);
console.log(swapTypeStr);
console.log(`Token In: ${tokenIn.symbol}, Amt: ${amtInScaled.toString()}`);
console.log(
`Token Out: ${tokenOut.symbol}, Amt: ${amtOutScaled.toString()}`
);
console.log(`Cost to swap: ${costToSwapScaled.toString()}`);
console.log(`Return Considering Fees: ${returnWithFeesScaled.toString()}`);
}