Feat: Web3 Rainbowkit Integration (#4019)

* add new rainbow app and metadata

* add rainbowkit components

* add rainbow to event-type form

* create wallet connection ui

* verify signature when event is booked

* extract rainbow logic to app-store

* fix issues, dynamic import, theming

* skeleton, better api logic

* add gate logic to /[user]/book

* Fixes package.json

* Update yarn.lock

* Type fixes

Co-authored-by: zomars <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-09-05 15:10:58 -06:00
1 parent faf62ac8e7
commit 18d697436c
36 files changed
+2305 -279

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
import { Dispatch, useState, useEffect } from "react";
import { JSONObject } from "superjson/dist/types";
import RainbowGate from "@calcom/app-store/rainbow/components/RainbowKit";
export type Gate = undefined | "rainbow"; // Add more like ` | "geolocation" | "payment"`
export type GateState = {
rainbowToken?: string;
};
type GateProps = {
children: React.ReactNode;
gates: Gate[];
metadata: JSONObject;
dispatch: Dispatch<Partial<GateState>>;
};
// To add a new Gate just add the gate logic to the switch statement
const Gates: React.FC<GateProps> = ({ children, gates, metadata, dispatch }) => {
const [rainbowToken, setRainbowToken] = useState<string>();
useEffect(() => {
dispatch({ rainbowToken });
}, [rainbowToken, dispatch]);
let gateWrappers = <>{children}</>;
// Recursively wraps the `gateWrappers` with new gates allowing for multiple gates
for (const gate of gates) {
switch (gate) {
case "rainbow":
if (metadata.blockchainId && metadata.smartContractAddress && !rainbowToken) {
gateWrappers = (
<RainbowGate
setToken={setRainbowToken}
chainId={metadata.blockchainId as number}
tokenAddress={metadata.smartContractAddress as string}>
{gateWrappers}
</RainbowGate>
);
}
}
}
return gateWrappers;
};
export default Gates;
@@ -20,6 +20,7 @@ type AvailableTimesProps = {
seatsPerTimeSlot?: number | null;
slots?: Slot[];
isLoading: boolean;
ethSignature?: string;
};
const AvailableTimes: FC<AvailableTimesProps> = ({
@@ -31,6 +32,7 @@ const AvailableTimes: FC<AvailableTimesProps> = ({
recurringCount,
timeFormat,
seatsPerTimeSlot,
ethSignature,
}) => {
const { t, i18n } = useLocale();
const router = useRouter();
@@ -69,6 +71,7 @@ const AvailableTimes: FC<AvailableTimesProps> = ({
slug: eventTypeSlug,
/** Treat as recurring only when a count exist and it's not a rescheduling workflow */
count: recurringCount && !rescheduleUid ? recurringCount : undefined,
ethSignature,
},
};
@@ -4,7 +4,8 @@ import { SchedulingType } from "@prisma/client";
import * as Collapsible from "@radix-ui/react-collapsible";
import { TFunction } from "next-i18next";
import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import { useReducer, useEffect, useMemo, useState } from "react";
import { Toaster } from "react-hot-toast";
import { FormattedNumber, IntlProvider } from "react-intl";
import { z } from "zod";
@@ -34,6 +35,7 @@ import { timeZone as localStorageTimeZone } from "@lib/clock";
import { useExposePlanGlobally } from "@lib/hooks/useExposePlanGlobally";
import { isBrandingHidden } from "@lib/isBrandingHidden";
import Gates, { Gate, GateState } from "@components/Gates";
import AvailableTimes from "@components/booking/AvailableTimes";
import TimeOptions from "@components/booking/TimeOptions";
import { UserAvatars } from "@components/booking/UserAvatars";
@@ -46,8 +48,6 @@ import type { DynamicAvailabilityPageProps } from "../../../pages/d/[link]/[slug
import type { AvailabilityTeamPageProps } from "../../../pages/team/[slug]/[type]";
import { AvailableEventLocations } from "../AvailableEventLocations";
export type Props = AvailabilityTeamPageProps | AvailabilityPageProps | DynamicAvailabilityPageProps;
const GoBackToPreviousPage = ({ t }: { t: TFunction }) => {
const router = useRouter();
const path = router.asPath.split("/");
@@ -113,6 +113,7 @@ const SlotPicker = ({
users,
seatsPerTimeSlot,
weekStart = 0,
ethSignature,
}: {
eventType: Pick<EventType, "id" | "schedulingType" | "slug">;
timeFormat: string;
@@ -121,6 +122,7 @@ const SlotPicker = ({
recurringEventCount?: number;
users: string[];
weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
ethSignature?: string;
}) => {
const [selectedDate, setSelectedDate] = useState<Dayjs>();
const [browsingDate, setBrowsingDate] = useState<Dayjs>();
@@ -202,6 +204,7 @@ const SlotPicker = ({
eventTypeSlug={eventType.slug}
seatsPerTimeSlot={seatsPerTimeSlot}
recurringCount={recurringEventCount}
ethSignature={ethSignature}
/>
)}
</>
@@ -284,6 +287,8 @@ const useRouterQuery = <T extends string>(name: T) => {
} & { setQuery: typeof setQuery };
};
export type Props = AvailabilityTeamPageProps | AvailabilityPageProps | DynamicAvailabilityPageProps;
const AvailabilityPage = ({ profile, eventType }: Props) => {
const router = useRouter();
const isEmbed = useIsEmbed();
@@ -299,6 +304,13 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
const [timeZone, setTimeZone] = useState<string>();
const [timeFormat, setTimeFormat] = useState(detectBrowserTimeFormat);
const [isAvailableTimesVisible, setIsAvailableTimesVisible] = useState<boolean>();
const [gateState, gateDispatcher] = useReducer(
(state: GateState, newState: Partial<GateState>) => ({
...state,
...newState,
}),
{}
);
useEffect(() => {
setTimeZone(localStorageTimeZone() || dayjs.tz.guess());
@@ -325,7 +337,7 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
}, [telemetry]);
// get dynamic user list here
const userList = eventType.users.map((user) => user.username).filter(notEmpty);
const userList = eventType.users ? eventType.users.map((user) => user.username).filter(notEmpty) : [];
// Recurring event sidebar requires more space
const maxWidth = isAvailableTimesVisible
? recurringEventCount
@@ -349,8 +361,16 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
if (rawSlug.length > 1) rawSlug.pop(); //team events have team name as slug, but user events have [user]/[type] as slug.
const slug = rawSlug.join("/");
// Define conditional gates here
const gates = [
// Rainbow gate is only added if the event has both a `blockchainId` and a `smartContractAddress`
eventType.metadata && eventType.metadata.blockchainId && eventType.metadata.smartContractAddress
? ("rainbow" as Gate)
: undefined,
];
return (
<>
<Gates gates={gates} metadata={eventType.metadata} dispatch={gateDispatcher}>
<HeadSeo
title={`${rescheduleUid ? t("reschedule") : ""} ${eventType.title} | ${profile.name}`}
description={`${rescheduleUid ? t("reschedule") : ""} ${eventType.title}`}
@@ -587,13 +607,15 @@ const AvailabilityPage = ({ profile, eventType }: Props) => {
users={userList}
seatsPerTimeSlot={eventType.seatsPerTimeSlot || undefined}
recurringEventCount={recurringEventCount}
ethSignature={gateState.rainbowToken}
/>
</div>
</div>
{(!eventType.users[0] || !isBrandingHidden(eventType.users[0])) && !isEmbed && <PoweredByCal />}
</main>
</div>
</>
<Toaster position="bottom-right" />
</Gates>
);
};
@@ -5,7 +5,7 @@ import { isValidPhoneNumber } from "libphonenumber-js";
import { useSession } from "next-auth/react";
import Head from "next/head";
import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState, useReducer } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { FormattedNumber, IntlProvider } from "react-intl";
import { ReactMultiEmail } from "react-multi-email";
@@ -48,6 +48,7 @@ import createRecurringBooking from "@lib/mutations/bookings/create-recurring-boo
import { parseDate, parseRecurringDates } from "@lib/parseDate";
import slugify from "@lib/slugify";
import Gates, { Gate, GateState } from "@components/Gates";
import { UserAvatars } from "@components/booking/UserAvatars";
import EventTypeDescriptionSafeHTML from "@components/eventtype/EventTypeDescriptionSafeHTML";
@@ -55,15 +56,6 @@ import { BookPageProps } from "../../../pages/[user]/book";
import { HashLinkPageProps } from "../../../pages/d/[link]/book";
import { TeamBookingPageProps } from "../../../pages/team/[slug]/book";
declare global {
// eslint-disable-next-line no-var
var web3: {
currentProvider: {
selectedAddress: string;
};
};
}
type BookingPageProps = BookPageProps | TeamBookingPageProps | HashLinkPageProps;
type BookingFormValues = {
@@ -98,6 +90,13 @@ const BookingPage = ({
const { data: session } = useSession();
const isBackgroundTransparent = useIsBackgroundTransparent();
const telemetry = useTelemetry();
const [gateState, gateDispatcher] = useReducer(
(state: GateState, newState: Partial<GateState>) => ({
...state,
...newState,
}),
{}
);
useEffect(() => {
if (top !== window) {
@@ -359,6 +358,7 @@ const BookingPage = ({
hashedLink,
smsReminderNumber:
selectedLocationType === LocationType.Phone ? booking.phone : booking.smsReminderNumber,
ethSignature: gateState.rainbowToken,
}));
recurringMutation.mutate(recurringBookings);
} else {
@@ -386,6 +386,7 @@ const BookingPage = ({
hashedLink,
smsReminderNumber:
selectedLocationType === LocationType.Phone ? booking.phone : booking.smsReminderNumber,
ethSignature: gateState.rainbowToken,
});
}
};
@@ -412,8 +413,16 @@ const BookingPage = ({
});
}
// Define conditional gates here
const gates = [
// Rainbow gate is only added if the event has both a `blockchainId` and a `smartContractAddress`
eventType.metadata && eventType.metadata.blockchainId && eventType.metadata.smartContractAddress
? ("rainbow" as Gate)
: undefined,
];
return (
<div>
<Gates gates={gates} metadata={eventType.metadata} dispatch={gateDispatcher}>
<Head>
<title>
{rescheduleUid
@@ -873,7 +882,7 @@ const BookingPage = ({
</div>
</div>
</main>
</div>
</Gates>
);
};
@@ -16,6 +16,10 @@ type RecurringEventControllerProps = {
onRecurringEventDefined: (value: boolean) => void;
};
/**
* @deprecated
* use component from `/apps/web/components/v2/eventtype/RecurringEventController` instead
**/
export default function RecurringEventController({
recurringEvent,
formMethods,
@@ -2,13 +2,12 @@ import { EventTypeSetupInfered, FormValues } from "pages/v2/event-types/[type]";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import RecurringEventController from "@components/v2/eventtype/RecurringEventController";
import RecurringEventController from "./RecurringEventController";
export const EventRecurringTab = ({
eventType,
hasPaymentIntegration,
}: Pick<EventTypeSetupInfered, "eventType" | "hasPaymentIntegration">) => {
const formMethods = useFormContext<FormValues>();
const requirePayment = eventType.price > 0;
const [recurringEventDefined, setRecurringEventDefined] = useState(
eventType.recurringEvent?.count !== undefined
@@ -20,7 +19,6 @@ export const EventRecurringTab = ({
paymentEnabled={hasPaymentIntegration && requirePayment}
onRecurringEventDefined={setRecurringEventDefined}
recurringEvent={eventType.recurringEvent}
formMethods={formMethods}
/>
</div>
);
@@ -1,28 +1,27 @@
import type { FormValues } from "pages/event-types/[type]";
import { useState } from "react";
import { UseFormReturn } from "react-hook-form";
import { useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Frequency } from "@calcom/prisma/zod-utils";
import type { RecurringEvent } from "@calcom/types/Calendar";
import { Alert } from "@calcom/ui/Alert";
import { Label, Switch, Select } from "@calcom/ui/v2";
import { Label, Select, Switch } from "@calcom/ui/v2";
type RecurringEventControllerProps = {
recurringEvent: RecurringEvent | null;
formMethods: UseFormReturn<FormValues>;
paymentEnabled: boolean;
onRecurringEventDefined: (value: boolean) => void;
};
export default function RecurringEventController({
recurringEvent,
formMethods,
paymentEnabled,
onRecurringEventDefined,
}: RecurringEventControllerProps) {
const { t } = useLocale();
const [recurringEventState, setRecurringEventState] = useState<RecurringEvent | null>(recurringEvent);
const formMethods = useFormContext<FormValues>();
/* Just yearly-0, monthly-1 and weekly-2 */
const recurringEventFreqOptions = Object.entries(Frequency)
+1
View File
@@ -27,6 +27,7 @@ export type BookingCreateBody = {
hasHashedBookingLink: boolean;
hashedLink?: string | null;
smsReminderNumber?: string;
ethSignature?: string;
};
export type BookingResponse = Booking & {
+5
View File
@@ -6,6 +6,7 @@ import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { getLocationValueForDB, LocationObject } from "@calcom/app-store/locations";
import { handleEthSignature } from "@calcom/app-store/rainbow/utils/ethereum";
import { handlePayment } from "@calcom/app-store/stripepayment/lib/server";
import { cancelScheduledJobs, scheduleTrigger } from "@calcom/app-store/zapier/lib/nodeScheduler";
import EventManager from "@calcom/core/EventManager";
@@ -350,6 +351,10 @@ async function handler(req: NextApiRequest) {
console.log("available users", users);
// @TODO: use the returned address somewhere in booking creation?
// const address: string | undefined = await ...
await handleEthSignature(eventType.metadata, reqBody.ethSignature);
const [organizerUser] = users;
const tOrganizer = await getTranslation(organizerUser.locale ?? "en", "common");
+1
View File
@@ -154,6 +154,7 @@ export default function IntegrationsPage() {
<CalendarListContainer />
<IntegrationsContainer variant="payment" className="mt-8" />
<IntegrationsContainer variant="other" className="mt-8" />
<IntegrationsContainer variant="web3" className="mt-8" />
</>
) : (
<EmptyScreen
+22
View File
@@ -5,6 +5,7 @@ import * as RadioGroup from "@radix-ui/react-radio-group";
import classNames from "classnames";
import { isValidPhoneNumber } from "libphonenumber-js";
import { GetServerSidePropsContext } from "next";
import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { Controller, Noop, useForm, UseFormReturn } from "react-hook-form";
@@ -67,6 +68,10 @@ import WebhookListContainer from "@components/webhook/WebhookListContainer";
import { getTranslation } from "@server/lib/i18n";
import { TRPCClientError } from "@trpc/client";
const RainbowInstallForm = dynamic(() => import("@calcom/rainbow/components/RainbowInstallForm"), {
suspense: true,
});
type OptionTypeBase = {
label: string;
value: EventLocationType["type"];
@@ -115,6 +120,8 @@ export type FormValues = {
};
successRedirectUrl: string;
giphyThankYouPage: string;
blockchainId: number;
smartContractAddress: string;
};
const SuccessRedirectEdit = <T extends UseFormReturn<FormValues>>({
@@ -236,6 +243,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
hasPaymentIntegration,
currency,
hasGiphyIntegration,
hasRainbowIntegration,
} = props;
const router = useRouter();
@@ -558,6 +566,8 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
const {
periodDates,
periodCountCalendarDays,
smartContractAddress,
blockchainId,
giphyThankYouPage,
beforeBufferTime,
afterBufferTime,
@@ -579,6 +589,8 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
afterEventBuffer: afterBufferTime,
seatsPerTimeSlot: Number.isNaN(seatsPerTimeSlot) ? null : seatsPerTimeSlot,
metadata: {
...(smartContractAddress ? { smartContractAddress } : {}),
...(blockchainId ? { blockchainId } : { blockchainId: 1 }),
...(giphyThankYouPage ? { giphyThankYouPage } : {}),
},
});
@@ -1056,6 +1068,14 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
)}
/>
{hasRainbowIntegration && (
<RainbowInstallForm
formMethods={formMethods}
blockchainId={(eventType.metadata.blockchainId as number) || 1}
smartContractAddress={(eventType.metadata.smartContractAddress as string) || ""}
/>
)}
<hr className="my-2 border-neutral-200" />
<Controller
name="minimumBookingNotice"
@@ -1884,6 +1904,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
};
const hasGiphyIntegration = !!credentials.find((credential) => credential.type === "giphy_other");
const hasRainbowIntegration = !!credentials.find((credential) => credential.type === "rainbow_web3");
// backwards compat
if (eventType.users.length === 0 && !eventType.team) {
@@ -1947,6 +1968,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
teamMembers,
hasPaymentIntegration,
hasGiphyIntegration,
hasRainbowIntegration,
currency,
currentUserMembership,
},
@@ -1093,6 +1093,14 @@
"customize_your_brand_colors": "Customize your own brand colour into your booking page.",
"pro": "Pro",
"removes_cal_branding": "Removes any Cal related brandings, i.e. 'Powered by Cal.'",
"web3": "Web3",
"rainbow_token_gated": "This event type is token gated.",
"rainbow_connect_wallet_gate": "Connect your wallet if you own <1>{{name}}</1> (<3>{{symbol}}</3>).",
"rainbow_insufficient_balance": "Your connected wallet doesn't contain enough <1>{{symbol}}</1>.",
"rainbow_sign_message_request": "Sign the message request on your wallet.",
"rainbow_signature_error": "Error requesting signature from your wallet.",
"token_address": "Token Address",
"blockchain": "Blockchain",
"old_password": "Old password",
"secure_password": "Your new super secure password",
"error_updating_password": "Error updating password",