@nano133/nanoterra 0.8.1 → 0.9.3
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/CHANGELOG.md +92 -0
- package/README.md +390 -6
- package/ai/SPEC.md +71 -3
- package/dist/admin/panel/mount.d.ts +3 -0
- package/dist/admin/panel/mount.js +4 -2
- package/dist/player-signin/adapters/d1.d.ts +10 -0
- package/dist/player-signin/adapters/d1.js +108 -0
- package/dist/player-signin/adapters/firestore.d.ts +45 -0
- package/dist/player-signin/adapters/firestore.js +168 -0
- package/dist/player-signin/conformance.d.ts +11 -0
- package/dist/player-signin/conformance.js +160 -0
- package/dist/player-signin/handler.d.ts +64 -0
- package/dist/player-signin/handler.js +364 -0
- package/dist/player-signin/host.d.ts +4 -0
- package/dist/player-signin/host.js +10 -0
- package/dist/player-signin/index.d.ts +9 -0
- package/dist/player-signin/index.js +15 -0
- package/dist/player-signin/memory.d.ts +15 -0
- package/dist/player-signin/memory.js +101 -0
- package/dist/player-signin/panel/index.d.ts +9 -0
- package/dist/player-signin/panel/index.js +8 -0
- package/dist/player-signin/panel/memo.d.ts +12 -0
- package/dist/player-signin/panel/memo.js +41 -0
- package/dist/player-signin/panel/mount.d.ts +21 -0
- package/dist/player-signin/panel/mount.js +107 -0
- package/dist/player-signin/panel/view.d.ts +48 -0
- package/dist/player-signin/panel/view.js +363 -0
- package/dist/player-signin/panel/words.d.ts +103 -0
- package/dist/player-signin/panel/words.js +111 -0
- package/dist/player-signin/scheme-check.d.ts +3 -0
- package/dist/player-signin/scheme-check.js +14 -0
- package/dist/player-signin/scheme.d.ts +13 -0
- package/dist/player-signin/scheme.js +28 -0
- package/dist/player-signin/types.d.ts +116 -0
- package/dist/player-signin/types.js +33 -0
- package/dist/shop/adapters/d1.d.ts +25 -0
- package/dist/shop/adapters/d1.js +200 -0
- package/dist/shop/adapters/firestore.d.ts +53 -0
- package/dist/shop/adapters/firestore.js +245 -0
- package/dist/shop/address.d.ts +14 -0
- package/dist/shop/address.js +104 -0
- package/dist/shop/amount.d.ts +26 -0
- package/dist/shop/amount.js +59 -0
- package/dist/shop/conformance.d.ts +13 -0
- package/dist/shop/conformance.js +203 -0
- package/dist/shop/handler.d.ts +76 -0
- package/dist/shop/handler.js +156 -0
- package/dist/shop/index.d.ts +19 -0
- package/dist/shop/index.js +21 -0
- package/dist/shop/match.d.ts +23 -0
- package/dist/shop/match.js +58 -0
- package/dist/shop/memory.d.ts +13 -0
- package/dist/shop/memory.js +106 -0
- package/dist/shop/nodes.d.ts +47 -0
- package/dist/shop/nodes.js +106 -0
- package/dist/shop/orders.d.ts +47 -0
- package/dist/shop/orders.js +82 -0
- package/dist/shop/panel/index.d.ts +9 -0
- package/dist/shop/panel/index.js +14 -0
- package/dist/shop/panel/looks.d.ts +33 -0
- package/dist/shop/panel/looks.js +61 -0
- package/dist/shop/panel/mount.d.ts +68 -0
- package/dist/shop/panel/mount.js +221 -0
- package/dist/shop/panel/pay.d.ts +27 -0
- package/dist/shop/panel/pay.js +128 -0
- package/dist/shop/panel/qr.d.ts +9 -0
- package/dist/shop/panel/qr.js +281 -0
- package/dist/shop/panel/words.d.ts +89 -0
- package/dist/shop/panel/words.js +79 -0
- package/dist/shop/price.d.ts +23 -0
- package/dist/shop/price.js +43 -0
- package/dist/shop/scan.d.ts +24 -0
- package/dist/shop/scan.js +80 -0
- package/dist/shop/security.d.ts +10 -0
- package/dist/shop/security.js +56 -0
- package/dist/shop/store.d.ts +101 -0
- package/dist/shop/store.js +4 -0
- package/dist/shop/worker.d.ts +43 -0
- package/dist/shop/worker.js +76 -0
- package/package.json +21 -6
- package/src/admin/panel/mount.ts +7 -2
- package/src/player-signin/adapters/d1.sql +45 -0
- package/src/player-signin/adapters/d1.ts +120 -0
- package/src/player-signin/adapters/firestore.ts +194 -0
- package/src/player-signin/conformance.ts +184 -0
- package/src/player-signin/handler.ts +404 -0
- package/src/player-signin/host.ts +12 -0
- package/src/player-signin/index.ts +20 -0
- package/src/player-signin/memory.ts +94 -0
- package/src/player-signin/panel/index.ts +13 -0
- package/src/player-signin/panel/memo.ts +49 -0
- package/src/player-signin/panel/mount.ts +129 -0
- package/src/player-signin/panel/style.css +478 -0
- package/src/player-signin/panel/view.ts +433 -0
- package/src/player-signin/panel/words.ts +210 -0
- package/src/player-signin/scheme-check.ts +14 -0
- package/src/player-signin/scheme.ts +32 -0
- package/src/player-signin/types.ts +103 -0
- package/src/shop/adapters/d1.sql +52 -0
- package/src/shop/adapters/d1.ts +245 -0
- package/src/shop/adapters/firestore.ts +281 -0
- package/src/shop/address.ts +102 -0
- package/src/shop/amount.ts +66 -0
- package/src/shop/conformance.ts +232 -0
- package/src/shop/handler.ts +202 -0
- package/src/shop/index.ts +30 -0
- package/src/shop/match.ts +63 -0
- package/src/shop/memory.ts +102 -0
- package/src/shop/nodes.ts +115 -0
- package/src/shop/orders.ts +93 -0
- package/src/shop/panel/index.ts +19 -0
- package/src/shop/panel/looks.ts +106 -0
- package/src/shop/panel/mount.ts +280 -0
- package/src/shop/panel/pay.ts +192 -0
- package/src/shop/panel/qr.ts +256 -0
- package/src/shop/panel/style.css +538 -0
- package/src/shop/panel/words.ts +172 -0
- package/src/shop/price.ts +52 -0
- package/src/shop/scan.ts +90 -0
- package/src/shop/security.ts +50 -0
- package/src/shop/store.ts +99 -0
- package/src/shop/worker.ts +107 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// The shop store for a game on Firestore (the Admin SDK). The package has no Firebase dependency: the adapter uses the small interface below, which the
|
|
2
|
+
// Admin SDK's `Firestore` fits. It reads and writes ONLY its five collections.
|
|
3
|
+
//
|
|
4
|
+
// import { createFirestoreShop } from "@nano133/nanoterra/shop/firestore";
|
|
5
|
+
// const store = createFirestoreShop(getFirestore());
|
|
6
|
+
//
|
|
7
|
+
// The data model (the five collection names can be changed; the first three are the ones the admin's Firestore store reads):
|
|
8
|
+
// orders/{id} { player, lookId, usd, rate, amount, amountLock, status, createdAt, expiresAt, holdUntil, hash, payer, paidAt, visitor }
|
|
9
|
+
// owned/{player__lookId} { player, lookId, orderId, grantedAt } (the player's id with encodeURIComponent: a Nano address stays as it is)
|
|
10
|
+
// meta/rate { value: JSON { usd, sources }, at } meta/scan { value: "", at }
|
|
11
|
+
// shop_amounts/{amount} { orderId, holdUntil } the reservation: a document for each held amount, so two orders cannot hold one (a transaction makes it)
|
|
12
|
+
// shop_hashes/{hash} { orderId } one payment pays one order: a document for each recorded payment
|
|
13
|
+
// Every write that a rule depends on is a transaction that reads what it checks. Indexes: the single-field indexes Firestore makes by itself are enough
|
|
14
|
+
// (the queries are equalities, and one `<` on shop_amounts.holdUntil).
|
|
15
|
+
|
|
16
|
+
import { paidStatus } from "../orders.js";
|
|
17
|
+
import { FORGOTTEN, type ForgetResult, type OrderStatus, type Settled, type ShopOrder, type ShopStore } from "../store.js";
|
|
18
|
+
|
|
19
|
+
export type ShopDocSnap = { exists: boolean; data(): Record<string, unknown> | undefined };
|
|
20
|
+
export interface ShopDocRef {
|
|
21
|
+
get(): Promise<ShopDocSnap>;
|
|
22
|
+
}
|
|
23
|
+
export type ShopQuerySnap = { docs: { id: string; ref: ShopDocRef; data(): Record<string, unknown> }[] };
|
|
24
|
+
export interface ShopQuery {
|
|
25
|
+
where(field: string, op: "==" | "<", value: unknown): ShopQuery;
|
|
26
|
+
limit(n: number): ShopQuery;
|
|
27
|
+
get(): Promise<ShopQuerySnap>;
|
|
28
|
+
}
|
|
29
|
+
export interface ShopCollection extends ShopQuery {
|
|
30
|
+
doc(id: string): ShopDocRef;
|
|
31
|
+
}
|
|
32
|
+
/** A transaction: every read before the first write, as Firestore asks. */
|
|
33
|
+
export interface ShopTransaction {
|
|
34
|
+
get(ref: ShopDocRef): Promise<ShopDocSnap>;
|
|
35
|
+
set(ref: ShopDocRef, data: Record<string, unknown>, options?: { merge?: boolean }): unknown;
|
|
36
|
+
delete(ref: ShopDocRef): unknown;
|
|
37
|
+
}
|
|
38
|
+
export interface ShopBatch {
|
|
39
|
+
set(ref: ShopDocRef, data: Record<string, unknown>, options?: { merge?: boolean }): unknown;
|
|
40
|
+
delete(ref: ShopDocRef): unknown;
|
|
41
|
+
commit(): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
export interface FirestoreShopLike {
|
|
44
|
+
collection(name: string): ShopCollection;
|
|
45
|
+
runTransaction<T>(fn: (tx: ShopTransaction) => Promise<T>): Promise<T>;
|
|
46
|
+
batch(): ShopBatch;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type ShopCollections = { orders?: string; owned?: string; meta?: string; amounts?: string; hashes?: string };
|
|
50
|
+
|
|
51
|
+
/** The most documents one query reads: a small game's orders of one player, or its held amounts. */
|
|
52
|
+
export const FIRESTORE_SHOP_SCAN = 2000;
|
|
53
|
+
|
|
54
|
+
const text = (v: unknown, fallback = ""): string => (typeof v === "string" ? v : fallback);
|
|
55
|
+
const num = (v: unknown, fallback = 0): number => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
|
|
56
|
+
const orNull = (v: unknown): string | null => (typeof v === "string" ? v : null);
|
|
57
|
+
const STATUSES: readonly OrderStatus[] = ["open", "paid", "expired", "paid_late"];
|
|
58
|
+
|
|
59
|
+
function orderOf(id: string, d: Record<string, unknown>): ShopOrder {
|
|
60
|
+
return {
|
|
61
|
+
id,
|
|
62
|
+
player: text(d.player),
|
|
63
|
+
lookId: text(d.lookId),
|
|
64
|
+
usd: text(d.usd, "0"),
|
|
65
|
+
rate: num(d.rate),
|
|
66
|
+
amount: text(d.amount, "0"),
|
|
67
|
+
amountLock: orNull(d.amountLock),
|
|
68
|
+
status: (STATUSES as readonly unknown[]).includes(d.status) ? (d.status as OrderStatus) : "expired",
|
|
69
|
+
createdAt: num(d.createdAt),
|
|
70
|
+
expiresAt: num(d.expiresAt),
|
|
71
|
+
holdUntil: num(d.holdUntil),
|
|
72
|
+
hash: orNull(d.hash),
|
|
73
|
+
payer: orNull(d.payer),
|
|
74
|
+
paidAt: typeof d.paidAt === "number" ? d.paidAt : null,
|
|
75
|
+
visitor: orNull(d.visitor),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const dataOf = (o: ShopOrder): Record<string, unknown> => ({
|
|
80
|
+
player: o.player,
|
|
81
|
+
lookId: o.lookId,
|
|
82
|
+
usd: o.usd,
|
|
83
|
+
rate: o.rate,
|
|
84
|
+
amount: o.amount,
|
|
85
|
+
amountLock: o.amountLock,
|
|
86
|
+
status: o.status,
|
|
87
|
+
createdAt: o.createdAt,
|
|
88
|
+
expiresAt: o.expiresAt,
|
|
89
|
+
holdUntil: o.holdUntil,
|
|
90
|
+
hash: o.hash,
|
|
91
|
+
payer: o.payer,
|
|
92
|
+
paidAt: o.paidAt,
|
|
93
|
+
visitor: o.visitor,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
export function createFirestoreShop(db: FirestoreShopLike, collections: ShopCollections = {}): ShopStore {
|
|
97
|
+
const C = {
|
|
98
|
+
orders: collections.orders ?? "orders",
|
|
99
|
+
owned: collections.owned ?? "owned",
|
|
100
|
+
meta: collections.meta ?? "meta",
|
|
101
|
+
amounts: collections.amounts ?? "shop_amounts",
|
|
102
|
+
hashes: collections.hashes ?? "shop_hashes",
|
|
103
|
+
};
|
|
104
|
+
const col = (name: keyof typeof C) => db.collection(C[name]);
|
|
105
|
+
const ownedId = (player: string, lookId: string) => `${encodeURIComponent(player)}__${lookId}`;
|
|
106
|
+
const ordersOf = (player: string) => col("orders").where("player", "==", player).limit(FIRESTORE_SHOP_SCAN);
|
|
107
|
+
|
|
108
|
+
async function commitAll(writes: ((b: ShopBatch) => void)[]) {
|
|
109
|
+
// A batch holds at most 500 writes.
|
|
110
|
+
for (let i = 0; i < writes.length; i += 400) {
|
|
111
|
+
const batch = db.batch();
|
|
112
|
+
for (const w of writes.slice(i, i + 400)) w(batch);
|
|
113
|
+
await batch.commit();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const tidy = async (now: number) => {
|
|
118
|
+
// Each change reads the document again in a transaction: a blind write could undo a payment that was recorded meanwhile.
|
|
119
|
+
const open = (await col("orders").where("status", "==", "open").limit(FIRESTORE_SHOP_SCAN).get()).docs.filter((d) => num(d.data().expiresAt) < now);
|
|
120
|
+
for (const d of open) {
|
|
121
|
+
await db.runTransaction(async (tx) => {
|
|
122
|
+
const snap = await tx.get(d.ref);
|
|
123
|
+
const o = snap.exists ? snap.data() : undefined;
|
|
124
|
+
if (o && o.status === "open" && num(o.expiresAt) < now) tx.set(d.ref, { status: "expired" }, { merge: true });
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const stale = (await col("amounts").where("holdUntil", "<", now).limit(FIRESTORE_SHOP_SCAN).get()).docs;
|
|
128
|
+
for (const d of stale) {
|
|
129
|
+
await db.runTransaction(async (tx) => {
|
|
130
|
+
const snap = await tx.get(d.ref);
|
|
131
|
+
const lock = snap.exists ? snap.data() : undefined;
|
|
132
|
+
if (!lock || num(lock.holdUntil) >= now) return;
|
|
133
|
+
const orderRef = col("orders").doc(text(lock.orderId));
|
|
134
|
+
const order = await tx.get(orderRef);
|
|
135
|
+
tx.delete(d.ref);
|
|
136
|
+
if (order.exists && order.data()?.amountLock === d.id) tx.set(orderRef, { amountLock: null }, { merge: true });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
tidy,
|
|
143
|
+
|
|
144
|
+
async heldAmounts(amounts) {
|
|
145
|
+
const want = new Set(amounts);
|
|
146
|
+
return new Set((await col("amounts").limit(FIRESTORE_SHOP_SCAN).get()).docs.map((d) => d.id).filter((id) => want.has(id)));
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
async insert(o) {
|
|
150
|
+
const lockRef = col("amounts").doc(o.amount);
|
|
151
|
+
const orderRef = col("orders").doc(o.id);
|
|
152
|
+
return db.runTransaction(async (tx) => {
|
|
153
|
+
const [lock, order] = [await tx.get(lockRef), await tx.get(orderRef)];
|
|
154
|
+
if (lock.exists || order.exists) return false;
|
|
155
|
+
tx.set(lockRef, { orderId: o.id, holdUntil: o.holdUntil });
|
|
156
|
+
tx.set(orderRef, dataOf({ ...o, amountLock: o.amount, status: "open", hash: null, payer: null, paidAt: null }));
|
|
157
|
+
return true;
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
async order(id) {
|
|
162
|
+
const snap = await col("orders").doc(id).get();
|
|
163
|
+
const d = snap.exists ? snap.data() : undefined;
|
|
164
|
+
return d ? orderOf(id, d) : null;
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
async openOrder(player, lookId, until) {
|
|
168
|
+
const docs = (await ordersOf(player).where("lookId", "==", lookId).where("status", "==", "open").get()).docs;
|
|
169
|
+
const list = docs.map((d) => orderOf(d.id, d.data())).filter((o) => o.player === player && o.expiresAt > until).sort((a, b) => b.createdAt - a.createdAt);
|
|
170
|
+
return list[0] ?? null;
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
async countOpen(player, now) {
|
|
174
|
+
return (await ordersOf(player).where("status", "==", "open").get()).docs.map((d) => orderOf(d.id, d.data())).filter((o) => o.player === player && o.expiresAt > now).length;
|
|
175
|
+
},
|
|
176
|
+
|
|
177
|
+
async owns(player, lookId) {
|
|
178
|
+
const snap = await col("owned").doc(ownedId(player, lookId)).get();
|
|
179
|
+
return snap.exists && snap.data()?.player === player;
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
async owned(player) {
|
|
183
|
+
const rows = (await col("owned").where("player", "==", player).limit(FIRESTORE_SHOP_SCAN).get()).docs.map((d) => d.data());
|
|
184
|
+
return rows
|
|
185
|
+
.filter((r) => r.player === player)
|
|
186
|
+
.sort((a, b) => num(a.grantedAt) - num(b.grantedAt) || (text(a.lookId) < text(b.lookId) ? -1 : 1))
|
|
187
|
+
.map((r) => text(r.lookId));
|
|
188
|
+
},
|
|
189
|
+
|
|
190
|
+
async held() {
|
|
191
|
+
const locks = (await col("amounts").limit(FIRESTORE_SHOP_SCAN).get()).docs;
|
|
192
|
+
const out: ShopOrder[] = [];
|
|
193
|
+
for (const l of locks) {
|
|
194
|
+
const id = text(l.data().orderId);
|
|
195
|
+
const snap = await col("orders").doc(id).get();
|
|
196
|
+
const d = snap.exists ? snap.data() : undefined;
|
|
197
|
+
if (d && d.amountLock === l.id) out.push(orderOf(id, d));
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
async usedHashes(hashes) {
|
|
203
|
+
const snaps = await Promise.all(hashes.map(async (h) => [h, await col("hashes").doc(h).get()] as const));
|
|
204
|
+
return new Set(snaps.filter(([, s]) => s.exists).map(([h]) => h));
|
|
205
|
+
},
|
|
206
|
+
|
|
207
|
+
async settle(order, pay, now): Promise<Settled> {
|
|
208
|
+
const orderRef = col("orders").doc(order.id);
|
|
209
|
+
const hashRef = col("hashes").doc(pay.hash);
|
|
210
|
+
return db.runTransaction(async (tx) => {
|
|
211
|
+
const hash = await tx.get(hashRef);
|
|
212
|
+
const snap = await tx.get(orderRef);
|
|
213
|
+
const d = snap.exists ? snap.data() : undefined;
|
|
214
|
+
const lockRef = col("amounts").doc(text(d?.amountLock, order.amount));
|
|
215
|
+
const lock = await tx.get(lockRef);
|
|
216
|
+
const o = d ? orderOf(order.id, d) : null;
|
|
217
|
+
const ownedRef = col("owned").doc(ownedId(o?.player ?? order.player, o?.lookId ?? order.lookId));
|
|
218
|
+
const owned = await tx.get(ownedRef);
|
|
219
|
+
if (!o || (o.status !== "open" && o.status !== "expired") || o.amountLock === null) return "taken";
|
|
220
|
+
if (hash.exists) return "used";
|
|
221
|
+
const status = paidStatus(o, pay.seenMs);
|
|
222
|
+
tx.set(orderRef, dataOf({ ...o, status, hash: pay.hash, payer: pay.payer, paidAt: pay.seenMs, amountLock: null }));
|
|
223
|
+
if (lock.exists && lock.data()?.orderId === order.id) tx.delete(lockRef);
|
|
224
|
+
tx.set(hashRef, { orderId: order.id });
|
|
225
|
+
if (status === "paid" && !owned.exists) tx.set(ownedRef, { player: o.player, lookId: o.lookId, orderId: o.id, grantedAt: now });
|
|
226
|
+
return status;
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
async claimScan(now, gapMs) {
|
|
231
|
+
const ref = col("meta").doc("scan");
|
|
232
|
+
return db.runTransaction(async (tx) => {
|
|
233
|
+
const snap = await tx.get(ref);
|
|
234
|
+
const at = snap.exists ? num(snap.data()?.at, -Infinity) : -Infinity;
|
|
235
|
+
if (at > now - gapMs) return false;
|
|
236
|
+
tx.set(ref, { value: "", at: now });
|
|
237
|
+
return true;
|
|
238
|
+
});
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
async readRate() {
|
|
242
|
+
const snap = await col("meta").doc("rate").get();
|
|
243
|
+
const d = snap.exists ? snap.data() : undefined;
|
|
244
|
+
if (!d || typeof d.value !== "string" || typeof d.at !== "number") return null;
|
|
245
|
+
try {
|
|
246
|
+
const v = JSON.parse(d.value) as { usd?: unknown; sources?: unknown };
|
|
247
|
+
if (typeof v.usd !== "number" || !Number.isFinite(v.usd) || !Array.isArray(v.sources) || !v.sources.every((s) => typeof s === "string")) return null;
|
|
248
|
+
return { usd: v.usd, sources: v.sources as string[], at: d.at };
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
|
|
254
|
+
async saveRate(rate) {
|
|
255
|
+
const batch = db.batch();
|
|
256
|
+
batch.set(col("meta").doc("rate"), { value: JSON.stringify({ usd: rate.usd, sources: rate.sources }), at: rate.at });
|
|
257
|
+
await batch.commit();
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
async forget(player, now): Promise<ForgetResult> {
|
|
261
|
+
await tidy(now);
|
|
262
|
+
const mine = (await ordersOf(player).get()).docs.map((d) => ({ ref: d.ref, o: orderOf(d.id, d.data()) })).filter((x) => x.o.player === player);
|
|
263
|
+
const waiting = mine.filter((x) => x.o.amountLock !== null);
|
|
264
|
+
if (waiting.length) return { deleted: 0, kept: 0, waitUntil: Math.max(...waiting.map((x) => x.o.holdUntil)) };
|
|
265
|
+
const owned = (await col("owned").where("player", "==", player).limit(FIRESTORE_SHOP_SCAN).get()).docs.filter((d) => d.data().player === player);
|
|
266
|
+
const paidBy = (await col("orders").where("payer", "==", player).limit(FIRESTORE_SHOP_SCAN).get()).docs.filter((d) => d.data().status === "paid");
|
|
267
|
+
const writes: ((b: ShopBatch) => void)[] = [];
|
|
268
|
+
let deleted = 0;
|
|
269
|
+
let kept = 0;
|
|
270
|
+
for (const d of owned) (writes.push((b) => b.delete(d.ref)), deleted++);
|
|
271
|
+
for (const { ref, o } of mine) {
|
|
272
|
+
if (o.hash === null) (writes.push((b) => b.delete(ref)), deleted++);
|
|
273
|
+
else (writes.push((b) => b.set(ref, { player: FORGOTTEN, visitor: null }, { merge: true })), kept++);
|
|
274
|
+
}
|
|
275
|
+
// A paid order keeps no payer; a paid-late one keeps it: the creator sends that payment back by hand.
|
|
276
|
+
for (const d of paidBy) writes.push((b) => b.set(d.ref, { payer: FORGOTTEN }, { merge: true }));
|
|
277
|
+
await commitAll(writes);
|
|
278
|
+
return { deleted, kept, waitUntil: null };
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// The creator's address (the payee): a whole Nano address, its shape AND its checksum. A typo in a receive address would send every payment to an
|
|
2
|
+
// account nobody holds the key for, so the shop sells only to an address whose checksum is right (the game starter checks it with @nano133/signin's
|
|
3
|
+
// `validAddress`; this package has no dependency, so it carries the 5-byte BLAKE2b that the checksum needs, and nothing else of it).
|
|
4
|
+
|
|
5
|
+
/** The address that belongs to nobody (its key is all zeros): the example in the game starter's wrangler.jsonc. A shop with it is in test mode. */
|
|
6
|
+
export const EXAMPLE_ADDRESS = "nano_1111111111111111111111111111111111111111111111111111hifc8npp";
|
|
7
|
+
|
|
8
|
+
const ALPHABET = "13456789abcdefghijkmnopqrstuwxyz";
|
|
9
|
+
const SHAPE = /^nano_[13][13456789abcdefghijkmnopqrstuwxyz]{59}$/;
|
|
10
|
+
|
|
11
|
+
const MASK = (1n << 64n) - 1n;
|
|
12
|
+
const IV = [
|
|
13
|
+
0x6a09e667f3bcc908n, 0xbb67ae8584caa73bn, 0x3c6ef372fe94f82bn, 0xa54ff53a5f1d36f1n, 0x510e527fade682d1n, 0x9b05688c2b3e6c1fn, 0x1f83d9abfb41bd6bn, 0x5be0cd19137e2179n,
|
|
14
|
+
];
|
|
15
|
+
const SIGMA = [
|
|
16
|
+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
|
|
17
|
+
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
|
|
18
|
+
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
|
|
19
|
+
[7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
|
|
20
|
+
[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
|
|
21
|
+
[2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
|
|
22
|
+
[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
|
|
23
|
+
[13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
|
|
24
|
+
[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
|
|
25
|
+
[10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
|
|
26
|
+
];
|
|
27
|
+
const rotr = (x: bigint, n: bigint) => ((x >> n) | (x << (64n - n))) & MASK;
|
|
28
|
+
|
|
29
|
+
/** BLAKE2b of at most 128 bytes (one block), `outLen` bytes, no key (RFC 7693). Enough for a checksum of a 32-byte key. */
|
|
30
|
+
export function blake2bShort(input: Uint8Array, outLen: number): Uint8Array {
|
|
31
|
+
if (input.length > 128 || outLen < 1 || outLen > 64) throw new Error("blake2bShort: one block of at most 128 bytes, 1 to 64 bytes out");
|
|
32
|
+
const h = IV.slice();
|
|
33
|
+
h[0] ^= 0x01010000n ^ BigInt(outLen);
|
|
34
|
+
const block = new Uint8Array(128);
|
|
35
|
+
block.set(input);
|
|
36
|
+
const m: bigint[] = [];
|
|
37
|
+
for (let i = 0; i < 16; i++) {
|
|
38
|
+
let w = 0n;
|
|
39
|
+
for (let b = 7; b >= 0; b--) w = (w << 8n) | BigInt(block[i * 8 + b]);
|
|
40
|
+
m.push(w);
|
|
41
|
+
}
|
|
42
|
+
const v = [...h, ...IV];
|
|
43
|
+
v[12] ^= BigInt(input.length);
|
|
44
|
+
v[14] ^= MASK;
|
|
45
|
+
const g = (a: number, b: number, c: number, d: number, x: bigint, y: bigint) => {
|
|
46
|
+
v[a] = (v[a] + v[b] + x) & MASK;
|
|
47
|
+
v[d] = rotr(v[d] ^ v[a], 32n);
|
|
48
|
+
v[c] = (v[c] + v[d]) & MASK;
|
|
49
|
+
v[b] = rotr(v[b] ^ v[c], 24n);
|
|
50
|
+
v[a] = (v[a] + v[b] + y) & MASK;
|
|
51
|
+
v[d] = rotr(v[d] ^ v[a], 16n);
|
|
52
|
+
v[c] = (v[c] + v[d]) & MASK;
|
|
53
|
+
v[b] = rotr(v[b] ^ v[c], 63n);
|
|
54
|
+
};
|
|
55
|
+
for (let r = 0; r < 12; r++) {
|
|
56
|
+
const s = SIGMA[r % 10];
|
|
57
|
+
g(0, 4, 8, 12, m[s[0]], m[s[1]]);
|
|
58
|
+
g(1, 5, 9, 13, m[s[2]], m[s[3]]);
|
|
59
|
+
g(2, 6, 10, 14, m[s[4]], m[s[5]]);
|
|
60
|
+
g(3, 7, 11, 15, m[s[6]], m[s[7]]);
|
|
61
|
+
g(0, 5, 10, 15, m[s[8]], m[s[9]]);
|
|
62
|
+
g(1, 6, 11, 12, m[s[10]], m[s[11]]);
|
|
63
|
+
g(2, 7, 8, 13, m[s[12]], m[s[13]]);
|
|
64
|
+
g(3, 4, 9, 14, m[s[14]], m[s[15]]);
|
|
65
|
+
}
|
|
66
|
+
const out = new Uint8Array(outLen);
|
|
67
|
+
for (let i = 0; i < outLen; i++) out[i] = Number(((h[i >> 3] ^ v[i >> 3] ^ v[(i >> 3) + 8]) >> BigInt(8 * (i & 7))) & 0xffn);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Base-32 text (Nano's alphabet) as a big number. */
|
|
72
|
+
const bitsOf = (text: string): bigint => [...text].reduce((n, c) => (n << 5n) | BigInt(ALPHABET.indexOf(c)), 0n);
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* True for a whole Nano address: "nano_" (or "xrb_"), its shape, and its checksum (the last 8 characters: the BLAKE2b-40 of the key, bytes reversed).
|
|
76
|
+
* One wrong character fails it.
|
|
77
|
+
*/
|
|
78
|
+
export function validAddress(address: unknown): address is string {
|
|
79
|
+
if (typeof address !== "string") return false;
|
|
80
|
+
const a = address.replace(/^xrb_/, "nano_");
|
|
81
|
+
if (!SHAPE.test(a)) return false;
|
|
82
|
+
const body = a.slice(5);
|
|
83
|
+
// 52 characters are 260 bits: 4 bits that must be zero, then the 32-byte key.
|
|
84
|
+
const key = bitsOf(body.slice(0, 52));
|
|
85
|
+
if (key >> 256n !== 0n) return false;
|
|
86
|
+
const bytes = new Uint8Array(32);
|
|
87
|
+
for (let i = 0; i < 32; i++) bytes[i] = Number((key >> BigInt(8 * (31 - i))) & 0xffn);
|
|
88
|
+
const check = blake2bShort(bytes, 5).reverse();
|
|
89
|
+
const want = check.reduce((n, b) => (n << 8n) | BigInt(b), 0n);
|
|
90
|
+
return bitsOf(body.slice(52)) === want;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The payee as the shop uses it: a whole address in lower case with the "nano_" prefix, or null (no address, the example, or a wrong checksum). With
|
|
95
|
+
* null the shop is in test mode: no pay screen shows an address, a QR code or a wallet link.
|
|
96
|
+
*/
|
|
97
|
+
export function payeeOf(address: unknown): string | null {
|
|
98
|
+
if (typeof address !== "string") return null;
|
|
99
|
+
const a = address.trim().toLowerCase().replace(/^xrb_/, "nano_");
|
|
100
|
+
if (!a || a === EXAMPLE_ADDRESS) return null;
|
|
101
|
+
return validAddress(a) ? a : null;
|
|
102
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Nano amounts for the shop, in raw. 1 XNO is 10^30 raw, more than a JavaScript number holds exactly, so amounts are decimal strings and the math is
|
|
2
|
+
// BigInt. Never use a float for an amount that is paid or compared. (The game starter's src/shared/amount.ts, moved here unchanged.)
|
|
3
|
+
//
|
|
4
|
+
// Every order asks for a CLEAN amount: the price, rounded up to a step of 0.0001 XNO. While another held order has that exact amount, the next order
|
|
5
|
+
// asks for one step more (./orders.ts). So an amount has at most four decimals. Wallets that shorten an amount (Cake Wallet cuts a link's amount to
|
|
6
|
+
// 6 decimals; Natrium and Nautilus send 6 decimals when the payer touches the amount field) still send it exactly, and the payment matches its order.
|
|
7
|
+
|
|
8
|
+
export { RAW_PER_XNO, xnoText } from "../admin/amount.js";
|
|
9
|
+
|
|
10
|
+
/** One step: 0.0001 XNO. */
|
|
11
|
+
export const STEP_RAW = 10n ** 26n;
|
|
12
|
+
/** Sane bounds for dollars per XNO: outside them a price feed is wrong, not the market. */
|
|
13
|
+
export const MIN_RATE = 0.05;
|
|
14
|
+
export const MAX_RATE = 100;
|
|
15
|
+
/** The highest price a look can have, in US dollars (the looks file allows up to PRICE_MAX_USD, $1000). */
|
|
16
|
+
export const MAX_USD = 10_000;
|
|
17
|
+
|
|
18
|
+
/** A raw amount: digits only, no leading zero, not zero, at most 39 digits. */
|
|
19
|
+
export function isRaw(s: unknown): s is string {
|
|
20
|
+
return typeof s === "string" && /^[1-9][0-9]{0,38}$/.test(s);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Whole steps of 0.0001 XNO, so at most four decimals. */
|
|
24
|
+
export function isClean(raw: unknown): raw is string {
|
|
25
|
+
return isRaw(raw) && BigInt(raw) % STEP_RAW === 0n;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The number of 0.0001 XNO steps for `usd` dollars at `rate` dollars per XNO, rounded UP (the creator never gets less than the price), or null when
|
|
30
|
+
* the price or the rate can't be used.
|
|
31
|
+
*/
|
|
32
|
+
export function stepsFromUsd(usd: number, rate: number): number | null {
|
|
33
|
+
if (!Number.isFinite(usd) || !Number.isFinite(rate) || usd <= 0 || usd > MAX_USD || rate < MIN_RATE || rate > MAX_RATE) return null;
|
|
34
|
+
// A tiny allowance, so float noise (0.01 / 0.5 * 10000 = 200.00000000000003) doesn't add a whole step.
|
|
35
|
+
return Math.max(1, Math.ceil((usd / rate) * 10_000 - 1e-6));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function rawFromSteps(steps: number | bigint): string {
|
|
39
|
+
const n = BigInt(steps);
|
|
40
|
+
if (n <= 0n) throw new Error("an amount must be above zero");
|
|
41
|
+
return (n * STEP_RAW).toString();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The clean price in raw, or null. */
|
|
45
|
+
export function priceRaw(usd: number, rate: number): string | null {
|
|
46
|
+
const steps = stepsFromUsd(usd, rate);
|
|
47
|
+
return steps === null ? null : rawFromSteps(steps);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A clean amount plus `more` steps. */
|
|
51
|
+
export function plusSteps(raw: string, more: number): string {
|
|
52
|
+
if (!isClean(raw)) throw new Error("not a clean amount");
|
|
53
|
+
return (BigInt(raw) + BigInt(more) * STEP_RAW).toString();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** -1, 0 or 1. */
|
|
57
|
+
export function compareRaw(a: string, b: string): number {
|
|
58
|
+
const x = BigInt(a);
|
|
59
|
+
const y = BigInt(b);
|
|
60
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The standard payment link: the amount in raw, every digit (docs.nano.org, URI and QR code standards). */
|
|
64
|
+
export function nanoUri(address: string, raw: string): string {
|
|
65
|
+
return `nano:${address}?amount=${raw}`;
|
|
66
|
+
}
|