@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/dist/client.js CHANGED
@@ -1,13 +1,19 @@
1
- import { formatEther, getAddress, isAddress, parseEventLogs, stringToHex } from "viem";
1
+ import { erc20Abi, formatEther, getAddress, isAddress, parseEventLogs, stringToHex } 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 } 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 } from "./odds.js";
10
+ import { createJobs, DEFAULT_MAX_JOB_FUND } from "./jobs.js";
9
11
  export const DEFAULT_MAX_STAKE = 10n ** 16n;
10
12
  export const DEFAULT_MAX_BOND = MIN_OPENER_BOND;
13
+ // The factory's own errors, then the Call's that a call through the factory can revert with.
14
+ const tokenFactoryErrors = [...tokenFactoryAbi, ...tokenCallAbi.filter((item) => item.type === "error" && !tokenFactoryAbi.some((own) => own.type === "error" && own.name === item.name))];
15
+ /** An older API answers without `asset` and `bonus`: its Calls are all ETH. */
16
+ const withAsset = (c) => ({ ...c, asset: c.asset ?? ETH_ASSET, bonus: c.bonus ?? "0" });
11
17
  const STATUS = ["open", "settled", "disputed", "final", "voided"];
12
18
  const TYPES = ["posted", "onchain", "price", "deed"];
13
19
  const SIDE_CODE = { holds: 1, breaks: 2 };
