@playmos/sdk 0.1.5 → 0.2.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/dist/index.js CHANGED
@@ -1,64 +1,6 @@
1
+ import { InvalidAmountError, ConfigError, MissingFieldError, AuthError, WalletConnectionError, InsufficientGasError, PaymentFailedError, ApiError } from './chunk-B7SHFZYY.js';
2
+ export { ApiError, AuthError, ConfigError, InsufficientGasError, InvalidAmountError, MissingFieldError, PaymentFailedError, PlaymosError, WalletConnectionError } from './chunk-B7SHFZYY.js';
1
3
  import { encodeFunctionData, numberToHex, keccak256, toBytes } from 'viem';
2
- import { timingSafeEqual, createHmac } from 'crypto';
3
-
4
- // src/errors.ts
5
- var PlaymosError = class extends Error {
6
- constructor(code, message, detail) {
7
- super(message);
8
- this.name = new.target.name;
9
- this.code = code;
10
- this.detail = detail;
11
- Object.setPrototypeOf(this, new.target.prototype);
12
- }
13
- };
14
- var InvalidAmountError = class extends PlaymosError {
15
- constructor(amount) {
16
- super(
17
- "invalid_amount",
18
- `Invalid amount: ${JSON.stringify(amount)}. Provide a positive USD decimal string with at most 2 decimals, e.g. "4.99".`,
19
- { amount }
20
- );
21
- }
22
- };
23
- var MissingFieldError = class extends PlaymosError {
24
- constructor(field) {
25
- super("missing_field", `Missing required field: "${field}".`, { field });
26
- }
27
- };
28
- var InsufficientGasError = class extends PlaymosError {
29
- constructor(detail) {
30
- super(
31
- "insufficient_gas",
32
- `The player's wallet has too little ETH to pay gas. Ask them to add a little ETH, or switch to gas.mode: "sponsored".`,
33
- detail
34
- );
35
- }
36
- };
37
- var WalletConnectionError = class extends PlaymosError {
38
- constructor(message = "Could not connect the player's wallet.", detail) {
39
- super("wallet_connection", message, detail);
40
- }
41
- };
42
- var PaymentFailedError = class extends PlaymosError {
43
- constructor(message = "The on-chain payment did not complete.", detail) {
44
- super("payment_failed", message, detail);
45
- }
46
- };
47
- var AuthError = class extends PlaymosError {
48
- constructor(message = "Invalid or missing API key.", detail) {
49
- super("auth", message, detail);
50
- }
51
- };
52
- var ApiError = class extends PlaymosError {
53
- constructor(message, detail) {
54
- super("api_error", message, detail);
55
- }
56
- };
57
- var ConfigError = class extends PlaymosError {
58
- constructor(message, detail) {
59
- super("config", message, detail);
60
- }
61
- };
62
4
 
63
5
  // src/config.ts
64
6
  var CHAIN_ID = {
@@ -359,6 +301,17 @@ var playmosPayAbi = [
359
301
  }
360
302
  ];
361
303
  var prizePoolAbi = [
304
+ {
305
+ type: "function",
306
+ name: "openRound",
307
+ stateMutability: "nonpayable",
308
+ inputs: [
309
+ { name: "roundId", type: "bytes32" },
310
+ { name: "series", type: "bytes32" },
311
+ { name: "entry", type: "uint256" }
312
+ ],
313
+ outputs: []
314
+ },
362
315
  {
363
316
  type: "function",
364
317
  name: "enter",
@@ -369,6 +322,40 @@ var prizePoolAbi = [
369
322
  ],
370
323
  outputs: []
371
324
  },
325
+ {
326
+ type: "function",
327
+ name: "lockRound",
328
+ stateMutability: "nonpayable",
329
+ inputs: [{ name: "roundId", type: "bytes32" }],
330
+ outputs: []
331
+ },
332
+ {
333
+ type: "function",
334
+ name: "settle",
335
+ stateMutability: "nonpayable",
336
+ inputs: [
337
+ { name: "roundId", type: "bytes32" },
338
+ { name: "winners", type: "address[]" },
339
+ { name: "amounts", type: "uint256[]" }
340
+ ],
341
+ outputs: []
342
+ },
343
+ {
344
+ type: "function",
345
+ name: "getRound",
346
+ stateMutability: "view",
347
+ inputs: [{ name: "roundId", type: "bytes32" }],
348
+ outputs: [
349
+ { name: "state", type: "uint8" },
350
+ { name: "series", type: "bytes32" },
351
+ { name: "entry", type: "uint256" },
352
+ { name: "pot", type: "uint256" },
353
+ { name: "entrantCount", type: "uint256" },
354
+ { name: "payable_", type: "uint256" },
355
+ { name: "inheritedSeed", type: "uint256" },
356
+ { name: "lockedAt", type: "uint256" }
357
+ ]
358
+ },
372
359
  {
373
360
  type: "function",
374
361
  name: "hasEntered",
@@ -378,6 +365,13 @@ var prizePoolAbi = [
378
365
  { name: "identity", type: "bytes32" }
379
366
  ],
380
367
  outputs: [{ type: "bool" }]
368
+ },
369
+ {
370
+ type: "function",
371
+ name: "withdraw",
372
+ stateMutability: "nonpayable",
373
+ inputs: [],
374
+ outputs: [{ name: "amount", type: "uint256" }]
381
375
  }
382
376
  ];
