-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathreservecoin.jsx
More file actions
492 lines (467 loc) · 16.3 KB
/
Copy pathreservecoin.jsx
File metadata and controls
492 lines (467 loc) · 16.3 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import React, { useState } from "react";
import MetamaskConnectButton from "../components/molecules/MetamaskConnectButton/MetamaskConnectButton";
import CoinCard from "../components/molecules/CoinCard/CoinCard";
import OperationSelector from "../components/organisms/OperationSelector/OperationSelector";
import ModalTransaction from "../components/organisms/Modals/ModalTransaction";
import ModalPending from "../components/organisms/Modals/ModalPending";
import BuySellButton from "../components/molecules/BuySellButton/BuySellButton";
import "./_CoinSection.scss";
import { useAppProvider } from "../context/AppProvider";
import useBuyOrSell from "../utils/hooks/useBuyOrSell";
import { TRANSACTION_VALIDITY } from "../utils/constants";
import {
calculateBcUsdEquivalent,
calculateRcUsdEquivalent,
getRcUsdEquivalent,
stringToBigNumber,
validatePositiveNumber
} from "../utils/helpers";
import {
buyRcTx,
promiseTx,
sellRcTx,
tradeDataPriceBuyRc,
tradeDataPriceSellRc,
checkBuyableRc,
checkSellableRc,
verifyTx,
BC_DECIMALS,
isTxLimitReached,
DJED_ADDRESS,
FEE_UI_UNSCALED,
UI
} from "../utils/ethereum";
import { ethers } from "ethers";
import {
ConnectWSCButton,
TransactionConfigWSCProvider,
useWSCProvider,
useModal as useWSCModal
} from "milkomeda-wsc-ui-test-beta";
import djedArtifact from "../artifacts/Djed.json";
import { useAccount } from "wagmi";
export default function ReserveCoin() {
const {
web3,
isWalletConnected,
isWrongChain,
djedContract,
coinsDetails,
decimals,
accountDetails,
coinBudgets,
account,
signer,
systemParams,
coinContracts
} = useAppProvider();
const { isWSCConnected } = useWSCProvider();
const { setOpen } = useWSCModal();
const { buyOrSell, isBuyActive, setBuyOrSell } = useBuyOrSell();
const [tradeData, setTradeData] = useState({});
const [value, setValue] = useState(null);
const [termsAccepted, setTermsAccepted] = useState(false);
const [txError, setTxError] = useState(null);
const [txStatus, setTxStatus] = useState("idle");
const [buyValidity, setBuyValidity] = useState(
TRANSACTION_VALIDITY.WALLET_NOT_CONNECTED
);
const [sellValidity, setSellValidity] = useState(
TRANSACTION_VALIDITY.WALLET_NOT_CONNECTED
);
const txStatusPending = txStatus === "pending";
const txStatusRejected = txStatus === "rejected";
const txStatusSuccess = txStatus === "success";
const updateBuyTradeData = (amountScaled) => {
const inputSanity = validatePositiveNumber(amountScaled);
if (inputSanity !== TRANSACTION_VALIDITY.OK) {
setBuyValidity(inputSanity);
return;
}
const getTradeData = async () => {
try {
const data = await tradeDataPriceBuyRc(
djedContract,
decimals.rcDecimals,
amountScaled
);
const bcUsdEquivalent = calculateBcUsdEquivalent(
coinsDetails,
parseFloat(data.totalScaled.replaceAll(",", ""))
).replaceAll(",", "");
setTradeData(data);
if (!isWalletConnected) {
setBuyValidity(TRANSACTION_VALIDITY.WALLET_NOT_CONNECTED);
} else if (isWrongChain) {
setBuyValidity(TRANSACTION_VALIDITY.WRONG_NETWORK);
} else if (
isTxLimitReached(
bcUsdEquivalent,
coinsDetails.unscaledNumberSc,
systemParams.thresholdSupplySC
)
) {
setBuyValidity(TRANSACTION_VALIDITY.TRANSACTION_LIMIT_REACHED);
} else if (
stringToBigNumber(accountDetails.unscaledBalanceBc, BC_DECIMALS).lt(
stringToBigNumber(data.totalBCUnscaled, BC_DECIMALS)
)
) {
setBuyValidity(TRANSACTION_VALIDITY.INSUFFICIENT_BC);
} else {
checkBuyableRc(
djedContract,
data.amountUnscaled,
coinBudgets?.unscaledBudgetRc
).then((res) => setBuyValidity(res));
}
} catch (error) {
console.log("error", error);
}
};
getTradeData();
};
const updateSellTradeData = (amountScaled) => {
const inputSanity = validatePositiveNumber(amountScaled);
if (inputSanity !== TRANSACTION_VALIDITY.OK) {
setSellValidity(inputSanity);
return;
}
const getTradeData = async () => {
try {
const data = await tradeDataPriceSellRc(
djedContract,
decimals.rcDecimals,
amountScaled
);
const rcUsdEquivalent = calculateRcUsdEquivalent(
coinsDetails,
parseFloat(data.amountScaled.replaceAll(",", ""))
).replaceAll(",", "");
setTradeData(data);
if (!isWalletConnected) {
setSellValidity(TRANSACTION_VALIDITY.WALLET_NOT_CONNECTED);
} else if (isWrongChain) {
setSellValidity(TRANSACTION_VALIDITY.WRONG_NETWORK);
} else if (
isTxLimitReached(
rcUsdEquivalent,
coinsDetails.unscaledNumberSc,
systemParams.thresholdSupplySC
)
) {
setSellValidity(TRANSACTION_VALIDITY.TRANSACTION_LIMIT_REACHED);
} else if (
stringToBigNumber(accountDetails.unscaledBalanceRc, decimals.rcDecimals).lt(
stringToBigNumber(data.amountUnscaled, decimals.rcDecimals)
)
) {
setSellValidity(TRANSACTION_VALIDITY.INSUFFICIENT_RC);
} else {
checkSellableRc(
djedContract,
data.amountUnscaled,
accountDetails?.unscaledBalanceRc
).then((res) => setSellValidity(res));
}
} catch (error) {
console.log("error", error);
}
};
getTradeData();
};
const onChangeBuyInput = (amountScaled) => {
setValue(amountScaled);
updateBuyTradeData(amountScaled);
};
const onChangeSellInput = (amountScaled) => {
setValue(amountScaled);
updateSellTradeData(amountScaled);
};
const buyRc = (total) => {
console.log("Attempting to buy RC for", total);
setTxStatus("pending");
// TODO: pass to buyRcTx a parameter to enforce gasLimit if we are using WSC
promiseTx(isWalletConnected, buyRcTx(djedContract, account, total), signer)
.then(({ hash }) => {
verifyTx(web3, hash).then((res) => {
if (res) {
console.log("Buy RC success!");
setTxStatus("success");
} else {
console.log("Buy RC reverted!");
setTxError("The transaction reverted.");
setTxStatus("rejected");
}
});
})
.catch((err) => {
console.error("Error:", err.message);
setTxStatus("rejected");
setTxError("MetaMask error. See developer console for details.");
});
};
const sellRc = (amount) => {
console.log("Attempting to sell RC in amount", amount);
setTxStatus("pending");
promiseTx(isWalletConnected, sellRcTx(djedContract, account, amount), signer)
.then(({ hash }) => {
verifyTx(web3, hash).then((res) => {
console.log(hash, "hash");
if (res) {
console.log("Sell RC success!", hash);
setTxStatus("success");
} else {
console.log("Sell RC reverted!");
setTxError("The transaction reverted.");
setTxStatus("rejected");
}
});
})
.catch((err) => {
console.error("Error:", err.message);
setTxStatus("rejected");
setTxError("MetaMask error. See developer console for details.");
});
};
const tradeFxn = isBuyActive
? buyRc.bind(null, tradeData.totalBCUnscaled)
: sellRc.bind(null, tradeData.amountUnscaled);
const currentAmount = isBuyActive
? tradeData.totalBCUnscaled
: tradeData.amountUnscaled;
const onSubmit = (e) => {
if (!isWalletConnected) return;
if (!termsAccepted) return;
e.preventDefault();
if (isWSCConnected) {
setOpen(true);
return;
}
tradeFxn();
};
const transactionValidated = isBuyActive
? buyValidity === TRANSACTION_VALIDITY.OK
: sellValidity === TRANSACTION_VALIDITY.OK;
const buttonDisabled =
isNaN(parseFloat(value)) ||
parseFloat(value) === 0 ||
isWrongChain ||
!transactionValidated;
const rcFloat = parseFloat(coinsDetails?.scaledNumberRc.replaceAll(",", ""));
const rcConverted = getRcUsdEquivalent(coinsDetails, rcFloat);
return (
<main style={{ padding: "1rem 0" }}>
<div className="StablecoinSection">
<div className="Left">
<h1>ReserveCoin {/*<strong>Name</strong>*/}</h1>
<div className="DescriptionContainer">
<p>
A ReserveCoin represents a portion of the surplus of the underlying reserves
of {process.env.REACT_APP_CHAIN_COIN} in the Djed Tefnut protocol. As such,
ReserveCoins have a leveraged volatile price that increases when the price
of {process.env.REACT_APP_CHAIN_COIN} increases and decreases when the price
of {process.env.REACT_APP_CHAIN_COIN} decreases. Furthermore, ReserveCoin
holders ultimately benefit from fees paid to the Djed protocol, since most
fees are accumulated into the reserve and hence contribute to the reserve
surplus.
</p>
<p>
You are always allowed to buy and sell ReserveCoins. Djed Tefnut has no minimum
or maximum reserve ratio restrictions, allowing unrestricted minting and
redemption of ReserveCoins at any time.
</p>
<p>
There is a limit of {process.env.REACT_APP_LIMIT_PER_TXN} USD worth of{" "}
{process.env.REACT_APP_CHAIN_COIN} per transaction.
</p>
<p>
ReserveCoins are implemented as a standard ERC-20 token contract and the
contract's address is{" "}
<a
href={`${process.env.REACT_APP_EXPLORER}address/${coinContracts?.reserveCoin._address}`}
target="_blank"
rel="noreferrer"
>
{coinContracts?.reserveCoin._address}
</a>
.
</p>
</div>
<CoinCard
coinIcon="/coin-icon-two.png"
coinName={`${process.env.REACT_APP_RC_NAME}`}
priceAmount={coinsDetails?.scaledBuyPriceRc}
sellPriceAmount={coinsDetails?.scaledSellPriceRc}
circulatingAmount={coinsDetails?.scaledNumberRc} //"1,345,402.15"
tokenName={`${process.env.REACT_APP_RC_SYMBOL}`}
equivalence={rcConverted}
/>
</div>
<div className="Right">
<h2 className="SubtTitle">
<strong>
Buy <>&</> Sell
</strong>{" "}
{process.env.REACT_APP_RC_NAME}
</h2>
<form onSubmit={onSubmit}>
<div className="PurchaseContainer">
<OperationSelector
coinName={`${process.env.REACT_APP_RC_SYMBOL}`}
selectionCallback={() => {
setBuyOrSell();
setValue(null);
setBuyValidity(TRANSACTION_VALIDITY.ZERO_INPUT);
setSellValidity(TRANSACTION_VALIDITY.ZERO_INPUT);
}}
onChangeBuyInput={onChangeBuyInput}
onChangeSellInput={onChangeSellInput}
tradeData={tradeData}
inputValue={value}
inputValid={transactionValidated}
scaledCoinBalance={accountDetails?.scaledBalanceRc}
scaledBaseBalance={accountDetails?.scaledBalanceBc}
fee={systemParams?.fee}
treasuryFee={systemParams?.treasuryFee}
buyValidity={buyValidity}
sellValidity={sellValidity}
isSellDisabled={Number(coinsDetails?.scaledNumberRc) === 0}
/>
</div>
<input
type="checkbox"
id="accept-terms"
name="accept-terms"
onChange={() => setTermsAccepted(!termsAccepted)}
checked={termsAccepted}
required
/>
<label htmlFor="accept-terms" className="accept-terms">
I agree to the{" "}
<a href="/terms-of-use" target="_blank" rel="noreferrer">
Terms of Use
</a>
.
</label>
<div className="ConnectWallet">
<br />
{isWalletConnected ? (
<>
{/*value != null ? (
<p className="Disclaimer">
This transaction is expected to{" "}
{transactionValidated ? (
<strong>succeed.</strong>
) : (
<strong>fail!</strong>
)}
</p>
) : null*/}
{isWSCConnected ? (
<WSCButton
disabled={value === null || isWrongChain || !termsAccepted}
currentAmount={currentAmount}
stepTxDirection={isBuyActive ? "buy" : "sell"}
unwrapAmount={
isBuyActive ? tradeData.amountUnscaled : tradeData.totalBCUnscaled
}
/>
) : (
<BuySellButton
disabled={buttonDisabled}
buyOrSell={buyOrSell}
currencyName={`${process.env.REACT_APP_RC_SYMBOL}`}
/>
)}
</>
) : (
<>
<p className="Disclaimer">
In order to interact, you need to connect your wallet.
</p>
<MetamaskConnectButton />
</>
)}
</div>
</form>
{txStatusRejected && (
<ModalTransaction
transactionType="Failed Transaction"
transactionStatus="/transaction-failed.svg"
statusText="Failed transaction!"
statusDescription={txError}
/>
)}
{txStatusPending ? (
<ModalPending
transactionType="Confirmation"
transactionStatus="/transaction-success.svg"
statusText="Pending for confirmation"
statusDescription="This transaction can take a while, once the process finish you will see the transaction reflected in your wallet."
/>
) : txStatusSuccess ? (
<ModalTransaction
transactionType="Success Transaction"
transactionStatus="/transaction-success.svg"
statusText="Succesful transaction!"
statusDescription=""
/>
) : null}
</div>
</div>
</main>
);
}
const WSCButton = ({ disabled, currentAmount, unwrapAmount, stepTxDirection }) => {
const { address: account } = useAccount();
const buyOptions = {
defaultWrapToken: {
unit: "lovelace",
amount: currentAmount
},
defaultUnwrapToken: {
unit: process.env.REACT_APP_EVM_RESERVECOIN_ADDRESS,
amount: unwrapAmount // amountUnscaled
},
titleModal: "Buy RC with WSC",
evmTokenAddress: process.env.REACT_APP_EVM_RESERVECOIN_ADDRESS,
evmContractRequest: {
address: DJED_ADDRESS,
abi: djedArtifact.abi,
functionName: "buyReserveCoins", //account, FEE_UI_UNSCALED, UI
args: [account, FEE_UI_UNSCALED, UI],
overrides: {
value: ethers.BigNumber.from(currentAmount ?? "0")
}
}
};
const sellOptions = {
defaultWrapToken: {
unit: process.env.REACT_APP_CARDANO_RESERVECOIN_ADDRESS,
amount: currentAmount
},
defaultUnwrapToken: {
unit: "",
amount: unwrapAmount // totalBCUnscaled
},
titleModal: "Sell RC with WSC",
evmTokenAddress: process.env.REACT_APP_EVM_RESERVECOIN_ADDRESS,
evmContractRequest: {
address: DJED_ADDRESS,
abi: djedArtifact.abi,
functionName: "sellReserveCoins", //amount, account, FEE_UI_UNSCALED, UI
args: [currentAmount, account, FEE_UI_UNSCALED, UI],
overrides: {
value: "0"
}
}
};
return (
<TransactionConfigWSCProvider
options={stepTxDirection === "buy" ? buyOptions : sellOptions}
>
<ConnectWSCButton disabled={disabled} />
</TransactionConfigWSCProvider>
);
};