@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.
Files changed (122) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +390 -6
  3. package/ai/SPEC.md +71 -3
  4. package/dist/admin/panel/mount.d.ts +3 -0
  5. package/dist/admin/panel/mount.js +4 -2
  6. package/dist/player-signin/adapters/d1.d.ts +10 -0
  7. package/dist/player-signin/adapters/d1.js +108 -0
  8. package/dist/player-signin/adapters/firestore.d.ts +45 -0
  9. package/dist/player-signin/adapters/firestore.js +168 -0
  10. package/dist/player-signin/conformance.d.ts +11 -0
  11. package/dist/player-signin/conformance.js +160 -0
  12. package/dist/player-signin/handler.d.ts +64 -0
  13. package/dist/player-signin/handler.js +364 -0
  14. package/dist/player-signin/host.d.ts +4 -0
  15. package/dist/player-signin/host.js +10 -0
  16. package/dist/player-signin/index.d.ts +9 -0
  17. package/dist/player-signin/index.js +15 -0
  18. package/dist/player-signin/memory.d.ts +15 -0
  19. package/dist/player-signin/memory.js +101 -0
  20. package/dist/player-signin/panel/index.d.ts +9 -0
  21. package/dist/player-signin/panel/index.js +8 -0
  22. package/dist/player-signin/panel/memo.d.ts +12 -0
  23. package/dist/player-signin/panel/memo.js +41 -0
  24. package/dist/player-signin/panel/mount.d.ts +21 -0
  25. package/dist/player-signin/panel/mount.js +107 -0
  26. package/dist/player-signin/panel/view.d.ts +48 -0
  27. package/dist/player-signin/panel/view.js +363 -0
  28. package/dist/player-signin/panel/words.d.ts +103 -0
  29. package/dist/player-signin/panel/words.js +111 -0
  30. package/dist/player-signin/scheme-check.d.ts +3 -0
  31. package/dist/player-signin/scheme-check.js +14 -0
  32. package/dist/player-signin/scheme.d.ts +13 -0
  33. package/dist/player-signin/scheme.js +28 -0
  34. package/dist/player-signin/types.d.ts +116 -0
  35. package/dist/player-signin/types.js +33 -0
  36. package/dist/shop/adapters/d1.d.ts +25 -0
  37. package/dist/shop/adapters/d1.js +200 -0
  38. package/dist/shop/adapters/firestore.d.ts +53 -0
  39. package/dist/shop/adapters/firestore.js +245 -0
  40. package/dist/shop/address.d.ts +14 -0
  41. package/dist/shop/address.js +104 -0
  42. package/dist/shop/amount.d.ts +26 -0
  43. package/dist/shop/amount.js +59 -0
  44. package/dist/shop/conformance.d.ts +13 -0
  45. package/dist/shop/conformance.js +203 -0
  46. package/dist/shop/handler.d.ts +76 -0
  47. package/dist/shop/handler.js +156 -0
  48. package/dist/shop/index.d.ts +19 -0
  49. package/dist/shop/index.js +21 -0
  50. package/dist/shop/match.d.ts +23 -0
  51. package/dist/shop/match.js +58 -0
  52. package/dist/shop/memory.d.ts +13 -0
  53. package/dist/shop/memory.js +106 -0
  54. package/dist/shop/nodes.d.ts +47 -0
  55. package/dist/shop/nodes.js +106 -0
  56. package/dist/shop/orders.d.ts +47 -0
  57. package/dist/shop/orders.js +82 -0
  58. package/dist/shop/panel/index.d.ts +9 -0
  59. package/dist/shop/panel/index.js +14 -0
  60. package/dist/shop/panel/looks.d.ts +33 -0
  61. package/dist/shop/panel/looks.js +61 -0
  62. package/dist/shop/panel/mount.d.ts +68 -0
  63. package/dist/shop/panel/mount.js +221 -0
  64. package/dist/shop/panel/pay.d.ts +27 -0
  65. package/dist/shop/panel/pay.js +128 -0
  66. package/dist/shop/panel/qr.d.ts +9 -0
  67. package/dist/shop/panel/qr.js +281 -0
  68. package/dist/shop/panel/words.d.ts +89 -0
  69. package/dist/shop/panel/words.js +79 -0
  70. package/dist/shop/price.d.ts +23 -0
  71. package/dist/shop/price.js +43 -0
  72. package/dist/shop/scan.d.ts +24 -0
  73. package/dist/shop/scan.js +80 -0
  74. package/dist/shop/security.d.ts +10 -0
  75. package/dist/shop/security.js +56 -0
  76. package/dist/shop/store.d.ts +101 -0
  77. package/dist/shop/store.js +4 -0
  78. package/dist/shop/worker.d.ts +43 -0
  79. package/dist/shop/worker.js +76 -0
  80. package/package.json +21 -6
  81. package/src/admin/panel/mount.ts +7 -2
  82. package/src/player-signin/adapters/d1.sql +45 -0
  83. package/src/player-signin/adapters/d1.ts +120 -0
  84. package/src/player-signin/adapters/firestore.ts +194 -0
  85. package/src/player-signin/conformance.ts +184 -0
  86. package/src/player-signin/handler.ts +404 -0
  87. package/src/player-signin/host.ts +12 -0
  88. package/src/player-signin/index.ts +20 -0
  89. package/src/player-signin/memory.ts +94 -0
  90. package/src/player-signin/panel/index.ts +13 -0
  91. package/src/player-signin/panel/memo.ts +49 -0
  92. package/src/player-signin/panel/mount.ts +129 -0
  93. package/src/player-signin/panel/style.css +478 -0
  94. package/src/player-signin/panel/view.ts +433 -0
  95. package/src/player-signin/panel/words.ts +210 -0
  96. package/src/player-signin/scheme-check.ts +14 -0
  97. package/src/player-signin/scheme.ts +32 -0
  98. package/src/player-signin/types.ts +103 -0
  99. package/src/shop/adapters/d1.sql +52 -0
  100. package/src/shop/adapters/d1.ts +245 -0
  101. package/src/shop/adapters/firestore.ts +281 -0
  102. package/src/shop/address.ts +102 -0
  103. package/src/shop/amount.ts +66 -0
  104. package/src/shop/conformance.ts +232 -0
  105. package/src/shop/handler.ts +202 -0
  106. package/src/shop/index.ts +30 -0
  107. package/src/shop/match.ts +63 -0
  108. package/src/shop/memory.ts +102 -0
  109. package/src/shop/nodes.ts +115 -0
  110. package/src/shop/orders.ts +93 -0
  111. package/src/shop/panel/index.ts +19 -0
  112. package/src/shop/panel/looks.ts +106 -0
  113. package/src/shop/panel/mount.ts +280 -0
  114. package/src/shop/panel/pay.ts +192 -0
  115. package/src/shop/panel/qr.ts +256 -0
  116. package/src/shop/panel/style.css +538 -0
  117. package/src/shop/panel/words.ts +172 -0
  118. package/src/shop/price.ts +52 -0
  119. package/src/shop/scan.ts +90 -0
  120. package/src/shop/security.ts +50 -0
  121. package/src/shop/store.ts +99 -0
  122. package/src/shop/worker.ts +107 -0
