Skip to content

Safe support for minting a Hypercert #484

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

Merged
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
2 changes: 2 additions & 0 deletions components/global/extra-content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ interface ExtraContentProps {
receipt?: TransactionReceipt;
}

// TODO: not really reusable for safe. breaks when minting hypercert from safe.
// We should make this reusable for all strategies.
export function ExtraContent({
message = "Your hypercert has been minted successfully!",
hypercertId,
Expand Down
169 changes: 169 additions & 0 deletions hypercerts/EOAMintHypercertStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { track } from "@vercel/analytics";
import { waitForTransactionReceipt } from "viem/actions";

import { createExtraContent } from "@/components/global/extra-content";
import { generateHypercertIdFromReceipt } from "@/lib/generateHypercertIdFromReceipt";
import { revalidatePathServerAction } from "@/app/actions/revalidatePathServerAction";

import {
MintHypercertParams,
MintHypercertStrategy,
} from "./MintHypercertStrategy";
import { Address, Chain } from "viem";
import { HypercertClient } from "@hypercerts-org/sdk";
import { UseWalletClientReturnType } from "wagmi";
import { useStepProcessDialogContext } from "@/components/global/step-process-dialog";
import { useQueueMintBlueprint } from "@/blueprints/hooks/queueMintBlueprint";

export class EOAMintHypercertStrategy extends MintHypercertStrategy {
constructor(
protected address: Address,
protected chain: Chain,
protected client: HypercertClient,
protected dialogContext: ReturnType<typeof useStepProcessDialogContext>,
protected queueMintBlueprint: ReturnType<typeof useQueueMintBlueprint>,
protected walletClient: UseWalletClientReturnType,
) {
super(address, chain, client, dialogContext, walletClient);
}

// FIXME: this is a long ass method. Break it down into smaller ones.
async execute({
metaData,
units,
transferRestrictions,
allowlistRecords,
blueprintId,
}: MintHypercertParams) {
const { setDialogStep, setSteps, setOpen, setTitle, setExtraContent } =
this.dialogContext;
const { mutateAsync: queueMintBlueprint } = this.queueMintBlueprint;
const { data: walletClient } = this.walletClient;

if (!this.client) {
setOpen(false);
throw new Error("No client found");
}

const isBlueprint = !!blueprintId;
setOpen(true);
setSteps([
{ id: "preparing", description: "Preparing to mint hypercert..." },
{ id: "minting", description: "Minting hypercert on-chain..." },
...(isBlueprint
? [{ id: "blueprint", description: "Queueing blueprint mint..." }]
: []),
{ id: "confirming", description: "Waiting for on-chain confirmation" },
{ id: "route", description: "Creating your new hypercert's link..." },
{ id: "done", description: "Minting complete!" },
]);
setTitle("Minting hypercert");
await setDialogStep("preparing", "active");
console.log("preparing...");

let hash;
try {
await setDialogStep("minting", "active");
console.log("minting...");
hash = await this.client.mintHypercert({
metaData,
totalUnits: units,
transferRestriction: transferRestrictions,
allowList: allowlistRecords,
});
} catch (error: unknown) {
console.error("Error minting hypercert:", error);
throw new Error(
`Failed to mint hypercert: ${error instanceof Error ? error.message : "Unknown error"}`,
);
}

if (!hash) {
throw new Error("No transaction hash returned");
}

if (blueprintId) {
try {
await setDialogStep("blueprint", "active");
await queueMintBlueprint({
blueprintId,
txHash: hash,
});
} catch (error: unknown) {
console.error("Error queueing blueprint mint:", error);
throw new Error(
`Failed to queue blueprint mint: ${error instanceof Error ? error.message : "Unknown error"}`,
);
}
}
await setDialogStep("confirming", "active");
console.log("Mint submitted", {
hash,
});
track("Mint submitted", {
hash,
});
let receipt;

try {
receipt = await waitForTransactionReceipt(walletClient!, {
confirmations: 3,
hash,
});
console.log({ receipt });
} catch (error: unknown) {
console.error("Error waiting for transaction receipt:", error);
await setDialogStep(
"confirming",
"error",
error instanceof Error ? error.message : "Unknown error",
);
throw new Error(
`Failed to confirm transaction: ${error instanceof Error ? error.message : "Unknown error"}`,
);
}

if (receipt?.status === "reverted") {
throw new Error("Transaction reverted: Minting failed");
}

await setDialogStep("route", "active");

let hypercertId;
try {
hypercertId = generateHypercertIdFromReceipt(receipt, this.chain.id);
console.log("Mint completed", {
hypercertId: hypercertId || "not found",
});
track("Mint completed", {
hypercertId: hypercertId || "not found",
});
console.log({ hypercertId });
} catch (error) {
console.error("Error generating hypercert ID:", error);
await setDialogStep(
"route",
"error",
error instanceof Error ? error.message : "Unknown error",
);
}

const extraContent = createExtraContent({
receipt,
hypercertId,
chain: this.chain,
});
setExtraContent(extraContent);

await setDialogStep("done", "completed");

// TODO: Clean up these revalidations.
// https://github.com/hypercerts-org/hypercerts-app/pull/484#discussion_r2011898721
await revalidatePathServerAction([
"/collections",
"/collections/edit/[collectionId]",
`/profile/${this.address}`,
{ path: `/`, type: "layout" },
]);
}
}
30 changes: 30 additions & 0 deletions hypercerts/MintHypercertStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Address, Chain } from "viem";
import {
HypercertClient,
HypercertMetadata,
TransferRestrictions,
AllowlistEntry,
} from "@hypercerts-org/sdk";
import { UseWalletClientReturnType } from "wagmi";

import { useStepProcessDialogContext } from "@/components/global/step-process-dialog";

export interface MintHypercertParams {
metaData: HypercertMetadata;
units: bigint;
transferRestrictions: TransferRestrictions;
allowlistRecords?: AllowlistEntry[] | string;
blueprintId?: number;
}

export abstract class MintHypercertStrategy {
constructor(
protected address: Address,
protected chain: Chain,
protected client: HypercertClient,
protected dialogContext: ReturnType<typeof useStepProcessDialogContext>,
protected walletClient: UseWalletClientReturnType,
) {}

abstract execute(params: MintHypercertParams): Promise<void>;
}
93 changes: 93 additions & 0 deletions hypercerts/SafeMintHypercertStrategy.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {
MintHypercertStrategy,
MintHypercertParams,
} from "./MintHypercertStrategy";

import { Button } from "@/components/ui/button";
import { generateSafeAppLink } from "@/lib/utils";
import { ExternalLink } from "lucide-react";
import { Chain } from "viem";

export class SafeMintHypercertStrategy extends MintHypercertStrategy {
async execute({
metaData,
units,
transferRestrictions,
allowlistRecords,
}: MintHypercertParams) {
const { setDialogStep, setSteps, setOpen, setTitle, setExtraContent } =
this.dialogContext;

if (!this.client) {
setOpen(false);
throw new Error("No client found");
}

setOpen(true);
setTitle("Minting hypercert");
setSteps([
{ id: "preparing", description: "Preparing to mint hypercert..." },
{ id: "submitting", description: "Submitting to Safe..." },
{ id: "queued", description: "Transaction queued in Safe" },
]);

await setDialogStep("preparing", "active");

try {
await setDialogStep("submitting", "active");
await this.client.mintHypercert({
metaData,
totalUnits: units,
transferRestriction: transferRestrictions,
allowList: allowlistRecords,
overrides: {
safeAddress: this.address as `0x${string}`,
},
});

await setDialogStep("queued", "completed");

setExtraContent(() => (
<DialogFooter chain={this.chain} safeAddress={this.address} />
));
} catch (error) {
console.error(error);
await setDialogStep(
"submitting",
"error",
error instanceof Error ? error.message : "Unknown error",
);
throw error;
}
}
}

function DialogFooter({
chain,
safeAddress,
}: {
chain: Chain;
safeAddress: string;
}) {
return (
<div className="flex flex-col space-y-2">
<p className="text-lg font-medium">Success</p>
<p className="text-sm font-medium">
We&apos;ve submitted the transaction requests to the connected Safe.
</p>
<div className="flex space-x-4 py-4 justify-center">
{chain && (
<Button asChild>
<a
href={generateSafeAppLink(chain, safeAddress as `0x${string}`)}
target="_blank"
rel="noopener noreferrer"
>
View Safe <ExternalLink size={14} className="ml-2" />
</a>
</Button>
)}
</div>
</div>
);
}
Loading