383
377
  async function sendCalls(provider, from, chainId, calls, paymasterUrl) {
@@ -511,57 +505,51 @@ function mockEntryPayment(args) {
511
505
  mock: true
512
506
  };
513
507
  }
514
- var WebhookSignatureError = class extends PlaymosError {
515
- constructor(message) {
516
- super("api_error", `Webhook signature verification failed: ${message}`);
517
- }
518
- };
519
- function parseHeader(header) {
520
- const parts = Object.fromEntries(
521
- header.split(",").map((kv) => {
522
- const [k, v] = kv.split("=");
523
- return [k?.trim(), v?.trim()];
524
- })
525
- );
526
- const t = Number(parts["t"]);
527
- const v1 = parts["v1"];
528
- if (!Number.isFinite(t) || !v1) throw new WebhookSignatureError("malformed signature header");
529
- return { t, v1 };
530
- }
531
- function computeSignature(secret, t, rawBody) {
532
- return createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
533
- }
534
- function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
535
- if (!signatureHeader || Array.isArray(signatureHeader)) {
536
- throw new WebhookSignatureError("missing signature header");
537
- }
538
- if (!secret) throw new WebhookSignatureError("missing signing secret");
539
- const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
540
- const { t, v1 } = parseHeader(signatureHeader);
541
- const tolerance = opts.toleranceSeconds ?? 300;
542
- const nowSec = Math.floor(Date.now() / 1e3);
543
- if (Math.abs(nowSec - t) > tolerance) {
544
- throw new WebhookSignatureError(`timestamp outside tolerance (${tolerance}s)`);
545
- }
546
- const expected = computeSignature(secret, t, body);
547
- const a = Buffer.from(expected, "hex");
548
- const b = Buffer.from(v1, "hex");
549
- if (a.length !== b.length || !timingSafeEqual(a, b)) {
550
- throw new WebhookSignatureError("signature mismatch");
551
- }
552
- return JSON.parse(body);
553
- }
554
508
 
555
509
  // src/client.ts
510
+ var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
511
+ function requireAddressField(value, field) {
512
+ if (typeof value !== "string" || value.trim() === "") {
513
+ throw new MissingFieldError(field);
514
+ }
515
+ if (!ADDRESS_RE.test(value)) {
516
+ throw new ConfigError(
517
+ `${field} must be a 0x-prefixed 20-byte wallet address (Phase 1a transfers settle server-held wallets), got: ${JSON.stringify(value)}`,
518
+ { field, value }
519
+ );
520
+ }
521
+ return value.toLowerCase();
522
+ }
523
+ function partyRef(value, field) {
524
+ if (typeof value !== "string" || value.trim() === "") throw new MissingFieldError(field);
525
+ if (value.startsWith("0x")) return requireAddressField(value, field);
526
+ return value;
527
+ }
556
528
  var IAP_FEE_BPS = 100;
557
529
  var POOL_BPS = 6e3;
558
530
  var SEED_BPS = 3e3;
559
531
  var RAKE_BPS = 1e3;
