@shippedcalls/sdk 0.4.0 → 0.6.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,14 +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";
9
10
  import { createJobs, DEFAULT_MAX_JOB_FUND } from "./jobs.js";
10
11
  export const DEFAULT_MAX_STAKE = 10n ** 16n;
11
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" });
12
17
  const STATUS = ["open", "settled", "disputed", "final", "voided"];
13
18
  const TYPES = ["posted", "onchain", "price", "deed"];
14
19
  const SIDE_CODE = { holds: 1, breaks: 2 };
@@ -125,6 +130,8 @@ export function createClient(options = {}) {
125
130
  const { reads, writes } = clientsFor({ chainId, urls: rpcEndpoints(options.rpc), account, transport: options.transport });
126
131
  const doFetch = options.fetch ?? globalThis.fetch;
127
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;
128
135
  let chainChecked = false;
129
136
  async function request(path, init) {
130
137
  let res;
@@ -141,21 +148,45 @@ export function createClient(options = {}) {
141
148
  }
142
149
  const read = (address, abi, functionName, args = []) => reads.readContract({ address, abi, functionName, args });
143
150
  const callRead = (address, functionName, args = []) => read(address, callAbi, functionName, args);
144
- async function guarded(work) {
151
+ async function guarded(work, asset = "ETH") {
145
152
  try {
146
153
  return await work();
147
154
  }
148
155
  catch (error) {
149
- throw describe(error);
156
+ throw describe(error, asset);
150
157
  }
151
158
  }
152
- const isCall = async (address) => (await Promise.all(factories.map((f) => read(f, factoryAbi, "isCall", [address])))).some(Boolean);
153
- 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) {
154
180
  const address = addressOf(value);
155
- if (!(await isCall(address)))
156
- throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
157
- 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");
158
188
  }
189
+ const abiOf = (target) => (target.asset.symbol === "ETH" ? callAbi : tokenCallAbi);
159
190
  function wallet() {
160
191
  if (!account)
161
192
  throw new CallsError("Set a wallet to send this: CALLS_PRIVATE_KEY, or `privateKey` or `account` in code.", "no_wallet");
@@ -198,6 +229,61 @@ export function createClient(options = {}) {
198
229
  throw new CallsError("An amount is wei, as a bigint above zero.", "bad_amount");
199
230
  return amount;
200
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
+ }
201
287
  const roundState = (market) => {
202
288
  const name = marketOf(market);
203
289
  return request(`/v1/rounds/${name}`).catch((error) => {
@@ -206,28 +292,33 @@ export function createClient(options = {}) {
206
292
  };
207
293
  const eventOf = (receipt, abi, eventName) => parseEventLogs({ abi, logs: receipt.logs, eventName })[0]?.args;
208
294
  async function chainQuote(address, side, amount) {
209
- const [member, status, closeAt, holds, breaks, block] = await Promise.all([
210
- 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([
211
301
  callRead(address, "status").catch(() => null),
212
302
  callRead(address, "closeAt").catch(() => null),
213
303
  callRead(address, "pool", [1]).catch(() => null),
214
304
  callRead(address, "pool", [2]).catch(() => null),
305
+ isUsdg ? read(address, tokenCallAbi, "bonus").catch(() => null) : 0n,
215
306
  reads.getBlock({ blockTag: "latest" }),
216
307
  ]);
217
- if (!member)
218
- throw new CallsError("That address is not a Call of the Shipped Calls factory.", "not_a_call");
219
- if (status == null || closeAt == null || holds == null || breaks == null)
308
+ if (status == null || closeAt == null || holds == null || breaks == null || bonus == null)
220
309
  throw new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
221
310
  const pools = { holds, breaks };
222
- const q = quoteOf(pools, side, amount);
311
+ const q = quoteOf(pools, side, amount, bonus);
223
312
  return {
224
313
  call: address,
225
314
  side,
226
315
  amount: amount.toString(),
316
+ asset: target.asset,
317
+ bonus: bonus.toString(),
227
318
  status: STATUS[status],
228
319
  bettingOpen: status === 0 && block.timestamp < closeAt,
229
320
  closeAt: Number(closeAt),
230
- minBet: MIN_BET.toString(),
321
+ minBet: minBet.toString(),
231
322
  pools: { holds: holds.toString(), breaks: breaks.toString() },
232
323
  poolsAfter: { holds: q.poolsAfter.holds.toString(), breaks: q.poolsAfter.breaks.toString() },
233
324
  impliedBps: q.impliedBps,
@@ -244,53 +335,84 @@ export function createClient(options = {}) {
244
335
  address: account?.address ?? null,
245
336
  chainId,
246
337
  factory,
338
+ /** The factory USDG Calls open on, or null when this client knows none. */
339
+ usdgFactory,
247
340
  /** Hold payment until the work is accepted: the worker opens a job, the client funds it, a named reviewer releases it. */
248
341
  jobs: createJobs({ reads, chainId, send, guarded, wallet, toTx: (receipt) => toTx(receipt, chainId), maxFund: options.maxJobFund ?? DEFAULT_MAX_JOB_FUND }),
249
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. */
250
344
  async calls(filters = {}) {
251
- 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 ?? [] };
252
351
  },
253
- call: async (address) => request(`/v1/calls/${addressOf(address)}`),
254
352
  /** The latest bets across every Call, or every bet on one Call with `call`. */
255
353
  async bets({ call, limit } = {}) {
256
354
  if (call)
257
355
  return (await client.call(call)).bets;
258
356
  return (await request(`/v1/bets/recent${query({ limit })}`)).bets;
259
357
  },
260
- async tape({ limit } = {}) {
261
- 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;
262
361
  },
263
- leaderboard: (filters = {}) => request(`/v1/leaderboard${query(filters)}`),
264
- 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) })}`),
265
364
  /** Shipped agents: name, rule and wallet. */
266
365
  async agents() {
267
366
  return (await request("/v1/agents")).agents;
268
367
  },
269
368
  proof: () => request("/v1/proof"),
270
369
  /**
271
- * What `amount` wei on `side` pays with the pools as they stand. Reads the pools from the chain, and from the API if
272
- * 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.
273
373
  */
274
374
  async quote(address, side, amount) {
275
375
  const call = addressOf(address);
276
376
  const name = sideOf(side);
277
- if (amount < MIN_BET)
278
- throw new CallsError("The minimum bet is 0.001 ETH.", "BetTooSmall");
279
377
  try {
280
378
  return await chainQuote(call, name, amount);
281
379
  }
282
380
  catch (error) {
283
381
  if (error instanceof CallsError && error.code !== "rpc_unavailable")
284
382
  throw error;
285
- return request(`/v1/calls/${call}/quote${query({ side: name, amount })}`);
383
+ return withAsset(await request(`/v1/calls/${call}/quote${query({ side: name, amount })}`));
286
384
  }
287
385
  },
288
- /** One wallet's open positions and settled Calls from the API, with its balance and what it can claim from the chain. */
289
- 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" } = {}) {
290
405
  const who = walletOr(address);
291
- 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
+ ]);
292
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) })));
293
- 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 };
294
416
  },
295
417
  // Reads from the chain, current to the block.
296
418
  isCall: (address) => guarded(() => isCall(addressOf(address))),
@@ -308,32 +430,100 @@ export function createClient(options = {}) {
308
430
  return (await callRead(call, "callType")) === 3 ? 0 : DISPUTE_WINDOW;
309
431
  }
310
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
+ }),
311
438
  async odds(address) {
312
- const [holds, breaks] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks")]);
313
- 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) };
314
441
  },
315
442
  payoutOf: (address, who) => guarded(() => callRead(addressOf(address), "payoutOf", [walletOr(who)])),
316
443
  stake: (address, side, who) => guarded(() => callRead(addressOf(address), "stake", [walletOr(who), SIDE_CODE[sideOf(side)]])),
317
444
  balance: (who) => guarded(() => reads.getBalance({ address: walletOr(who) })),
318
445
  /**
319
- * Stakes `amount` wei on `side`. Refuses an amount over `maxStake` and an address that is not one of the factory's
320
- * 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.
321
451
  */
322
- async bet(address, side, amount, { maxStake: cap = maxStake } = {}) {
452
+ async bet(address, side, amount, { maxStake: cap = maxStake, maxStakeUsdg: usdgCap = maxStakeUsdg } = {}) {
323
453
  const name = sideOf(side);
324
- if (amount > cap)
325
- 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;
326
457
  return guarded(async () => {
327
- const call = await mustBeCall(address);
328
- // The API may be down; the chain still takes the bet, so its word only ever stops one.
329
- const stored = await client.call(call).catch(() => null);
330
- if (stored?.unresolvable)
331
- 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);
332
466
  const receipt = await send({ address: call, abi: callAbi, functionName: "bet", args: [SIDE_CODE[name]], value: amount });
333
467
  const placed = eventOf(receipt, callAbi, "Bet");
334
- return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
335
- });
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);
336
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"),
337
527
  /** Five minutes, up or down. The contract's address comes from the API, so a new deployment needs no new client. */
338
528
  rounds: {
339
529
  /** Every market's round taking bets, the round running and its latest results, in one read. */
@@ -425,31 +615,48 @@ export function createClient(options = {}) {
425
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() };
426
616
  }),
427
617
  },
428
- /** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
429
- claim: (address) => guarded(async () => {
430
- const call = await mustBeCall(address);
431
- const receipt = await send({ address: call, abi: callAbi, functionName: "claim" });
432
- const paid = eventOf(receipt, callAbi, "Claimed");
433
- return { ...toTx(receipt, chainId), call, amount: paid?.amount.toString() ?? null };
434
- }),
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
+ },
435
630
  /** Pays the opener's bond and fee share. Anyone can send it; the money only ever goes to the opener. */
436
- claimOpener: (address) => guarded(async () => {
437
- const call = await mustBeCall(address);
438
- const receipt = await send({ address: call, abi: callAbi, functionName: "claimOpener" });
439
- const paid = eventOf(receipt, callAbi, "OpenerPaid");
440
- return { ...toTx(receipt, chainId), call, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
441
- }),
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
+ },
442
639
  /** Makes a Settled Call Final once its dispute window has passed. Anyone can send it. */
443
- finalize: (address) => guarded(async () => {
444
- const call = await mustBeCall(address);
445
- return { ...toTx(await send({ address: call, abi: callAbi, functionName: "finalize" }), chainId), call };
446
- }),
447
- /** 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. */
448
- dispute: (address) => guarded(async () => {
449
- const call = await mustBeCall(address);
450
- const bond = await callRead(call, "DISPUTE_BOND");
451
- return { ...toTx(await send({ address: call, abi: callAbi, functionName: "dispute", value: bond }), chainId), call, bond: bond.toString() };
452
- }),
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
+ },
453
660
  /**
454
661
  * Opens a Call. Stores the sentence and spec with `POST /v1/calls` first, because Shipped settles from the stored
455
662
  * spec, checks the API's hashes against its own, then sends `CallsFactory.open` with the bond.