@dunbackmeadow/commerce-sdk 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +256 -3
- package/dist/index.d.ts +186 -0
- package/dist/index.js +378 -0
- package/dist/luma-D0rL0u8I.d.ts +597 -0
- package/dist/react/index.d.ts +67 -0
- package/dist/react/index.js +288 -0
- package/docs/API_REFERENCE.md +358 -0
- package/docs/LUMA_INTEGRATION_GUIDE.md +291 -0
- package/package.json +70 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var DunbackApiError = class extends Error {
|
|
3
|
+
/** Machine-readable, e.g. "invalid_request", "payment_amount_short", "order_deadline_passed". */
|
|
4
|
+
code;
|
|
5
|
+
status;
|
|
6
|
+
details;
|
|
7
|
+
constructor(status, code, message, details) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "DunbackApiError";
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.details = details;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var PAYMENT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
16
|
+
"payment_pending",
|
|
17
|
+
"payment_not_found",
|
|
18
|
+
"payment_amount_short",
|
|
19
|
+
"payment_already_used",
|
|
20
|
+
"invalid_payment_signature",
|
|
21
|
+
"invalid_payment",
|
|
22
|
+
"insufficient_funds",
|
|
23
|
+
"settlement_failed"
|
|
24
|
+
]);
|
|
25
|
+
function isPaymentError(e) {
|
|
26
|
+
return e instanceof DunbackApiError && PAYMENT_ERROR_CODES.has(e.code);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/client.ts
|
|
30
|
+
var DEFAULT_BASE_URL = "https://dunbackmeadow.com/api/partner/v1";
|
|
31
|
+
var SANDBOX_BASE_URL = "https://sandbox.dunbackmeadow.com/api/partner/v1";
|
|
32
|
+
var KEY_RE = /^dbk_(live|test)_([a-z0-9-]{2,40})_[A-Za-z0-9_-]{32,}$/;
|
|
33
|
+
function randomKey() {
|
|
34
|
+
const c = globalThis.crypto;
|
|
35
|
+
return c?.randomUUID ? c.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
36
|
+
}
|
|
37
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
38
|
+
var DunbackClient = class {
|
|
39
|
+
/** "test" (sandbox) or "live" (production), from the key. */
|
|
40
|
+
mode;
|
|
41
|
+
/** The app the key belongs to, from the key. */
|
|
42
|
+
appId;
|
|
43
|
+
apiKey;
|
|
44
|
+
baseUrl;
|
|
45
|
+
timeoutMs;
|
|
46
|
+
fetchImpl;
|
|
47
|
+
constructor(opts) {
|
|
48
|
+
const parsed = KEY_RE.exec(String(opts?.apiKey || "").trim());
|
|
49
|
+
if (!parsed) throw new Error("DunbackClient: a dbk_live_/dbk_test_ API key is required. Create one in the Dunback Developer Dashboard.");
|
|
50
|
+
this.apiKey = parsed[0];
|
|
51
|
+
this.mode = parsed[1];
|
|
52
|
+
this.appId = parsed[2];
|
|
53
|
+
this.baseUrl = (opts.baseUrl || (this.mode === "test" ? SANDBOX_BASE_URL : DEFAULT_BASE_URL)).replace(/\/$/, "");
|
|
54
|
+
this.timeoutMs = opts.timeoutMs ?? 3e4;
|
|
55
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
56
|
+
if (!this.fetchImpl) throw new Error("DunbackClient: global fetch is missing (Node 18+ required).");
|
|
57
|
+
}
|
|
58
|
+
/** Low-level request. Retries network errors and 5xx (POSTs only with an Idempotency-Key). */
|
|
59
|
+
async request(method, path, body, opts = {}) {
|
|
60
|
+
const headers = { Authorization: `Bearer ${this.apiKey}`, Accept: "application/json" };
|
|
61
|
+
if (body !== void 0) headers["Content-Type"] = "application/json";
|
|
62
|
+
if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
|
|
63
|
+
const retriable = method === "GET" || !!opts.idempotencyKey;
|
|
64
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
65
|
+
let res;
|
|
66
|
+
try {
|
|
67
|
+
res = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
68
|
+
method,
|
|
69
|
+
headers,
|
|
70
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
71
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? this.timeoutMs)
|
|
72
|
+
});
|
|
73
|
+
} catch (e) {
|
|
74
|
+
if (retriable && attempt < 2) {
|
|
75
|
+
await sleep(500 * 2 ** attempt);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
throw new DunbackApiError(0, "network_error", e.message);
|
|
79
|
+
}
|
|
80
|
+
const text = await res.text();
|
|
81
|
+
let json = null;
|
|
82
|
+
try {
|
|
83
|
+
json = text ? JSON.parse(text) : null;
|
|
84
|
+
} catch {
|
|
85
|
+
}
|
|
86
|
+
if (res.ok) return json;
|
|
87
|
+
if (retriable && res.status >= 500 && attempt < 2) {
|
|
88
|
+
await sleep(500 * 2 ** attempt);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const err = json?.error || {};
|
|
92
|
+
throw new DunbackApiError(res.status, err.code || `http_${res.status}`, err.message || text || res.statusText, err.details);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** The app and environment this key belongs to. Handy as a "is my key working?" check. */
|
|
96
|
+
async me() {
|
|
97
|
+
return this.request("GET", "/me");
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Cuisines a host can pick when creating an event. Pass the venue to count
|
|
101
|
+
* only restaurants in its metro area (the ones that can cater there);
|
|
102
|
+
* without one, counts cover the whole platform. Pass `{ guests }` (expected
|
|
103
|
+
* guests) to count only restaurants able to cater that many: restaurants
|
|
104
|
+
* may limit guests per order or require a minimum order. See also
|
|
105
|
+
* cuisineCatalog().
|
|
106
|
+
*/
|
|
107
|
+
async listCuisines(venue, query = {}) {
|
|
108
|
+
return (await this.cuisineCatalog(venue, query)).data;
|
|
109
|
+
}
|
|
110
|
+
/** listCuisines() plus which metro area the counts are for (`metro` is null when Dunback doesn't serve the venue's area). */
|
|
111
|
+
async cuisineCatalog(venue, query = {}) {
|
|
112
|
+
const q = new URLSearchParams();
|
|
113
|
+
for (const k of ["city", "state", "zip"]) {
|
|
114
|
+
const v = String(venue?.[k] ?? "").trim();
|
|
115
|
+
if (v) q.set(k, v);
|
|
116
|
+
}
|
|
117
|
+
const hasVenue = q.toString() !== "";
|
|
118
|
+
if (query.guests != null) {
|
|
119
|
+
if (!Number.isInteger(query.guests) || query.guests < 1) throw new TypeError("guests must be a whole number, 1 or more");
|
|
120
|
+
q.set("guests", String(query.guests));
|
|
121
|
+
}
|
|
122
|
+
if (query.serviceStyle) q.set("serviceStyle", query.serviceStyle);
|
|
123
|
+
const qs = q.toString();
|
|
124
|
+
const r = await this.request("GET", `/catalog/cuisines${qs ? `?${qs}` : ""}`);
|
|
125
|
+
return {
|
|
126
|
+
data: r.data,
|
|
127
|
+
scope: r.scope ?? (hasVenue ? "metro" : "platform"),
|
|
128
|
+
metro: r.metro ?? null,
|
|
129
|
+
guests: r.guests ?? query.guests ?? null,
|
|
130
|
+
serviceStyle: r.serviceStyle ?? query.serviceStyle ?? null
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
catering = {
|
|
134
|
+
/** Sends the guest list; Dunback's catering agent composes up to 3 priced options (async). */
|
|
135
|
+
create: (input, opts = {}) => this.request("POST", "/catering/requests", input, { idempotencyKey: opts.idempotencyKey ?? randomKey() }),
|
|
136
|
+
get: (requestId) => this.request("GET", `/catering/requests/${encodeURIComponent(requestId)}`),
|
|
137
|
+
/** All catering requests made under one partnerReference (e.g. one Luma event), newest first. */
|
|
138
|
+
listByReference: async (partnerReference) => (await this.request("GET", `/catering/requests?partnerReference=${encodeURIComponent(partnerReference)}`)).data,
|
|
139
|
+
/**
|
|
140
|
+
* Polls until composing is done (usually 5-30 s). Prefer the
|
|
141
|
+
* `catering.options_ready` webhook in production; this is for scripts and agents.
|
|
142
|
+
*/
|
|
143
|
+
waitForOptions: async (requestId, { timeoutMs = 12e4, intervalMs = 2500 } = {}) => {
|
|
144
|
+
const until = Date.now() + timeoutMs;
|
|
145
|
+
for (; ; ) {
|
|
146
|
+
const r = await this.catering.get(requestId);
|
|
147
|
+
if (r.status !== "COMPOSING") return r;
|
|
148
|
+
if (Date.now() > until) throw new DunbackApiError(408, "timeout", "Dunback is still composing options; try again shortly.");
|
|
149
|
+
await sleep(intervalMs);
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
/** The host picks an option: creates the order and its payment links. */
|
|
153
|
+
select: (requestId, input, opts = {}) => this.request("POST", `/catering/requests/${encodeURIComponent(requestId)}/select`, input, { idempotencyKey: opts.idempotencyKey ?? randomKey(), timeoutMs: 6e4 })
|
|
154
|
+
};
|
|
155
|
+
orders = {
|
|
156
|
+
/** Current state; also re-checks Stripe, so it is safe to poll after a checkout redirect. */
|
|
157
|
+
get: (orderId) => this.request("GET", `/orders/${encodeURIComponent(orderId)}`),
|
|
158
|
+
/** Tell Dunback about a USDC transfer (optional: transfers of the exact amount are detected automatically). */
|
|
159
|
+
confirmUsdcPayment: (orderId, txHash) => this.request("POST", `/orders/${encodeURIComponent(orderId)}/usdc/confirm`, { txHash }, { timeoutMs: 9e4 }),
|
|
160
|
+
/**
|
|
161
|
+
* Corrects the delivery address, on-site contact and note while the order
|
|
162
|
+
* is AWAITING_PAYMENT (the payer can do the same on the hosted payment
|
|
163
|
+
* page). The price stays as quoted, so the new address must be in an area
|
|
164
|
+
* Dunback delivers to, inside the restaurant's delivery area and within
|
|
165
|
+
* about a mile of the original; otherwise it fails with 422
|
|
166
|
+
* `delivery_area_not_launched`, `outside_delivery_area` or `address_moved`
|
|
167
|
+
* (create a new catering request instead). Sends `order.delivery_updated`.
|
|
168
|
+
*/
|
|
169
|
+
updateDelivery: (orderId, input) => this.request("POST", `/orders/${encodeURIComponent(orderId)}/delivery`, input),
|
|
170
|
+
/** Unpaid orders: cancels the payment links. Confirmed orders: cancels at the restaurant (before its order deadline) and refunds. */
|
|
171
|
+
cancel: (orderId, reason) => this.request("POST", `/orders/${encodeURIComponent(orderId)}/cancel`, { reason }),
|
|
172
|
+
/** Polls until the order leaves AWAITING_PAYMENT/PAID/FULFILLING. */
|
|
173
|
+
waitForSettlement: async (orderId, { timeoutMs = 15 * 6e4, intervalMs = 5e3 } = {}) => {
|
|
174
|
+
const until = Date.now() + timeoutMs;
|
|
175
|
+
for (; ; ) {
|
|
176
|
+
const o = await this.orders.get(orderId);
|
|
177
|
+
if (!["AWAITING_PAYMENT", "PAID", "FULFILLING"].includes(o.status)) return o;
|
|
178
|
+
if (Date.now() > until) return o;
|
|
179
|
+
await sleep(intervalMs);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// src/webhooks.ts
|
|
186
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
187
|
+
function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300, now = Date.now() } = {}) {
|
|
188
|
+
if (!signatureHeader) throw new Error("Missing Dunback-Signature header.");
|
|
189
|
+
const parts = Object.fromEntries(
|
|
190
|
+
signatureHeader.split(",").map((kv) => kv.trim().split("=", 2))
|
|
191
|
+
);
|
|
192
|
+
const t = Number(parts.t);
|
|
193
|
+
const v1 = parts.v1;
|
|
194
|
+
if (!Number.isFinite(t) || !v1) throw new Error("Malformed Dunback-Signature header.");
|
|
195
|
+
if (Math.abs(now / 1e3 - t) > toleranceSeconds) throw new Error("Webhook timestamp is outside the tolerance window.");
|
|
196
|
+
const body = typeof rawBody === "string" ? rawBody : Buffer.from(rawBody).toString("utf8");
|
|
197
|
+
const expected = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");
|
|
198
|
+
const a = Buffer.from(expected, "hex");
|
|
199
|
+
const b = Buffer.from(v1, "hex");
|
|
200
|
+
if (a.length !== b.length || !timingSafeEqual(a, b)) throw new Error("Invalid webhook signature.");
|
|
201
|
+
return JSON.parse(body);
|
|
202
|
+
}
|
|
203
|
+
function signWebhookPayload(rawBody, secret, t = Math.floor(Date.now() / 1e3)) {
|
|
204
|
+
return `t=${t},v1=${createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex")}`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/luma.ts
|
|
208
|
+
var DUNBACK_REGISTRATION_QUESTION = {
|
|
209
|
+
id: "dunback_food_allergies",
|
|
210
|
+
label: "Food allergies or dietary needs",
|
|
211
|
+
description: "Optional. By answering, you agree that Dunback Meadow and the restaurant may use your answer to prepare a safe meal for you. Leave blank if none.",
|
|
212
|
+
type: "long_text",
|
|
213
|
+
required: false,
|
|
214
|
+
placeholder: "e.g. peanuts, shellfish, vegetarian, celiac"
|
|
215
|
+
};
|
|
216
|
+
var ATTENDING_STATUSES = /* @__PURE__ */ new Set(["approved", "going", "checked_in", "confirmed"]);
|
|
217
|
+
var ALLERGY_LABEL_RE = /allerg|dietary|diet|food restriction/i;
|
|
218
|
+
function answerText(a) {
|
|
219
|
+
const v = a.answer ?? a.value;
|
|
220
|
+
if (v == null) return "";
|
|
221
|
+
if (Array.isArray(v)) return v.join(", ");
|
|
222
|
+
return String(v);
|
|
223
|
+
}
|
|
224
|
+
var NONE_RE = /^\s*(none|no|n\/a|na|nope|nothing|-|no allergies)\s*\.?\s*$/i;
|
|
225
|
+
function attendingGuests(guests, includeStatuses) {
|
|
226
|
+
return guests.map((g) => "guest" in g && g.guest ? g.guest : g).filter((g) => !g.approval_status || includeStatuses.has(String(g.approval_status).toLowerCase()));
|
|
227
|
+
}
|
|
228
|
+
var guestName = (g) => (g.user_name || g.name || g.user_email || g.email || "Guest").trim();
|
|
229
|
+
function allergyAnswer(g, { questionId = DUNBACK_REGISTRATION_QUESTION.id, otherQuestionsHaveConsent = false }) {
|
|
230
|
+
const answers = g.registration_answers || [];
|
|
231
|
+
const own = answers.find((a) => a.question_id === questionId);
|
|
232
|
+
if (own) return { text: answerText(own).slice(0, 500).trim(), consent: true };
|
|
233
|
+
const other = answers.find((a) => ALLERGY_LABEL_RE.test(a.label || ""));
|
|
234
|
+
return { text: other ? answerText(other).slice(0, 500).trim() : "", consent: otherQuestionsHaveConsent };
|
|
235
|
+
}
|
|
236
|
+
function toDunbackAttendees(guests, options = {}) {
|
|
237
|
+
return attendingGuests(guests, options.includeStatuses || ATTENDING_STATUSES).map((g) => {
|
|
238
|
+
const { text, consent } = allergyAnswer(g, options);
|
|
239
|
+
const shared = consent && text && !NONE_RE.test(text);
|
|
240
|
+
const a = { externalId: g.api_id || g.id, name: guestName(g), allergies: shared ? text : "" };
|
|
241
|
+
if (shared) a.allergyConsent = true;
|
|
242
|
+
const email = g.user_email || g.email;
|
|
243
|
+
if (email) a.email = email;
|
|
244
|
+
if (g.phone_number) a.phone = g.phone_number;
|
|
245
|
+
return a;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function guestsWithUnsharedAllergies(guests, options = {}) {
|
|
249
|
+
return attendingGuests(guests, options.includeStatuses || ATTENDING_STATUSES).filter((g) => {
|
|
250
|
+
const { text, consent } = allergyAnswer(g, options);
|
|
251
|
+
return !consent && text && !NONE_RE.test(text);
|
|
252
|
+
}).map(guestName);
|
|
253
|
+
}
|
|
254
|
+
function toDunbackAddress(geo) {
|
|
255
|
+
if (!geo?.address || !geo.city || !geo.postal_code) {
|
|
256
|
+
throw new Error("Dunback catering needs a street address, city and ZIP for the venue (online events can't be catered).");
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
address1: geo.address,
|
|
260
|
+
city: geo.city,
|
|
261
|
+
state: geo.region || "",
|
|
262
|
+
zip: geo.postal_code,
|
|
263
|
+
country: (geo.country_code || "US").toUpperCase().slice(0, 2)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function toVenueLocation(geo) {
|
|
267
|
+
const address = String(geo?.address ?? "").trim();
|
|
268
|
+
const city = String(geo?.city ?? "").trim();
|
|
269
|
+
const zip = String(geo?.postal_code ?? "").trim();
|
|
270
|
+
if (!address || !city || !zip) return null;
|
|
271
|
+
return { city, state: String(geo?.region ?? "").trim(), zip };
|
|
272
|
+
}
|
|
273
|
+
function buildCateringRequest(args) {
|
|
274
|
+
const { event, guests, settings, host } = args;
|
|
275
|
+
if (!settings?.enabled) throw new Error("Dunback catering is not enabled for this event.");
|
|
276
|
+
const onsite = args.onsiteContact || settings.onsiteContact || (host.phone ? { name: host.name, phone: host.phone, email: host.email } : null);
|
|
277
|
+
if (!onsite) throw new Error("An on-site contact with a phone number is required for delivery.");
|
|
278
|
+
const attendees = [...toDunbackAttendees(guests), ...args.extraAttendees || []];
|
|
279
|
+
if (!attendees.length) throw new Error("The event has no attending guests yet.");
|
|
280
|
+
return {
|
|
281
|
+
partnerReference: `luma:${event.api_id || event.id}`,
|
|
282
|
+
event: { name: event.name, startsAt: event.start_at, timeZone: event.timezone, ...event.url ? { url: event.url } : {} },
|
|
283
|
+
...settings.deliveryDeadlineLocal ? { deliveryDeadlineLocal: settings.deliveryDeadlineLocal } : {},
|
|
284
|
+
cuisine: settings.cuisine,
|
|
285
|
+
serviceStyle: settings.serviceStyle ?? "meal_boxes",
|
|
286
|
+
includeDrinks: settings.includeDrinks ?? true,
|
|
287
|
+
...settings.budgetPerGuest ? { budgetPerGuest: settings.budgetPerGuest } : {},
|
|
288
|
+
deliveryAddress: args.deliveryAddress || toDunbackAddress(event.geo_address_json),
|
|
289
|
+
onsiteContact: onsite,
|
|
290
|
+
deliveryNotes: settings.deliveryNotes || "",
|
|
291
|
+
host,
|
|
292
|
+
attendees
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function canOrderFood(settings, event, now = /* @__PURE__ */ new Date()) {
|
|
296
|
+
if (!settings?.enabled) return { ok: false, reason: "Dunback catering is off for this event." };
|
|
297
|
+
if (Date.parse(event.start_at) <= now.getTime()) return { ok: false, reason: "The event has started." };
|
|
298
|
+
if (settings.guestListDeadline && Date.parse(settings.guestListDeadline) > now.getTime()) {
|
|
299
|
+
return { ok: false, reason: "The guest list isn't final yet." };
|
|
300
|
+
}
|
|
301
|
+
return { ok: true };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// src/x402.ts
|
|
305
|
+
var toB64 = (obj) => btoa(JSON.stringify(obj));
|
|
306
|
+
var fromB64 = (s) => JSON.parse(atob(s.replace(/-/g, "+").replace(/_/g, "/")));
|
|
307
|
+
function randomNonce() {
|
|
308
|
+
const b = new Uint8Array(32);
|
|
309
|
+
globalThis.crypto.getRandomValues(b);
|
|
310
|
+
return `0x${[...b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
|
|
311
|
+
}
|
|
312
|
+
async function payOrderWithX402(order, signer, { fetch: fetchImpl = globalThis.fetch, maxAmountUsdc } = {}) {
|
|
313
|
+
const url = order.payment?.usdc?.x402Url;
|
|
314
|
+
if (!url) throw new Error("This order has no x402 payment URL (is it still awaiting payment, with USDC offered?).");
|
|
315
|
+
const challenge = await fetchImpl(url, { method: "POST" });
|
|
316
|
+
if (challenge.status !== 402) {
|
|
317
|
+
const body2 = await challenge.json().catch(() => ({}));
|
|
318
|
+
throw new DunbackApiError(challenge.status, body2?.error?.code || "unexpected_response", body2?.error?.message || "Expected a 402 payment challenge.");
|
|
319
|
+
}
|
|
320
|
+
const header = challenge.headers.get("PAYMENT-REQUIRED");
|
|
321
|
+
const required = header ? fromB64(header) : await challenge.json();
|
|
322
|
+
const accept = required?.accepts?.find((a) => a.network === "eip155:137");
|
|
323
|
+
if (!accept) throw new Error("No Polygon USDC payment option was offered.");
|
|
324
|
+
const amountUsdc = Number(accept.amount) / 1e6;
|
|
325
|
+
if (maxAmountUsdc != null && amountUsdc > maxAmountUsdc) {
|
|
326
|
+
throw new Error(`Dunback asks ${amountUsdc} USDC, above your limit of ${maxAmountUsdc}.`);
|
|
327
|
+
}
|
|
328
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
329
|
+
const message = {
|
|
330
|
+
from: signer.address,
|
|
331
|
+
to: accept.payTo,
|
|
332
|
+
value: accept.amount,
|
|
333
|
+
validAfter: "0",
|
|
334
|
+
validBefore: String(now + Math.min(3600, accept.maxTimeoutSeconds ?? 300)),
|
|
335
|
+
nonce: randomNonce()
|
|
336
|
+
};
|
|
337
|
+
const signature = await signer.signTypedData({
|
|
338
|
+
domain: { name: accept.extra?.name || "USD Coin", version: accept.extra?.version || "2", chainId: 137, verifyingContract: accept.asset },
|
|
339
|
+
types: {
|
|
340
|
+
TransferWithAuthorization: [
|
|
341
|
+
{ name: "from", type: "address" },
|
|
342
|
+
{ name: "to", type: "address" },
|
|
343
|
+
{ name: "value", type: "uint256" },
|
|
344
|
+
{ name: "validAfter", type: "uint256" },
|
|
345
|
+
{ name: "validBefore", type: "uint256" },
|
|
346
|
+
{ name: "nonce", type: "bytes32" }
|
|
347
|
+
]
|
|
348
|
+
},
|
|
349
|
+
primaryType: "TransferWithAuthorization",
|
|
350
|
+
message
|
|
351
|
+
});
|
|
352
|
+
const paid = await fetchImpl(url, {
|
|
353
|
+
method: "POST",
|
|
354
|
+
headers: { "PAYMENT-SIGNATURE": toB64({ x402Version: 2, scheme: "exact", network: accept.network, accepted: accept, payload: { authorization: message, signature } }) }
|
|
355
|
+
});
|
|
356
|
+
const body = await paid.json().catch(() => ({}));
|
|
357
|
+
if (!paid.ok) throw new DunbackApiError(paid.status, body?.error?.code || "payment_failed", body?.error?.message || "The x402 payment was not accepted.");
|
|
358
|
+
return body;
|
|
359
|
+
}
|
|
360
|
+
export {
|
|
361
|
+
ATTENDING_STATUSES,
|
|
362
|
+
DEFAULT_BASE_URL,
|
|
363
|
+
DUNBACK_REGISTRATION_QUESTION,
|
|
364
|
+
DunbackApiError,
|
|
365
|
+
DunbackClient,
|
|
366
|
+
PAYMENT_ERROR_CODES,
|
|
367
|
+
SANDBOX_BASE_URL,
|
|
368
|
+
buildCateringRequest,
|
|
369
|
+
canOrderFood,
|
|
370
|
+
guestsWithUnsharedAllergies,
|
|
371
|
+
isPaymentError,
|
|
372
|
+
payOrderWithX402,
|
|
373
|
+
signWebhookPayload,
|
|
374
|
+
toDunbackAddress,
|
|
375
|
+
toDunbackAttendees,
|
|
376
|
+
toVenueLocation,
|
|
377
|
+
verifyWebhook
|
|
378
|
+
};
|