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

create metadata field #33

Merged
merged 4 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 4 additions & 4 deletions packages/connectkit/src/components/DaimoPay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,12 @@ const DaimoPayProviderWithoutSolana = ({
// Order just updated...
if (daimoPayOrder?.mode !== DaimoPayOrderMode.HYDRATED) return;

const { sourceStatus, intentStatus } = daimoPayOrder;
const { intentStatus } = daimoPayOrder;
let intervalMs = 0;
if (sourceStatus === DaimoPayOrderStatusSource.WAITING_PAYMENT) {
if (intentStatus === DaimoPayIntentStatus.UNPAID) {
intervalMs = 2500; // additional, faster polling in WaitingOther
} else if (intentStatus === DaimoPayIntentStatus.PENDING) {
intervalMs = 300; // poll fast from (payment initiated) to (finished)
} else if (intentStatus === DaimoPayIntentStatus.STARTED) {
intervalMs = 300; // poll fast from payment started to payment completed
} else {
return;
}
Expand Down
73 changes: 47 additions & 26 deletions packages/connectkit/src/components/DaimoPayButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
assertNotNull,
DaimoPayIntentStatus,
DaimoPayOrderMode,
DaimoPayOrderStatusSource,
DaimoPayUserMetadata,
getDaimoPayOrderView,
PaymentBouncedEvent,
PaymentCompletedEvent,
PaymentStartedEvent,
Expand Down Expand Up @@ -64,6 +65,14 @@ type PayButtonPaymentProps =
* Preferred tokens. These appear first in the token list.
*/
preferredTokens?: { chain: number; address: Address }[];
/**
* External ID. E.g. a correlation ID.
*/
externalId?: string;
/**
* Developer metadata. E.g. correlation ID.
* */
metadata?: DaimoPayUserMetadata;
}
| {
/** The payment ID, generated via the Daimo Pay API. Replaces params above. */
Expand Down Expand Up @@ -154,6 +163,8 @@ function DaimoPayButtonCustom(props: DaimoPayButtonCustomProps) {
paymentOptions: props.paymentOptions,
preferredChains: props.preferredChains,
preferredTokens: props.preferredTokens,
externalId: props.externalId,
metadata: props.metadata,
}
: null;
let payId = "payId" in props ? props.payId : null;
Expand All @@ -178,9 +189,8 @@ function DaimoPayButtonCustom(props: DaimoPayButtonCustomProps) {
const { onPaymentStarted, onPaymentCompleted, onPaymentBounced } = props;

const order = paymentState.daimoPayOrder;
const intentStatus = order?.intentStatus;
const hydOrder = order?.mode === DaimoPayOrderMode.HYDRATED ? order : null;
const isStarted =
hydOrder?.sourceStatus !== DaimoPayOrderStatusSource.WAITING_PAYMENT;

// Functions to show and hide the modal
const { children, closeOnSuccess } = props;
Expand All @@ -191,33 +201,44 @@ function DaimoPayButtonCustom(props: DaimoPayButtonCustomProps) {
};
const hide = () => context.setOpen(false);

useEffect(() => {
if (hydOrder == null || !isStarted) return;
onPaymentStarted?.({
paymentId: writeDaimoPayOrderID(hydOrder.id),
type: "payment_started",
chainId: assertNotNull(hydOrder.sourceTokenAmount).token.chainId,
txHash: assertNotNull(hydOrder.sourceInitiateTxHash),
});
}, [isStarted]);

// Emit event handlers when payment status changes
useEffect(() => {
if (hydOrder == null) return;
if (hydOrder.intentStatus === DaimoPayIntentStatus.PENDING) return;
if (intentStatus === DaimoPayIntentStatus.UNPAID) return;

const commonFields = {
paymentId: writeDaimoPayOrderID(hydOrder.id),
chainId: assertNotNull(hydOrder.destFinalCallTokenAmount).token.chainId,
txHash: assertNotNull(
hydOrder.destFastFinishTxHash ?? hydOrder.destClaimTxHash,
),
};
if (hydOrder.intentStatus === DaimoPayIntentStatus.SUCCESSFUL) {
onPaymentCompleted?.({ type: "payment_completed", ...commonFields });
} else if (hydOrder.intentStatus === DaimoPayIntentStatus.REFUNDED) {
onPaymentBounced?.({ type: "payment_bounced", ...commonFields });
if (intentStatus === DaimoPayIntentStatus.STARTED) {
onPaymentStarted?.({
type: DaimoPayIntentStatus.STARTED,
paymentId: writeDaimoPayOrderID(hydOrder.id),
chainId: hydOrder.destFinalCallTokenAmount.token.chainId,
txHash: assertNotNull(
hydOrder.sourceInitiateTxHash,
`source initiate tx hash null on order ${hydOrder.id} when intent status is ${intentStatus}`,
),
payment: getDaimoPayOrderView(hydOrder),
});
} else if (
intentStatus === DaimoPayIntentStatus.COMPLETED ||
intentStatus === DaimoPayIntentStatus.BOUNCED
) {
const event = {
type: intentStatus,
paymentId: writeDaimoPayOrderID(hydOrder.id),
chainId: hydOrder.destFinalCallTokenAmount.token.chainId,
txHash: assertNotNull(
hydOrder.destFastFinishTxHash ?? hydOrder.destClaimTxHash,
`dest tx hash null on order ${hydOrder.id} when intent status is ${intentStatus}`,
),
payment: getDaimoPayOrderView(hydOrder),
};

if (intentStatus === DaimoPayIntentStatus.COMPLETED) {
onPaymentCompleted?.(event as PaymentCompletedEvent);
} else if (intentStatus === DaimoPayIntentStatus.BOUNCED) {
onPaymentBounced?.(event as PaymentBouncedEvent);
}
}
}, [hydOrder?.intentStatus]);
}, [hydOrder?.id, intentStatus]);

useEffect(() => {
if (props.defaultOpen) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,34 +106,4 @@ const PayWithSolanaToken: React.FC = () => {
);
};

const LoadingContainer = styled(motion.div)`
display: flex;
align-items: center;
justify-content: center;
margin: 10px auto 16px;
height: 120px;
`;
const AnimationContainer = styled(motion.div)<{
$circle: boolean;
}>`
user-select: none;
position: relative;
--spinner-error-opacity: 0;
&:before {
content: "";
position: absolute;
inset: 1px;
opacity: 0;
background: var(--ck-body-color-danger);
${(props) =>
props.$circle &&
css`
inset: -5px;
border-radius: 50%;
background: none;
box-shadow: inset 0 0 0 3.5px var(--ck-body-color-danger);
`}
}
`;

export default PayWithSolanaToken;
27 changes: 4 additions & 23 deletions packages/connectkit/src/hooks/useDaimoPayStatus.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,24 @@
import {
DaimoPayIntentStatus,
DaimoPayOrderMode,
DaimoPayOrderStatusSource,
writeDaimoPayOrderID,
} from "@daimo/common";
import { DaimoPayIntentStatus, writeDaimoPayOrderID } from "@daimo/common";
import { usePayContext } from "../components/DaimoPay";
import { PaymentStatus } from "../types";

/** Returns the current payment, or undefined if there is none.
*
* Status values:
* - `payment_pending` - the user has not paid yet
* - `payment_unpaid` - the user has not paid yet
* - `payment_started` - the user has paid & payment is in progress. This status
* typically lasts a few seconds.
* - `payment_completed` - the final call or transfer succeeded
* - `payment_bounced` - the final call or transfer reverted. Funds were sent
* to the payment's configured refund address on the destination chain.
*/
export function useDaimoPayStatus():
| { paymentId: string; status: PaymentStatus }
| { paymentId: string; status: DaimoPayIntentStatus }
| undefined {
const { paymentState } = usePayContext();
if (!paymentState || !paymentState.daimoPayOrder) return undefined;

const order = paymentState.daimoPayOrder;
const paymentId = writeDaimoPayOrderID(order.id);
if (order.mode === DaimoPayOrderMode.HYDRATED) {
if (order.intentStatus !== DaimoPayIntentStatus.PENDING) {
if (order.intentStatus === DaimoPayIntentStatus.SUCCESSFUL) {
return { paymentId, status: "payment_completed" };
} else {
return { paymentId, status: "payment_bounced" };
}
} else if (
order.sourceStatus !== DaimoPayOrderStatusSource.WAITING_PAYMENT
) {
return { paymentId, status: "payment_started" };
}
}

return { paymentId, status: "payment_pending" };
return { paymentId, status: order.intentStatus };
}
13 changes: 9 additions & 4 deletions packages/connectkit/src/hooks/usePaymentState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
assertNotNull,
DaimoPayOrder,
DaimoPayTokenAmount,
DaimoPayUserMetadata,
DepositAddressPaymentOptionData,
DepositAddressPaymentOptionMetadata,
DepositAddressPaymentOptions,
Expand All @@ -20,7 +21,6 @@ import { Address, formatUnits, Hex, parseUnits } from "viem";
import { useAccount, useEnsName } from "wagmi";

import { DaimoPayModalOptions, PaymentOption } from "../types";
import { generatePayId } from "../utils/exports";
import { detectPlatform } from "../utils/platform";
import { TrpcClient } from "../utils/trpc";
import { useDepositAddressOptions } from "./useDepositAddressOptions";
Expand Down Expand Up @@ -61,6 +61,10 @@ export interface PayParams {
preferredChains?: number[];
/** Preferred tokens. These appear first in the token list. */
preferredTokens?: { chain: number; address: Address }[];
/** External ID. E.g. a correlation ID. */
externalId?: string;
/** Developer metadata. E.g. correlation ID. */
Copy link
Member

@dcposch dcposch Feb 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metadata associated with this payment. Use eg. to track correlated IDs.

metadata?: DaimoPayUserMetadata;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

confirming that we don't expose our previous metadata anywhere... fortunately, it looks like we don't

}

/** Creates (or loads) a payment and manages the corresponding modal. */
Expand Down Expand Up @@ -215,6 +219,7 @@ export function usePaymentState({
id: order.id.toString(),
toUnits,
metadata: order.metadata,
userMetadata: payParams.metadata,
isAmountEditable: isDepositFlow,
},
platform,
Expand Down Expand Up @@ -376,14 +381,12 @@ export function usePaymentState({
};

const generatePreviewOrder = async (payParams: PayParams) => {
const newPayId = generatePayId();
const newId = readDaimoPayOrderID(newPayId).toString();
// toUnits is undefined if and only if we're in deposit flow.
// Set dummy value for deposit flow, since user can edit the amount.
const toUnits = payParams.toUnits == null ? "0" : payParams.toUnits;

const orderPreview = await trpc.previewOrder.query({
id: newId,
appId: payParams.appId,
toChain: payParams.toChain,
toToken: payParams.toToken,
toUnits,
Expand All @@ -399,6 +402,8 @@ export function usePaymentState({
preferredTokens: payParams.preferredTokens,
},
},
externalId: payParams.externalId,
userMetadata: payParams.metadata,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

});

setDaimoPayOrder(orderPreview);
Expand Down
7 changes: 0 additions & 7 deletions packages/connectkit/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,6 @@ export type DaimoPayModalOptions = {
closeOnSuccess?: boolean;
};

/** Payment status. See webhooks and React useDaimoPayStatus() hook. */
export type PaymentStatus =
| "payment_pending"
| "payment_started"
| "payment_completed"
| "payment_bounced";

// TODO: move types here from daimo-common/daimoPay.ts:
// type PayEventBase = {
// /** The type of payment event. */
Expand Down
8 changes: 0 additions & 8 deletions packages/connectkit/src/utils/exports.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
// Exported utilities, useful for @daimo/pay users.
import { writeDaimoPayOrderID } from "@daimo/common";
import { getDAv2Chains } from "@daimo/contract";
import { bytesToBigInt } from "viem";
import packageJson from "../../package.json";

export const daimoPayVersion = packageJson.version;

/** Generates a globally-unique payId. */
export function generatePayId(): string {
const id = bytesToBigInt(crypto.getRandomValues(new Uint8Array(32)));
return writeDaimoPayOrderID(id);
}

/** Chain ids supported by Daimo Pay. */
export const supportedChainIds = new Set(
[...getDAv2Chains(false), ...getDAv2Chains(true)].map((c) => c.chainId),
Expand Down