@@ -124,6 +130,8 @@ export function createClient(options = {}) {
124
130
  const { reads, writes } = clientsFor({ chainId, urls: rpcEndpoints(options.rpc), account, transport: options.transport });
125
131
  const doFetch = options.fetch ?? globalThis.fetch;
126
132
  const maxStake = options.maxStake ?? DEFAULT_MAX_STAKE;
133
+ const maxStakeUsdg = options.maxStakeUsdg ?? DEFAULT_MAX_STAKE_USDG;
134
+ const usdgFactory = options.usdgFactory === undefined ? (options.factory ? null : USDG_FACTORY) : options.usdgFactory ? addressOf(options.usdgFactory, "factory") : null;
127
135
  let chainChecked = false;
128
136
  async function request(path, init) {
129
137
  let res;
@@ -140,21 +148,45 @@ export function createClient(options = {}) {
140
148
  }
141
149
  const read = (address, abi, functionName, args = []) => reads.readContract({ address, abi, functionName, args });
142
150
  const callRead = (address, functionName, args = []) => read(address, callAbi, functionName, args);
143
- async function guarded(work) {
151
+ async function guarded(work, asset = "ETH") {
144
152
  try {
145
153
  return await work();
146
154
  }
147
155
  catch (error) {
148
- throw describe(error);
156
+ throw describe(error, asset);
149
157
  }
150
158
  }
151
- const isCall = async (address) => (await Promise.all(factories.map((f) => read(f, factoryAbi, "isCall", [address])))).some(Boolean);
152
- async function mustBeCall(value) {
159
+ // The token is the factory's to name, so a rehearsal on another chain reads its own.
160
+ let usdgAsset = null;
161
+ const usdg = () => (usdgAsset ??= usdgFactory
162
+ ? read(usdgFactory, tokenFactoryAbi, "asset").then((address) => ({ ...USDG_ASSET, address: getAddress(address) }), (error) => {
163
+ usdgAsset = null;
164
+ throw error;
165
+ })
166
+ : Promise.resolve(USDG_ASSET));
167
+ async function factoryOf(address) {
168
+ const [eth, token] = await Promise.all([
169
+ Promise.all(factories.map((f) => read(f, factoryAbi, "isCall", [address]))),
170
+ usdgFactory ? read(usdgFactory, tokenFactoryAbi, "isCall", [address]) : false,
171
+ ]);
172
+ const index = eth.findIndex(Boolean);
173
+ if (index >= 0)
174
+ return { factory: factories[index], usdg: false };
175
+ return token ? { factory: usdgFactory, usdg: true } : null;
176
+ }
177
+ const isCall = async (address) => (await factoryOf(address)) !== null;
178
+ /** Only a Call one of the factories made gets money: the factory's word is the check, never the address's own. */
179
+ async function callOf(value) {
153
180
  const address = addressOf(value);
154
- if (!(await isCall(address)))
155
- throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
156
- return address;
181
+ const made = await factoryOf(address);
182
+ if (made)
183
+ return { address, asset: made.usdg ? await usdg() : ETH_ASSET, factory: made.factory };
184
+ if (!usdgFactory && (await client.call(address).catch(() => null))?.asset.symbol === "USDG") {
185
+ 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");
186
+ }
187
+ throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
157
188
  }
189
+ const abiOf = (target) => (target.asset.symbol === "ETH" ? callAbi : tokenCallAbi);
158
190
  function wallet() {
159
191
  if (!account)
160
192
  throw new CallsError("Set a wallet to send this: CALLS_PRIVATE_KEY, or `privateKey` or `account` in code.", "no_wallet");
@@ -197,6 +229,61 @@ export function createClient(options = {}) {
197
229
  throw new CallsError("An amount is wei, as a bigint above zero.", "bad_amount");
198
230
  return amount;
199
231
  };
232
+ async function approvalOf(token, spender, owner, amount) {
233
+ const [balance, allowance] = await Promise.all([
234
+ read(token, erc20Abi, "balanceOf", [owner]),
235
+ read(token, erc20Abi, "allowance", [owner, spender]),
236
+ ]);
237
+ const { approve, short } = approvalFor(balance, allowance, amount);
238
+ return { token, spender, owner, balance: balance.toString(), allowance: allowance.toString(), amount: amount.toString(), approve: approve?.toString() ?? null, short: short.toString() };
239
+ }
240
+ /**
241
+ * A USDG write pulls what it names, so the spender needs the allowance first: approves exactly `amount` when short,
242
+ * as its own transaction, then sends `write`. A failure after the approval says the approval went through.
243
+ */
244
+ async function withApproval(asset, spender, amount, then, write) {
245
+ const approval = await approvalOf(asset.address, spender, wallet().address, amount);
246
+ if (approval.short !== "0")
247
+ throw new CallsError(`This wallet holds ${formatAmount(approval.balance, asset)}, and this ${then} needs ${formatAmount(amount, asset)}. Nothing was sent.`, "insufficient_usdg");
248
+ let approved = null;
249
+ if (approval.approve) {
250
+ try {
251
+ approved = toTx(await send({ address: asset.address, abi: erc20Abi, functionName: "approve", args: [spender, amount] }), chainId);
252
+ }
253
+ catch (error) {
254
+ const known = describe(error, "USDG");
255
+ throw known.code === RECEIPT_UNKNOWN ? new CallsError(`${known.message} It was the approval, so the ${then} was not sent.`, RECEIPT_UNKNOWN) : known;
256
+ }
257
+ }
258
+ try {
259
+ return { receipt: await write(), approval: approved };
260
+ }
261
+ catch (error) {
262
+ if (!approved)
263
+ throw error;
264
+ const known = describe(error, "USDG");
265
+ 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);
266
+ }
267
+ }
268
+ async function refuseUnresolvable(call) {
269
+ // The API may be down; the chain still takes the bet, so its word only ever stops one.
270
+ const stored = await client.call(call).catch(() => null);
271
+ if (stored?.unresolvable)
272
+ 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");
273
+ }
274
+ // USDG moves before the Call checks anything, and an approval costs gas, so a write that would fail stops here.
275
+ async function intoUsdgCall(target, amount, cap, what, args) {
276
+ if (amount > cap)
277
+ 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");
278
+ if (what === "bet" && amount < USDG_MIN_BET)
279
+ throw new CallsError("The minimum bet is 1 USDG.", "BetTooSmall");
280
+ wallet();
281
+ await refuseUnresolvable(target.address);
282
+ const [status, closeAt, block] = await Promise.all([callRead(target.address, "status"), callRead(target.address, "closeAt"), reads.getBlock({ blockTag: "latest" })]);
283
+ if (status !== 0 || block.timestamp >= closeAt)
284
+ throw new CallsError(what === "bet" ? "Betting has closed on this Call." : "Betting has closed on this Call, and with it the bonus pot.", "BettingClosed");
285
+ return withApproval(target.asset, target.factory, amount, what, () => send({ address: target.factory, abi: tokenFactoryErrors, functionName: what === "bet" ? "bet" : "addBonus", args }));
286
+ }
200
287
  const roundState = (market) => {
201
288
  const name = marketOf(market);
202
289
  return request(`/v1/rounds/${name}`).catch((error) => {
@@ -205,28 +292,33 @@ export function createClient(options = {}) {
205
292
  };
206
293
  const eventOf = (receipt, abi, eventName) => parseEventLogs({ abi, logs: receipt.logs, eventName })[0]?.args;
207
294
  async function chainQuote(address, side, amount) {
208
- const [member, status, closeAt, holds, breaks, block] = await Promise.all([
209
- isCall(address),
295
+ const target = await callOf(address);
296
+ const isUsdg = target.asset.symbol === "USDG";
297
+ const minBet = isUsdg ? USDG_MIN_BET : MIN_BET;
298
+ if (amount < minBet)
299
+ throw new CallsError(`The minimum bet is ${formatAmount(minBet, target.asset)}.`, "BetTooSmall");
300
+ const [status, closeAt, holds, breaks, bonus, block] = await Promise.all([
210
301
  callRead(address, "status").catch(() => null),
211
302
  callRead(address, "closeAt").catch(() => null),
212
303
  callRead(address, "pool", [1]).catch(() => null),
213
304
  callRead(address, "pool", [2]).catch(() => null),
305
+ isUsdg ? read(address, tokenCallAbi, "bonus").catch(() => null) : 0n,
214
306
  reads.getBlock({ blockTag: "latest" }),
215
307
  ]);
216
- if (!member)
217
- throw new CallsError("That address is not a Call of the Shipped Calls factory.", "not_a_call");
218
- if (status == null || closeAt == null || holds == null || breaks == null)
308
+ if (status == null || closeAt == null || holds == null || breaks == null || bonus == null)
219
309
  throw new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
220
310
  const pools = { holds, breaks };
221
- const q = quoteOf(pools, side, amount);
311
+ const q = quoteOf(pools, side, amount, bonus);
222
312
  return {
223
313
  call: address,
224
314
  side,
225
315
  amount: amount.toString(),
316
+ asset: target.asset,
317
+ bonus: bonus.toString(),
226
318
  status: STATUS[status],
227
319
  bettingOpen: status === 0 && block.timestamp < closeAt,
228
320
  closeAt: Number(closeAt),
229
- minBet: MIN_BET.toString(),
321
+ minBet: minBet.toString(),
230
322
  pools: { holds: holds.toString(), breaks: breaks.toString() },
231
323
  poolsAfter: { holds: q.poolsAfter.holds.toString(), breaks: q.poolsAfter.breaks.toString() },
232
324
  impliedBps: q.impliedBps,
@@ -243,51 +335,84 @@ export function createClient(options = {}) {
243
335
  address: account?.address ?? null,
244
336
  chainId,
245
337
  factory,
338
+ /** The factory USDG Calls open on, or null when this client knows none. */
339
+ usdgFactory,
340
+ /** Hold payment until the work is accepted: the worker opens a job, the client funds it, a named reviewer releases it. */
341
+ jobs: createJobs({ reads, chainId, send, guarded, wallet, toTx: (receipt) => toTx(receipt, chainId), maxFund: options.maxJobFund ?? DEFAULT_MAX_JOB_FUND }),
246
342
  // Reads from the API. It follows the chain by up to a minute; the chain reads below do not.
343
+ /** Every asset by default; `asset` keeps to Calls staked in one. */
247
344
  async calls(filters = {}) {
248
- return (await request(`/v1/calls${query(filters)}`)).calls;
345
+ const asset = filters.asset && assetSymbolOf(filters.asset);
346
+ return (await request(`/v1/calls${query({ ...filters, asset })}`)).calls.map(withAsset);
347
+ },
348
+ call: async (address) => {
349
+ const call = await request(`/v1/calls/${addressOf(address)}`);
350
+ return { ...withAsset(call), bonuses: call.bonuses ?? [] };
249
351
  },
250
- call: async (address) => request(`/v1/calls/${addressOf(address)}`),
251
352
  /** The latest bets across every Call, or every bet on one Call with `call`. */
252
353
  async bets({ call, limit } = {}) {
253
354
  if (call)
254
355
  return (await client.call(call)).bets;
255
356
  return (await request(`/v1/bets/recent${query({ limit })}`)).bets;
256
357
  },
257
- async tape({ limit } = {}) {
258
- return (await request(`/v1/tape${query({ limit })}`)).items;
358
+ // The tape, boards and players count one asset at a time, ETH unless `asset` asks for USDG.
359
+ async tape({ limit, asset } = {}) {
360
+ return (await request(`/v1/tape${query({ limit, asset: asset && assetSymbolOf(asset) })}`)).items;
259
361
  },
260
- leaderboard: (filters = {}) => request(`/v1/leaderboard${query(filters)}`),
261
- player: async (address) => request(`/v1/players/${walletOr(address)}`),
362
+ leaderboard: (filters = {}) => request(`/v1/leaderboard${query({ ...filters, asset: filters.asset && assetSymbolOf(filters.asset) })}`),
363
+ player: async (address, { asset } = {}) => request(`/v1/players/${walletOr(address)}${query({ asset: asset && assetSymbolOf(asset) })}`),
262
364
  /** Shipped agents: name, rule and wallet. */
263
365
  async agents() {
264
366
  return (await request("/v1/agents")).agents;
265
367
  },
266
368
  proof: () => request("/v1/proof"),
267
369
  /**
268
- * What `amount` wei on `side` pays with the pools as they stand. Reads the pools from the chain, and from the API if
269
- * no endpoint answers. Later bets move the payout until betting closes.
370
+ * What `amount` on `side` pays with the pools as they stand, in base units of the Call's asset, its share of any
371
+ * bonus included. Reads the pools from the chain, and from the API if no endpoint answers. Later bets move the
372
+ * payout until betting closes.
270
373
  */
271
374
  async quote(address, side, amount) {
272
375
  const call = addressOf(address);
273
376
  const name = sideOf(side);
274
- if (amount < MIN_BET)
275
- throw new CallsError("The minimum bet is 0.001 ETH.", "BetTooSmall");
276
377
  try {
277
378
  return await chainQuote(call, name, amount);
278
379
  }
279
380
  catch (error) {
280
381
  if (error instanceof CallsError && error.code !== "rpc_unavailable")
281
382
  throw error;
282
- return request(`/v1/calls/${call}/quote${query({ side: name, amount })}`);
383
+ return withAsset(await request(`/v1/calls/${call}/quote${query({ side: name, amount })}`));
283
384
  }
284
385
  },
285
- /** One wallet's open positions and settled Calls from the API, with its balance and what it can claim from the chain. */
286
- async positions(address) {
386
+ /** What a Call is staked in, from the chain, or from the API if no endpoint answers. */
387
+ async assetOf(address) {
388
+ const call = addressOf(address);
389
+ try {
390
+ return (await callOf(call)).asset;
391
+ }
392
+ catch (error) {
393
+ if (error instanceof CallsError)
394
+ throw error;
395
+ return (await client.call(call).catch(() => {
396
+ throw describe(error);
397
+ })).asset;
398
+ }
399
+ },
400
+ /**
401
+ * One wallet's open positions and settled Calls in one asset, ETH unless `asset` asks for USDG, from the API, with
402
+ * its balance and what it can claim from the chain. `gas` is its ETH, which pays the gas either way.
403
+ */
404
+ async positions(address, { asset = "ETH" } = {}) {
287
405
  const who = walletOr(address);
288
- const [player, balance] = await Promise.all([client.player(who), reads.getBalance({ address: who }).catch(() => null)]);
406
+ const symbol = assetSymbolOf(asset);
407
+ const unit = symbol === "ETH" ? ETH_ASSET : await usdg().catch(() => USDG_ASSET);
408
+ const [player, gas, tokens] = await Promise.all([
409
+ client.player(who, symbol === "ETH" ? {} : { asset: symbol }),
410
+ reads.getBalance({ address: who }).catch(() => null),
411
+ unit.address ? read(unit.address, erc20Abi, "balanceOf", [who]).catch(() => null) : null,
412
+ ]);
289
413
  const settled = await Promise.all(player.shelf.slice(0, SHELF_READS).map(async (row) => ({ ...row, owed: await client.payoutOf(row.call, who).then(String, () => null) })));
290
- return { address: who, balance: balance == null ? null : balance.toString(), positions: player.positions, settled, week: player.week, all: player.all };
414
+ const balance = unit.address ? tokens : gas;
415
+ 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 };
291
416
  },
292
417
  // Reads from the chain, current to the block.
293
418
  isCall: (address) => guarded(() => isCall(addressOf(address))),
@@ -305,32 +430,100 @@ export function createClient(options = {}) {
305
430
  return (await callRead(call, "callType")) === 3 ? 0 : DISPUTE_WINDOW;
306
431
  }
307
432
  }),
433
+ /** The bonus pot sponsors added to a USDG Call, USDG units. 0 on an ETH Call, which has none. */
434
+ bonus: (address) => guarded(async () => {
435
+ const target = await callOf(address);
436
+ return target.asset.symbol === "USDG" ? read(target.address, tokenCallAbi, "bonus") : 0n;
437
+ }),
308
438
  async odds(address) {
309
- const [holds, breaks] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks")]);
310
- return { pools: { holds, breaks }, ...odds({ holds, breaks }) };
439
+ const [holds, breaks, bonus] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks"), client.bonus(address)]);
440
+ return { pools: { holds, breaks }, bonus, ...odds({ holds, breaks }, bonus) };
311
441
  },
312
442
  payoutOf: (address, who) => guarded(() => callRead(addressOf(address), "payoutOf", [walletOr(who)])),
313
443
  stake: (address, side, who) => guarded(() => callRead(addressOf(address), "stake", [walletOr(who), SIDE_CODE[sideOf(side)]])),
314
444
  balance: (who) => guarded(() => reads.getBalance({ address: walletOr(who) })),
315
445
  /**
316
- * Stakes `amount` wei on `side`. Refuses an amount over `maxStake` and an address that is not one of the factory's
317
- * Calls before anything goes out; simulates first, so a bet the contract would refuse costs nothing.
446
+ * Stakes `amount` on `side`, in base units of the Call's asset. Refuses an address that is not a Call of one of the
447
+ * factories, and an amount over the cap for its asset (`maxStake` in wei on an ETH Call, `maxStakeUsdg` in USDG
448
+ * units on a USDG Call), before anything goes out. A USDG bet goes through the USDG factory, and when the factory's
449
+ * allowance is short it first approves exactly `amount` in a transaction of its own, reported as `approval`. Every
450
+ * transaction simulates first, so one the contract would refuse costs nothing.
318
451
  */
319
- async bet(address, side, amount, { maxStake: cap = maxStake } = {}) {
452
+ async bet(address, side, amount, { maxStake: cap = maxStake, maxStakeUsdg: usdgCap = maxStakeUsdg } = {}) {
320
453
  const name = sideOf(side);
321
- if (amount > cap)
322
- 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");
454
+ const target = await guarded(() => callOf(address));
455
+ const { asset } = target;
456
+ const call = target.address;
323
457
  return guarded(async () => {
324
- const call = await mustBeCall(address);
325
- // The API may be down; the chain still takes the bet, so its word only ever stops one.
326
- const stored = await client.call(call).catch(() => null);
327
- if (stored?.unresolvable)
328
- 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");
458
+ if (asset.symbol === "USDG") {
459
+ const { receipt, approval } = await intoUsdgCall(target, amount, usdgCap, "bet", [call, SIDE_CODE[name], amount]);
460
+ const placed = eventOf(receipt, tokenCallAbi, "Bet");
461
+ return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), asset, approval, pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
462
+ }
463
+ if (amount > cap)
464
+ 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");
465
+ await refuseUnresolvable(call);
329
466
  const receipt = await send({ address: call, abi: callAbi, functionName: "bet", args: [SIDE_CODE[name]], value: amount });
330
467
  const placed = eventOf(receipt, callAbi, "Bet");
331
- return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
332
- });
468
+ return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), asset, approval: null, pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
469
+ }, asset.symbol);
333
470
  },
471
+ /**
472
+ * What adding `amount` USDG units to a USDG Call's bonus pot does, with the pot as it stands. Winners share the pot
473
+ * 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
474
+ * takes back what they put in. Sends nothing.
475
+ */
476
+ bonusQuote: (address, amount) => guarded(async () => {
477
+ if (typeof amount !== "bigint" || amount <= 0n)
478
+ throw new CallsError("A bonus is USDG units, as a bigint above zero.", "bad_amount");
479
+ const target = await callOf(address);
480
+ if (target.asset.symbol !== "USDG")
481
+ throw new CallsError("Bonus pots are on USDG Calls only, and this Call is staked in ETH.", "not_usdg");
482
+ const [status, closeAt, holds, breaks, bonus, sponsored, block] = await Promise.all([
483
+ callRead(target.address, "status"),
484
+ callRead(target.address, "closeAt"),
485
+ callRead(target.address, "pool", [1]),
486
+ callRead(target.address, "pool", [2]),
487
+ read(target.address, tokenCallAbi, "bonus"),
488
+ account ? read(target.address, tokenCallAbi, "bonusOf", [account.address]) : null,
489
+ reads.getBlock({ blockTag: "latest" }),
490
+ ]);
491
+ return {
492
+ call: target.address,
493
+ asset: target.asset,
494
+ amount: amount.toString(),
495
+ status: STATUS[status],
496
+ bettingOpen: status === 0 && block.timestamp < closeAt,
497
+ closeAt: Number(closeAt),
498
+ pools: { holds: holds.toString(), breaks: breaks.toString() },
499
+ bonus: bonus.toString(),
500
+ bonusAfter: (bonus + amount).toString(),
501
+ sponsored: sponsored == null ? null : sponsored.toString(),
502
+ };
503
+ }, "USDG"),
504
+ /**
505
+ * Adds `amount` USDG units to a USDG Call's bonus pot while betting is open, through the USDG factory, approving
506
+ * exactly `amount` first when the allowance is short. Counts against the same cap as a USDG bet. Adding to the pot
507
+ * buys no stake: to share in it, bet.
508
+ */
509
+ async addBonus(address, amount, { maxStakeUsdg: usdgCap = maxStakeUsdg } = {}) {
510
+ if (typeof amount !== "bigint" || amount <= 0n)
511
+ throw new CallsError("A bonus is USDG units, as a bigint above zero.", "bad_amount");
512
+ const target = await guarded(() => callOf(address));
513
+ if (target.asset.symbol !== "USDG")
514
+ throw new CallsError("Bonus pots are on USDG Calls only, and this Call is staked in ETH. Nothing was sent.", "not_usdg");
515
+ return guarded(async () => {
516
+ const { receipt, approval } = await intoUsdgCall(target, amount, usdgCap, "bonus", [target.address, amount]);
517
+ const added = eventOf(receipt, tokenCallAbi, "BonusAdded");
518
+ return { ...toTx(receipt, chainId), call: target.address, amount: amount.toString(), asset: target.asset, approval, bonus: added?.bonus.toString() ?? null };
519
+ }, "USDG");
520
+ },
521
+ /** The wallet's USDG, what it has allowed the USDG factory, and the approval a bet or bonus of `amount` would send first. */
522
+ usdgApproval: (amount, who) => guarded(async () => {
523
+ if (!usdgFactory)
524
+ throw new CallsError("This client knows no USDG factory. Set CALLS_USDG_FACTORY, or `usdgFactory` in code.", "usdg_unknown");
525
+ return approvalOf((await usdg()).address, usdgFactory, walletOr(who), amount);
526
+ }, "USDG"),
334
527
  /** Five minutes, up or down. The contract's address comes from the API, so a new deployment needs no new client. */
335
528
  rounds: {
336
529
  /** Every market's round taking bets, the round running and its latest results, in one read. */
@@ -422,31 +615,48 @@ export function createClient(options = {}) {
422
615
  return { ...toTx(receipt, chainId), rounds: batch.length, left: account.unclaimedRounds - batch.length, amount: (paid.reduce((sum, log) => sum + log.args.amount, 0n) - cut).toString(), cut: cut.toString() };
423
616
  }),
424
617
  },
425
- /** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
426
- claim: (address) => guarded(async () => {
427
- const call = await mustBeCall(address);
428
- const receipt = await send({ address: call, abi: callAbi, functionName: "claim" });
429
- const paid = eventOf(receipt, callAbi, "Claimed");
430
- return { ...toTx(receipt, chainId), call, amount: paid?.amount.toString() ?? null };
431
- }),
618
+ /**
619
+ * Collects winnings or a refund once the Call is Final or Voided, in the Call's asset, a sponsor's bonus coming back
620
+ * with it when the bonus refunds. The money only ever goes to the wallet that sends this.
621
+ */
622
+ async claim(address) {
623
+ const target = await guarded(() => callOf(address));
624
+ return guarded(async () => {
625
+ const receipt = await send({ address: target.address, abi: abiOf(target), functionName: "claim" });
626
+ const paid = eventOf(receipt, abiOf(target), "Claimed");
627
+ return { ...toTx(receipt, chainId), call: target.address, asset: target.asset, amount: paid?.amount.toString() ?? null };
628
+ }, target.asset.symbol);
629
+ },
432
630
  /** Pays the opener's bond and fee share. Anyone can send it; the money only ever goes to the opener. */
433
- claimOpener: (address) => guarded(async () => {
434
- const call = await mustBeCall(address);
435
- const receipt = await send({ address: call, abi: callAbi, functionName: "claimOpener" });
436
- const paid = eventOf(receipt, callAbi, "OpenerPaid");
437
- return { ...toTx(receipt, chainId), call, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
438
- }),
631
+ async claimOpener(address) {
632
+ const target = await guarded(() => callOf(address));
633
+ return guarded(async () => {
634
+ const receipt = await send({ address: target.address, abi: abiOf(target), functionName: "claimOpener" });
635
+ const paid = eventOf(receipt, abiOf(target), "OpenerPaid");
636
+ return { ...toTx(receipt, chainId), call: target.address, asset: target.asset, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
637
+ }, target.asset.symbol);
638
+ },
439
639
  /** Makes a Settled Call Final once its dispute window has passed. Anyone can send it. */
440
- finalize: (address) => guarded(async () => {
441
- const call = await mustBeCall(address);
442
- return { ...toTx(await send({ address: call, abi: callAbi, functionName: "finalize" }), chainId), call };
443
- }),
444
- /** 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. */
445
- dispute: (address) => guarded(async () => {
446
- const call = await mustBeCall(address);
447
- const bond = await callRead(call, "DISPUTE_BOND");
448
- return { ...toTx(await send({ address: call, abi: callAbi, functionName: "dispute", value: bond }), chainId), call, bond: bond.toString() };
449
- }),
640
+ async finalize(address) {
641
+ const target = await guarded(() => callOf(address));
642
+ return guarded(async () => ({ ...toTx(await send({ address: target.address, abi: abiOf(target), functionName: "finalize" }), chainId), call: target.address }), target.asset.symbol);
643
+ },
644
+ /**
645
+ * Disputes a settled result inside its window, posting the dispute bond: 0.02 ETH on an ETH Call, 20 USDG on a USDG
646
+ * Call, which pulls it after an approval of exactly the bond to the Call. The court rules; the bond comes back if it
647
+ * flips the result.
648
+ */
649
+ async dispute(address) {
650
+ const target = await guarded(() => callOf(address));
651
+ const call = target.address;
652
+ return guarded(async () => {
653
+ const bond = await read(call, abiOf(target), "DISPUTE_BOND");
654
+ if (target.asset.symbol === "ETH")
655
+ return { ...toTx(await send({ address: call, abi: callAbi, functionName: "dispute", value: bond }), chainId), call, asset: target.asset, bond: bond.toString(), approval: null };
656
+ const { receipt, approval } = await withApproval(target.asset, call, bond, "dispute", () => send({ address: call, abi: tokenCallAbi, functionName: "dispute" }));
657
+ return { ...toTx(receipt, chainId), call, asset: target.asset, bond: bond.toString(), approval };
658
+ }, target.asset.symbol);
659
+ },
450
660
  /**
451
661
  * Opens a Call. Stores the sentence and spec with `POST /v1/calls` first, because Shipped settles from the stored
452
662
  * spec, checks the API's hashes against its own, then sends `CallsFactory.open` with the bond.