Skip to content

Commit

Permalink
deal with callbacks response for RedemptionSubmitted and RedemptionCo…
Browse files Browse the repository at this point in the history
…nfirmed
  • Loading branch information
levalleux-ludo committed Oct 18, 2023
1 parent c7b27af commit 4d739c1
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -371,13 +371,13 @@ ${FormModel.formFields.phone.placeholder}: ${phoneField.value}`;
console.error("Error while redeeming", error);
// call postRedemptionSubmitted if error before the transaction is submitted OR postRedemptionConfirmed if error after
if (isTxPending) {
postRedemptionSubmitted?.({
postRedemptionConfirmed?.({
redemptionInfo,
isError: true,
error: { ...error }
});
} else {
postRedemptionConfirmed?.({
postRedemptionSubmitted?.({
redemptionInfo,
isError: true,
error: { ...error }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Confirmation, { ConfirmationProps } from "./Confirmation";
import { NonModalProps, useNonModalContext } from "../../../nonModal/NonModal";
import Typography from "../../../../ui/Typography";
import { theme } from "../../../../../theme";
import { useAccount } from "wagmi";

const colors = theme.colors.light;

Expand All @@ -29,6 +30,7 @@ export function ConfirmationView({
? getAddress(exchange.seller.assistant)
: "";
const dispatch = useNonModalContext();
const { address } = useAccount();
useEffect(() => {
dispatch({
payload: {
Expand All @@ -45,7 +47,13 @@ export function ConfirmationView({
}, [dispatch]);
return (
<>
{exchange ? (
{!exchange ? (
<p>Exchange could not be retrieved.</p>
) : exchange.buyer?.wallet?.toLowerCase() !== address?.toLowerCase() ? (
<p>You do not own this exchange.</p>
) : exchange.state !== "COMMITTED" ? (
<p>Invalid exchange state.</p>
) : (
<Confirmation
exchangeId={exchange.id}
offerId={offerId as string}
Expand All @@ -57,8 +65,6 @@ export function ConfirmationView({
onSuccess={onSuccess}
hideModal={hideModal}
/>
) : (
<p>Exchange could not be retrieved</p>
)}
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type RedemptionProps = {
type WidgetProps = RedemptionProps &
IpfsProviderProps &
Omit<ConfigProviderProps, "magicLinkKey" | "infuraKey"> &
RedemptionContextProps &
Omit<RedemptionContextProps, "setWidgetAction"> &
EnvironmentProviderProps &
ConvertionRateProviderProps &
Omit<WalletConnectionProviderProps, "children" | "envName">;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { RedemptionContext, RedemptionContextProps } from "./RedemptionContext";
export function RedemptionProvider({
children,
...rest
}: RedemptionContextProps & { children: ReactNode }) {
}: Omit<RedemptionContextProps, "setWidgetAction"> & { children: ReactNode }) {
const [widgetAction, setWidgetAction] = useState(rest.widgetAction);
return (
<RedemptionContext.Provider
Expand Down
153 changes: 97 additions & 56 deletions packages/react-kit/src/hooks/callbacks/useRedemptionCallbacks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,56 @@ export type DeliveryInfoCallbackResponse = {
resume: boolean;
};

export type RedeemTransactionSubmittedCallbackResponse = {
accepted: boolean;
reason: string;
};

export type RedeemTransactionConfirmedCallbackResponse = {
accepted: boolean;
reason: string;
};

async function fetchAndReadResponse(
step: "deliveryInfo" | "redemptionSubmitted" | "redemptionConfirmed",
input: RequestInfo | URL,
init?: RequestInit | undefined
): Promise<
| DeliveryInfoCallbackResponse
| RedeemTransactionSubmittedCallbackResponse
| RedeemTransactionConfirmedCallbackResponse
> {
try {
const response = await fetch(input, init);
const isTrueOrOkOrYes = (s: string) =>
!!s && ["true", "ok", "yes"].includes(s.toLowerCase());
let responseBody;
try {
responseBody = await response.json();
} catch {}
const accepted =
response.ok && isTrueOrOkOrYes(responseBody?.accepted?.toString());
if (!accepted) {
throw new Error(responseBody?.reason?.toString() || response.statusText);
}
return {
accepted,
resume:
step !== "deliveryInfo"
? undefined
: isTrueOrOkOrYes(responseBody?.resume?.toString()),
reason: ""
};
} catch (error) {
console.error(`An error happened when posting ${step}: ${error}`);
return {
accepted: false,
reason: (error as Error).toString(),
resume: step !== "deliveryInfo" ? undefined : false
};
}
}

function postDeliveryInfoCallback(
postDeliveryInfoUrl: string,
postDeliveryInfoHeaders: { [key: string]: string } | undefined
Expand All @@ -60,87 +110,78 @@ function postDeliveryInfoCallback(
const signature = signer
? await signer.signMessage(JSON.stringify(message))
: undefined;
try {
const response = await fetch(postDeliveryInfoUrl, {
method: "POST",
body: JSON.stringify({
message,
signature
}),
headers: {
"content-type": "application/json;charset=UTF-8",
...postDeliveryInfoHeaders
}
});
const isTrueOrOkOrYes = (s: string) =>
!!s && ["true", "ok", "yes"].includes(s.toLowerCase());
let responseBody;
try {
responseBody = await response.json();
} catch {}
const accepted =
response.ok && isTrueOrOkOrYes(responseBody?.accepted?.toString());
const resume =
accepted && isTrueOrOkOrYes(responseBody?.resume?.toString());
const reason = accepted
? ""
: responseBody?.reason?.toString() || response.statusText;
return {
accepted,
resume,
reason
};
} catch (error) {
return {
accepted: false,
reason: (error as Error).toString(),
resume: false
};
}
return fetchAndReadResponse("deliveryInfo", postDeliveryInfoUrl, {
method: "POST",
body: JSON.stringify({
step: "deliveryInfo",
message,
signature
}),
headers: {
"content-type": "application/json;charset=UTF-8",
...postDeliveryInfoHeaders
}
}) as Promise<DeliveryInfoCallbackResponse>;
};
}

function postRedemptionSubmittedCallback(
postRedemptionSubmittedUrl: string,
postRedemptionSubmittedHeaders: { [key: string]: string } | undefined
) {
return async (message: RedeemTransactionSubmittedMessage) => {
return async (
message: RedeemTransactionSubmittedMessage
): Promise<RedeemTransactionConfirmedCallbackResponse> => {
if (!postRedemptionSubmittedUrl) {
throw new Error(
"[postRedemptionSubmittedCallback] postRedemptionSubmittedUrl is not defined"
);
}
// TODO: get response from server and throw exception in case of an error
await fetch(postRedemptionSubmittedUrl, {
method: "POST",
body: JSON.stringify(message),
headers: {
"content-type": "application/json;charset=UTF-8",
...postRedemptionSubmittedHeaders
return fetchAndReadResponse(
"redemptionSubmitted",
postRedemptionSubmittedUrl,
{
method: "POST",
body: JSON.stringify({
step: "redemptionSubmitted",
message
}),
headers: {
"content-type": "application/json;charset=UTF-8",
...postRedemptionSubmittedHeaders
}
}
});
) as Promise<RedeemTransactionConfirmedCallbackResponse>;
};
}

function postRedemptionConfirmedCallback(
postRedemptionConfirmedUrl: string,
postRedemptionConfirmedHeaders: { [key: string]: string } | undefined
) {
return async (message: RedeemTransactionConfirmedMessage) => {
return async (
message: RedeemTransactionConfirmedMessage
): Promise<RedeemTransactionSubmittedCallbackResponse> => {
if (!postRedemptionConfirmedUrl) {
throw new Error(
"[postDeliveryInfoCallback] postDeliveryInfoUrl is not defined"
"[postRedemptionConfirmedCallback] postRedemptionConfirmedUrl is not defined"
);
}
// TODO: get response from server and throw exception in case of an error
await fetch(postRedemptionConfirmedUrl, {
method: "POST",
body: JSON.stringify(message),
headers: {
"content-type": "application/json;charset=UTF-8",
...postRedemptionConfirmedHeaders
return fetchAndReadResponse(
"redemptionConfirmed",
postRedemptionConfirmedUrl,
{
method: "POST",
body: JSON.stringify({
step: "redemptionConfirmed",
message
}),
headers: {
"content-type": "application/json;charset=UTF-8",
...postRedemptionConfirmedHeaders
}
}
});
) as Promise<RedeemTransactionSubmittedCallbackResponse>;
};
}

Expand Down
52 changes: 50 additions & 2 deletions packages/react-kit/src/stories/widgets/Redemption.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ RedemptionCallbacksRedeemConfirm.args = {
...Redemption.args,
showRedemptionOverview: false,
widgetAction: RedemptionWidgetAction.CONFIRM_REDEEM,
exchangeId: "133",
exchangeId: "149",
deliveryInfo: process.env.REACT_APP_DELIVERY_ADDRESS_MOCK
? JSON.parse(process.env.REACT_APP_DELIVERY_ADDRESS_MOCK)
: undefined,
Expand Down Expand Up @@ -123,8 +123,56 @@ RedemptionCallbacksFailure2.args = {
...Redemption.args,
showRedemptionOverview: false,
widgetAction: RedemptionWidgetAction.REDEEM_FORM,
exchangeId: "133",
exchangeId: "149",
postDeliveryInfoUrl: "http://localhost:3666/fail2",
postRedemptionSubmittedUrl: "http://localhost:3666/submitted",
postRedemptionConfirmedUrl: "http://localhost:3666/confirmed"
};

export const RedemptionCallbacksFailure3: ComponentStory<
typeof RedemptionWidget
> = Template.bind({});

RedemptionCallbacksFailure3.args = {
...Redemption.args,
showRedemptionOverview: false,
widgetAction: RedemptionWidgetAction.CONFIRM_REDEEM,
exchangeId: "149",
deliveryInfo: {
name: "TOTO",
streetNameAndNumber: "1 grand place",
city: "LILLE",
state: "NORD",
zip: "59000",
country: "FR",
email: "toto@mail.com",
phone: "+33123456789"
},
postDeliveryInfoUrl: "http://localhost:3666/deliveryInfo",
postRedemptionSubmittedUrl: "http://localhost:3666/fail3",
postRedemptionConfirmedUrl: "http://localhost:3666/confirmed"
};

export const RedemptionCallbacksFailure4: ComponentStory<
typeof RedemptionWidget
> = Template.bind({});

RedemptionCallbacksFailure4.args = {
...Redemption.args,
showRedemptionOverview: false,
widgetAction: RedemptionWidgetAction.CONFIRM_REDEEM,
exchangeId: "149",
deliveryInfo: {
name: "TOTO",
streetNameAndNumber: "1 grand place",
city: "LILLE",
state: "NORD",
zip: "59000",
country: "FR",
email: "toto@mail.com",
phone: "+33123456789"
},
postDeliveryInfoUrl: "http://localhost:3666/deliveryInfo",
postRedemptionSubmittedUrl: "http://localhost:3666/submitted",
postRedemptionConfirmedUrl: "http://localhost:3666/fail4"
};

0 comments on commit 4d739c1

Please sign in to comment.