Skip to content

Commit

Permalink
Merge branch 'testnet' into feat/paymaster-feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Marchand-Nicolas committed Jul 1, 2024
2 parents 9dacac2 + 1545c3f commit 56496e0
Show file tree
Hide file tree
Showing 18 changed files with 241 additions and 74 deletions.
7 changes: 4 additions & 3 deletions components/UI/searchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { TextField, styled } from "@mui/material";
import styles from "../../styles/search.module.css";
import SearchResult from "../UI/searchResult";
import { utils } from "starknetid.js";
import { Abi, Contract, Provider } from "starknet";
import { Abi, Contract, Provider, Result } from "starknet";
import naming_abi from "../../abi/starknet/naming_abi.json";
import { StarknetIdJsContext } from "../../context/StarknetIdJsProvider";
import { isValidDomain, getDomainWithStark } from "../../utils/stringService";
Expand Down Expand Up @@ -205,8 +205,9 @@ const SearchBar: FunctionComponent<SearchBarProps> = ({
if (signal?.aborted) {
return reject("Aborted");
}
contract?.call("domain_to_data", [encoded]).then((res) => {
if (Number(res?.["expiry"]) < currentTimeStamp) {
contract?.call("domain_to_data", [encoded]).then((res: Result) => {
const callResult = res as CallResult;
if (Number(callResult?.["expiry"]) < currentTimeStamp) {
resolve({
name,
error: false,
Expand Down
5 changes: 4 additions & 1 deletion components/discount/freeRenewalDiscount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,10 @@ const FreeRenewalCheckout: FunctionComponent<FreeRenewalCheckoutProps> = ({
}
// Add AutoRenewal calls for all currencies
selectedDomainsToArray(selectedDomains).map((domain) => {
if (needSubscription && needSubscription[domain]?.[currency]) {
if (
needSubscription &&
needSubscription.needSubscription[domain]?.[currency]
) {
const encodedDomain = utils
.encodeDomain(domain)
.map((element) => element.toString())[0];
Expand Down
86 changes: 44 additions & 42 deletions components/discount/registerDiscount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ import { FunctionComponent, useEffect, useState } from "react";
import Button from "../UI/button";
import { useAccount, useContractWrite } from "@starknet-react/core";
import { utils } from "starknetid.js";
import { getDomainWithStark, isValidEmail } from "../../utils/stringService";
import {
applyRateToBigInt,
hexToDecimal,
numberToFixedString,
} from "../../utils/feltService";
formatHexString,
getDomainWithStark,
isValidEmail,
} from "../../utils/stringService";
import { applyRateToBigInt, hexToDecimal } from "../../utils/feltService";
import { useDisplayName } from "../../hooks/displayName.tsx";
import { Call } from "starknet";
import { posthog } from "posthog-js";
import TxConfirmationModal from "../UI/txConfirmationModal";
import styles from "../../styles/components/registerV2.module.css";
import TextField from "../UI/textField";
import { Divider } from "@mui/material";
Expand Down Expand Up @@ -40,6 +39,9 @@ import {
getDomainPriceAltcoin,
getTokenQuote,
} from "../../utils/altcoinService";
import { getPriceFromDomain } from "@/utils/priceService";
import { useRouter } from "next/router";
import { formatDomainData } from "@/utils/cacheDomainData";

type RegisterDiscountProps = {
domain: string;
Expand All @@ -49,6 +51,7 @@ type RegisterDiscountProps = {
priceInEth: string;
mailGroups: string[];
goBack: () => void;
sponsor?: string;
};

const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
Expand All @@ -59,7 +62,9 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
priceInEth,
mailGroups,
goBack,
sponsor = "0",
}) => {
const router = useRouter();
const [targetAddress, setTargetAddress] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [emailError, setEmailError] = useState<boolean>(true);
Expand All @@ -74,12 +79,11 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
);
const [invalidBalance, setInvalidBalance] = useState<boolean>(false);
const [salt, setSalt] = useState<string | undefined>();
const [isTxModalOpen, setIsTxModalOpen] = useState(false);
const encodedDomain = utils
.encodeDomain(domain)
.map((element) => element.toString())[0];
const [termsBox, setTermsBox] = useState<boolean>(true);
const [renewalBox, setRenewalBox] = useState<boolean>(true);
const [termsBox, setTermsBox] = useState<boolean>(false);
const [renewalBox, setRenewalBox] = useState<boolean>(false);
const [metadataHash, setMetadataHash] = useState<string | undefined>();
const { account, address } = useAccount();
const { writeAsync: execute, data: registerData } = useContractWrite({
Expand All @@ -93,6 +97,7 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
const needsAllowance = useAllowanceCheck(displayedCurrency, address);
const tokenBalances = useBalances(address); // fetch the user balances for all whitelisted tokens
const [loadingPrice, setLoadingPrice] = useState<boolean>(false);
const [tokenIdRedirect, setTokenIdRedirect] = useState<string>("0");

// on first load, we generate a salt
useEffect(() => {
Expand Down Expand Up @@ -168,21 +173,6 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
}
}, [address]);

// Set sponsor
// useEffect(() => {
// const referralData = localStorage.getItem("referralData");
// if (referralData) {
// const data = JSON.parse(referralData);
// if (data.sponsor && data?.expiry >= new Date().getTime()) {
// setSponsor(data.sponsor);
// } else {
// setSponsor("0");
// }
// } else {
// setSponsor("0");
// }
// }, [domain]);

// Set Register Multicall
useEffect(() => {
if (displayedCurrency !== CurrencyType.ETH && !quoteData) return;
Expand All @@ -195,14 +185,15 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
// Common calls
const calls = [
registrationCalls.approve(price, ERC20Contract[displayedCurrency]),
registrationCalls.mint(newTokenId),
];

if (displayedCurrency === CurrencyType.ETH) {
calls.push(
registrationCalls.buy(
encodedDomain,
newTokenId,
"0",
sponsor,
duration,
txMetadataHash,
discountId
Expand All @@ -213,7 +204,7 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
registrationCalls.altcoinBuy(
encodedDomain,
newTokenId,
"0",
sponsor,
duration,
txMetadataHash,
ERC20Contract[displayedCurrency],
Expand All @@ -240,21 +231,28 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({

// If the user has toggled autorenewal
if (renewalBox) {
const yearlyPriceInEth = getPriceFromDomain(1, domain);
const allowance = getAutoRenewAllowance(
displayedCurrency,
salesTaxRate,
displayedCurrency === CurrencyType.ETH
? String(yearlyPriceInEth)
: String(
(yearlyPriceInEth * BigInt(quoteData?.quote ?? "0")) /
BigInt(1e18)
) // Convert the yearly price in eth to the altcoin yearly price
);

if (needsAllowance) {
calls.push(
autoRenewalCalls.approve(
ERC20Contract[displayedCurrency],
AutoRenewalContracts[displayedCurrency],
String(Number(price) / duration)
allowance
)
);
}

const allowance = getAutoRenewAllowance(
displayedCurrency,
salesTaxRate,
price
);
calls.push(
autoRenewalCalls.enableRenewal(
AutoRenewalContracts[displayedCurrency],
Expand All @@ -266,6 +264,7 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
}

// Merge and set the call data
setTokenIdRedirect(String(newTokenId));
setCallData(calls);
}, [
duration,
Expand All @@ -283,6 +282,7 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
discountId,
quoteData,
displayedCurrency,
sponsor,
]);

useEffect(() => {
Expand All @@ -296,7 +296,7 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
body: JSON.stringify({
meta_hash: metadataHash,
email,
groups: mailGroups, // Domain Owner group + quantumleap group^
groups: mailGroups, // Domain Owner group
tax_state: isSwissResident ? "switzerland" : "none",
salt: salt,
}),
Expand All @@ -314,7 +314,15 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
status: "pending",
},
});
setIsTxModalOpen(true);
formatDomainData(
tokenIdRedirect,
formatHexString(address as string),
getDomainWithStark(domain),
duration,
Boolean(!hasMainDomain), // isMainDomain
undefined // Selected PFPs
);
router.push(`/confirmation?tokenId=${tokenIdRedirect}`);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [registerData]); // We want to execute this only once after the tx is sent

Expand Down Expand Up @@ -375,9 +383,9 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
</div>
<div className={styles.summary}>
<RegisterSummary
ethRegistrationPrice={price}
ethRegistrationPrice={priceInEth}
registrationPrice={price}
duration={Number(numberToFixedString(duration / 365))}
duration={duration}
renewalBox={false}
salesTaxRate={salesTaxRate}
isSwissResident={isSwissResident}
Expand Down Expand Up @@ -426,12 +434,6 @@ const RegisterDiscount: FunctionComponent<RegisterDiscountProps> = ({
</div>
</div>
<img className={styles.image} src="/visuals/register.webp" />
<TxConfirmationModal
txHash={registerData?.transaction_hash}
isTxModalOpen={isTxModalOpen}
closeModal={() => setIsTxModalOpen(false)}
title="Your domain is on it's way !"
/>
</div>
);
};
Expand Down
7 changes: 5 additions & 2 deletions components/domains/registerSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ const RegisterSummary: FunctionComponent<RegisterSummaryProps> = ({

useEffect(() => {
function computeUsdPrice() {
const durationToUse = duration > 1 ? duration : 1;
if (ethUsdPrice && ethRegistrationPrice) {
return (
Number(ethUsdPrice) *
Number(gweiToEth(ethRegistrationPrice)) *
duration
durationToUse
).toFixed(2);
}
return "0";
Expand All @@ -82,6 +83,7 @@ const RegisterSummary: FunctionComponent<RegisterSummaryProps> = ({
setUsdRegistrationPrice(computeUsdPrice());
}, [ethRegistrationPrice, ethUsdPrice, duration]);

// Ideally, this should be a separate components
function displayPrice(priceToPay: string, salesTaxInfo: string): ReactNode {
return (
<div className="flex items-center justify-center">
Expand Down Expand Up @@ -119,6 +121,7 @@ const RegisterSummary: FunctionComponent<RegisterSummaryProps> = ({
salesTaxRate *
Number(gweiToEth(ethRegistrationPrice)) *
Number(ethUsdPrice);

const salesTaxInfo = salesTaxAmountUsd
? ` (+ ${numberToFixedString(
salesTaxAmountUsd
Expand All @@ -127,7 +130,7 @@ const RegisterSummary: FunctionComponent<RegisterSummaryProps> = ({

const registerPrice = Number(gweiToEth(registrationPrice));
const registerPriceStr =
registerPrice != 0 ? numberToFixedString(registerPrice, 3) : "0";
registerPrice != 0 ? numberToFixedString(registerPrice, 4) : "0";
if (isUpselled && discountedPrice) {
return displayDiscountedPrice(
registerPriceStr,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
StarknetSignature,
} from "@anima-protocol/personhood-sdk-react";
import { useAccount } from "@starknet-react/core";
import { Call, TypedData } from "starknet";
import { Call, TypedData, constants } from "starknet";
import { useContractWrite } from "@starknet-react/core";
import { hexToDecimal } from "../../../../utils/feltService";
import {
Expand Down
5 changes: 3 additions & 2 deletions hooks/naming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ export function useDataFromDomain(domain: string): FullDomainData {
args: [encoded],
});

const res = data as CallResult;
return {
expiry: data?.["expiry"],
owner: data?.["owner"],
expiry: res?.["expiry"],
owner: res?.["owner"],
error: error?.message as string,
};
}
7 changes: 4 additions & 3 deletions hooks/useAllowanceCheck.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ export default function useAllowanceCheck(
});

useEffect(() => {
const erc20AllowanceRes = erc20AllowanceData as CallResult;
if (
erc20AllowanceError ||
(erc20AllowanceData &&
erc20AllowanceData["remaining"].low !== UINT_128_MAX &&
erc20AllowanceData["remaining"].high !== UINT_128_MAX)
(erc20AllowanceRes &&
erc20AllowanceRes["remaining"].low !== UINT_128_MAX &&
erc20AllowanceRes["remaining"].high !== UINT_128_MAX)
) {
setNeedsAllowance(true);
} else {
Expand Down
5 changes: 3 additions & 2 deletions hooks/useBalances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,13 @@ export default function useBalances(address?: string) {

useEffect(() => {
if (erc20BalanceError || !erc20BalanceData) return;
const erc20BalanceRes = erc20BalanceData as bigint[][];
const currencies = Object.values(CurrencyType);
const balanceEntries: TokenBalance = {};
currencies.forEach((currency, index) => {
const balance = fromUint256(
BigInt(erc20BalanceData[index][0]),
BigInt(erc20BalanceData[index][1])
BigInt(erc20BalanceRes[index][0]),
BigInt(erc20BalanceRes[index][1])
);
balanceEntries[currency] = balance;
});
Expand Down
5 changes: 3 additions & 2 deletions hooks/useNeedAllowances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,11 @@ export default function useNeedsAllowances(
if (erc20AllowanceError || !erc20AllowanceData) return;
const currencyNames = Object.values(CurrencyType);
const needsAllowancesEntries: Record<string, boolean> = {};
const erc20AllowanceRes = erc20AllowanceData as bigint[][];
currencyNames.forEach((currency, index) => {
const balance = fromUint256(
BigInt(erc20AllowanceData[index][0]),
BigInt(erc20AllowanceData[index][1])
BigInt(erc20AllowanceRes[index][0]),
BigInt(erc20AllowanceRes[index][1])
);
needsAllowancesEntries[currency] = balance === "0";
});
Expand Down
Loading

0 comments on commit 56496e0

Please sign in to comment.