@@ -0,0 +1,89 @@
1
+ import type { Hat } from "../../looks/look.js";
2
+ export type ShopWords = {
3
+ /** The sheet's title, the Looks key's word and the sheet's name for a screen reader. The option `title` wins over it. */
4
+ title: string;
5
+ /** The close key's name for a screen reader. */
6
+ close: string;
7
+ /** The tabs' name for a screen reader. */
8
+ kinds: string;
9
+ /** The outfits' tab. */
10
+ outfits: string;
11
+ /** The tab of a wear slot of the game's own ("shovel"). The option `slots` wins over it. */
12
+ slotTab: (slot: string) => string;
13
+ /** The plain choice of a wear slot ("No shovel"). The option `slots` wins over it. */
14
+ slotPlain: (slot: string) => string;
15
+ /** The line under an outfit: what it changes (its hat, or the colour only). */
16
+ outfitLine: (hat: Hat | null) => string;
17
+ /** The line under an item of a wear slot. */
18
+ itemLine: (slot: string) => string;
19
+ /** Added to the line of a free look, and the plain choice's line. */
20
+ free: string;
21
+ /** Added to the line of a look the player owns. */
22
+ yours: string;
23
+ wear: string;
24
+ wearing: string;
25
+ /** The Buy key, with the look's price ("$0.25"). */
26
+ buy: (price: string) => string;
27
+ /** Under the list. */
28
+ looksNote: string;
29
+ /** Under the list and at Buy, while nobody is signed in. */
30
+ signInFirst: string;
31
+ /** The title of Buy and of the pay sheet. */
32
+ buyTitle: (look: string) => string;
33
+ making: string;
34
+ /** An order that did not start, with no words from the server. */
35
+ orderFailed: string;
36
+ /** The words of a refusal: the server's own (`text`, in English) and its HTTP status (0: no answer). Default: the server's words. */
37
+ refusal: (text: string, status: number) => string;
38
+ /** The key back to the looks. */
39
+ back: string;
40
+ /** The key that signs in again after "Sign in first." (401). */
41
+ signIn: string;
42
+ /** The line under the title. */
43
+ lookLine: (look: string) => string;
44
+ /** The amount in XNO, large ("0.25 XNO"). */
45
+ amount: (xno: string) => string;
46
+ /** The amount in dollars, beside it ("= $0.25"). */
47
+ usd: (usd: string) => string;
48
+ /** Above the amount, live only: the player must send this exact amount. */
49
+ sendExactly: string;
50
+ /** Under the stamp in test mode: nothing can be paid here. */
51
+ testNote: string;
52
+ /** The wallet key in test mode, off, with its reason. */
53
+ walletOff: string;
54
+ /** The wallet key (live). */
55
+ wallet: string;
56
+ /** The QR code's name for a screen reader. */
57
+ qrLabel: (xno: string) => string;
58
+ /** The fold with the amount and the address to type by hand. */
59
+ byHand: string;
60
+ amountLabel: string;
61
+ /** The address's label in the fold. */
62
+ toLabel: string;
63
+ /** In the fold: another amount does not match the order. */
64
+ byHandNote: string;
65
+ copy: string;
66
+ copied: string;
67
+ copyFailed: string;
68
+ /** The time left (live only): the order ends then. */
69
+ endsIn: (time: string) => string;
70
+ waiting: string;
71
+ noConnection: string;
72
+ stillWaiting: string;
73
+ checkAgain: string;
74
+ paid: string;
75
+ paidLine: (look: string) => string;
76
+ /** A payment after the order ended: it gives no look, and the creator sends it back. */
77
+ paidLate: string;
78
+ /** The order ended: a payment sent in time still counts. */
79
+ expired: string;
80
+ /** The price's sources ("CoinGecko", "Kraken", "KuCoin"). "Powered by CoinGecko" is added when CoinGecko is one and the words leave it out. */
81
+ prices: (sources: readonly string[]) => string;
82
+ };
83
+ /** CoinGecko's words: its API terms ask for them wherever its price shows. */
84
+ export declare const COINGECKO_CREDIT = "Powered by CoinGecko";
85
+ export declare const SHOP_WORDS: ShopWords;
86
+ /** The game's words over the defaults. A key the game leaves out, or gives as undefined, keeps its default. */
87
+ export declare function shopWords(over?: Partial<ShopWords>): ShopWords;
88
+ /** The price's line: the game's words, with "Powered by CoinGecko" added when CoinGecko is a source and the words leave it out. */
89
+ export declare function priceLine(words: ShopWords, sources: readonly string[]): string;
@@ -0,0 +1,79 @@
1
+ // Every word that the shop's sheets show: the looks sheet, Buy and the pay sheet. A game gives `words` to `mountShop` (or to `looksView` and `payPanel`)
2
+ // with the keys it wants to change, in its own words or language; the rest stay these. A text with a value in it is a function of that value.
3
+ //
4
+ // Two things a game cannot change, because a player's money depends on them: the stamp "TEST MODE: DO NOT PAY" (it is not a key), and the words
5
+ // "Powered by CoinGecko" while CoinGecko is one of the price feeds (CoinGecko's API terms ask for them: `priceLine` adds them when `prices` leaves
6
+ // them out).
7
+ //
8
+ // The defaults are short on purpose (Wes, 2026-11-01: fewer words): the pay sheet shows at most 30 words, and no sentence has more than 10.
9
+ const HATS = { cap: "with a cap", beanie: "with a beanie", crown: "with a crown", tophat: "with a top hat" };
10
+ const spaced = (slot) => slot.replace(/-/g, " ");
11
+ /** CoinGecko's words: its API terms ask for them wherever its price shows. */
12
+ export const COINGECKO_CREDIT = "Powered by CoinGecko";
13
+ export const SHOP_WORDS = {
14
+ title: "Looks",
15
+ close: "Close",
16
+ kinds: "Kinds of looks",
17
+ outfits: "Outfits",
18
+ slotTab: (slot) => spaced(slot.charAt(0).toUpperCase() + slot.slice(1)),
19
+ slotPlain: (slot) => `No ${spaced(slot)}`,
20
+ outfitLine: (hat) => (hat ? HATS[hat] : "colour only"),
21
+ itemLine: (slot) => spaced(slot),
22
+ free: "free",
23
+ yours: "yours",
24
+ wear: "Wear",
25
+ wearing: "Wearing",
26
+ buy: (price) => `Buy ${price}`,
27
+ looksNote: "Looks never change play. Pay in Nano, straight to the creator.",
28
+ signInFirst: "Sign in first to buy a look.",
29
+ buyTitle: (look) => `Buy ${look}`,
30
+ making: "Making your order…",
31
+ orderFailed: "The order did not start. Try again.",
32
+ refusal: (text) => text,
33
+ back: "Back",
34
+ signIn: "Sign in",
35
+ lookLine: () => "It never changes play.",
36
+ amount: (xno) => `${xno} XNO`,
37
+ usd: (usd) => `= ${usd}`,
38
+ sendExactly: "Send exactly",
39
+ testNote: "Nothing can be paid here.",
40
+ walletOff: "Wallet off: test mode",
41
+ wallet: "Open wallet",
42
+ qrLabel: (xno) => `QR code to pay ${xno} XNO`,
43
+ byHand: "Enter by hand",
44
+ amountLabel: "Amount",
45
+ toLabel: "To",
46
+ byHandNote: "Another amount does not match.",
47
+ copy: "Copy",
48
+ copied: "Copied",
49
+ copyFailed: "Copy failed",
50
+ endsIn: (time) => `Ends in ${time}.`,
51
+ waiting: "Waiting for payment…",
52
+ noConnection: "No connection. Trying again…",
53
+ stillWaiting: "Still waiting. Already paid? Press Check again.",
54
+ checkAgain: "Check again",
55
+ paid: "Paid. Thank you!",
56
+ paidLine: (look) => `${look} is yours.`,
57
+ paidLate: "Paid after the order ended, so no look. The creator sends it back.",
58
+ expired: "This order ended. Paid in time? Wait here: it still counts.",
59
+ prices: (sources) => {
60
+ const others = sources.filter((s) => s !== "CoinGecko");
61
+ const credit = sources.includes("CoinGecko") ? ` ${COINGECKO_CREDIT}.` : "";
62
+ return others.length ? `Price: ${others.join(", ")}.${credit}` : credit.trim();
63
+ },
64
+ };
65
+ /** The game's words over the defaults. A key the game leaves out, or gives as undefined, keeps its default. */
66
+ export function shopWords(over) {
67
+ const out = { ...SHOP_WORDS };
68
+ for (const [k, v] of Object.entries(over ?? {}))
69
+ if (v !== undefined && k in SHOP_WORDS)
70
+ out[k] = v;
71
+ return out;
72
+ }
73
+ /** The price's line: the game's words, with "Powered by CoinGecko" added when CoinGecko is a source and the words leave it out. */
74
+ export function priceLine(words, sources) {
75
+ const line = words.prices(sources).trim();
76
+ if (!sources.includes("CoinGecko") || line.includes(COINGECKO_CREDIT))
77
+ return line;
78
+ return `${line}${line ? " " : ""}${COINGECKO_CREDIT}.`;
79
+ }
@@ -0,0 +1,23 @@
1
+ import type { Fetch } from "./nodes.js";
2
+ import type { ShopStore } from "./store.js";
3
+ export type PriceFeed = {
4
+ name: string;
5
+ url: string;
6
+ read: (j: any) => unknown;
7
+ };
8
+ export declare const PRICE_FEEDS: readonly PriceFeed[];
9
+ export declare const RATE_FRESH_MS: number;
10
+ export declare const RATE_LAST_GOOD_MS: number;
11
+ export type Rate = {
12
+ usd: number;
13
+ at: number;
14
+ sources: string[];
15
+ stale: boolean;
16
+ };
17
+ /** Asks every feed at once and returns the median of the believable answers, or null. */
18
+ export declare function readFeeds(fetchFn: Fetch, feeds?: readonly PriceFeed[], timeoutMs?: number): Promise<{
19
+ usd: number;
20
+ sources: string[];
21
+ } | null>;
22
+ /** Dollars per XNO now, or null when no believable price is known. */
23
+ export declare function usdPerXno(store: Pick<ShopStore, "readRate" | "saveRate">, fetchFn: Fetch, now?: number, feeds?: readonly PriceFeed[]): Promise<Rate | null>;
@@ -0,0 +1,43 @@
1
+ // Dollars per XNO (the game starter's src/worker/price.ts): the median of public price feeds that need no key, so one wrong feed cannot move the price.
2
+ // The answer is kept 5 minutes (in the store: `readRate`, `saveRate`). When every feed fails, the last good price is used for up to 6 hours; after that,
3
+ // new orders wait ("Prices are not available") and nothing is sold at a guessed price.
4
+ //
5
+ // CoinGecko's API terms ask for the words "Powered by CoinGecko": the pay screen shows them.
6
+ import { MAX_RATE, MIN_RATE } from "./amount.js";
7
+ export const PRICE_FEEDS = [
8
+ { name: "CoinGecko", url: "https://api.coingecko.com/api/v3/simple/price?ids=nano&vs_currencies=usd", read: (j) => j?.nano?.usd },
9
+ { name: "Kraken", url: "https://api.kraken.com/0/public/Ticker?pair=NANOUSD", read: (j) => Object.values(j?.result ?? {})[0]?.c?.[0] },
10
+ { name: "KuCoin", url: "https://api.kucoin.com/api/v1/market/orderbook/level1?symbol=XNO-USDT", read: (j) => j?.data?.price },
11
+ ];
12
+ export const RATE_FRESH_MS = 5 * 60_000;
13
+ export const RATE_LAST_GOOD_MS = 6 * 60 * 60_000;
14
+ /** Asks every feed at once and returns the median of the believable answers, or null. */
15
+ export async function readFeeds(fetchFn, feeds = PRICE_FEEDS, timeoutMs = 4000) {
16
+ const answers = await Promise.allSettled(feeds.map(async (f) => {
17
+ const res = await fetchFn(f.url, { headers: { Accept: "application/json", "User-Agent": "nano-game-starter" }, signal: AbortSignal.timeout(timeoutMs) });
18
+ if (!res.ok)
19
+ throw new Error(`HTTP ${res.status}`);
20
+ return Number(f.read(await res.json()));
21
+ }));
22
+ const good = answers
23
+ .map((a, i) => ({ name: feeds[i].name, v: a.status === "fulfilled" ? a.value : NaN }))
24
+ .filter((x) => Number.isFinite(x.v) && x.v >= MIN_RATE && x.v <= MAX_RATE)
25
+ .sort((a, b) => a.v - b.v);
26
+ if (!good.length)
27
+ return null;
28
+ return { usd: good[Math.floor(good.length / 2)].v, sources: good.map((g) => g.name) };
29
+ }
30
+ /** Dollars per XNO now, or null when no believable price is known. */
31
+ export async function usdPerXno(store, fetchFn, now = Date.now(), feeds = PRICE_FEEDS) {
32
+ const last = await store.readRate();
33
+ if (last && now - last.at < RATE_FRESH_MS)
34
+ return { usd: last.usd, sources: last.sources, at: last.at, stale: false };
35
+ const fresh = await readFeeds(fetchFn, feeds);
36
+ if (fresh) {
37
+ await store.saveRate({ ...fresh, at: now });
38
+ return { ...fresh, at: now, stale: false };
39
+ }
40
+ if (last && now - last.at < RATE_LAST_GOOD_MS)
41
+ return { usd: last.usd, sources: last.sources, at: last.at, stale: true };
42
+ return null;
43
+ }
@@ -0,0 +1,24 @@
1
+ import { type NanoNode, type RpcOptions } from "./nodes.js";
2
+ import type { ShopStore } from "./store.js";
3
+ export declare const SCAN_GAP_MS = 4000;
4
+ export type ScanResult = {
5
+ scanned: boolean;
6
+ settled: {
7
+ id: string;
8
+ status: string;
9
+ }[];
10
+ error?: string;
11
+ };
12
+ export type ScanOptions = {
13
+ /** The creator's address (a checked one: `payeeOf`). Null: no scan. */
14
+ address: string | null;
15
+ /** The nodes to ask (`nodesFor`). */
16
+ nodes: readonly NanoNode[];
17
+ /** The time now in ms (default Date.now()). */
18
+ at?: number;
19
+ rpc?: RpcOptions;
20
+ };
21
+ /** Scans the creator's address once and settles the held orders it pays. Fails closed: when the nodes cannot be read, nothing is credited. */
22
+ export declare function scanPayments(store: ShopStore, opts: ScanOptions): Promise<ScanResult>;
23
+ /** For tests: forget the kept send blocks. */
24
+ export declare function forgetBlocks(): void;
@@ -0,0 +1,80 @@
1
+ // The payment scan (the game starter's src/worker/sweep.ts): one look at the creator's address settles every held order at once. It READS the ledger and
2
+ // writes only the store: no key, no send. (The starter calls it "sweep"; it moves no money, unlike @nano133/checkout's sweep.)
3
+ //
4
+ // A player's pay screen asks for it every 5 seconds, the admin page on "Check payments now", and a cron every 10 minutes (for a player who paid and closed
5
+ // the page). Node load stays flat however many players pay: the whole game makes at most one scan every SCAN_GAP_MS, and none when no order is held.
6
+ import { candidates, checkSend } from "./match.js";
7
+ import { rpc } from "./nodes.js";
8
+ import { smallestAmount } from "./orders.js";
9
+ export const SCAN_GAP_MS = 4000;
10
+ /** The most entries one RPC read asks for. */
11
+ const COUNT = "50";
12
+ /** A confirmed send never changes: its answer is kept for an hour (in this copy of the server). */
13
+ const blockCache = new Map();
14
+ async function blockInfo(nodes, hash, o, now) {
15
+ const hit = blockCache.get(hash);
16
+ if (hit && hit.until > now)
17
+ return hit.info;
18
+ const { answer } = await rpc(nodes, { action: "block_info", hash, json_block: "true" }, o);
19
+ if (answer && (answer.confirmed === "true" || answer.confirmed === true)) {
20
+ if (blockCache.size > 500)
21
+ blockCache.clear();
22
+ blockCache.set(hash, { info: answer, until: now + 3_600_000 });
23
+ }
24
+ return answer;
25
+ }
26
+ /** Scans the creator's address once and settles the held orders it pays. Fails closed: when the nodes cannot be read, nothing is credited. */
27
+ export async function scanPayments(store, opts) {
28
+ const now = opts.at ?? Date.now();
29
+ const o = opts.rpc ?? {};
30
+ await store.tidy(now);
31
+ const address = opts.address;
32
+ if (!address)
33
+ return { scanned: false, settled: [] };
34
+ const held = await store.held();
35
+ if (!held.length)
36
+ return { scanned: false, settled: [] };
37
+ if (!(await store.claimScan(now, SCAN_GAP_MS)))
38
+ return { scanned: false, settled: [] };
39
+ const settled = [];
40
+ try {
41
+ // Only amounts a held order asks for: small sends ("dust") cannot push a payment out of the list.
42
+ const threshold = smallestAmount(held);
43
+ const receivable = await rpc(opts.nodes, { action: "receivable", account: address, count: COUNT, threshold, source: "true" }, o);
44
+ // A new address has no history yet: the node answers "Account not found" (null here).
45
+ const history = await rpc(opts.nodes, { action: "account_history", account: address, count: COUNT, raw: "true" }, o);
46
+ const byAmount = new Map(held.map((h) => [h.amount, h]));
47
+ const found = candidates(receivable.answer, history.answer, new Set(byAmount.keys()));
48
+ if (!found.size)
49
+ return { scanned: true, settled };
50
+ // A payment that already paid (or was recorded for) an order never counts again.
51
+ const used = await store.usedHashes([...found.keys()]);
52
+ for (const [hash, amount] of found) {
53
+ if (used.has(hash))
54
+ continue;
55
+ const order = byAmount.get(amount);
56
+ if (!order)
57
+ continue;
58
+ const info = await blockInfo(opts.nodes, hash, o, now);
59
+ if (!info)
60
+ continue;
61
+ const verdict = checkSend(info, address, order.amount, order.createdAt);
62
+ if (verdict.kind !== "paid")
63
+ continue;
64
+ const result = await store.settle(order, { hash, payer: verdict.payer, seenMs: verdict.seenMs }, now);
65
+ if (result === "paid" || result === "paid_late") {
66
+ settled.push({ id: order.id, status: result });
67
+ byAmount.delete(amount);
68
+ }
69
+ }
70
+ return { scanned: true, settled };
71
+ }
72
+ catch (e) {
73
+ // Fail closed: nothing is credited when the nodes cannot be read. The next scan tries again.
74
+ return { scanned: false, settled, error: e instanceof Error ? e.message : String(e) };
75
+ }
76
+ }
77
+ /** For tests: forget the kept send blocks. */
78
+ export function forgetBlocks() {
79
+ blockCache.clear();
80
+ }
@@ -0,0 +1,10 @@
1
+ /** Turnstile (Cloudflare's free check that a visitor is a person) loads from here. */
2
+ export declare const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
3
+ /** The sources the shop adds, by directive. */
4
+ export declare const SHOP_CSP: Readonly<Record<string, readonly string[]>>;
5
+ /**
6
+ * A policy with more sources: `policy` is a CSP text ("default-src 'none'; script-src 'self'") or a map of directives to sources, and each of `more` adds
7
+ * its sources to the same directive (a directive that is not there yet is added). A source is never written twice. The order of the policy is kept.
8
+ * A directive that has 'none' and gets a source loses the 'none' (the two cannot stand together).
9
+ */
10
+ export declare function mergeCsp(policy: string | Readonly<Record<string, readonly string[]>>, ...more: Readonly<Record<string, readonly string[]>>[]): string;
@@ -0,0 +1,56 @@
1
+ // The shop's needs in a game's Content Security Policy, as LISTS that a game merges into its own policy. Never a whole file: the game keeps every
2
+ // source it has (its own frames, its own scripts), and adds these.
3
+ //
4
+ // import { SHOP_CSP, mergeCsp } from "@nano133/nanoterra/shop";
5
+ // const policy = mergeCsp(MY_CSP, SHOP_CSP);
6
+ //
7
+ // The pay sheet draws its QR code on a canvas (no picture from another site), and the wallet key is a plain "nano:" link (a CSP does not limit links).
8
+ // Only Turnstile (the person check, when the game turns it on) needs another origin: its script and its frame.
9
+ /** Turnstile (Cloudflare's free check that a visitor is a person) loads from here. */
10
+ export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
11
+ /** The sources the shop adds, by directive. */
12
+ export const SHOP_CSP = {
13
+ "script-src": [TURNSTILE_ORIGIN],
14
+ "frame-src": [TURNSTILE_ORIGIN],
15
+ "connect-src": ["'self'"],
16
+ };
17
+ /**
18
+ * A policy with more sources: `policy` is a CSP text ("default-src 'none'; script-src 'self'") or a map of directives to sources, and each of `more` adds
19
+ * its sources to the same directive (a directive that is not there yet is added). A source is never written twice. The order of the policy is kept.
20
+ * A directive that has 'none' and gets a source loses the 'none' (the two cannot stand together).
21
+ */
22
+ export function mergeCsp(policy, ...more) {
23
+ const map = new Map();
24
+ const add = (directive, sources) => {
25
+ const name = directive.trim().toLowerCase();
26
+ if (!/^[a-z-]+$/.test(name))
27
+ throw new Error(`not a CSP directive: ${directive}`);
28
+ const list = map.get(name) ?? [];
29
+ for (const s of sources) {
30
+ if (!s || /[;,\s]/.test(s))
31
+ throw new Error(`not a CSP source: ${s}`);
32
+ if (!list.includes(s))
33
+ list.push(s);
34
+ }
35
+ map.set(name, list);
36
+ };
37
+ if (typeof policy === "string") {
38
+ for (const part of policy.split(";")) {
39
+ const [name, ...sources] = part.trim().split(/\s+/).filter(Boolean);
40
+ if (name)
41
+ add(name, sources);
42
+ }
43
+ }
44
+ else
45
+ for (const [k, v] of Object.entries(policy))
46
+ add(k, v);
47
+ for (const m of more)
48
+ for (const [k, v] of Object.entries(m))
49
+ add(k, v);
50
+ return [...map]
51
+ .map(([name, sources]) => {
52
+ const list = sources.length > 1 ? sources.filter((s) => s !== "'none'") : sources;
53
+ return list.length ? `${name} ${list.join(" ")}` : name;
54
+ })
55
+ .join("; ");
56
+ }
@@ -0,0 +1,101 @@
1
+ export type OrderStatus = "open" | "paid" | "expired" | "paid_late";
2
+ /** One order: a player asked to buy a look. Amounts are raw, as text; times are ms since 1970. */
3
+ export type ShopOrder = {
4
+ /** 24 hex characters. */
5
+ id: string;
6
+ /** The signed-in player who made it (the game's player id: the starter's is the Nano address). Only this player sees the order. */
7
+ player: string;
8
+ lookId: string;
9
+ /** The price in US dollars when the order was made: "0.25". */
10
+ usd: string;
11
+ /** Dollars per XNO that turned the price into XNO. */
12
+ rate: number;
13
+ /** The exact amount to pay: a clean amount (at most 4 decimals of XNO). */
14
+ amount: string;
15
+ /**
16
+ * The reservation: equal to `amount` while a payment of it may still be matched to this order, null after. No two orders ever hold the same amount
17
+ * (the store's unique rule), so one payment can only match one order.
18
+ */
19
+ amountLock: string | null;
20
+ status: OrderStatus;
21
+ createdAt: number;
22
+ /** The order takes a payment until then. */
23
+ expiresAt: number;
24
+ /** The amount stays reserved until then (a late payment is still seen, and never counts for a newer order). */
25
+ holdUntil: number;
26
+ /** The paying send block: one payment pays one order, once (the store's unique rule). */
27
+ hash: string | null;
28
+ /** The account that sent it. */
29
+ payer: string | null;
30
+ /** When the node first saw that send. */
31
+ paidAt: number | null;
32
+ /** A keyed hash of the buyer's IP address, for limits (never the address), or null. */
33
+ visitor: string | null;
34
+ };
35
+ /** What `settle` did. "used": that payment already paid another order. "taken": this order was settled meanwhile (or its amount is no longer held). */
36
+ export type Settled = "paid" | "paid_late" | "used" | "taken";
37
+ /** A payment the scan found: the send's hash, its account and when the node first saw it. */
38
+ export type Payment = {
39
+ hash: string;
40
+ payer: string;
41
+ seenMs: number;
42
+ };
43
+ /** The price of XNO the shop keeps (the median of the feeds) and when it read it. */
44
+ export type KeptRate = {
45
+ usd: number;
46
+ sources: string[];
47
+ at: number;
48
+ };
49
+ /**
50
+ * What `forget` did. `waitUntil`: the player has an order whose amount is still held (a payment may still come for it), so NOTHING was deleted; try again
51
+ * after that time. Else `deleted` rows went (owned looks, and orders that were never paid), and `kept` paid orders stay as the creator's sales record,
52
+ * with the player (and the payer of a paid order) replaced by FORGOTTEN.
53
+ */
54
+ export type ForgetResult = {
55
+ deleted: number;
56
+ kept: number;
57
+ waitUntil: number | null;
58
+ };
59
+ /** The stand-in for a player who used "Delete my data", in the orders that stay as the creator's sales record. */
60
+ export declare const FORGOTTEN = "deleted";
61
+ /**
62
+ * The shop's database. An adapter writes ONLY orders, owned looks, the kept price and the scan's claim (and their locks). Each call is ONE step: a
63
+ * transaction, a batch, or a statement that holds its own check.
64
+ */
65
+ export interface ShopStore {
66
+ /** Marks the open orders past `expiresAt` "expired", and frees the amounts whose `holdUntil` is past (the amount lock goes, the order stays). */
67
+ tidy(now: number): Promise<void>;
68
+ /** Which of `amounts` an order holds now. */
69
+ heldAmounts(amounts: readonly string[]): Promise<Set<string>>;
70
+ /**
71
+ * Writes a new order that holds its amount (`amountLock` = `amount`). False, and nothing written, when another order holds that amount now: the
72
+ * unique rule, checked in the same step as the write. Any other failure throws.
73
+ */
74
+ insert(order: ShopOrder): Promise<boolean>;
75
+ order(id: string): Promise<ShopOrder | null>;
76
+ /** The newest open order of this player for this look that still runs at `until`, or null. */
77
+ openOrder(player: string, lookId: string, until: number): Promise<ShopOrder | null>;
78
+ /** How many open orders this player has that still run at `now`. */
79
+ countOpen(player: string, now: number): Promise<number>;
80
+ /** Whether a paid order gave this player this look. */
81
+ owns(player: string, lookId: string): Promise<boolean>;
82
+ /** The ids of every look that paid orders gave this player (free looks are everyone's and are not stored). */
83
+ owned(player: string): Promise<string[]>;
84
+ /** The orders whose amount is held: the only ones a payment can be matched to. */
85
+ held(): Promise<ShopOrder[]>;
86
+ /** Which of `hashes` already paid (or were recorded for) an order. */
87
+ usedHashes(hashes: readonly string[]): Promise<Set<string>>;
88
+ /**
89
+ * Records a payment for a held order, exactly once, in ONE step: the order becomes "paid" (sent while it was open: `pay.seenMs` at most
90
+ * CLOCK_SLACK_MS after `expiresAt`) and the look is given to the ORDER's player (once: one owned row per player and look), or "paid_late" (no look);
91
+ * either way the hash is recorded and the amount freed. "taken" when the order is not open or expired with its amount held (it was settled meanwhile,
92
+ * or its hold ended), else "used" when the hash paid another order. Either way nothing changes.
93
+ */
94
+ settle(order: ShopOrder, pay: Payment, now: number): Promise<Settled>;
95
+ /** Claims the next payment scan: true for exactly one caller in each `gapMs`. */
96
+ claimScan(now: number, gapMs: number): Promise<boolean>;
97
+ readRate(): Promise<KeptRate | null>;
98
+ saveRate(rate: KeptRate): Promise<void>;
99
+ /** "Delete my data" for the shop (see ForgetResult). */
100
+ forget(player: string, now: number): Promise<ForgetResult>;
101
+ }
@@ -0,0 +1,4 @@
1
+ // The shop's records and the store contract. The package has no database: a game gives a store (memory, D1 or Firestore here, or its own that passes
2
+ // "@nano133/nanoterra/shop/conformance"). The rules of money live in the store's few writes, so each one says exactly what it must do in ONE step.
3
+ /** The stand-in for a player who used "Delete my data", in the orders that stay as the creator's sales record. */
4
+ export const FORGOTTEN = "deleted";
@@ -0,0 +1,43 @@
1
+ import type { D1Like } from "../admin/adapters/d1.js";
2
+ import { type ShopTables } from "./adapters/d1.js";
3
+ import { SHOP_LIMITS, type ShopHandler, type ShopHandlerOptions } from "./handler.js";
4
+ import { type Fetch } from "./nodes.js";
5
+ import type { ShopStore } from "./store.js";
6
+ /** The settings the shop reads. Every one is optional except the database. */
7
+ export type ShopEnv = {
8
+ DB: D1Like;
9
+ RECEIVE_ADDRESS?: string;
10
+ TEST_MODE?: string;
11
+ NODE_API_KEY?: string;
12
+ NANO_NODES?: string;
13
+ TURNSTILE_SITE_KEY?: string;
14
+ TURNSTILE_SECRET?: string;
15
+ };
16
+ export type ShopOptions = Pick<ShopHandlerOptions, "catalogue" | "player" | "base" | "now" | "onError" | "rate" | "rpc"> & {
17
+ /** The D1 table names (default: the starter's). */
18
+ tables?: ShopTables;
19
+ /** The `fetch` for Turnstile's check (a test gives its own). */
20
+ fetch?: Fetch;
21
+ };
22
+ /** Whether Turnstile is on: the site key AND the secret are both set. */
23
+ export declare const turnstileOn: (env: Pick<ShopEnv, "TURNSTILE_SITE_KEY" | "TURNSTILE_SECRET">) => boolean;
24
+ /** True when the person check passes, or when Turnstile is off (the starter's turnstile.ts). The secret is sent to Cloudflare only. */
25
+ export declare function turnstileCheck(env: Pick<ShopEnv, "TURNSTILE_SITE_KEY" | "TURNSTILE_SECRET">, token: unknown, ip: string | null, fetchFn?: Fetch): Promise<boolean>;
26
+ export type Shop = ShopHandler & {
27
+ store: ShopStore;
28
+ /** What the game's page needs (the starter's GET /api/config gives these two): whether pay screens are in test mode, and Turnstile's site key or null. */
29
+ config(): {
30
+ testMode: boolean;
31
+ turnstileSiteKey: string | null;
32
+ };
33
+ /** For the admin's Status card: the address, test mode, Turnstile, the nodes' names and plain sentences about what is still off. */
34
+ status(): {
35
+ address: string | null;
36
+ testMode: boolean;
37
+ turnstile: boolean;
38
+ nodes: string[];
39
+ warnings: string[];
40
+ };
41
+ };
42
+ export declare function createShop(env: ShopEnv, options: ShopOptions): Shop;
43
+ export { SHOP_LIMITS };
@@ -0,0 +1,76 @@
1
+ // The shop for a Cloudflare Worker with D1, set up from the game starter's own settings (wrangler.jsonc "vars" and secrets). One call gives the routes,
2
+ // the cron's payment scan, what the page and the admin need to know, and the store:
3
+ //
4
+ // import { createShop } from "@nano133/nanoterra/shop/worker";
5
+ // import looks from "../../looks.json";
6
+ // const shop = createShop(env, { catalogue: looks, player: async (req) => (await sessionOf(env.DB, req))?.address ?? null });
7
+ // const answer = await shop.handle(request); // null when it is not a shop route
8
+ // ...
9
+ // async scheduled(_e, env, ctx) { ctx.waitUntil(createShop(env, opts).scan()); } // the */10 cron
10
+ //
11
+ // The settings (the starter's names): RECEIVE_ADDRESS (the creator's address; the example or a wrong checksum keeps test mode), TEST_MODE ("on" keeps
12
+ // test mode with a real address), NODE_API_KEY (secret, optional: Nanswap Nodes first), NANO_NODES (optional: the game's own nodes), TURNSTILE_SITE_KEY
13
+ // and the secret TURNSTILE_SECRET (both, or no person check). "none", "skip", "off" and "-" mean "not set". The store is D1 on the starter's tables
14
+ // (`env.DB`; the migration is "@nano133/nanoterra/shop/d1.sql"). The player's sign-in is the game's own (`player`).
15
+ import { createD1Shop, d1Limit, visitorKey } from "./adapters/d1.js";
16
+ import { createShopHandler, SHOP_LIMITS } from "./handler.js";
17
+ import { nodesFor, settingValue } from "./nodes.js";
18
+ const VERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
19
+ /** "on", "true", "1" or "yes" (any case). */
20
+ const isOn = (v) => /^(on|true|1|yes)$/i.test((v ?? "").trim());
21
+ /** Whether Turnstile is on: the site key AND the secret are both set. */
22
+ export const turnstileOn = (env) => Boolean(settingValue(env.TURNSTILE_SECRET) && settingValue(env.TURNSTILE_SITE_KEY));
23
+ /** True when the person check passes, or when Turnstile is off (the starter's turnstile.ts). The secret is sent to Cloudflare only. */
24
+ export async function turnstileCheck(env, token, ip, fetchFn = (i, init) => fetch(i, init)) {
25
+ if (!turnstileOn(env))
26
+ return true;
27
+ if (typeof token !== "string" || !token || token.length > 2048)
28
+ return false;
29
+ const form = new FormData();
30
+ form.append("secret", settingValue(env.TURNSTILE_SECRET));
31
+ form.append("response", token);
32
+ if (ip)
33
+ form.append("remoteip", ip);
34
+ try {
35
+ const res = await fetchFn(VERIFY, { method: "POST", body: form, signal: AbortSignal.timeout(5000) });
36
+ const out = (await res.json());
37
+ return out.success === true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ export function createShop(env, options) {
44
+ const store = createD1Shop(env.DB, { tables: options.tables });
45
+ const nodes = nodesFor(env);
46
+ const turnstile = turnstileOn(env);
47
+ const handler = createShopHandler({
48
+ ...options,
49
+ store,
50
+ payee: env.RECEIVE_ADDRESS ?? null,
51
+ testMode: isOn(env.TEST_MODE),
52
+ nodes,
53
+ visitor: (req) => visitorKey(env.DB, req, { meta: options.tables?.meta }),
54
+ // Two layers, as the starter: the game's router counts every call in memory; this one counts new orders for the whole game, in D1 (`hits`).
55
+ limit: (key, limit, windowMs, at) => d1Limit(env.DB, key, limit, windowMs, at),
56
+ personCheck: turnstile ? (token, req) => turnstileCheck(env, token, req.headers.get("CF-Connecting-IP"), options.fetch) : undefined,
57
+ });
58
+ return {
59
+ ...handler,
60
+ store,
61
+ config: () => ({ testMode: handler.testMode, turnstileSiteKey: turnstile ? settingValue(env.TURNSTILE_SITE_KEY) : null }),
62
+ status() {
63
+ const warnings = [];
64
+ if (handler.testMode)
65
+ warnings.push(handler.payee ? "Test mode is on (TEST_MODE). Pay screens say TEST MODE: DO NOT PAY." : "Test mode: no receive address is set.");
66
+ if (!turnstile)
67
+ warnings.push(settingValue(env.TURNSTILE_SECRET) || settingValue(env.TURNSTILE_SITE_KEY)
68
+ ? "Turnstile is OFF: set both TURNSTILE_SITE_KEY and the secret TURNSTILE_SECRET."
69
+ : "Turnstile is OFF: sign-in and orders are not checked for bots. Add a free Turnstile widget (see README).");
70
+ if (!settingValue(env.NODE_API_KEY))
71
+ warnings.push("No NODE_API_KEY: payments are checked on public Nano nodes only, which promise no uptime.");
72
+ return { address: handler.payee, testMode: handler.testMode, turnstile, nodes: nodes.map((n) => n.name), warnings };
73
+ },
74
+ };
75
+ }
76
+ export { SHOP_LIMITS };