Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add zora join #3819

Merged
merged 6 commits into from
Sep 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions apps/web/src/components/Channel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,9 @@ const ViewChannel: NextPage = () => {

const fetchCommunity = async (): Promise<Channel> => {
const response: {
data: {
result: Channel;
};
data: { result: Channel };
} = await axios.get(`${CHANNELS_WORKER_URL}/get/${slug}`);
setMembersCount(response.data?.result.members[0].count);
setMembersCount(response.data?.result.members);

return response.data?.result;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const MintAction: FC<MintActionProps> = ({ nft, zoraLink, publication }) => {

const nftAddress = nft.address;
const recipient = address as Address;
const comment = 'Minted via Lenster';
const comment = 'Minted from Lenster';
const mintReferral = ADMIN_ADDRESS;
const nftPriceInEth = parseInt(nft.price) / 10 ** 18;
const mintFee = parseEther('0.000777');
Expand Down
100 changes: 31 additions & 69 deletions apps/web/src/components/Shared/Channel/Join.tsx
Original file line number Diff line number Diff line change
@@ -1,103 +1,65 @@
import { useChannelMemberCountStore } from '@components/Channel/Details';
import { UserPlusIcon } from '@heroicons/react/24/outline';
import { CHANNELS_WORKER_URL } from '@lenster/data/constants';
import { Localstorage } from '@lenster/data/storage';
import { PROFILE } from '@lenster/data/tracking';
import type { Channel } from '@lenster/types/lenster';
import { Button, Spinner } from '@lenster/ui';
import errorToast from '@lib/errorToast';
import { Leafwatch } from '@lib/leafwatch';
import { Button, Modal } from '@lenster/ui';
import { t } from '@lingui/macro';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { useRouter } from 'next/router';
import { type FC, useState } from 'react';
import toast from 'react-hot-toast';
import { useAppStore } from 'src/store/app';
import { useGlobalModalStateStore } from 'src/store/modals';

import Mint from './Mint';

interface JoinProps {
channel: Channel;
}

const Join: FC<JoinProps> = ({ channel }) => {
const { pathname } = useRouter();
const currentProfile = useAppStore((state) => state.currentProfile);
const { membersCount, setMembersCount } = useChannelMemberCountStore();
const setShowAuthModal = useGlobalModalStateStore(
(state) => state.setShowAuthModal
);
const [showMintModal, setShowMintModal] = useState(false);
const [joined, setJoined] = useState(false);
const [submitting, setSubmitting] = useState(false);

const isChannelMember = async () => {
try {
const response = await axios.get(`${CHANNELS_WORKER_URL}/isMember`, {
params: {
profileId: currentProfile?.id,
channelId: channel.id
}
params: { by: currentProfile?.ownedBy, contract: channel.contract }
});
const { data } = response;
setJoined(data.isMember);
} catch {}
};

const { isLoading } = useQuery(
['isChannelMember', channel.id, currentProfile?.id],
() => isChannelMember()
['isChannelMember', channel.contract, currentProfile?.ownedBy],
() => isChannelMember(),
{ enabled: Boolean(currentProfile) }
);

const createMembership = async () => {
if (!currentProfile) {
setShowAuthModal(true);
return;
}

try {
setSubmitting(true);
await axios.post(
`${CHANNELS_WORKER_URL}/joinOrLeave`,
{ profileId: currentProfile?.id, channelId: channel?.id },
{
headers: {
'X-Access-Token': localStorage.getItem(Localstorage.AccessToken)
}
}
);
setJoined(!joined);
setMembersCount(joined ? membersCount - 1 : membersCount + 1);
toast.success(joined ? t`Left successfully!` : t`Joined successfully!`);
Leafwatch.track(PROFILE.FOLLOW, {
path: pathname,
profile_id: currentProfile?.id,
channel_id: channel?.id
});
} catch (error) {
setSubmitting(false);
errorToast(error);
} finally {
setSubmitting(false);
}
};
if (!currentProfile) {
return null;
}

return (
<Button
className="!px-3 !py-1.5 text-sm"
onClick={createMembership}
aria-label="Join"
disabled={submitting || isLoading}
icon={
submitting ? (
<Spinner size="xs" />
) : (
<UserPlusIcon className="h-4 w-4" />
)
}
outline
>
{isLoading ? t`Loading...` : joined ? t`Leave` : t`Join`}
</Button>
<>
<Button
className="!px-3 !py-1.5 text-sm"
onClick={() => setShowMintModal(true)}
aria-label="Join"
disabled={isLoading}
icon={<UserPlusIcon className="h-4 w-4" />}
outline
>
{isLoading ? t`Loading...` : joined ? t`Joined` : t`Join`}
</Button>
<Modal
show={showMintModal}
title={t`Join Channel`}
icon={<UserPlusIcon className="text-brand h-5 w-5" />}
onClose={() => setShowMintModal(false)}
>
<Mint channel={channel} joined={joined} />
</Modal>
</>
);
};

Expand Down
160 changes: 160 additions & 0 deletions apps/web/src/components/Shared/Channel/Mint.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { useChannelMemberCountStore } from '@components/Channel/Details';
import { CurrencyDollarIcon, UserPlusIcon } from '@heroicons/react/24/outline';
import { CheckCircleIcon } from '@heroicons/react/24/solid';
import { ZoraERC721Drop } from '@lenster/abis';
import { ADMIN_ADDRESS } from '@lenster/data/constants';
import type { Channel } from '@lenster/types/lenster';
import { Button, Spinner } from '@lenster/ui';
import { t, Trans } from '@lingui/macro';
import Link from 'next/link';
import { type FC } from 'react';
import { useAppStore } from 'src/store/app';
import type { Address } from 'viem';
import { parseEther } from 'viem';
import { zora } from 'viem/chains';
import {
useChainId,
useContractWrite,
usePrepareContractWrite,
useWaitForTransaction
} from 'wagmi';

import SwitchNetwork from '../SwitchNetwork';

const NO_BALANCE_ERROR = 'exceeds the balance of the account';

interface MintProps {
channel: Channel;
joined: boolean;
}

const Mint: FC<MintProps> = ({ channel, joined }) => {
const { membersCount, setMembersCount } = useChannelMemberCountStore();
const currentProfile = useAppStore((state) => state.currentProfile);
const chain = useChainId();

const nftAddress = channel.contract as Address;
const recipient = currentProfile?.ownedBy;
const comment = 'Joined from Lenster';
const mintReferral = ADMIN_ADDRESS;
const mintFee = parseEther('0.000777');
const value = (parseEther('0') + mintFee) * 1n;
const abi = ZoraERC721Drop;
const args = [recipient, 1n, comment, mintReferral];

const {
config,
isError: isPrepareError,
error: prepareError
} = usePrepareContractWrite({
chainId: zora.id,
address: nftAddress,
functionName: 'mintWithRewards',
abi,
args,
value
});
const {
write,
data,
isLoading: isContractWriteLoading
} = useContractWrite({
...config,
onSuccess: () => setMembersCount(membersCount + 1)
});
const { isLoading, isSuccess } = useWaitForTransaction({
chainId: zora.id,
hash: data?.hash
});

const mintingOrSuccess = isLoading || isSuccess;

// Errors
const noBalanceError = prepareError?.message?.includes(NO_BALANCE_ERROR);

return (
<div className="p-5">
{!joined ? (
<div className="mb-3 text-lg font-bold">Join {channel.name}</div>
) : null}
<div>
{joined ? (
<Trans>
You are already a member in <b>{channel.name}</b> channel.
</Trans>
) : (
<Trans>
Join <b>{channel.name}</b> channel in Zora network and get your
membership NFT.
</Trans>
)}
</div>
{!joined ? (
!mintingOrSuccess ? (
<div className="flex">
{chain !== zora.id ? (
<SwitchNetwork
className="mt-5 w-full justify-center"
toChainId={zora.id}
title={t`Switch to Zora`}
/>
) : isPrepareError ? (
noBalanceError ? (
<Link
className="w-full"
href="https://app.uniswap.org"
target="_blank"
rel="noopener noreferrer"
>
<Button
className="mt-5 w-full justify-center"
icon={<CurrencyDollarIcon className="h-5 w-5" />}
size="md"
>
<Trans>You don't have balance</Trans>
</Button>
</Link>
) : null
) : (
<Button
className="mt-5 w-full justify-center"
disabled={!write}
onClick={() => write?.()}
icon={
isContractWriteLoading ? (
<Spinner className="mr-1" size="xs" />
) : (
<UserPlusIcon className="h-5 w-5" />
)
}
>
<Trans>Join</Trans>
</Button>
)}
</div>
) : (
<div className="mt-5 text-sm font-medium">
{isLoading ? (
<div className="flex items-center space-x-1.5">
<Spinner size="xs" />
<div>
<Trans>Joining in progress</Trans>
</div>
</div>
) : null}
{isSuccess ? (
<div className="flex items-center space-x-1.5">
<CheckCircleIcon className="h-5 w-5 text-green-500" />
<div>
<Trans>Joined successful</Trans>
</div>
</div>
) : null}
</div>
)
) : null}
</div>
);
};

export default Mint;
4 changes: 1 addition & 3 deletions packages/types/lenster.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { Database } from '@lenster/supabase/database.types';

export type Channel = Database['public']['Tables']['channels']['Row'] & {
members: {
count: number;
}[];
members: number;
};
11 changes: 9 additions & 2 deletions packages/workers/channels/src/handlers/getChannel.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import response from '@lenster/lib/response';
import createSupabaseClient from '@lenster/supabase/createSupabaseClient';

import getMembersCount from '../helpers/getMembersCount';
import type { WorkerRequest } from '../types';

export default async (request: WorkerRequest) => {
Expand All @@ -10,11 +11,17 @@ export default async (request: WorkerRequest) => {
const client = createSupabaseClient(request.env.SUPABASE_KEY);
const { data } = await client
.from('channels')
.select('*, members:channel_memberships(count)')
.select('*')
.eq('slug', slug)
.single();

return response({ success: true, result: data });
return response({
success: true,
result: {
...data,
members: await getMembersCount(data?.contract as `0x${string}`)
}
});
} catch (error) {
throw error;
}
Expand Down
19 changes: 7 additions & 12 deletions packages/workers/channels/src/handlers/isMember.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
import response from '@lenster/lib/response';
import createSupabaseClient from '@lenster/supabase/createSupabaseClient';

import haveMintedZoraNft from '../helpers/haveMintedZoraNft';
import type { WorkerRequest } from '../types';

export default async (request: WorkerRequest) => {
const profileId = request.query.profileId as string;
const channelId = request.query.channelId as string;
const by = request.query.by as `0x${string}`;
const contract = request.query.contract as `0x${string}`;

try {
const client = createSupabaseClient(request.env.SUPABASE_KEY);
const { data } = await client
.from('channel_memberships')
.select('*')
.eq('profile_id', profileId)
.eq('channel_id', channelId)
.single();

return response({ success: true, isMember: data ? true : false });
return response({
success: true,
isMember: await haveMintedZoraNft(by, contract)
});
} catch (error) {
throw error;
}
Expand Down
Loading
Loading