From f947c8e54919343ac4f5f951d2f701651c06dd52 Mon Sep 17 00:00:00 2001
From: Sebastian <sebasjm@gmail.com>
Date: Fri, 31 Mar 2023 19:09:41 -0300
Subject: calculate using server

---
 packages/demobank-ui/src/pages/BusinessAccount.tsx | 95 ++++++++++------------
 1 file changed, 42 insertions(+), 53 deletions(-)

(limited to 'packages/demobank-ui/src/pages/BusinessAccount.tsx')

diff --git a/packages/demobank-ui/src/pages/BusinessAccount.tsx b/packages/demobank-ui/src/pages/BusinessAccount.tsx
index 4c322764e..262376fa2 100644
--- a/packages/demobank-ui/src/pages/BusinessAccount.tsx
+++ b/packages/demobank-ui/src/pages/BusinessAccount.tsx
@@ -34,6 +34,7 @@ import { useAccountDetails } from "../hooks/access.js";
 import {
   useCashoutDetails,
   useCircuitAccountAPI,
+  useEstimator,
   useRatiosAndFeeConfig,
 } from "../hooks/circuit.js";
 import {
@@ -230,7 +231,10 @@ function CreateCashout({
   const ratiosResult = useRatiosAndFeeConfig();
   const result = useAccountDetails(account);
   const [error, saveError] = useState<ErrorMessage | undefined>();
-
+  const {
+    estimateByCredit: calculateFromCredit,
+    estimateByDebit: calculateFromDebit,
+  } = useEstimator();
   const [form, setForm] = useState<Partial<FormType>>({ isDebit: true });
 
   const { createCashout } = useCircuitAccountAPI();
@@ -256,21 +260,45 @@ function CreateCashout({
 
   if (!sellRate || sellRate < 0) return <div>error rate</div>;
 
-  const amount = Amounts.parse(`${balance.currency}:${form.amount}`);
+  const amount = Amounts.parseOrThrow(
+    `${!form.isDebit ? fiatCurrency : balance.currency}:${
+      !form.amount ? "0" : form.amount
+    }`,
+  );
 
   useEffect(() => {
-    if (!amount) {
-      setCalc(zeroCalc);
-    } else {
-      if (form.isDebit) {
-        calculateFromDebit(amount, sellFee, sellRate).then((r) => {
+    if (form.isDebit) {
+      calculateFromDebit(amount, sellFee, sellRate)
+        .then((r) => {
           setCalc(r);
+          saveError(undefined);
+        })
+        .catch((error) => {
+          saveError(
+            error instanceof RequestError
+              ? buildRequestErrorMessage(i18n, error.cause)
+              : {
+                  title: i18n.str`Could not estimate the cashout`,
+                  description: error.message,
+                },
+          );
         });
-      } else {
-        calculateFromCredit(amount, sellFee, sellRate).then((r) => {
+    } else {
+      calculateFromCredit(amount, sellFee, sellRate)
+        .then((r) => {
           setCalc(r);
+          saveError(undefined);
+        })
+        .catch((error) => {
+          saveError(
+            error instanceof RequestError
+              ? buildRequestErrorMessage(i18n, error.cause)
+              : {
+                  title: i18n.str`Could not estimate the cashout`,
+                  description: error.message,
+                },
+          );
         });
-      }
     }
   }, [form.amount, form.isDebit]);
 
@@ -326,14 +354,10 @@ function CreateCashout({
               type="text"
               readonly
               class="currency-indicator"
-              size={
-                !form.isDebit ? fiatCurrency.length : balance.currency.length
-              }
-              maxLength={
-                !form.isDebit ? fiatCurrency.length : balance.currency.length
-              }
+              size={amount?.currency.length ?? 0}
+              maxLength={amount?.currency.length ?? 0}
               tabIndex={-1}
-              value={!form.isDebit ? fiatCurrency : balance.currency}
+              value={amount?.currency ?? ""}
             />
             &nbsp;
             <input
@@ -588,9 +612,7 @@ function CreateCashout({
               if (errors) return;
               try {
                 const res = await createCashout({
-                  amount_credit: `${fiatCurrency}:${Amounts.stringifyValue(
-                    calc.credit,
-                  )}`,
+                  amount_credit: Amounts.stringify(calc.credit),
                   amount_debit: Amounts.stringify(calc.debit),
                   subject: form.subject,
                   tan_channel: form.channel,
@@ -842,39 +864,6 @@ function truncate(a: AmountJson): AmountJson {
   return Amounts.parseOrThrow(truncated);
 }
 
-type TransferCalculation = {
-  debit: AmountJson;
-  credit: AmountJson;
-  beforeFee: AmountJson;
-};
-
-async function calculateFromDebit(
-  amount: AmountJson,
-  sellFee: AmountJson,
-  sellRate: number,
-): Promise<TransferCalculation> {
-  const debit = amount;
-
-  const beforeFee = truncate(Amounts.divide(debit, 1 / sellRate));
-
-  const credit = Amounts.sub(beforeFee, sellFee).amount;
-  return { debit, credit, beforeFee };
-}
-
-async function calculateFromCredit(
-  amount: AmountJson,
-  sellFee: AmountJson,
-  sellRate: number,
-): Promise<TransferCalculation> {
-  const credit = amount;
-
-  const beforeFee = Amounts.add(credit, sellFee).amount;
-
-  const debit = truncate(Amounts.divide(beforeFee, sellRate));
-
-  return { debit, credit, beforeFee };
-}
-
 export function assertUnreachable(x: never): never {
   throw new Error("Didn't expect to get here");
 }
-- 
cgit v1.2.3