560
532
  var Playmos = class {
561
533
  constructor(config) {
534
+ /**
535
+ * Webhook helpers. Signature verification is **server-only** (Node `crypto`) and
536
+ * lives on `@playmos/sdk/server` so browser bundlers never see `node:crypto` (#9).
537
+ *
538
+ * import { verifyWebhook } from "@playmos/sdk/server";
539
+ * const event = verifyWebhook(rawBody, req.headers["x-playmos-signature"], secret);
540
+ */
562
541
  this.webhooks = {
563
- /** Verify a webhook signature and return the parsed event (server-side). */
564
- verify: (rawBody, signatureHeader, secret) => verifyWebhook(rawBody, signatureHeader, secret)
542
+ /**
543
+ * @deprecated Use `import { verifyWebhook } from "@playmos/sdk/server"` instead.
544
+ * Throws if called — kept as a discoverable pointer so call sites fail loudly
545
+ * with a fix instruction rather than a silent missing method.
546
+ */
547
+ verify: (_rawBody, _signatureHeader, _secret) => {
548
+ throw new ConfigError(
549
+ 'playmos.webhooks.verify is server-only and no longer ships in the browser entry (issue #9). Use: import { verifyWebhook } from "@playmos/sdk/server"',
550
+ { entry: "@playmos/sdk/server" }
551
+ );
552
+ }
565
553
  };
566
554
  this.payouts = {
567
555
  /** Choose how the studio is paid: "usdc" (default) or "fiat" (Bridge). */
@@ -569,18 +557,236 @@ var Playmos = class {
569
557
  /** Create a Bridge KYC onboarding link (fiat payout). */
570
558
  createOnboardingLink: () => this.http.post("/payouts/onboarding_link", {})
571
559
  };
560
+ /**
561
+ * Skill/contest **round lifecycle** (issue #13) — closes the enterRound loop.
562
+ *
563
+ * Scores never leave the studio. Flow:
564
+ * rounds.open → players enterRound → studio scores → rounds.lock →
565
+ * rounds.settle({ ranking }) → contract pays winners.
566
+ *
567
+ * Operator txs are signed by the Playmos service (OPERATOR_ROLE key).
568
+ */
569
+ this.rounds = {
570
+ open: async (input) => {
571
+ requireField(input?.gameId, "gameId");
572
+ requireField(input?.roundId, "roundId");
573
+ requireField(input?.entryAmount, "entryAmount");
574
+ if (!input?.payout || typeof input.payout !== "object") {
575
+ throw new ConfigError("payout rule is required (winner-take-all | top-n | custom)");
576
+ }
577
+ validateAmount(input.entryAmount);
578
+ const { round } = await this.http.post("/rounds", {
579
+ gameId: input.gameId,
580
+ roundId: input.roundId,
581
+ entryAmount: input.entryAmount,
582
+ payout: input.payout,
583
+ closeAt: input.closeAt,
584
+ seriesKey: input.seriesKey,
585
+ roundKey: input.roundKey
586
+ });
587
+ return round;
588
+ },
589
+ lock: async (input) => {
590
+ requireField(input?.roundId, "roundId");
591
+ const { round } = await this.http.post(
592
+ `/rounds/${encodeURIComponent(input.roundId)}/lock`,
593
+ { gameId: input.gameId }
594
+ );
595
+ return round;
596
+ },
597
+ settle: async (input) => {
598
+ requireField(input?.roundId, "roundId");
599
+ if (!input?.results) throw new ConfigError("results are required (ranking or winners)");
600
+ const { settle } = await this.http.post(
601
+ `/rounds/${encodeURIComponent(input.roundId)}/settle`,
602
+ { gameId: input.gameId, results: input.results }
603
+ );
604
+ return settle;
605
+ },
606
+ get: async (input) => {
607
+ requireField(input?.roundId, "roundId");
608
+ const { round } = await this.http.get(
609
+ `/rounds/${encodeURIComponent(input.roundId)}`
610
+ );
611
+ return round;
612
+ }
613
+ };
614
+ /**
615
+ * `agents` — assign wallets to the NPCs YOUR game already owns, so they can transact USDC in your economy.
616
+ * The game creates the NPCs; the SDK only creates the WALLET for a game-supplied id. Engine-agnostic
617
+ * (Unity/Unreal/Godot/web all call the same REST). Requires a secret test key (`sk_test_`) on the sandbox.
618
+ */
572
619
  this.agents = {
573
- /** Assign a wallet to any identity (incl. an AI NPC). Idempotent by agentId. */
574
- createWallet: (input) => {
620
+ /** Assign (or return) the wallet for a game NPC id. Idempotent safe to call wherever your NPCs spawn. */
621
+ createWallet: async (input) => {
622
+ requireField(input?.agentId, "agentId");
623
+ const { agent } = await this.http.post("/agents/wallets", { agentId: input.agentId });
624
+ return agent;
625
+ },
626
+ /** Resolve one NPC's wallet by your id. */
627
+ wallet: async (agentId) => {
628
+ requireField(agentId, "agentId");
629
+ const { agent } = await this.http.get(`/agents/wallets/${encodeURIComponent(agentId)}`);
630
+ return agent;
631
+ },
632
+ /** List the NPC wallets you've assigned in this studio. */
633
+ list: async () => {
634
+ const { agents } = await this.http.get("/agents/wallets");
635
+ return agents;
636
+ },
637
+ /** Sandbox faucet: fund an NPC with USDC from your treasury (per-NPC lifetime cap). */
638
+ fund: (input) => {
575
639
  requireField(input?.agentId, "agentId");
576
- return this.http.post("/agents/wallets", { agentId: input.agentId });
640
+ validateAmount(input.amount);
641
+ return this.http.post(`/agents/wallets/${encodeURIComponent(input.agentId)}/fund`, { amount: input.amount });
577
642
  },
578
- /** Agent↔agent USDC transfer; the configured taxBps is skimmed to Playmos. */
643
+ /** NPC→NPC (or →player) USDC transfer, by id. A thin alias of `playmos.transfer` (which is canonical). */
579
644
  pay: (input) => {
580
645
  requireField(input?.from, "from");
581
646
  requireField(input?.to, "to");
582
- validateAmount(input?.amount);
583
- return this.http.post("/agents/pay", input);
647
+ return this.transfer({ from: input.from, to: input.to, amount: input.amount, feeBps: input.feeBps, feeSink: input.feeSink });
648
+ }
649
+ };
650
+ /**
651
+ * `escrow` — the fair-exchange primitive (Phase 2): lock the payer's USDC on-chain the instant a deal
652
+ * opens (`hold`), then move it exactly once — `release` (→ payee, fee skimmed) XOR `refund` (→ payer,
653
+ * 100%). The contract holds the funds trustlessly; YOUR game decides the rule (who resolves, and when).
654
+ * A `deadline` auto-refund guarantees funds never get stuck. Pass the `hold` result's `id` to the rest.
655
+ */
656
+ this.escrow = {
657
+ /** Open a deal: lock `amount` of the payer's USDC into the on-chain escrow. Retries are idempotent.
658
+ * `async` so client-side validation surfaces as a rejected promise, not a synchronous throw. */
659
+ hold: async (input) => {
660
+ const amountMicro = validateAmount(input.amount);
661
+ const payer = input.payer === void 0 ? void 0 : requireAddressField(input.payer, "payer");
662
+ const payee = requireAddressField(input.payee, "payee");
663
+ const feeBps = input.feeBps ?? 0;
664
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4) {
665
+ throw new ConfigError(
666
+ `feeBps must be an integer in [0, 10000] (fee is taken at release only; refunds are 100%), got: ${JSON.stringify(input.feeBps)}`,
667
+ { feeBps: input.feeBps }
668
+ );
669
+ }
670
+ const feeSink = feeBps > 0 ? requireAddressField(input.feeSink, "feeSink") : input.feeSink === void 0 ? void 0 : requireAddressField(input.feeSink, "feeSink");
671
+ const resolver = input.resolver === void 0 ? void 0 : requireAddressField(input.resolver, "resolver");
672
+ const idempotencyKey = input.idempotencyKey ?? prefixedId("idem");
673
+ const feeMicro = amountMicro * BigInt(feeBps) / 10000n;
674
+ const { escrow } = await this.http.post(
675
+ "/escrows",
676
+ {
677
+ payer,
678
+ payee,
679
+ amount: input.amount,
680
+ feeBps,
681
+ feeSink,
682
+ resolver,
683
+ expiresIn: input.expiresIn,
684
+ deadline: input.deadline,
685
+ memo: input.memo,
686
+ idempotencyKey
687
+ },
688
+ { idempotencyKey }
689
+ );
690
+ return {
691
+ ...escrow,
692
+ payee: escrow.payee ?? payee,
693
+ amount: escrow.amount ?? formatMicroToUsd(amountMicro),
694
+ feeBps: escrow.feeBps ?? feeBps,
695
+ feeSink: escrow.feeSink ?? feeSink ?? null,
696
+ resolver: escrow.resolver ?? resolver ?? null,
697
+ feeAtRelease: escrow.feeAtRelease ?? formatMicroToUsd(feeMicro),
698
+ netAtRelease: escrow.netAtRelease ?? formatMicroToUsd(amountMicro - feeMicro),
699
+ idempotentReplay: Boolean(escrow.idempotentReplay)
700
+ };
701
+ },
702
+ /** Release a held deal to the payee (fee skimmed). `escrowId` is the `hold` result's `id`. */
703
+ release: async (input) => {
704
+ requireField(input?.escrowId, "escrowId");
705
+ const { escrow } = await this.http.post(`/escrows/${encodeURIComponent(input.escrowId)}/release`, {});
706
+ return escrow;
707
+ },
708
+ /** Refund a held deal to the payer (100%, untaxed). `escrowId` is the `hold` result's `id`. */
709
+ refund: async (input) => {
710
+ requireField(input?.escrowId, "escrowId");
711
+ const { escrow } = await this.http.post(`/escrows/${encodeURIComponent(input.escrowId)}/refund`, {});
712
+ return escrow;
713
+ },
714
+ /** Verify a deal's on-chain state (reconciles a `settling` hold wedged by a crash). */
715
+ get: async (escrowId) => {
716
+ requireField(escrowId, "escrowId");
717
+ const { escrow } = await this.http.get(`/escrows/${encodeURIComponent(escrowId)}`);
718
+ return escrow;
719
+ }
720
+ };
721
+ /**
722
+ * `marketplace` — list an item, and the seller is paid ONLY when it's bought (Phase 3a, off-chain items).
723
+ * Built on `escrow`: `buy` locks the buyer's USDC on-chain, `confirm` (after your game server delivers the
724
+ * item) pays the seller, and a no-delivery/timeout `refund`s the buyer. `deliver: true` on `buy` collapses
725
+ * lock+pay into one call when your server delivers synchronously. On-chain items are Phase 3b.
726
+ */
727
+ this.marketplace = {
728
+ /** List an off-chain item for sale. No money moves. Idempotent on `idempotencyKey`. */
729
+ list: async (input) => {
730
+ if (!input?.item || input.item.kind !== "offchain") {
731
+ throw new ConfigError('marketplace.list requires item = { kind: "offchain", sku: "<your-item-id>" } (on-chain items are Phase 3b)', { item: input?.item });
732
+ }
733
+ validateAmount(input.price);
734
+ const seller = requireAddressField(input.seller, "seller");
735
+ const feeBps = input.feeBps;
736
+ if (feeBps !== void 0 && (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4)) {
737
+ throw new ConfigError(`feeBps must be an integer in [0, 10000], got: ${JSON.stringify(feeBps)}`, { feeBps });
738
+ }
739
+ const feeSink = input.feeSink === void 0 ? void 0 : requireAddressField(input.feeSink, "feeSink");
740
+ const { listing } = await this.http.post("/listings", {
741
+ seller,
742
+ item: input.item,
743
+ price: input.price,
744
+ feeBps,
745
+ feeSink,
746
+ deliveryWindow: input.deliveryWindow,
747
+ expiresIn: input.expiresIn,
748
+ gameId: input.gameId,
749
+ idempotencyKey: input.idempotencyKey
750
+ });
751
+ return listing;
752
+ },
753
+ /** Buy a listing: lock the buyer's USDC in escrow. Pass `deliver: true` to also pay the seller in one call. */
754
+ buy: async (input) => {
755
+ requireField(input?.listingId, "listingId");
756
+ const buyer = input.buyer === void 0 ? void 0 : requireAddressField(input.buyer, "buyer");
757
+ return this.http.post(`/listings/${encodeURIComponent(input.listingId)}/buy`, { buyer, deliver: input.deliver === true });
758
+ },
759
+ /** Confirm delivery → the seller is paid (release), fee skimmed. */
760
+ confirm: async (input) => {
761
+ requireField(input?.listingId, "listingId");
762
+ return this.http.post(`/listings/${encodeURIComponent(input.listingId)}/confirm`, {});
763
+ },
764
+ /** Refund the buyer 100% (seller couldn't deliver / dispute / timeout). */
765
+ refund: async (input) => {
766
+ requireField(input?.listingId, "listingId");
767
+ return this.http.post(`/listings/${encodeURIComponent(input.listingId)}/refund`, {});
768
+ },
769
+ /** Delist an unsold listing (pure DB, no tx). */
770
+ cancel: async (input) => {
771
+ requireField(input?.listingId, "listingId");
772
+ const { listing } = await this.http.post(`/listings/${encodeURIComponent(input.listingId)}/cancel`, {});
773
+ return listing;
774
+ },
775
+ /** Fetch a listing + its on-chain-verified sale status. */
776
+ get: async (listingId) => {
777
+ requireField(listingId, "listingId");
778
+ return this.http.get(`/listings/${encodeURIComponent(listingId)}`);
779
+ }
780
+ };
781
+ /**
782
+ * `transfers` — read-back / confirmation for a prior `transfer()` (issue #27).
783
+ * Poll when POST returned `status: "settling"`; reconciles against chain (incl. gasless agent path).
784
+ */
785
+ this.transfers = {
786
+ get: async (transferId) => {
787
+ requireField(transferId, "transferId");
788
+ const res = await this.http.get(`/transfers/${encodeURIComponent(transferId)}`);
789
+ return res.transfer;
584
790
  }
585
791
  };
586
792
  this.config = config;
@@ -657,9 +863,11 @@ var Playmos = class {
657
863
  const playmosPay = intent.clientParams?.contractAddress ?? this.config.contracts?.playmosPay;
658
864
  const studio = intent.clientParams?.studio ?? input.studio;
659
865
  if (!playmosPay) throw new ConfigError("No PlaymosPay contract address (service intent + config.contracts both empty).");
660
- if (!studio) throw new ConfigError("No studio payout address for this payment.");
866
+ if (!studio) throw new ConfigError("No studio payout address for this payment (service must return clientParams.studio).");
867
+ if (!intent.clientParams?.studio && input.studio) ;
661
868
  const amountUnits = this.resolveUnits(intent, amountMicro);
662
- const calls = buildIapCalls({ usdc, playmosPay, paymentId: intent.payment.id, studio, amountUnits });
869
+ const paymentId = intent.clientParams?.paymentId ?? intent.payment.id;
870
+ const calls = buildIapCalls({ usdc, playmosPay, paymentId, studio, amountUnits });
663
871
  const { id: callsId } = await sendCalls(provider, from, this.env.chainId, calls, this.sponsorUrl(intent));
664
872
  const { txHash } = await waitForCalls(provider, callsId);
665
873
  return this.settle(intent.payment.id, txHash);
@@ -711,8 +919,9 @@ var Playmos = class {
711
919
  const usdc = intent.clientParams?.usdc ?? this.config.contracts?.usdc ?? USDC_ADDRESS[this.env.network];
712
920
  const prizePool = intent.clientParams?.contractAddress ?? this.config.contracts?.prizePool;
713
921
  if (!prizePool) throw new ConfigError("No PrizePool contract address for this game (service intent + config.contracts both empty).");
714
- const roundKey = input.roundKey ?? intent.clientParams?.roundKey ?? intent.clientParams?.roundId ?? `${input.gameId}:${input.roundId}`;
715
- const identity = input.identity ?? intent.clientParams?.identity ?? `${from}#${idempotencyKey}`;
922
+ const roundKey = intent.clientParams?.roundKey ?? intent.clientParams?.roundId ?? input.roundKey ?? intent.payment.roundId ?? input.roundId;
923
+ if (!roundKey) throw new ConfigError("No roundKey/roundId for enterRound (service clientParams missing).");
924
+ const identity = intent.clientParams?.identity ?? input.identity ?? intent.payment.identity ?? `${from}#${idempotencyKey}`;
716
925
  const amountUnits = this.resolveUnits(intent, amountMicro);
717
926
  const calls = buildEntryCalls({ usdc, prizePool, roundKey, identity, amountUnits });
718
927
  const { id: callsId } = await sendCalls(provider, from, this.env.chainId, calls, this.sponsorUrl(intent));
@@ -721,6 +930,64 @@ var Playmos = class {
721
930
  payment.identity = identity;
722
931
  return payment;
723
932
  }
933
+ /**
934
+ * `transfer` — the value-movement base primitive (Phase 1a): move USDC from one wallet to another,
935
+ * with a per-call fee. The GAME LOGIC is the authority — you already decided the move is valid — so
936
+ * this is a direct, unconditional push (use `escrow`/`marketplace` when a trust boundary needs fair
937
+ * exchange). The service settles it through the protocol-agnostic settlement core (idempotent,
938
+ * reserve-before-broadcast) and the on-chain PlaymosTransfer / PlaymosTransferAuth contracts.
939
+ *
940
+ * Fee is per-call: `feeBps` 0–10000 (+ `feeSink`). `feeBps: 0` is an untaxed reward/faucet transfer.
941
+ * Retries are safe: pass the same `idempotencyKey` and a re-call NEVER broadcasts a second tx —
942
+ * it returns the cached result (`idempotentReplay: true`).
943
+ *
944
+ * Confirmation: treat `status === "settled" && txHash` as final. If `settling`, call
945
+ * `playmos.transfers.get(id)` until settled/failed. BaseScan: `https://sepolia.basescan.org/tx/<txHash>`.
946
+ *
947
+ * NPC `from` requires `sk_test_` and settles gaslessly (NPC signs; service relays).
948
+ */
949
+ async transfer(input) {
950
+ const amountMicro = validateAmount(input.amount);
951
+ const from = input.from === void 0 ? void 0 : partyRef(input.from, "from");
952
+ const to = partyRef(input.to, "to");
953
+ const feeBps = input.feeBps ?? 0;
954
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4) {
955
+ throw new ConfigError(
956
+ `feeBps must be an integer in [0, 10000] (0 = untaxed reward/faucet; 500 = 5%; 10000 = 100%), got: ${JSON.stringify(input.feeBps)}`,
957
+ { feeBps: input.feeBps }
958
+ );
959
+ }
960
+ let feeSink;
961
+ if (feeBps > 0) {
962
+ feeSink = requireAddressField(input.feeSink, "feeSink");
963
+ } else if (input.feeSink !== void 0) {
964
+ feeSink = requireAddressField(input.feeSink, "feeSink");
965
+ }
966
+ const idempotencyKey = input.idempotencyKey ?? prefixedId("idem");
967
+ const res = await this.http.post(
968
+ "/transfers",
969
+ { from, to, amount: input.amount, memo: input.memo, feeBps, feeSink, idempotencyKey },
970
+ { idempotencyKey }
971
+ );
972
+ const t = res.transfer;
973
+ const feeMicro = amountMicro * BigInt(feeBps) / 10000n;
974
+ return {
975
+ id: t.id,
976
+ status: t.status,
977
+ txHash: t.txHash,
978
+ from: t.from,
979
+ // the service's resolved payer address (omitted when it's the redacted treasury signer)
980
+ to: t.to,
981
+ // the service's resolved payee address
982
+ amount: t.amount ?? formatMicroToUsd(amountMicro),
983
+ fee: t.fee ?? formatMicroToUsd(feeMicro),
984
+ net: t.net ?? formatMicroToUsd(amountMicro - feeMicro),
985
+ feeBps: t.feeBps ?? feeBps,
986
+ feeSink: t.feeSink ?? feeSink ?? null,
987
+ memo: t.memo ?? input.memo ?? null,
988
+ idempotentReplay: Boolean(t.idempotentReplay)
989
+ };
990
+ }
724
991
  /** Verify a payment by the service's on-chain read (spec §6.1). Idempotent. */
725
992
  async verify(paymentId) {
726
993
  requireField(paymentId, "paymentId");
@@ -812,6 +1079,30 @@ function previewIapSplit(amount) {
812
1079
  const { feeMicro, netMicro } = computeIapSplit(micro, IAP_FEE_BPS);
813
1080
  return { amount: formatMicroToUsd(micro), fee: formatMicroToUsd(feeMicro), net: formatMicroToUsd(netMicro) };
814
1081
  }
1082
+ function previewTransferSplit(amount, feeBps) {
1083
+ const micro = validateAmount(amount);
1084
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4) {
1085
+ throw new ConfigError(`feeBps must be an integer in [0, 10000], got: ${JSON.stringify(feeBps)}`, { feeBps });
1086
+ }
1087
+ const feeMicro = micro * BigInt(feeBps) / 10000n;
1088
+ return { amount: formatMicroToUsd(micro), fee: formatMicroToUsd(feeMicro), net: formatMicroToUsd(micro - feeMicro), feeBps };
1089
+ }
1090
+ function previewEscrowFee(amount, feeBps) {
1091
+ const micro = validateAmount(amount);
1092
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4) {
1093
+ throw new ConfigError(`feeBps must be an integer in [0, 10000], got: ${JSON.stringify(feeBps)}`, { feeBps });
1094
+ }
1095
+ const feeMicro = micro * BigInt(feeBps) / 10000n;
1096
+ return { amount: formatMicroToUsd(micro), fee: formatMicroToUsd(feeMicro), net: formatMicroToUsd(micro - feeMicro), feeBps };
1097
+ }
1098
+ function previewMarketplaceSplit(price, feeBps) {
1099
+ const micro = validateAmount(price);
1100
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1e4) {
1101
+ throw new ConfigError(`feeBps must be an integer in [0, 10000], got: ${JSON.stringify(feeBps)}`, { feeBps });
1102
+ }
1103
+ const feeMicro = micro * BigInt(feeBps) / 10000n;
1104
+ return { price: formatMicroToUsd(micro), fee: formatMicroToUsd(feeMicro), net: formatMicroToUsd(micro - feeMicro), feeBps };
1105
+ }
815
1106
  function previewPoolSplit(amount) {
816
1107
  const micro = validateAmount(amount);
817
1108
  const { poolMicro, seedMicro, rakeMicro } = computePoolSplit(micro, POOL_BPS, SEED_BPS, RAKE_BPS);
@@ -823,6 +1114,205 @@ function previewPoolSplit(amount) {
823
1114
  };
824
1115
  }
825
1116
 
826
- export { ApiError, AuthError, CHAIN_ID, ConfigError, DEFAULT_API_BASE_URL, InsufficientGasError, InvalidAmountError, MICRO_PER_USDC, MissingFieldError, PaymentFailedError, Playmos, PlaymosError, USDC_ADDRESS, USDC_DECIMALS, WalletConnectionError, WebhookSignatureError, computeIapSplit, computePoolSplit, formatMicroToUsd, parseUsdToMicro, prefixedId, previewIapSplit, previewPoolSplit, ulid, verifyWebhook };
1117
+ // src/payout.ts
1118
+ var PayoutError = class extends Error {
1119
+ constructor(message) {
1120
+ super(message);
1121
+ this.code = "payout_invalid";
1122
+ this.name = "PayoutError";
1123
+ }
1124
+ };
1125
+ var ADDRESS_RE2 = /^0x[0-9a-fA-F]{40}$/;
1126
+ var BPS = 10000n;
1127
+ function requireAddress(w, i) {
1128
+ if (!ADDRESS_RE2.test(w)) {
1129
+ throw new PayoutError(`ranking[${i}] must be a 0x-prefixed 20-byte address, got: ${JSON.stringify(w)}`);
1130
+ }
1131
+ return w.toLowerCase();
1132
+ }
1133
+ function parseUsdToMicroLoose(amount) {
1134
+ if (typeof amount !== "string" || !/^\d+(\.\d{1,6})?$/.test(amount.trim())) {
1135
+ throw new PayoutError(`invalid USD amount: ${JSON.stringify(amount)}`);
1136
+ }
1137
+ const [wholeRaw, frac = ""] = amount.trim().split(".");
1138
+ const whole = wholeRaw ?? "0";
1139
+ const fracPadded = (frac + "000000").slice(0, 6);
1140
+ const micro = BigInt(whole) * 1000000n + BigInt(fracPadded);
1141
+ if (micro <= 0n) throw new PayoutError(`amount must be > 0, got: ${JSON.stringify(amount)}`);
1142
+ return micro;
1143
+ }
1144
+ function computePayout(pool, ranking, rule) {
1145
+ if (typeof pool !== "bigint" || pool <= 0n) {
1146
+ throw new PayoutError(`pool must be a positive bigint (micro-USDC), got: ${String(pool)}`);
1147
+ }
1148
+ if (!Array.isArray(ranking) || ranking.length === 0) {
1149
+ throw new PayoutError("ranking must be a non-empty array of wallets (best-first)");
1150
+ }
1151
+ const wallets = ranking.map((w, i) => requireAddress(w, i));
1152
+ const seen = /* @__PURE__ */ new Set();
1153
+ for (const w of wallets) {
1154
+ if (seen.has(w)) throw new PayoutError(`duplicate wallet in ranking: ${w}`);
1155
+ seen.add(w);
1156
+ }
1157
+ if (rule.kind === "winner-take-all") {
1158
+ return [{ wallet: wallets[0], amount: pool }];
1159
+ }
1160
+ if (rule.kind === "top-n") {
1161
+ const splits = rule.splitsBps;
1162
+ if (!Array.isArray(splits) || splits.length === 0) {
1163
+ throw new PayoutError("top-n splitsBps must be a non-empty array");
1164
+ }
1165
+ if (splits.length > wallets.length) {
1166
+ throw new PayoutError(
1167
+ `top-n needs ${splits.length} ranked wallets but ranking only has ${wallets.length}`
1168
+ );
1169
+ }
1170
+ let sumBps = 0;
1171
+ for (const b of splits) {
1172
+ if (!Number.isInteger(b) || b <= 0 || b > 1e4) {
1173
+ throw new PayoutError(`each splitsBps entry must be an integer in (0, 10000], got: ${b}`);
1174
+ }
1175
+ sumBps += b;
1176
+ }
1177
+ if (sumBps !== 1e4) {
1178
+ throw new PayoutError(`splitsBps must sum to 10000, got ${sumBps}`);
1179
+ }
1180
+ const out = [];
1181
+ let allocated = 0n;
1182
+ for (let i = 0; i < splits.length; i++) {
1183
+ const amt = pool * BigInt(splits[i]) / BPS;
1184
+ out.push({ wallet: wallets[i], amount: amt });
1185
+ allocated += amt;
1186
+ }
1187
+ const remainder = pool - allocated;
1188
+ if (remainder < 0n) throw new PayoutError("internal: allocated more than pool");
1189
+ out[0] = { wallet: out[0].wallet, amount: out[0].amount + remainder };
1190
+ const filtered = out.filter((x) => x.amount > 0n);
1191
+ if (filtered.length === 0) throw new PayoutError("payout produced no positive amounts");
1192
+ const total = filtered.reduce((s, x) => s + x.amount, 0n);
1193
+ if (total !== pool) throw new PayoutError(`internal: sum ${total} != pool ${pool}`);
1194
+ return filtered;
1195
+ }
1196
+ if (rule.kind === "custom") {
1197
+ const amounts = rule.amounts;
1198
+ if (!Array.isArray(amounts) || amounts.length === 0) {
1199
+ throw new PayoutError("custom amounts must be a non-empty array of USD strings");
1200
+ }
1201
+ if (amounts.length > wallets.length) {
1202
+ throw new PayoutError(
1203
+ `custom amounts has ${amounts.length} entries but ranking only has ${wallets.length}`
1204
+ );
1205
+ }
1206
+ const out = [];
1207
+ let total = 0n;
1208
+ for (let i = 0; i < amounts.length; i++) {
1209
+ const amt = parseUsdToMicroLoose(amounts[i]);
1210
+ out.push({ wallet: wallets[i], amount: amt });
1211
+ total += amt;
1212
+ }
1213
+ if (total !== pool) {
1214
+ throw new PayoutError(
1215
+ `custom amounts sum to ${total} micro-USDC but pool is ${pool} \u2014 must match exactly`
1216
+ );
1217
+ }
1218
+ return out;
1219
+ }
1220
+ throw new PayoutError(`unknown payout rule kind: ${JSON.stringify(rule.kind)}`);
1221
+ }
1222
+
1223
+ // src/settlement.ts
1224
+ var ADDRESS_RE3 = /^0x[0-9a-fA-F]{40}$/;
1225
+ var DEFAULT_TTL_MS = 15 * 60 * 1e3;
1226
+ function requireAddress2(value, field) {
1227
+ if (typeof value !== "string" || value.trim() === "") {
1228
+ throw new MissingFieldError(field);
1229
+ }
1230
+ if (!ADDRESS_RE3.test(value)) {
1231
+ throw new ConfigError(`${field} must be a 0x-prefixed 20-byte address, got: ${JSON.stringify(value)}`, {
1232
+ field,
1233
+ value
1234
+ });
1235
+ }
1236
+ return value;
1237
+ }
1238
+ function requireNetwork(value) {
1239
+ if (value === "base" || value === "base-sepolia") return value;
1240
+ throw new ConfigError(`Unknown network: ${JSON.stringify(value)}. Expected one of ${Object.keys(CHAIN_ID).join(", ")}.`, {
1241
+ field: "network",
1242
+ value
1243
+ });
1244
+ }
1245
+ function createPaymentRequirement(input) {
1246
+ const now = (input.now ?? (() => /* @__PURE__ */ new Date()))();
1247
+ const payTo = requireAddress2(input.payTo, "payTo");
1248
+ const network = requireNetwork(input.network);
1249
+ const asset = input.asset ?? "USDC";
1250
+ if (asset !== "USDC") {
1251
+ throw new ConfigError(`Unsupported asset: ${JSON.stringify(asset)}. Only "USDC" is supported.`, { asset });
1252
+ }
1253
+ parseUsdToMicro(input.amount);
1254
+ const expiresAt = input.expiresAt ?? new Date(now.getTime() + (input.expiresInMs ?? DEFAULT_TTL_MS)).toISOString();
1255
+ const req = {
1256
+ id: input.id ?? prefixedId("preq"),
1257
+ payTo,
1258
+ amount: input.amount,
1259
+ asset,
1260
+ network,
1261
+ expiresAt
1262
+ };
1263
+ if (input.terms !== void 0) req.terms = input.terms;
1264
+ return req;
1265
+ }
1266
+ function serializePaymentRequirement(req) {
1267
+ const body = {
1268
+ id: req.id,
1269
+ payTo: req.payTo,
1270
+ amount: req.amount,
1271
+ asset: req.asset,
1272
+ network: req.network,
1273
+ expiresAt: req.expiresAt
1274
+ };
1275
+ if (req.terms !== void 0) body.terms = req.terms;
1276
+ return body;
1277
+ }
1278
+ function parsePaymentRequirement(input) {
1279
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
1280
+ throw new ConfigError("PaymentRequirement must be a JSON object.", { input });
1281
+ }
1282
+ const o = input;
1283
+ const id = o.id;
1284
+ if (typeof id !== "string" || id.trim() === "") throw new MissingFieldError("id");
1285
+ if (o.asset !== "USDC") {
1286
+ throw new ConfigError(`PaymentRequirement.asset must be "USDC", got: ${JSON.stringify(o.asset)}.`, {
1287
+ asset: o.asset
1288
+ });
1289
+ }
1290
+ const payTo = requireAddress2(o.payTo, "payTo");
1291
+ const network = requireNetwork(o.network);
1292
+ if (typeof o.amount !== "string") throw new InvalidAmountError(o.amount);
1293
+ parseUsdToMicro(o.amount);
1294
+ if (typeof o.expiresAt !== "string" || o.expiresAt.trim() === "") throw new MissingFieldError("expiresAt");
1295
+ if (o.terms !== void 0 && typeof o.terms !== "string") {
1296
+ throw new ConfigError("PaymentRequirement.terms must be a string when present.", { terms: o.terms });
1297
+ }
1298
+ const req = {
1299
+ id,
1300
+ payTo,
1301
+ amount: o.amount,
1302
+ asset: "USDC",
1303
+ network,
1304
+ expiresAt: o.expiresAt
1305
+ };
1306
+ if (o.terms !== void 0) req.terms = o.terms;
1307
+ return req;
1308
+ }
1309
+ function isWalletSignatureAuthorization(auth) {
1310
+ return auth.kind === "wallet-signature";
1311
+ }
1312
+ function isX402PayloadAuthorization(auth) {
1313
+ return auth.kind === "x402-payload";
1314
+ }
1315
+
1316
+ export { CHAIN_ID, DEFAULT_API_BASE_URL, MICRO_PER_USDC, PayoutError, Playmos, USDC_ADDRESS, USDC_DECIMALS, computeIapSplit, computePayout, computePoolSplit, createPaymentRequirement, formatMicroToUsd, isWalletSignatureAuthorization, isX402PayloadAuthorization, parsePaymentRequirement, parseUsdToMicro, prefixedId, previewEscrowFee, previewIapSplit, previewMarketplaceSplit, previewPoolSplit, previewTransferSplit, serializePaymentRequirement, ulid };
827
1317
  //# sourceMappingURL=index.js.map
828
1318
  //# sourceMappingURL=index.js.map