@shippedcalls/sdk 0.1.0 → 0.3.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/src/chain.ts CHANGED
@@ -3,8 +3,10 @@ import { createPublicClient, createWalletClient, defineChain, fallback, http, ty
3
3
  export const CHAIN_ID = 4663;
4
4
  export const API_URL = "https://calls.shipped.bond";
5
5
  export const EXPLORER = "https://robinhoodchain.blockscout.com";
6
- export const FACTORY = "0xf1F8E31D084B516b62E5646C684F7e955E8dA378" as const;
7
- export const CALLED_IT = "0x9AA338e1BFe2ee19e715a0dEAaa9596eDF690cE1" as const;
6
+ export const FACTORY = "0x6b60CaF2D0B263Be65b2f1afE2CEa78680AB5b40" as const;
7
+ export const CALLED_IT = "0x500855cA9F281A1383482399ADDd1651269BB866" as const;
8
+ /** Earlier factories whose Calls are still running, newest first. They stay Calls: bets, claims and disputes go on. */
9
+ export const PREVIOUS_FACTORIES: readonly `0x${string}`[] = ["0xf1F8E31D084B516b62E5646C684F7e955E8dA378"];
8
10
  export const DEEDS = "0xD5Da523ee49CB7Fe855B0C6fa38707190A9D531F" as const;
9
11
 
10
12
  // The order Shipped's own services run: the official endpoint, then POKT, which also serves old state, then dRPC.
package/src/cli.ts CHANGED
@@ -105,6 +105,11 @@ function clientFor(values: Values, env: NodeJS.ProcessEnv) {
105
105
  });
106
106
  }
107
107
 
