@shippedcalls/sdk 0.3.1 → 0.5.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/client.ts CHANGED
@@ -1,12 +1,14 @@
1
- import { formatEther, getAddress, isAddress, parseEventLogs, stringToHex, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
1
+ import { erc20Abi, 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, roundsAbi } from "./abi.js";
3
+ import { callAbi, factoryAbi, roundsAbi, tokenCallAbi, tokenFactoryAbi } from "./abi.js";
4
+ import { approvalFor, assetSymbolOf, DEFAULT_MAX_STAKE_USDG, ETH_ASSET, formatAmount, USDG_ASSET, USDG_MIN_BET, type Asset, type AssetSymbol } from "./assets.js";
4
5
  import { hashJson } from "./canonical.js";
5
- import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, rpcEndpoints } from "./chain.js";
6
+ import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, rpcEndpoints, USDG_FACTORY } from "./chain.js";
6
7
  import { CallsError, describe, RECEIPT_UNKNOWN, revertLine } from "./errors.js";
7
8
  import { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
8
9
  import { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, multipleOf, odds, quoteOf, roundInPlay, roundPayout, 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
+ import { createJobs, DEFAULT_MAX_JOB_FUND } from "./jobs.js";
11
+ import type { Approval, BonusQuote, 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
12
 
11
13
  export interface ClientOptions {
12
14
  /** The API's origin. https://calls.shipped.bond by default. */
@@ -16,12 +18,18 @@ export interface ClientOptions {
16
18
  /** A private key, or `account` for any viem account. Reads need neither. */
17
19
  privateKey?: string;
18
20
  account?: Account;
19
- /** The most one bet may stake, wei. 0.01 ETH by default. */
21
+ /** The most one bet may stake on an ETH Call, wei. 0.01 ETH by default. */
20
22
  maxStake?: bigint;
23
+ /** The most one bet or bonus may put into a USDG Call, USDG units. 10 USDG by default. */
24
+ maxStakeUsdg?: bigint;
25
+ /** The most one job call may lock, USDG units. 25 USDG by default. */
26
+ maxJobFund?: bigint;
21
27
  chainId?: number;
22
28
  factory?: Address;
23
29
  /** Earlier factories whose Calls this client still treats as Calls. The published ones unless `factory` is set. */
24
30
  previousFactories?: readonly Address[];
31
+ /** The factory USDG Calls open on. The published one unless `factory` is set; null leaves USDG Calls out. */
32
+ usdgFactory?: Address | null;
25
33
  fetch?: typeof fetch;
26
34
  /** A viem transport in place of `rpc`. */
27
35
  transport?: Transport;
@@ -30,6 +38,19 @@ export interface ClientOptions {
30
38
  export const DEFAULT_MAX_STAKE = 10n ** 16n;
31
39
  export const DEFAULT_MAX_BOND = MIN_OPENER_BOND;
32
40
 
41
+ /** A Call as the chain knows it: its address, what it is staked in and the factory that made it. */
42
+ interface Target {
43
+ address: Address;
44
+ asset: Asset;
45
+ factory: Address;
46
+ }
47
+
48
+ // The factory's own errors, then the Call's that a call through the factory can revert with.
49
+ const tokenFactoryErrors = [...(tokenFactoryAbi as Abi), ...(tokenCallAbi as Abi).filter((item) => item.type === "error" && !(tokenFactoryAbi as Abi).some((own) => own.type === "error" && own.name === item.name))];
50
+
51
+ /** An older API answers without `asset` and `bonus`: its Calls are all ETH. */
52
+ const withAsset = <T extends object>(c: T) => ({ ...c, asset: (c as { asset?: Asset }).asset ?? ETH_ASSET, bonus: (c as { bonus?: string }).bonus ?? "0" }) as T & { asset: Asset; bonus: string };
53
+
33
54
  const STATUS: readonly CallStatus[] = ["open", "settled", "disputed", "final", "voided"];
34
55
  const TYPES: readonly CallType[] = ["posted", "onchain", "price", "deed"];
35
56
  const SIDE_CODE = { holds: 1, breaks: 2 } as const;
@@ -146,6 +167,8 @@ export function createClient(options: ClientOptions = {}) {
146
167
  const { reads, writes } = clientsFor({ chainId, urls: rpcEndpoints(options.rpc), account, transport: options.transport });
147
168
  const doFetch = options.fetch ?? globalThis.fetch;
148
169
  const maxStake = options.maxStake ?? DEFAULT_MAX_STAKE;
170
+ const maxStakeUsdg = options.maxStakeUsdg ?? DEFAULT_MAX_STAKE_USDG;
171
+ const usdgFactory = options.usdgFactory === undefined ? (options.factory ? null : USDG_FACTORY) : options.usdgFactory ? addressOf(options.usdgFactory, "factory") : null;
149
172
  let chainChecked = false;
150
173
 
151
174
  async function request<T>(path: string, init?: RequestInit): Promise<T> {
@@ -163,22 +186,52 @@ export function createClient(options: ClientOptions = {}) {
163
186
  const read = <T>(address: Address, abi: Abi, functionName: string, args: unknown[] = []) => reads.readContract({ address, abi, functionName, args } as never) as Promise<T>;
164
187
  const callRead = <T>(address: Address, functionName: string, args: unknown[] = []) => read<T>(address, callAbi as Abi, functionName, args);
165
188
 
166
- async function guarded<T>(work: () => Promise<T>): Promise<T> {
189
+ async function guarded<T>(work: () => Promise<T>, asset: AssetSymbol = "ETH"): Promise<T> {
167
190
  try {
168
191
  return await work();
169
192
  } catch (error) {
170
- throw describe(error);
193
+ throw describe(error, asset);
171
194
  }
172
195
  }
173
196
 
174
- const isCall = async (address: Address) => (await Promise.all(factories.map((f) => read<boolean>(f, factoryAbi as Abi, "isCall", [address])))).some(Boolean);
197
+ // The token is the factory's to name, so a rehearsal on another chain reads its own.
198
+ let usdgAsset: Promise<Asset> | null = null;
199
+ const usdg = () =>
200
+ (usdgAsset ??= usdgFactory
201
+ ? read<Address>(usdgFactory, tokenFactoryAbi as Abi, "asset").then(
202
+ (address) => ({ ...USDG_ASSET, address: getAddress(address) }),
203
+ (error) => {
204
+ usdgAsset = null;
205
+ throw error;
206
+ },
207
+ )
208
+ : Promise.resolve(USDG_ASSET));
209
+
210
+ async function factoryOf(address: Address): Promise<{ factory: Address; usdg: boolean } | null> {
211
+ const [eth, token] = await Promise.all([
212
+ Promise.all(factories.map((f) => read<boolean>(f, factoryAbi as Abi, "isCall", [address]))),
213
+ usdgFactory ? read<boolean>(usdgFactory, tokenFactoryAbi as Abi, "isCall", [address]) : false,
214
+ ]);
215
+ const index = eth.findIndex(Boolean);
216
+ if (index >= 0) return { factory: factories[index]!, usdg: false };
217
+ return token ? { factory: usdgFactory!, usdg: true } : null;
218
+ }
219
+
220
+ const isCall = async (address: Address) => (await factoryOf(address)) !== null;
175
221
 
176
- async function mustBeCall(value: unknown): Promise<Address> {
222
+ /** Only a Call one of the factories made gets money: the factory's word is the check, never the address's own. */
223
+ async function callOf(value: unknown): Promise<Target> {
177
224
  const address = addressOf(value);
178
- if (!(await isCall(address))) throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
179
- return address;
225
+ const made = await factoryOf(address);
226
+ if (made) return { address, asset: made.usdg ? await usdg() : ETH_ASSET, factory: made.factory };
227
+ if (!usdgFactory && (await client.call(address).catch(() => null))?.asset.symbol === "USDG") {
228
+ throw new CallsError("This is a USDG Call, and this client knows no USDG factory to check it against, so nothing was sent. Set CALLS_USDG_FACTORY, or `usdgFactory` in code.", "usdg_unknown");
229
+ }
230
+ throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
180
231
  }
181
232
 
233
+ const abiOf = (target: Target) => (target.asset.symbol === "ETH" ? callAbi : tokenCallAbi) as Abi;
234
+
182
235
  function wallet(): Account {
183
236
  if (!account) throw new CallsError("Set a wallet to send this: CALLS_PRIVATE_KEY, or `privateKey` or `account` in code.", "no_wallet");
184
237
  return account;
@@ -219,6 +272,57 @@ export function createClient(options: ClientOptions = {}) {
219
272
  return amount;
220
273
  };
221
274
 
275
+ async function approvalOf(token: Address, spender: Address, owner: Address, amount: bigint): Promise<Approval> {
276
+ const [balance, allowance] = await Promise.all([
277
+ read<bigint>(token, erc20Abi as Abi, "balanceOf", [owner]),
278
+ read<bigint>(token, erc20Abi as Abi, "allowance", [owner, spender]),
279
+ ]);
280
+ const { approve, short } = approvalFor(balance, allowance, amount);
281
+ return { token, spender, owner, balance: balance.toString(), allowance: allowance.toString(), amount: amount.toString(), approve: approve?.toString() ?? null, short: short.toString() };
282
+ }
283
+
284
+ /**
285
+ * A USDG write pulls what it names, so the spender needs the allowance first: approves exactly `amount` when short,
286
+ * as its own transaction, then sends `write`. A failure after the approval says the approval went through.
287
+ */
288
+ async function withApproval(asset: Asset, spender: Address, amount: bigint, then: string, write: () => Promise<TransactionReceipt>) {
289
+ const approval = await approvalOf(asset.address!, spender, wallet().address, amount);
290
+ if (approval.short !== "0") throw new CallsError(`This wallet holds ${formatAmount(approval.balance, asset)}, and this ${then} needs ${formatAmount(amount, asset)}. Nothing was sent.`, "insufficient_usdg");
291
+ let approved: Tx | null = null;
292
+ if (approval.approve) {
293
+ try {
294
+ approved = toTx(await send({ address: asset.address!, abi: erc20Abi as Abi, functionName: "approve", args: [spender, amount] }), chainId);
295
+ } catch (error) {
296
+ const known = describe(error, "USDG");
297
+ throw known.code === RECEIPT_UNKNOWN ? new CallsError(`${known.message} It was the approval, so the ${then} was not sent.`, RECEIPT_UNKNOWN) : known;
298
+ }
299
+ }
300
+ try {
301
+ return { receipt: await write(), approval: approved };
302
+ } catch (error) {
303
+ if (!approved) throw error;
304
+ const known = describe(error, "USDG");
305
+ throw new CallsError(`${known.message} It came after an approval of ${formatAmount(amount, asset)}, which went through: ${approved.explorerUrl ?? approved.hash}.`, known.code, known.status);
306
+ }
307
+ }
308
+
309
+ async function refuseUnresolvable(call: Address) {
310
+ // The API may be down; the chain still takes the bet, so its word only ever stops one.
311
+ const stored = await client.call(call).catch(() => null);
312
+ 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");
313
+ }
314
+
315
+ // USDG moves before the Call checks anything, and an approval costs gas, so a write that would fail stops here.
316
+ async function intoUsdgCall(target: Target, amount: bigint, cap: bigint, what: "bet" | "bonus", args: unknown[]) {
317
+ if (amount > cap) throw new CallsError(`${formatAmount(amount, target.asset)} is over the ${formatAmount(cap, target.asset)} limit on one ${what}. Raise the limit to ${what === "bet" ? "place" : "add"} it.`, "over_max_stake");
318
+ if (what === "bet" && amount < USDG_MIN_BET) throw new CallsError("The minimum bet is 1 USDG.", "BetTooSmall");
319
+ wallet();
320
+ await refuseUnresolvable(target.address);
321
+ const [status, closeAt, block] = await Promise.all([callRead<number>(target.address, "status"), callRead<bigint>(target.address, "closeAt"), reads.getBlock({ blockTag: "latest" })]);
322
+ if (status !== 0 || block.timestamp >= closeAt) throw new CallsError(what === "bet" ? "Betting has closed on this Call." : "Betting has closed on this Call, and with it the bonus pot.", "BettingClosed");
323
+ return withApproval(target.asset, target.factory, amount, what, () => send({ address: target.factory, abi: tokenFactoryErrors, functionName: what === "bet" ? "bet" : "addBonus", args }));
324
+ }
325
+
222
326
  const roundState = (market: string) => {
223
327
  const name = marketOf(market);
224
328
  return request<RoundsMarket & { open: boolean }>(`/v1/rounds/${name}`).catch((error: CallsError) => {
@@ -229,26 +333,31 @@ export function createClient(options: ClientOptions = {}) {
229
333
  const eventOf = <T>(receipt: TransactionReceipt, abi: Abi, eventName: string) => (parseEventLogs({ abi, logs: receipt.logs, eventName } as never) as unknown as { args: T }[])[0]?.args;
230
334
 
231
335
  async function chainQuote(address: Address, side: Side, amount: bigint): Promise<Quote> {
232
- const [member, status, closeAt, holds, breaks, block] = await Promise.all([
233
- isCall(address),
336
+ const target = await callOf(address);
337
+ const isUsdg = target.asset.symbol === "USDG";
338
+ const minBet = isUsdg ? USDG_MIN_BET : MIN_BET;
339
+ if (amount < minBet) throw new CallsError(`The minimum bet is ${formatAmount(minBet, target.asset)}.`, "BetTooSmall");
340
+ const [status, closeAt, holds, breaks, bonus, block] = await Promise.all([
234
341
  callRead<number>(address, "status").catch(() => null),
235
342
  callRead<bigint>(address, "closeAt").catch(() => null),
236
343
  callRead<bigint>(address, "pool", [1]).catch(() => null),
237
344
  callRead<bigint>(address, "pool", [2]).catch(() => null),
345
+ isUsdg ? read<bigint>(address, tokenCallAbi as Abi, "bonus").catch(() => null) : 0n,
238
346
  reads.getBlock({ blockTag: "latest" }),
239
347
  ]);
240
- if (!member) throw new CallsError("That address is not a Call of the Shipped Calls factory.", "not_a_call");
241
- if (status == null || closeAt == null || holds == null || breaks == null) throw new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
348
+ if (status == null || closeAt == null || holds == null || breaks == null || bonus == null) throw new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
242
349
  const pools = { holds, breaks };
243
- const q = quoteOf(pools, side, amount);
350
+ const q = quoteOf(pools, side, amount, bonus);
244
351
  return {
245
352
  call: address,
246
353
  side,
247
354
  amount: amount.toString(),
355
+ asset: target.asset,
356
+ bonus: bonus.toString(),
248
357
  status: STATUS[status]!,
249
358
  bettingOpen: status === 0 && block.timestamp < closeAt,
250
359
  closeAt: Number(closeAt),
251
- minBet: MIN_BET.toString(),
360
+ minBet: minBet.toString(),
252
361
  pools: { holds: holds.toString(), breaks: breaks.toString() },
253
362
  poolsAfter: { holds: q.poolsAfter.holds.toString(), breaks: q.poolsAfter.breaks.toString() },
254
363
  impliedBps: q.impliedBps,
@@ -266,23 +375,35 @@ export function createClient(options: ClientOptions = {}) {
266
375
  address: account?.address ?? null,
267
376
  chainId,
268
377
  factory,
378
+ /** The factory USDG Calls open on, or null when this client knows none. */
379
+ usdgFactory,
380
+
381
+ /** Hold payment until the work is accepted: the worker opens a job, the client funds it, a named reviewer releases it. */
382
+ jobs: createJobs({ reads, chainId, send, guarded, wallet, toTx: (receipt) => toTx(receipt, chainId), maxFund: options.maxJobFund ?? DEFAULT_MAX_JOB_FUND }),
269
383
 
270
384
  // Reads from the API. It follows the chain by up to a minute; the chain reads below do not.
271
385
 
272
- async calls(filters: { status?: CallStatus; type?: CallType; subject?: string; sort?: "closing" | "lopsided" | "pot" | "newest"; limit?: number; offset?: number } = {}): Promise<CallRow[]> {
273
- return (await request<{ calls: CallRow[] }>(`/v1/calls${query(filters)}`)).calls;
386
+ /** Every asset by default; `asset` keeps to Calls staked in one. */
387
+ async calls(filters: { status?: CallStatus; type?: CallType; subject?: string; asset?: AssetSymbol; sort?: "closing" | "lopsided" | "pot" | "newest"; limit?: number; offset?: number } = {}): Promise<CallRow[]> {
388
+ const asset = filters.asset && assetSymbolOf(filters.asset);
389
+ return (await request<{ calls: CallRow[] }>(`/v1/calls${query({ ...filters, asset })}`)).calls.map(withAsset);
390
+ },
391
+ call: async (address: string): Promise<CallDetail> => {
392
+ const call = await request<CallDetail>(`/v1/calls/${addressOf(address)}`);
393
+ return { ...withAsset(call), bonuses: call.bonuses ?? [] };
274
394
  },
275
- call: async (address: string) => request<CallDetail>(`/v1/calls/${addressOf(address)}`),
276
395
  /** The latest bets across every Call, or every bet on one Call with `call`. */
277
396
  async bets({ call, limit }: { call?: string; limit?: number } = {}): Promise<RecentBet[] | CallDetail["bets"]> {
278
397
  if (call) return (await client.call(call)).bets;
279
398
  return (await request<{ bets: RecentBet[] }>(`/v1/bets/recent${query({ limit })}`)).bets;
280
399
  },
281
- async tape({ limit }: { limit?: number } = {}): Promise<TapeItem[]> {
282
- return (await request<{ items: TapeItem[] }>(`/v1/tape${query({ limit })}`)).items;
400
+ // The tape, boards and players count one asset at a time, ETH unless `asset` asks for USDG.
401
+ async tape({ limit, asset }: { limit?: number; asset?: AssetSymbol } = {}): Promise<TapeItem[]> {
402
+ return (await request<{ items: TapeItem[] }>(`/v1/tape${query({ limit, asset: asset && assetSymbolOf(asset) })}`)).items;
283
403
  },
284
- leaderboard: (filters: { window?: "week" | "all"; board?: "profit" | "best" | "streak" | "openers"; limit?: number; me?: string } = {}) => request<Leaderboard>(`/v1/leaderboard${query(filters)}`),
285
- player: async (address?: string) => request<Player>(`/v1/players/${walletOr(address)}`),
404
+ leaderboard: (filters: { window?: "week" | "all"; board?: "profit" | "best" | "streak" | "openers"; limit?: number; me?: string; asset?: AssetSymbol } = {}) =>
405
+ request<Leaderboard>(`/v1/leaderboard${query({ ...filters, asset: filters.asset && assetSymbolOf(filters.asset) })}`),
406
+ player: async (address?: string, { asset }: { asset?: AssetSymbol } = {}) => request<Player>(`/v1/players/${walletOr(address)}${query({ asset: asset && assetSymbolOf(asset) })}`),
286
407
  /** Shipped agents: name, rule and wallet. */
287
408
  async agents(): Promise<ShippedAgent[]> {
288
409
  return (await request<{ agents: ShippedAgent[] }>("/v1/agents")).agents;
@@ -290,29 +411,52 @@ export function createClient(options: ClientOptions = {}) {
290
411
  proof: () => request<Proof>("/v1/proof"),
291
412
 
292
413
  /**
293
- * What `amount` wei on `side` pays with the pools as they stand. Reads the pools from the chain, and from the API if
294
- * no endpoint answers. Later bets move the payout until betting closes.
414
+ * What `amount` on `side` pays with the pools as they stand, in base units of the Call's asset, its share of any
415
+ * bonus included. Reads the pools from the chain, and from the API if no endpoint answers. Later bets move the
416
+ * payout until betting closes.
295
417
  */
296
418
  async quote(address: string, side: Side | string, amount: bigint): Promise<Quote> {
297
419
  const call = addressOf(address);
298
420
  const name = sideOf(side);
299
- if (amount < MIN_BET) throw new CallsError("The minimum bet is 0.001 ETH.", "BetTooSmall");
300
421
  try {
301
422
  return await chainQuote(call, name, amount);
302
423
  } catch (error) {
303
424
  if (error instanceof CallsError && error.code !== "rpc_unavailable") throw error;
304
- return request<Quote>(`/v1/calls/${call}/quote${query({ side: name, amount })}`);
425
+ return withAsset(await request<Quote>(`/v1/calls/${call}/quote${query({ side: name, amount })}`));
426
+ }
427
+ },
428
+
429
+ /** What a Call is staked in, from the chain, or from the API if no endpoint answers. */
430
+ async assetOf(address: string): Promise<Asset> {
431
+ const call = addressOf(address);
432
+ try {
433
+ return (await callOf(call)).asset;
434
+ } catch (error) {
435
+ if (error instanceof CallsError) throw error;
436
+ return (await client.call(call).catch(() => {
437
+ throw describe(error);
438
+ })).asset;
305
439
  }
306
440
  },
307
441
 
308
- /** One wallet's open positions and settled Calls from the API, with its balance and what it can claim from the chain. */
309
- async positions(address?: string): Promise<Positions> {
442
+ /**
443
+ * One wallet's open positions and settled Calls in one asset, ETH unless `asset` asks for USDG, from the API, with
444
+ * its balance and what it can claim from the chain. `gas` is its ETH, which pays the gas either way.
445
+ */
446
+ async positions(address?: string, { asset = "ETH" }: { asset?: AssetSymbol } = {}): Promise<Positions> {
310
447
  const who = walletOr(address);
311
- const [player, balance] = await Promise.all([client.player(who), reads.getBalance({ address: who }).catch(() => null)]);
448
+ const symbol = assetSymbolOf(asset);
449
+ const unit = symbol === "ETH" ? ETH_ASSET : await usdg().catch(() => USDG_ASSET);
450
+ const [player, gas, tokens] = await Promise.all([
451
+ client.player(who, symbol === "ETH" ? {} : { asset: symbol }),
452
+ reads.getBalance({ address: who }).catch(() => null),
453
+ unit.address ? read<bigint>(unit.address, erc20Abi as Abi, "balanceOf", [who]).catch(() => null) : null,
454
+ ]);
312
455
  const settled = await Promise.all(
313
456
  player.shelf.slice(0, SHELF_READS).map(async (row) => ({ ...row, owed: await client.payoutOf(row.call, who).then(String, () => null) })),
314
457
  );
315
- return { address: who, balance: balance == null ? null : balance.toString(), positions: player.positions, settled, week: player.week, all: player.all };
458
+ const balance = unit.address ? tokens : gas;
459
+ return { address: who, asset: unit, balance: balance == null ? null : balance.toString(), gas: gas == null ? null : gas.toString(), positions: player.positions, settled, week: player.week, all: player.all };
316
460
  },
317
461
 
318
462
  // Reads from the chain, current to the block.
@@ -331,32 +475,102 @@ export function createClient(options: ClientOptions = {}) {
331
475
  return (await callRead<number>(call, "callType")) === 3 ? 0 : DISPUTE_WINDOW;
332
476
  }
333
477
  }),
478
+ /** The bonus pot sponsors added to a USDG Call, USDG units. 0 on an ETH Call, which has none. */
479
+ bonus: (address: string) =>
480
+ guarded(async () => {
481
+ const target = await callOf(address);
482
+ return target.asset.symbol === "USDG" ? read<bigint>(target.address, tokenCallAbi as Abi, "bonus") : 0n;
483
+ }),
334
484
  async odds(address: string) {
335
- const [holds, breaks] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks")]);
336
- return { pools: { holds, breaks }, ...odds({ holds, breaks }) };
485
+ const [holds, breaks, bonus] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks"), client.bonus(address)]);
486
+ return { pools: { holds, breaks }, bonus, ...odds({ holds, breaks }, bonus) };
337
487
  },
338
488
  payoutOf: (address: string, who?: string) => guarded(() => callRead<bigint>(addressOf(address), "payoutOf", [walletOr(who)])),
339
489
  stake: (address: string, side: Side | string, who?: string) => guarded(() => callRead<bigint>(addressOf(address), "stake", [walletOr(who), SIDE_CODE[sideOf(side)]])),
340
490
  balance: (who?: string) => guarded(() => reads.getBalance({ address: walletOr(who) })),
341
491
 
342
492
  /**
343
- * Stakes `amount` wei on `side`. Refuses an amount over `maxStake` and an address that is not one of the factory's
344
- * Calls before anything goes out; simulates first, so a bet the contract would refuse costs nothing.
493
+ * Stakes `amount` on `side`, in base units of the Call's asset. Refuses an address that is not a Call of one of the
494
+ * factories, and an amount over the cap for its asset (`maxStake` in wei on an ETH Call, `maxStakeUsdg` in USDG
495
+ * units on a USDG Call), before anything goes out. A USDG bet goes through the USDG factory, and when the factory's
496
+ * allowance is short it first approves exactly `amount` in a transaction of its own, reported as `approval`. Every
497
+ * transaction simulates first, so one the contract would refuse costs nothing.
345
498
  */
346
- async bet(address: string, side: Side | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
499
+ async bet(address: string, side: Side | string, amount: bigint, { maxStake: cap = maxStake, maxStakeUsdg: usdgCap = maxStakeUsdg }: { maxStake?: bigint; maxStakeUsdg?: bigint } = {}) {
347
500
  const name = sideOf(side);
348
- 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");
501
+ const target = await guarded(() => callOf(address));
502
+ const { asset } = target;
503
+ const call = target.address;
349
504
  return guarded(async () => {
350
- const call = await mustBeCall(address);
351
- // The API may be down; the chain still takes the bet, so its word only ever stops one.
352
- const stored = await client.call(call).catch(() => null);
353
- 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");
505
+ if (asset.symbol === "USDG") {
506
+ const { receipt, approval } = await intoUsdgCall(target, amount, usdgCap, "bet", [call, SIDE_CODE[name], amount]);
507
+ const placed = eventOf<{ holdsPool: bigint; breaksPool: bigint }>(receipt, tokenCallAbi as Abi, "Bet");
508
+ return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), asset, approval, pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
509
+ }
510
+ 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");
511
+ await refuseUnresolvable(call);
354
512
  const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "bet", args: [SIDE_CODE[name]], value: amount });
355
513
  const placed = eventOf<{ holdsPool: bigint; breaksPool: bigint }>(receipt, callAbi as Abi, "Bet");
356
- return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
357
- });
514
+ return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), asset, approval: null, pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
515
+ }, asset.symbol);
516
+ },
517
+
518
+ /**
519
+ * What adding `amount` USDG units to a USDG Call's bonus pot does, with the pot as it stands. Winners share the pot
520
+ * by stake on top of the losing pool, with no fee on it; if the Call is voided or one side is empty, each sponsor
521
+ * takes back what they put in. Sends nothing.
522
+ */
523
+ bonusQuote: (address: string, amount: bigint): Promise<BonusQuote> =>
524
+ guarded(async () => {
525
+ if (typeof amount !== "bigint" || amount <= 0n) throw new CallsError("A bonus is USDG units, as a bigint above zero.", "bad_amount");
526
+ const target = await callOf(address);
527
+ if (target.asset.symbol !== "USDG") throw new CallsError("Bonus pots are on USDG Calls only, and this Call is staked in ETH.", "not_usdg");
528
+ const [status, closeAt, holds, breaks, bonus, sponsored, block] = await Promise.all([
529
+ callRead<number>(target.address, "status"),
530
+ callRead<bigint>(target.address, "closeAt"),
531
+ callRead<bigint>(target.address, "pool", [1]),
532
+ callRead<bigint>(target.address, "pool", [2]),
533
+ read<bigint>(target.address, tokenCallAbi as Abi, "bonus"),
534
+ account ? read<bigint>(target.address, tokenCallAbi as Abi, "bonusOf", [account.address]) : null,
535
+ reads.getBlock({ blockTag: "latest" }),
536
+ ]);
537
+ return {
538
+ call: target.address,
539
+ asset: target.asset,
540
+ amount: amount.toString(),
541
+ status: STATUS[status]!,
542
+ bettingOpen: status === 0 && block.timestamp < closeAt,
543
+ closeAt: Number(closeAt),
544
+ pools: { holds: holds.toString(), breaks: breaks.toString() },
545
+ bonus: bonus.toString(),
546
+ bonusAfter: (bonus + amount).toString(),
547
+ sponsored: sponsored == null ? null : sponsored.toString(),
548
+ };
549
+ }, "USDG"),
550
+
551
+ /**
552
+ * Adds `amount` USDG units to a USDG Call's bonus pot while betting is open, through the USDG factory, approving
553
+ * exactly `amount` first when the allowance is short. Counts against the same cap as a USDG bet. Adding to the pot
554
+ * buys no stake: to share in it, bet.
555
+ */
556
+ async addBonus(address: string, amount: bigint, { maxStakeUsdg: usdgCap = maxStakeUsdg }: { maxStakeUsdg?: bigint } = {}) {
557
+ if (typeof amount !== "bigint" || amount <= 0n) throw new CallsError("A bonus is USDG units, as a bigint above zero.", "bad_amount");
558
+ const target = await guarded(() => callOf(address));
559
+ if (target.asset.symbol !== "USDG") throw new CallsError("Bonus pots are on USDG Calls only, and this Call is staked in ETH. Nothing was sent.", "not_usdg");
560
+ return guarded(async () => {
561
+ const { receipt, approval } = await intoUsdgCall(target, amount, usdgCap, "bonus", [target.address, amount]);
562
+ const added = eventOf<{ bonus: bigint }>(receipt, tokenCallAbi as Abi, "BonusAdded");
563
+ return { ...toTx(receipt, chainId), call: target.address, amount: amount.toString(), asset: target.asset, approval, bonus: added?.bonus.toString() ?? null };
564
+ }, "USDG");
358
565
  },
359
566
 
567
+ /** The wallet's USDG, what it has allowed the USDG factory, and the approval a bet or bonus of `amount` would send first. */
568
+ usdgApproval: (amount: bigint, who?: string): Promise<Approval> =>
569
+ guarded(async () => {
570
+ if (!usdgFactory) throw new CallsError("This client knows no USDG factory. Set CALLS_USDG_FACTORY, or `usdgFactory` in code.", "usdg_unknown");
571
+ return approvalOf((await usdg()).address!, usdgFactory, walletOr(who), amount);
572
+ }, "USDG"),
573
+
360
574
  /** Five minutes, up or down. The contract's address comes from the API, so a new deployment needs no new client. */
361
575
  rounds: {
362
576
  /** Every market's round taking bets, the round running and its latest results, in one read. */
@@ -448,38 +662,50 @@ export function createClient(options: ClientOptions = {}) {
448
662
  }),
449
663
  },
450
664
 
451
- /** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
452
- claim: (address: string) =>
453
- guarded(async () => {
454
- const call = await mustBeCall(address);
455
- const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "claim" });
456
- const paid = eventOf<{ amount: bigint }>(receipt, callAbi as Abi, "Claimed");
457
- return { ...toTx(receipt, chainId), call, amount: paid?.amount.toString() ?? null };
458
- }),
665
+ /**
666
+ * Collects winnings or a refund once the Call is Final or Voided, in the Call's asset, a sponsor's bonus coming back
667
+ * with it when the bonus refunds. The money only ever goes to the wallet that sends this.
668
+ */
669
+ async claim(address: string) {
670
+ const target = await guarded(() => callOf(address));
671
+ return guarded(async () => {
672
+ const receipt = await send({ address: target.address, abi: abiOf(target), functionName: "claim" });
673
+ const paid = eventOf<{ amount: bigint }>(receipt, abiOf(target), "Claimed");
674
+ return { ...toTx(receipt, chainId), call: target.address, asset: target.asset, amount: paid?.amount.toString() ?? null };
675
+ }, target.asset.symbol);
676
+ },
459
677
 
460
678
  /** Pays the opener's bond and fee share. Anyone can send it; the money only ever goes to the opener. */
461
- claimOpener: (address: string) =>
462
- guarded(async () => {
463
- const call = await mustBeCall(address);
464
- const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "claimOpener" });
465
- const paid = eventOf<{ opener: Address; amount: bigint }>(receipt, callAbi as Abi, "OpenerPaid");
466
- return { ...toTx(receipt, chainId), call, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
467
- }),
679
+ async claimOpener(address: string) {
680
+ const target = await guarded(() => callOf(address));
681
+ return guarded(async () => {
682
+ const receipt = await send({ address: target.address, abi: abiOf(target), functionName: "claimOpener" });
683
+ const paid = eventOf<{ opener: Address; amount: bigint }>(receipt, abiOf(target), "OpenerPaid");
684
+ return { ...toTx(receipt, chainId), call: target.address, asset: target.asset, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
685
+ }, target.asset.symbol);
686
+ },
468
687
 
469
688
  /** Makes a Settled Call Final once its dispute window has passed. Anyone can send it. */
470
- finalize: (address: string) =>
471
- guarded(async () => {
472
- const call = await mustBeCall(address);
473
- return { ...toTx(await send({ address: call, abi: callAbi as Abi, functionName: "finalize" }), chainId), call };
474
- }),
689
+ async finalize(address: string) {
690
+ const target = await guarded(() => callOf(address));
691
+ return guarded(async () => ({ ...toTx(await send({ address: target.address, abi: abiOf(target), functionName: "finalize" }), chainId), call: target.address }), target.asset.symbol);
692
+ },
475
693
 
476
- /** Disputes a settled result inside its window, posting the dispute bond (0.02 ETH). The court rules; the bond comes back if it flips the result. */
477
- dispute: (address: string) =>
478
- guarded(async () => {
479
- const call = await mustBeCall(address);
480
- const bond = await callRead<bigint>(call, "DISPUTE_BOND");
481
- return { ...toTx(await send({ address: call, abi: callAbi as Abi, functionName: "dispute", value: bond }), chainId), call, bond: bond.toString() };
482
- }),
694
+ /**
695
+ * Disputes a settled result inside its window, posting the dispute bond: 0.02 ETH on an ETH Call, 20 USDG on a USDG
696
+ * Call, which pulls it after an approval of exactly the bond to the Call. The court rules; the bond comes back if it
697
+ * flips the result.
698
+ */
699
+ async dispute(address: string) {
700
+ const target = await guarded(() => callOf(address));
701
+ const call = target.address;
702
+ return guarded(async () => {
703
+ const bond = await read<bigint>(call, abiOf(target), "DISPUTE_BOND");
704
+ if (target.asset.symbol === "ETH") return { ...toTx(await send({ address: call, abi: callAbi as Abi, functionName: "dispute", value: bond }), chainId), call, asset: target.asset, bond: bond.toString(), approval: null };
705
+ const { receipt, approval } = await withApproval(target.asset, call, bond, "dispute", () => send({ address: call, abi: tokenCallAbi as Abi, functionName: "dispute" }));
706
+ return { ...toTx(receipt, chainId), call, asset: target.asset, bond: bond.toString(), approval };
707
+ }, target.asset.symbol);
708
+ },
483
709
 
484
710
  /**
485
711
  * Opens a Call. Stores the sentence and spec with `POST /v1/calls` first, because Shipped settles from the stored
package/src/errors.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, InsufficientFundsError } from "viem";
2
+ import type { AssetSymbol } from "./assets.js";
2
3
 
3
4
  /** Every failure the SDK raises: one sentence to show, and a code to branch on. A revert's code is its error name. */
4
5
  export class CallsError extends Error {
@@ -16,6 +17,7 @@ export class CallsError extends Error {
16
17
  export const RECEIPT_UNKNOWN = "receipt_unknown";
17
18
 
18
19
  export const NOT_ENOUGH_ETH = "Not enough ETH to cover this and gas.";
20
+ export const NOT_ENOUGH_GAS = "Not enough ETH for gas. A USDG Call takes its stake in USDG and its gas in ETH.";
19
21
 
20
22
  // Keyed by error name, or by `function.error` where one revert means different things on different calls.
21
23
  const REVERTS: Record<string, string> = {
@@ -44,19 +46,49 @@ const REVERTS: Record<string, string> = {
44
46
  MarketPaused: "This market isn't taking bets right now.",
45
47
  UnknownMarket: "Rounds has no such market.",
46
48
  GasTooLow: "This win's card needs more gas. Send at least the estimate.",
49
+ "rule.TooEarly": "Before the deadline a reviewer can only accept.",
50
+ "rule.WindowClosed": "The reviewer's window has closed. Anyone can now refund the client.",
51
+ "settleDefault.TooEarly": "The reviewer's window is still open.",
52
+ "fund.NotOpen": "This job has already been ruled on.",
53
+ NotVerifier: "Only the reviewer named in the job can rule on it.",
54
+ NotCreator: "Only the worker who opened the job can do that.",
55
+ NotPoster: "Only the worker or the reviewer can post evidence.",
56
+ NotOpen: "This job has already been ruled on.",
57
+ NothingOwed: "Nothing to collect for this wallet.",
58
+ UnknownDeed: "There is no job with that id.",
59
+ InvalidVerifier: "The reviewer has to be a different wallet from the worker.",
60
+ InvalidRefund: "The client has to be a different wallet from the worker.",
61
+ InvalidDeadline: "The deadline has to be at least ten minutes away and within three years.",
62
+ InvalidWindow: "The review window has to be between one hour and 60 days.",
63
+ InvalidEvidence: "Evidence is a link of up to 2,048 bytes.",
64
+ AssetNotAllowed: "The registry does not hold that token.",
65
+ CreationIsPaused: "The registry is not opening new jobs right now.",
66
+ AssetPaused: "USDG is paused by its issuer, so the Call cannot go final until it resumes.",
67
+ BonusTooSmall: "A bonus has to be more than zero.",
68
+ ShortTransfer: "The Call received less than the amount named, so it refused it.",
69
+ NotACall: "That address is not a Call of the USDG factory.",
70
+ SafeERC20FailedOperation: "The USDG transfer was refused. Check the wallet's USDG and its approval.",
71
+ };
72
+
73
+ // Where a USDG Call's revert means the same as an ETH Call's but the amounts differ.
74
+ const USDG_REVERTS: Record<string, string> = {
75
+ BetTooSmall: "The minimum bet is 1 USDG.",
76
+ BondTooSmall: "The bond is below the 20 USDG minimum.",
77
+ WrongBond: "The dispute bond is 20 USDG, approved to the Call first.",
47
78
  };
48
79
 
49
80
  /** One sentence for a failed read or write. RPC URLs can carry keys, so nothing from the transport is passed on. */
50
81
  export const revertLine = (name: string) => REVERTS[name] ?? `The contract would refuse this: ${name}.`;
51
82
 
52
- export function describe(error: unknown): CallsError {
83
+ /** `asset` is what the Call is staked in, which picks the amounts a refusal names. */
84
+ export function describe(error: unknown, asset: AssetSymbol = "ETH"): CallsError {
53
85
  if (error instanceof CallsError) return error;
54
86
  if (!(error instanceof BaseError)) return new CallsError("The request did not go through.", "unknown");
55
- if (error.walk((e) => e instanceof InsufficientFundsError) || /insufficient funds/i.test(error.message)) return new CallsError(NOT_ENOUGH_ETH, "insufficient_funds");
87
+ if (error.walk((e) => e instanceof InsufficientFundsError) || /insufficient funds/i.test(error.message)) return new CallsError(asset === "USDG" ? NOT_ENOUGH_GAS : NOT_ENOUGH_ETH, "insufficient_funds");
56
88
  const revert = error.walk((e) => e instanceof ContractFunctionRevertedError) as ContractFunctionRevertedError | null;
57
89
  const call = error.walk((e) => e instanceof ContractFunctionExecutionError) as ContractFunctionExecutionError | null;
58
90
  const name = revert?.data?.errorName;
59
- if (name) return new CallsError(REVERTS[`${call?.functionName}.${name}`] ?? REVERTS[name] ?? `The contract refused this: ${name}.`, name);
91
+ if (name) return new CallsError((asset === "USDG" ? USDG_REVERTS[name] : undefined) ?? REVERTS[`${call?.functionName}.${name}`] ?? REVERTS[name] ?? `The contract refused this: ${name}.`, name);
60
92
  if (revert) return new CallsError("The contract refused this.", "reverted");
61
93
  return new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
62
94
  }
package/src/index.ts CHANGED
@@ -1,8 +1,10 @@
1
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";
2
+ export { API_URL, CALLED_IT, CHAIN_ID, COUNCIL, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints, USDG, USDG_FACTORY } from "./chain.js";
3
+ export { callAbi, calledItAbi, factoryAbi, roundsAbi, tokenCallAbi, tokenFactoryAbi } from "./abi.js";
4
+ export { approvalFor, assetSymbolOf, DEFAULT_MAX_STAKE_USDG, ETH_ASSET, formatAmount, parseAmount, USDG_ASSET, USDG_DISPUTE_BOND, USDG_MIN_BET, USDG_MIN_OPENER_BOND, type Asset, type AssetSymbol } from "./assets.js";
4
5
  export { canonical, hashJson } from "./canonical.js";
5
6
  export { CallsError, RECEIPT_UNKNOWN } from "./errors.js";
6
7
  export { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
7
8
  export { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, PRICE_DISPUTE_WINDOW, RAKE_BPS, ethToWei, multipleOf, odds, payout, quoteOf, roundInPlay, roundPayout, type Pools, type Side } from "./odds.js";
8
9
  export type * from "./types.js";
10
+ export { bondNumberOf, checkJob, COUNCIL_MIN_FEE, DEFAULT_MAX_JOB_FUND, DEFAULT_REVIEW_WINDOW, jobMilestone, jobStateOf, jobTerms, readJobTag, usdgToUnits, type ChainDeed, type Job, type JobAgreement, type JobProblem, type JobsClient, type JobState, type JobTerms, type JobTx, type OpenJobInput } from "./jobs.js";