forked from ubiquity/uusd.ubq.fi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mint.ts
250 lines (201 loc) · 11.4 KB
/
mint.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
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
249
250
import { ethers } from "ethers";
import { appState, diamondContract, dollarSpotPrice, governanceSpotPrice, lusdPrice, userSigner } from "../main";
import { debounce } from "../utils";
import { CollateralOption, fetchCollateralOptions, populateCollateralDropdown } from "../common/collateral";
import { toggleSlippageSettings } from "../common/render-slippage-toggle";
import { renderErrorInModal } from "../common/display-popup-modal";
let currentOutput: {
totalDollarMint: ethers.BigNumber;
collateralNeeded: ethers.BigNumber;
governanceNeeded: ethers.BigNumber;
mintingFeeInDollar: ethers.BigNumber;
} | null = null;
export async function loadMintPage() {
const contentArea = document.getElementById("content-area");
if (contentArea) {
try {
// load Mint HTML
const response = await fetch("mint.html");
const html = await response.text();
contentArea.innerHTML = html;
// setup toggle for slippage settings
toggleSlippageSettings();
// fetch collateral options
const collateralOptions = await fetchCollateralOptions();
// add collateral options to dropdown
await populateCollateralDropdown(collateralOptions);
// handle collateral input
handleCollateralInput(collateralOptions);
// handle slippage checks
handleSlippageInput();
// link mint button
await linkMintButton();
} catch (error) {
console.error("Error loading mint page:", error);
}
}
}
async function calculateMintOutput(
selectedCollateral: CollateralOption,
dollarAmount: ethers.BigNumber,
isForceCollateralOnlyChecked: boolean
): Promise<{
totalDollarMint: ethers.BigNumber;
collateralNeeded: ethers.BigNumber;
governanceNeeded: ethers.BigNumber;
mintingFeeInDollar: ethers.BigNumber;
}> {
const collateralRatio = await diamondContract.collateralRatio();
const governancePrice = await diamondContract.getGovernancePriceUsd();
const poolPricePrecision = ethers.BigNumber.from("1000000");
let collateralNeeded: ethers.BigNumber;
let governanceNeeded: ethers.BigNumber;
if (isForceCollateralOnlyChecked || collateralRatio.gte(poolPricePrecision)) {
collateralNeeded = await diamondContract.getDollarInCollateral(selectedCollateral.index, dollarAmount);
governanceNeeded = ethers.BigNumber.from(0);
} else if (collateralRatio.isZero()) {
collateralNeeded = ethers.BigNumber.from(0);
governanceNeeded = dollarAmount.mul(poolPricePrecision).div(governancePrice);
} else {
const dollarForCollateral = dollarAmount.mul(collateralRatio).div(poolPricePrecision);
const dollarForGovernance = dollarAmount.sub(dollarForCollateral);
collateralNeeded = await diamondContract.getDollarInCollateral(selectedCollateral.index, dollarForCollateral);
governanceNeeded = dollarForGovernance.mul(poolPricePrecision).div(governancePrice);
}
const mintingFee = ethers.utils.parseUnits(selectedCollateral.mintingFee.toString(), 6);
// Calculate the dollar value of the minting fee
const mintingFeeInDollar = await diamondContract.getDollarInCollateral(selectedCollateral.index, dollarAmount.mul(mintingFee).div(poolPricePrecision));
const totalDollarMint = dollarAmount.mul(poolPricePrecision.sub(mintingFee)).div(poolPricePrecision);
return { totalDollarMint, collateralNeeded, governanceNeeded, mintingFeeInDollar };
}
function handleCollateralInput(collateralOptions: CollateralOption[]) {
const collateralSelect = document.getElementById("collateralSelect") as HTMLSelectElement;
const dollarAmountInput = document.getElementById("dollarAmount") as HTMLInputElement;
const forceCollateralOnly = document.getElementById("forceCollateralOnly") as HTMLInputElement;
const debouncedInputHandler = debounce(async () => {
const selectedCollateralIndex = collateralSelect.value;
const dollarAmountRaw = dollarAmountInput.value;
const dollarAmount = ethers.utils.parseUnits(dollarAmountRaw || "0", 18);
const isForceCollateralOnlyChecked = forceCollateralOnly.checked;
const selectedCollateral = collateralOptions.find((option) => option.index.toString() === selectedCollateralIndex);
if (selectedCollateral) {
currentOutput = await calculateMintOutput(selectedCollateral, dollarAmount, isForceCollateralOnlyChecked);
displayMintOutput(currentOutput, selectedCollateral);
}
}, 300); // 300ms debounce
dollarAmountInput.addEventListener("input", debouncedInputHandler);
forceCollateralOnly.addEventListener("change", debouncedInputHandler);
}
function handleSlippageInput() {
const dollarOutMinInput = document.getElementById("dollarOutMin") as HTMLInputElement;
const maxCollateralInInput = document.getElementById("maxCollateralIn") as HTMLInputElement;
const maxGovernanceInInput = document.getElementById("maxGovernanceIn") as HTMLInputElement;
const debouncedSlippageCheck = debounce(() => {
if (!currentOutput) return;
const dollarOutMin = dollarOutMinInput.value ? ethers.utils.parseUnits(dollarOutMinInput.value, 18) : ethers.BigNumber.from("0");
const maxCollateralIn = maxCollateralInInput.value ? ethers.utils.parseUnits(maxCollateralInInput.value, 18) : ethers.constants.MaxUint256;
const maxGovernanceIn = maxGovernanceInInput.value ? ethers.utils.parseUnits(maxGovernanceInInput.value, 18) : ethers.constants.MaxUint256;
if (currentOutput.totalDollarMint.lt(dollarOutMin)) {
renderErrorInModal(new Error("Dollar slippage exceeded"));
} else if (currentOutput.collateralNeeded.gt(maxCollateralIn)) {
renderErrorInModal(new Error("Collateral slippage exceeded"));
} else if (currentOutput.governanceNeeded.gt(maxGovernanceIn)) {
renderErrorInModal(new Error("Governance slippage exceeded"));
}
}, 1000); // 1s debounce
dollarOutMinInput.addEventListener("input", debouncedSlippageCheck);
maxCollateralInInput.addEventListener("input", debouncedSlippageCheck);
maxGovernanceInInput.addEventListener("input", debouncedSlippageCheck);
}
function displayMintOutput(
output: {
totalDollarMint: ethers.BigNumber;
collateralNeeded: ethers.BigNumber;
governanceNeeded: ethers.BigNumber;
mintingFeeInDollar: ethers.BigNumber;
},
selectedCollateral: CollateralOption
) {
const totalDollarMinted = document.getElementById("totalDollarMinted");
const collateralNeededElement = document.getElementById("collateralNeeded");
const governanceNeededElement = document.getElementById("governanceNeeded");
const mintingFeeElement = document.getElementById("mintingFee");
const formattedTotalDollarMint = parseFloat(ethers.utils.formatUnits(output.totalDollarMint, 18)).toFixed(2);
const formattedCollateralNeeded = parseFloat(ethers.utils.formatUnits(output.collateralNeeded, 18 - selectedCollateral.missingDecimals)).toFixed(2);
const formattedGovernanceNeeded = parseFloat(ethers.utils.formatUnits(output.governanceNeeded, 18)).toFixed(2);
const formattedMintingFeeInDollar = parseFloat(ethers.utils.formatUnits(output.mintingFeeInDollar, 18)).toFixed(2);
// Calculate dollar values using spot prices
const totalDollarMintValue = output.totalDollarMint.mul(ethers.utils.parseUnits(dollarSpotPrice as string, 18)).div(ethers.constants.WeiPerEther);
const formattedTotalDollarMintValue = parseFloat(ethers.utils.formatUnits(totalDollarMintValue, 18)).toFixed(2);
const collateralNeededValue = output.collateralNeeded.mul(ethers.utils.parseUnits(lusdPrice as string, 18)).div(ethers.constants.WeiPerEther);
const formattedCollateralNeededValue = parseFloat(ethers.utils.formatUnits(collateralNeededValue, 18)).toFixed(2);
const governanceNeededValue = output.governanceNeeded.mul(ethers.utils.parseUnits(governanceSpotPrice as string, 18)).div(ethers.constants.WeiPerEther);
const formattedGovernanceNeededValue = parseFloat(ethers.utils.formatUnits(governanceNeededValue, 18)).toFixed(2);
// Update the displayed values
if (totalDollarMinted) {
totalDollarMinted.textContent = `${formattedTotalDollarMint} UUSD ($${formattedTotalDollarMintValue})`;
}
if (collateralNeededElement) {
collateralNeededElement.textContent = `${formattedCollateralNeeded} ${selectedCollateral.name} ($${formattedCollateralNeededValue})`;
}
if (governanceNeededElement) {
governanceNeededElement.textContent = `${formattedGovernanceNeeded} UBQ ($${formattedGovernanceNeededValue})`;
}
if (mintingFeeElement) {
mintingFeeElement.textContent = `${selectedCollateral.mintingFee}% (${formattedMintingFeeInDollar} UUSD)`;
}
}
async function linkMintButton() {
const mintButton = document.getElementById("mintButton") as HTMLButtonElement;
const collateralSelect = document.getElementById("collateralSelect") as HTMLSelectElement;
const dollarAmountInput = document.getElementById("dollarAmount") as HTMLInputElement;
const forceCollateralOnly = document.getElementById("forceCollateralOnly") as HTMLInputElement;
const dollarOutMinInput = document.getElementById("dollarOutMin") as HTMLInputElement;
const maxCollateralInInput = document.getElementById("maxCollateralIn") as HTMLInputElement;
const maxGovernanceInInput = document.getElementById("maxGovernanceIn") as HTMLInputElement;
const updateButtonState = async () => {
const selectedCollateralIndex = collateralSelect.value;
const dollarAmountRaw = dollarAmountInput.value;
const dollarAmount = dollarAmountRaw ? ethers.utils.parseUnits(dollarAmountRaw, 18) : null;
mintButton.disabled = !appState.getIsConnectedState() || !selectedCollateralIndex || !dollarAmount || dollarAmount.isZero();
};
// Attach event listeners to update the button state whenever inputs change
collateralSelect.addEventListener("change", updateButtonState);
dollarAmountInput.addEventListener("input", updateButtonState);
forceCollateralOnly.addEventListener("change", updateButtonState);
mintButton.addEventListener("click", async () => {
const selectedCollateralIndex = collateralSelect.value;
const dollarAmountRaw = dollarAmountInput.value;
const dollarAmount = ethers.utils.parseUnits(dollarAmountRaw || "0", 18);
// use provided slippage values or default to min/max
const dollarOutMin = dollarOutMinInput.value ? ethers.utils.parseUnits(dollarOutMinInput.value, 18) : ethers.BigNumber.from("0");
const maxCollateralIn = maxCollateralInInput.value ? ethers.utils.parseUnits(maxCollateralInInput.value, 18) : ethers.constants.MaxUint256;
const maxGovernanceIn = maxGovernanceInInput.value ? ethers.utils.parseUnits(maxGovernanceInInput.value, 18) : ethers.constants.MaxUint256;
const isForceCollateralOnlyChecked = forceCollateralOnly.checked;
try {
const signerDiamondContract = diamondContract.connect(userSigner);
console.log("Mint Input", {
selectedCollateralIndex: parseInt(selectedCollateralIndex),
dollarAmount: dollarAmount.toString(),
dollarOutMin: dollarOutMin.toString(),
maxCollateralIn: maxCollateralIn.toString(),
maxGovernanceIn: maxGovernanceIn.toString(),
isForceCollateralOnlyChecked,
});
await signerDiamondContract.mintDollar(
parseInt(selectedCollateralIndex),
dollarAmount,
dollarOutMin,
maxCollateralIn,
maxGovernanceIn,
isForceCollateralOnlyChecked
);
alert("Minting transaction sent successfully!");
} catch (error) {
console.error("Minting transaction failed:", error);
renderErrorInModal(error instanceof Error ? error : new Error(String(error)));
}
});
// Initialize the button state on page load
await updateButtonState();
}