108
+ const windowLine = ({ disputeWindow, priceDisputeWindow }: { disputeWindow: number | null; priceDisputeWindow?: number | null }) => {
109
+ const hours = (disputeWindow ?? 0) / 3600;
110
+ return priceDisputeWindow ? `${priceDisputeWindow / 3600} h on a Price Call, ${hours} h on a Post or contract-read Call` : `${hours} h`;
111
+ };
112
+
108
113
  function rowLines(c: CallRow | CallDetail): string[] {
109
114
  const odds = c.status === "open" ? `Holds ${c.odds.holdsMultiple ?? "-"}x, Breaks ${c.odds.breaksMultiple ?? "-"}x` : c.outcome ? `${named(c.outcome)} won` : c.status;
110
115
  return [`${c.address} ${c.status} ${c.type} closes ${when(c.closeAt)} pot ${eth(c.pools.total)} ${odds}`, ` ${clean(c.callText) || "(no sentence stored)"}`];
@@ -238,7 +243,7 @@ async function run(command: string | undefined, args: string[], values: Values,
238
243
  const proof = await client.proof();
239
244
  const lines = [`${proof.chain.name} (chain ${proof.chain.id}). Factory ${proof.factory.address}.`];
240
245
  lines.push(...proof.contracts.map((c) => ` ${c.name}: ${c.address}${c.sourcify === "exact_match" ? ", source published, exact match" : ""}`));
241
- if (proof.rules.minBet) lines.push(`Minimum bet ${eth(proof.rules.minBet)}. Fee ${(proof.rules.rakeBps ?? 0) / 100}% of the losing pool. Dispute window ${(proof.rules.disputeWindow ?? 0) / 3600} h.`);
246
+ if (proof.rules.minBet) lines.push(`Minimum bet ${eth(proof.rules.minBet)}. Fee ${(proof.rules.rakeBps ?? 0) / 100}% of the losing pool. Dispute window ${windowLine(proof.rules)}.`);
242
247
  if (proof.activity) lines.push(`${proof.activity.opened} Calls opened, ${eth(proof.activity.staked)} staked, ${eth(proof.activity.paidOut)} paid out.`);
243
248
  if (proof.agents.length) lines.push(`Shipped agents: ${proof.agents.map((a) => a.name).join(", ")}.`);
244
249
  return { json: proof, lines };
package/src/client.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { formatEther, getAddress, isAddress, parseEventLogs, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
1
+ import { formatEther, getAddress, isAddress, parseEventLogs, stringToHex, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
2
2
  import { privateKeyToAccount } from "viem/accounts";
3
- import { callAbi, factoryAbi } from "./abi.js";
3
+ import { callAbi, factoryAbi, roundsAbi } from "./abi.js";
4
4
  import { hashJson } from "./canonical.js";
5
- import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, rpcEndpoints } from "./chain.js";
5
+ import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, rpcEndpoints } from "./chain.js";
6
6
  import { CallsError, describe } from "./errors.js";
7
7
  import { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
8
- import { MIN_BET, MIN_OPENER_BOND, odds, quoteOf, type Side } from "./odds.js";
9
- import type { CallDetail, CallRow, CallStatus, CallType, Leaderboard, OpenInput, Opened, Player, Positions, Prepared, Proof, Quote, RecentBet, Settlement, ShippedAgent, Stored, TapeItem, Tx } from "./types.js";
8
+ import { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, odds, quoteOf, type Side } from "./odds.js";
9
+ import type { CallDetail, CallRow, CallStatus, CallType, Leaderboard, Opened, OpenInput, Player, Positions, Prepared, Proof, Quote, RecentBet, RoundsAccount, RoundsFloor, RoundSide, RoundsMarket, Settlement, ShippedAgent, Stored, TapeItem, Tx } from "./types.js";
10
10
 
11
11
  export interface ClientOptions {
12
12
  /** The API's origin. https://calls.shipped.bond by default. */
@@ -20,6 +20,8 @@ export interface ClientOptions {
20
20
  maxStake?: bigint;
21
21
  chainId?: number;
22
22
  factory?: Address;
23
+ /** Earlier factories whose Calls this client still treats as Calls. The published ones unless `factory` is set. */
24
+ previousFactories?: readonly Address[];
23
25
  fetch?: typeof fetch;
24
26
  /** A viem transport in place of `rpc`. */
25
27
  transport?: Transport;
@@ -50,6 +52,22 @@ const deedsCoreAbi = [
50
52
  ] as const;
51
53
  const BOND_OPEN = 1;
52
54
 
55
+ export function roundSideOf(side: unknown): RoundSide {
56
+ const name = String(side).toLowerCase();
57
+ if (name === "up" || name === "down") return name;
58
+ throw new CallsError("Pick a side: up or down.", "bad_side");
59
+ }
60
+
61
+ function marketOf(market: unknown): string {
62
+ const name = String(market).toUpperCase();
63
+ if (!/^[A-Z0-9]{2,8}$/.test(name)) throw new CallsError("A market is a symbol such as ETH.", "bad_market");
64
+ return name;
65
+ }
66
+
67
+ const marketId = (market: string) => stringToHex(market, { size: 32 });
68
+ /** One transaction collects at most this many rounds; the rest wait for the next claim. */
69
+ const CLAIM_BATCH = 40;
70
+
53
71
  export function sideOf(side: unknown): Side {
54
72
  const name = String(side).toLowerCase();
55
73
  if (name === "holds" || name === "1") return "holds";
@@ -122,6 +140,7 @@ export function prepareOpen(input: OpenInput, chainId = CHAIN_ID): Prepared {
122
140
  export function createClient(options: ClientOptions = {}) {
123
141
  const chainId = options.chainId ?? CHAIN_ID;
124
142
  const factory = options.factory ?? FACTORY;
143
+ const factories = [factory, ...(options.previousFactories ?? (options.factory ? [] : PREVIOUS_FACTORIES))];
125
144
  const origin = (options.api ?? API_URL).replace(/\/$/, "");
126
145
  const account = options.account ?? (options.privateKey ? accountFromKey(options.privateKey) : undefined);
127
146
  const { reads, writes } = clientsFor({ chainId, urls: rpcEndpoints(options.rpc), account, transport: options.transport });
@@ -152,7 +171,7 @@ export function createClient(options: ClientOptions = {}) {
152
171
  }
153
172
  }
154
173
 
155
- const isCall = (address: Address) => read<boolean>(factory, factoryAbi as Abi, "isCall", [address]);
174
+ const isCall = async (address: Address) => (await Promise.all(factories.map((f) => read<boolean>(f, factoryAbi as Abi, "isCall", [address])))).some(Boolean);
156
175
 
157
176
  async function mustBeCall(value: unknown): Promise<Address> {
158
177
  const address = addressOf(value);
@@ -282,6 +301,17 @@ export function createClient(options: ClientOptions = {}) {
282
301
  isCall: (address: string) => guarded(() => isCall(addressOf(address))),
283
302
  pool: (address: string, side: Side | string) => guarded(() => callRead<bigint>(addressOf(address), "pool", [SIDE_CODE[sideOf(side)]])),
284
303
  status: (address: string) => guarded(async () => STATUS[await callRead<number>(addressOf(address), "status")]!),
304
+ /** Seconds this Call's result stays open to dispute after it settles. A Call of an earlier factory has no such read, and ran 24 hours. */
305
+ disputeWindow: (address: string) =>
306
+ guarded(async () => {
307
+ const call = addressOf(address);
308
+ try {
309
+ return Number(await callRead<bigint>(call, "disputeWindow"));
310
+ } catch (error) {
311
+ if ((describe(error) as CallsError).code === "rpc_unavailable") throw error;
312
+ return (await callRead<number>(call, "callType")) === 3 ? 0 : DISPUTE_WINDOW;
313
+ }
314
+ }),
285
315
  async odds(address: string) {
286
316
  const [holds, breaks] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks")]);
287
317
  return { pools: { holds, breaks }, ...odds({ holds, breaks }) };
@@ -299,12 +329,52 @@ export function createClient(options: ClientOptions = {}) {
299
329
  if (amount > cap) throw new CallsError(`${formatEther(amount)} ETH is over the ${formatEther(cap)} ETH limit on one bet. Raise the limit to place it.`, "over_max_stake");
300
330
  return guarded(async () => {
301
331
  const call = await mustBeCall(address);
332
+ // The API may be down; the chain still takes the bet, so its word only ever stops one.
333
+ const stored = await client.call(call).catch(() => null);
334
+ if (stored?.unresolvable) throw new CallsError(`Shipped can't settle this Call as written, so a stake here only comes back as a refund, from ${new Date(stored.unresolvable.refundsAt * 1000).toISOString()}. Nothing was sent.`, "unresolvable");
302
335
  const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "bet", args: [SIDE_CODE[name]], value: amount });
303
336
  const placed = eventOf<{ holdsPool: bigint; breaksPool: bigint }>(receipt, callAbi as Abi, "Bet");
304
337
  return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
305
338
  });
306
339
  },
307
340
 
341
+ /** Five minutes, up or down. The contract's address comes from the API, so a new deployment needs no new client. */
342
+ rounds: {
343
+ /** Every market's round taking bets, the round running and its latest results, in one read. */
344
+ markets: () => request<RoundsFloor>("/v1/rounds"),
345
+ state: (market: string) => request<RoundsMarket & { open: boolean }>(`/v1/rounds/${marketOf(market)}`),
346
+ /** A wallet's streak, today's stake and profit, what it can collect, its daily limit and its latest rounds. */
347
+ history: (who?: string) => guarded(() => request<RoundsAccount>(`/v1/accounts/${walletOr(who)}/rounds`)),
348
+
349
+ /** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while nothing is pricing rounds. */
350
+ async bet(market: string, side: RoundSide | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
351
+ const name = marketOf(market);
352
+ const chosen = roundSideOf(side);
353
+ if (amount > cap) throw new CallsError(`${formatEther(amount)} ETH is over the ${formatEther(cap)} ETH limit on one bet. Raise the limit to place it.`, "over_max_stake");
354
+ return guarded(async () => {
355
+ const floor = await request<RoundsFloor>("/v1/rounds");
356
+ if (!floor.markets.some((m) => m.market === name)) throw new CallsError(`Rounds has no ${name} market.`, "UnknownMarket");
357
+ if (!floor.open) throw new CallsError("Rounds aren't taking bets right now, so nothing was sent.", "rounds_closed");
358
+ const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "bet", args: [marketId(name), chosen === "up"], value: amount });
359
+ const placed = eventOf<{ epoch: bigint; upPool: bigint; downPool: bigint }>(receipt, roundsAbi as Abi, "Bet");
360
+ return { ...toTx(receipt, chainId), market: name, epoch: placed ? Number(placed.epoch) : null, side: chosen, amount: amount.toString(), pools: placed ? { up: placed.upPool.toString(), down: placed.downPool.toString() } : null };
361
+ });
362
+ },
363
+
364
+ /** Collects what this wallet is owed: every market, one market, or the epochs named. The money only ever goes to the wallet that sends this. */
365
+ claim: (market?: string, epochs?: readonly number[]) =>
366
+ guarded(async () => {
367
+ const only = market ? marketOf(market) : null;
368
+ const [floor, account] = await Promise.all([request<RoundsFloor>("/v1/rounds"), request<RoundsAccount>(`/v1/accounts/${wallet().address}/rounds`)]);
369
+ const owed = account.unclaimed.filter((o) => (!only || o.market === only) && (!epochs || epochs.includes(o.epoch)));
370
+ if (!owed.length) throw new CallsError("Nothing to claim for this wallet.", "NothingToClaim");
371
+ const batch = owed.slice(0, CLAIM_BATCH);
372
+ const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "claim", args: [batch.map((o) => marketId(o.market)), batch.map((o) => BigInt(o.epoch))] });
373
+ const paid = parseEventLogs({ abi: roundsAbi as Abi, logs: receipt.logs, eventName: "Claimed" } as never) as unknown as { args: { amount: bigint } }[];
374
+ return { ...toTx(receipt, chainId), rounds: batch.length, left: owed.length - batch.length, amount: paid.reduce((sum, log) => sum + log.args.amount, 0n).toString() };
375
+ }),
376
+ },
377
+
308
378
  /** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
309
379
  claim: (address: string) =>
310
380
  guarded(async () => {
package/src/errors.ts CHANGED
@@ -33,6 +33,13 @@ const REVERTS: Record<string, string> = {
33
33
  IsDeedCall: "A Call on a bond settles from the bond's ruling.",
34
34
  TransferFailed: "The payment could not be delivered to that address.",
35
35
  InsufficientBalance: NOT_ENOUGH_ETH,
36
+ TooLate: "Betting has closed on this round. The next one is open.",
37
+ BelowMinimum: "The minimum bet is 0.001 ETH.",
38
+ OverStakeCap: "One wallet can stake up to 0.5 ETH in a round.",
39
+ OverDailyLimit: "This would take the wallet past the daily limit it set for itself.",
40
+ OtherSide: "This wallet is already on the other side of this round.",
41
+ MarketPaused: "This market isn't taking bets right now.",
42
+ UnknownMarket: "Rounds has no such market.",
36
43
  };
37
44
 
38
45
  /** One sentence for a failed read or write. RPC URLs can carry keys, so nothing from the transport is passed on. */
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { createClient, accountFromKey, bondIdOf, prepareOpen, sideOf, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, type CallsClient, type ClientOptions } from "./client.js";
2
- export { API_URL, CALLED_IT, CHAIN_ID, DEEDS, EXPLORER, FACTORY, RPC_URLS, rpcEndpoints } from "./chain.js";
3
- export { callAbi, calledItAbi, factoryAbi } from "./abi.js";
1
+ export { createClient, accountFromKey, bondIdOf, prepareOpen, roundSideOf, sideOf, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, type CallsClient, type ClientOptions } from "./client.js";
2
+ export { API_URL, CALLED_IT, CHAIN_ID, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints } from "./chain.js";
3
+ export { callAbi, calledItAbi, factoryAbi, roundsAbi } from "./abi.js";
4
4
  export { canonical, hashJson } from "./canonical.js";
5
5
  export { CallsError } from "./errors.js";
6
6
  export { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
7
- export { MIN_BET, MIN_OPENER_BOND, RAKE_BPS, ethToWei, multipleOf, odds, payout, quoteOf, type Pools, type Side } from "./odds.js";
7
+ export { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, PRICE_DISPUTE_WINDOW, RAKE_BPS, ethToWei, multipleOf, odds, payout, quoteOf, type Pools, type Side } from "./odds.js";
8
8
  export type * from "./types.js";
package/src/odds.ts CHANGED
@@ -4,6 +4,9 @@ import { CallsError } from "./errors.js";
4
4
  export const RAKE_BPS = 400n;
5
5
  export const MIN_BET = 10n ** 15n;
6
6
  export const MIN_OPENER_BOND = 2n * 10n ** 16n;
7
+ /** Seconds. A Price Call has `PRICE_DISPUTE_WINDOW`; a bond Call has none. Every Call of an earlier factory has this one. */
8
+ export const DISPUTE_WINDOW = 24 * 3600;
9
+ export const PRICE_DISPUTE_WINDOW = 3600;
7
10
 
8
11
  const ETH_AMOUNT = /^\d+(\.\d{1,18})?$|^\.\d{1,18}$/;
9
12
 
package/src/types.ts CHANGED
@@ -45,6 +45,10 @@ export interface CallSummary {
45
45
  settledAt: number | null;
46
46
  finalizedAt: number | null;
47
47
  voidedAt: number | null;
48
+ /** Seconds after the settle in which anyone can dispute: 3600 on a Price Call, 86400 on a Post or contract-read Call and on every Call of an earlier factory, 0 on a bond Call. */
49
+ disputeWindow: number;
50
+ /** When this Call's window closes. Null until it settles, and on a bond Call. */
51
+ disputeEndsAt: number | null;
48
52
  }
49
53
 
50
54
  export interface CallRow extends CallSummary {
@@ -89,7 +93,7 @@ export interface CallDetail extends CallSummary {
89
93
  openedTx: Hash;
90
94
  unresolvable: { reason: string; refundsAt: number } | null;
91
95
  bets: Bet[];
92
- records: { tokenId: number; account: Address; txHash: Hash; block: number; at: number }[] | null;
96
+ records: { tokenId: number; account: Address; collection: Address | null; txHash: Hash; block: number; at: number }[] | null;
93
97
  }
94
98
 
95
99
  export interface RecentBet {
@@ -171,6 +175,7 @@ export interface Proof {
171
175
  chain: { id: number; name: string; explorerUrl: string | null; reachable: boolean };
172
176
  factory: { address: Address | null; fromBlock: number | null };
173
177
  calledIt: Address | null;
178
+ previousFactories: { address: Address; fromBlock: number; calledIt: Address | null }[];
174
179
  planned: boolean;
175
180
  contracts: { name: string; address: Address; code: boolean | null; sourcify: string | null; sourceUrl: string | null; explorerUrl: string | null }[];
176
181
  roles: Record<"resolver" | "court" | "treasury" | "pendingCourt", ({ address: Address; kind: string | null; explorerUrl: string | null } & Record<string, unknown>) | null> | null;
@@ -182,6 +187,7 @@ export interface Proof {
182
187
  openerBps: number | null;
183
188
  treasuryBps: number | null;
184
189
  disputeWindow: number | null;
190
+ priceDisputeWindow: number | null;
185
191
  resolverTimeout: number | null;
186
192
  courtTimeout: number | null;
187
193
  maxTerm: number | null;
@@ -297,3 +303,75 @@ export interface Positions {
297
303
  week: Player["week"];
298
304
  all: Player["all"];
299
305
  }
306
+
307
+ export type RoundOutcome = "up" | "down" | "refunded";
308
+ export type RoundSide = "up" | "down";
309
+
310
+ export interface RoundPools {
311
+ epoch: number;
312
+ lockAt: number;
313
+ closeAt: number;
314
+ up: Wei;
315
+ down: Wei;
316
+ bets: number;
317
+ /** What a winning stake pays per unit at these pools, floored to hundredths; null while either side is empty. */
318
+ upPays: number | null;
319
+ downPays: number | null;
320
+ }
321
+
322
+ export interface RoundResult {
323
+ market: string;
324
+ epoch: number;
325
+ outcome: RoundOutcome;
326
+ lockPrice: string | null;
327
+ closePrice: string | null;
328
+ up: Wei;
329
+ down: Wei;
330
+ pool: Wei;
331
+ rake: Wei;
332
+ pays: number | null;
333
+ decidedAt: number;
334
+ lockAt: number;
335
+ closeAt: number;
336
+ /** The public candles anyone can open to check the two prices. */
337
+ candles: { lock: string; close: string };
338
+ txHash: Hash;
339
+ }
340
+
341
+ export interface RoundsMarket {
342
+ market: string;
343
+ symbol: string;
344
+ price: string | null;
345
+ betting: RoundPools & { opensAt: number; cutoffAt: number };
346
+ running: RoundPools & { lockPrice: string | null };
347
+ last: RoundResult[];
348
+ }
349
+
350
+ export interface RoundsFloor {
351
+ now: number;
352
+ /** False while nothing is pricing rounds. A bet then would wait out the hour and refund, so the client refuses it. */
353
+ open: boolean;
354
+ contract: Address;
355
+ interval: number;
356
+ cutoff: number;
357
+ minBet: Wei;
358
+ maxStake: Wei;
359
+ rakeBps: number;
360
+ markets: RoundsMarket[];
361
+ feed: { market: string; epoch: number; wallet: Address; agent: string | null; up: boolean; amount: Wei; at: number; txHash: Hash }[];
362
+ }
363
+
364
+ export interface RoundsAccount {
365
+ wallet: Address;
366
+ streak: { current: number; best: number };
367
+ profitToday: Wei;
368
+ stakedToday: Wei;
369
+ played: number;
370
+ wins: number;
371
+ losses: number;
372
+ unclaimed: { market: string; epoch: number; amount: Wei }[];
373
+ unclaimedTotal: Wei;
374
+ rounds: { market: string; epoch: number; up: boolean; stake: Wei; outcome: RoundOutcome | null; payout: Wei | null; underdog: boolean; lockAt: number; closeAt: number }[];
375
+ /** The daily cap this wallet set for itself on chain, or null when no endpoint answered. */
376
+ limit: { cap: Wei; pendingCap: Wei; pendingAt: number; spentToday: Wei } | null;
377
+ }