| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { ItemId } from "../../shared/definitions/items.js"; |
| 4 | import { BlockType } from "../../shared/definitions/tiles.js"; |
| 5 | import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js"; |
| 6 | import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js"; |
| 7 | import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js"; |
| 8 | import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js"; |
| 9 | import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js"; |
| 10 | import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js"; |
| 11 | import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js"; |
| 12 | import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js"; |
| 13 | import { CHUNK_SIZE } from "../../shared/protocol/constants.js"; |
| 14 | |
| 15 | test("blank cheques cannot be listed on the marketplace", () => |
| 16 | { |
| 17 | const stack = { itemId: ItemId.blankCheque, quantity: 1 }; |
| 18 | assert.equal(canSellOnMarketplace(stack), false); |
| 19 | assert.throws( |
| 20 | () => assertMarketplaceSellable(stack), |
| 21 | (err) => err.message === "Blank cheques cannot be sold on the marketplace." |
| 22 | ); |
| 23 | }); |
| 24 | |
| 25 | test("written cheques can be listed on the marketplace", () => |
| 26 | { |
| 27 | const stack = { |
| 28 | itemId: ItemId.filledCheque, |
| 29 | quantity: 1, |
| 30 | instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 } |
| 31 | }; |
| 32 | assert.equal(canSellOnMarketplace(stack), true); |
| 33 | assert.doesNotThrow(() => assertMarketplaceSellable(stack)); |
| 34 | }); |
| 35 | |
| 36 | test("normal items are marketplace sellable by default", () => |
| 37 | { |
| 38 | assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true); |
| 39 | }); |
| 40 | |
| 41 | test("letters cannot be listed on the marketplace", () => |
| 42 | { |
| 43 | const own = { |
| 44 | itemId: ItemId.letter, |
| 45 | quantity: 1, |
| 46 | instance: { |
| 47 | kind: "letter", |
| 48 | letterId: "x", |
| 49 | authorCharacterId: 1, |
| 50 | authorDisplayName: "Ada", |
| 51 | body: "Hi", |
| 52 | opened: true |
| 53 | } |
| 54 | }; |
| 55 | const received = { |
| 56 | ...own, |
| 57 | instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" } |
| 58 | }; |
| 59 | assert.equal(canSellOnMarketplace(own, 1), false); |
| 60 | assert.equal(canSellOnMarketplace(received, 1), false); |
| 61 | assert.throws( |
| 62 | () => assertMarketplaceSellable(own, 1), |
| 63 | (err) => /letters cannot be sold on the marketplace/i.test(err.message) |
| 64 | ); |
| 65 | }); |
| 66 | |
| 67 | test("midpoint trade price rounds half units deterministically", () => |
| 68 | { |
| 69 | assert.equal(midpointTradePrice(100, 80), 90); |
| 70 | assert.equal(midpointTradePrice(101, 80), 91); |
| 71 | assert.equal(midpointTradePrice(80, 100), 90); |
| 72 | }); |
| 73 | |
| 74 | test("listing fee is 3% of notional rounded up", () => |
| 75 | { |
| 76 | assert.equal(marketOrderListingFee(100, 1), 3); |
| 77 | assert.equal(marketOrderListingFee(10, 1), 1); |
| 78 | assert.equal(marketOrderListingFee(8, 2), 1); |
| 79 | assert.equal(marketOrderListingFee(0, 5), 0); |
| 80 | }); |
| 81 | |
| 82 | test("market funds spend whole coin cheques and return change", () => |
| 83 | { |
| 84 | const slots = emptySlots(); |
| 85 | slots[0] = { |
| 86 | itemId: ItemId.filledCheque, |
| 87 | quantity: 1, |
| 88 | instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 } |
| 89 | }; |
| 90 | const paid = takeMarketFunds(slots, 25); |
| 91 | assert.equal(paid.ok, true); |
| 92 | assert.equal(paid.change, 15); |
| 93 | assert.equal(paid.redeemedCheques.length, 1); |
| 94 | assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true); |
| 95 | }); |
| 96 | |
| 97 | test("written cheque sell listing locks quantity to reserved goods", () => |
| 98 | { |
| 99 | const listing = resolveMarketSellListing({ |
| 100 | itemId: ItemId.filledCheque, |
| 101 | quantity: 1, |
| 102 | instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 } |
| 103 | }); |
| 104 | assert.equal(listing.isCheque, true); |
| 105 | assert.equal(listing.itemId, ItemId.apple); |
| 106 | assert.equal(listing.quantity, 7); |
| 107 | assert.equal(listing.quantityLocked, true); |
| 108 | }); |
| 109 | |
| 110 | function placePlaza (worldDb) |
| 111 | { |
| 112 | const data = createEmptyChunkData(); |
| 113 | data.open = true; |
| 114 | data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null }; |
| 115 | data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null }; |
| 116 | worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data)); |
| 117 | } |
| 118 | |
| 119 | test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () => |
| 120 | { |
| 121 | const harness = makeSimulation({ workerCount: 1 }); |
| 122 | try |
| 123 | { |
| 124 | placePlaza(harness.worldDb); |
| 125 | harness.simulation.reloadWorld(); |
| 126 | |
| 127 | const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" }); |
| 128 | const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" }); |
| 129 | const sellerBag = addCoinsToSlots(emptySlots(), 5); |
| 130 | assert.equal(sellerBag.ok, true); |
| 131 | sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 }; |
| 132 | harness.stateDb.saveBag(seller.character_id, { |
| 133 | inventory: sellerBag.slots, |
| 134 | equipment: emptyEquipment(), |
| 135 | vault: [], |
| 136 | vaultReserved: [] |
| 137 | }); |
| 138 | const buyerBag = addCoinsToSlots(emptySlots(), 100); |
| 139 | assert.equal(buyerBag.ok, true); |
| 140 | harness.stateDb.saveBag(buyer.character_id, { |
| 141 | inventory: buyerBag.slots, |
| 142 | equipment: emptyEquipment(), |
| 143 | vault: [], |
| 144 | vaultReserved: [] |
| 145 | }); |
| 146 | |
| 147 | const sellerId = harness.simulation.spawnCharacter(1, seller); |
| 148 | const buyerId = harness.simulation.spawnCharacter(2, buyer); |
| 149 | harness.simulation.step(); |
| 150 | |
| 151 | harness.simulation.enqueue(1, { |
| 152 | type: "place-market-sell", |
| 153 | characterId: seller.character_id, |
| 154 | slotIndex: 1, |
| 155 | quantity: 2, |
| 156 | minUnitPrice: 8 |
| 157 | }); |
| 158 | const sellResult = harness.simulation.step(); |
| 159 | assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events)); |
| 160 | assert.ok(sellResult.events.some((event) => event.type === "market-open")); |
| 161 | |
| 162 | harness.simulation.enqueue(2, { |
| 163 | type: "place-market-buy", |
| 164 | characterId: buyer.character_id, |
| 165 | itemId: ItemId.apple, |
| 166 | quantity: 2, |
| 167 | maxUnitPrice: 12 |
| 168 | }); |
| 169 | const buyResult = harness.simulation.step(); |
| 170 | assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events)); |
| 171 | const trade = buyResult.events.find((event) => event.type === "market-trade"); |
| 172 | assert.ok(trade, JSON.stringify(buyResult.events)); |
| 173 | assert.equal(trade.unitPrice, 10); |
| 174 | assert.equal(trade.quantity, 2); |
| 175 | |
| 176 | const buyerBagNow = harness.simulation.bagOf(buyerId); |
| 177 | assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true); |
| 178 | |
| 179 | // Coins go to bank; letter goes to the online seller's inventory. |
| 180 | for (let i = 0; i < 500; i++) |
| 181 | { |
| 182 | harness.advance(1000); |
| 183 | harness.simulation.step(); |
| 184 | const sellerVault = harness.stateDb.getBag(seller.character_id); |
| 185 | const sellerBag = harness.simulation.bagOf(sellerId); |
| 186 | const coins = countCoinsInSlots(sellerVault.vault ?? []); |
| 187 | const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter) |
| 188 | ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter); |
| 189 | if (coins >= 20 && letter) |
| 190 | { |
| 191 | assert.match(letter.instance.body, /sold|filled|proceeds/i); |
| 192 | assert.doesNotMatch(letter.instance.body, /Signed,/); |
| 193 | assert.equal(letter.instance.authorOrganization, "Central Exchange"); |
| 194 | assert.ok(letter.instance.authorDisplayName); |
| 195 | assert.equal(letter.origins?.[0]?.origin?.verb, "Written"); |
| 196 | assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName); |
| 197 | assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10); |
| 198 | return; |
| 199 | } |
| 200 | } |
| 201 | assert.fail("Seller did not receive coins in vault and letter"); |
| 202 | } |
| 203 | finally |
| 204 | { harness.close(); } |
| 205 | }); |
| 206 | |
| 207 | test("orders older than one month auto-cancel and return escrow to bank", () => |
| 208 | { |
| 209 | const harness = makeSimulation({ workerCount: 1 }); |
| 210 | try |
| 211 | { |
| 212 | placePlaza(harness.worldDb); |
| 213 | harness.simulation.reloadWorld(); |
| 214 | |
| 215 | const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); |
| 216 | const bag = addCoinsToSlots(emptySlots(), 50); |
| 217 | assert.equal(bag.ok, true); |
| 218 | harness.stateDb.saveBag(character.character_id, { |
| 219 | inventory: bag.slots, |
| 220 | equipment: emptyEquipment(), |
| 221 | vault: [], |
| 222 | vaultReserved: [] |
| 223 | }); |
| 224 | harness.simulation.spawnCharacter(1, character); |
| 225 | harness.simulation.step(); |
| 226 | |
| 227 | harness.simulation.enqueue(1, { |
| 228 | type: "place-market-buy", |
| 229 | characterId: character.character_id, |
| 230 | itemId: ItemId.apple, |
| 231 | quantity: 1, |
| 232 | maxUnitPrice: 10 |
| 233 | }); |
| 234 | const placed = harness.simulation.step(); |
| 235 | assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events)); |
| 236 | const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id); |
| 237 | assert.equal(open.length, 1); |
| 238 | |
| 239 | const order = open[0]; |
| 240 | harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?") |
| 241 | .run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId); |
| 242 | |
| 243 | const expired = harness.simulation.market.step(Date.now()); |
| 244 | assert.ok(expired.some((event) => event.type === "market-order-expired")); |
| 245 | assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0); |
| 246 | |
| 247 | for (let i = 0; i < 500; i++) |
| 248 | { |
| 249 | harness.advance(1000); |
| 250 | harness.simulation.step(); |
| 251 | const vault = harness.stateDb.getBag(character.character_id); |
| 252 | const bag = harness.simulation.bagOf(1); |
| 253 | const coins = countCoinsInSlots(vault.vault ?? []); |
| 254 | const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter) |
| 255 | ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter); |
| 256 | if (coins >= 10 && letter) |
| 257 | { |
| 258 | assert.match(letter.instance.body, /one month/i); |
| 259 | assert.doesNotMatch(letter.instance.body, /Signed,/); |
| 260 | assert.equal(letter.instance.authorOrganization, "Central Exchange"); |
| 261 | return; |
| 262 | } |
| 263 | } |
| 264 | assert.fail("Expired order did not return escrow letter"); |
| 265 | } |
| 266 | finally |
| 267 | { harness.close(); } |
| 268 | }); |
| 269 | |
| 270 | test("exchange letter instance carries Central Exchange signature fields", () => |
| 271 | { |
| 272 | const body = soldLetterBody({ |
| 273 | itemName: "Apple", |
| 274 | quantity: 1, |
| 275 | unitPrice: 5, |
| 276 | clerkName: "Bobby Pennies" |
| 277 | }); |
| 278 | assert.doesNotMatch(body, /Signed,/); |
| 279 | assert.doesNotMatch(body, /Bobby Pennies/); |
| 280 | assert.doesNotMatch(body, /Central Exchange/); |
| 281 | assert.match(body, /filled at 5 coins/); |
| 282 | assert.equal( |
| 283 | formatLetterSignature({ |
| 284 | authorDisplayName: "Bobby Pennies", |
| 285 | authorOrganization: CENTRAL_EXCHANGE_ORG |
| 286 | }), |
| 287 | "Signed:\nBobby Pennies\nCentral Exchange" |
| 288 | ); |
| 289 | assert.equal( |
| 290 | formatLetterSignature({ authorDisplayName: "The Bank" }), |
| 291 | "Signed:\nThe Bank" |
| 292 | ); |
| 293 | }); |
| 294 | |
| 295 | test("written origin labels match letter author", () => |
| 296 | { |
| 297 | assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally"); |
| 298 | assert.equal(CraftOriginVerb.written, "Written"); |
| 299 | }); |