@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/src/assets.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { formatUnits, type Address } from "viem";
2
+ import { USDG } from "./chain.js";
3
+ import { CallsError } from "./errors.js";
4
+ import { ethToWei } from "./odds.js";
5
+
6
+ // A Call is staked in ETH or in one ERC-20, USDG. Every amount on a Call is in base units of its own asset, and
7
+ // nothing here adds one asset to another.
8
+
9
+ export type AssetSymbol = "ETH" | "USDG";
10
+
11
+ /** What a Call is staked in, as the API names it on every Call. */
12
+ export interface Asset {
13
+ symbol: AssetSymbol;
14
+ /** The token's contract. Null for ETH. */
15
+ address: Address | null;
16
+ decimals: number;
17
+ }
18
+
19
+ export const ETH_ASSET: Asset = Object.freeze({ symbol: "ETH", address: null, decimals: 18 });
20
+ export const USDG_ASSET: Asset = Object.freeze({ symbol: "USDG", address: USDG, decimals: 6 });
21
+
22
+ // The amounts script/DeployTokenCalls.s.sol deploys USDG Calls with, in USDG base units.
23
+ /** A USDG bet is 1 USDG or more. */
24
+ export const USDG_MIN_BET = 1_000_000n;
25
+ /** A USDG Call opens on a bond of 20 USDG or more. */
26
+ export const USDG_MIN_OPENER_BOND = 20_000_000n;
27
+ /** A USDG Call's dispute bond: 20 USDG, whatever the opener posted. */
28
+ export const USDG_DISPUTE_BOND = 20_000_000n;
29
+ /** The most one USDG bet or bonus may put in unless the caller raises it: 10 USDG. */
30
+ export const DEFAULT_MAX_STAKE_USDG = 10_000_000n;
31
+
32
+ /** "usdg", "USDG" or an Asset to its symbol. Anything else is refused. */
33
+ export function assetSymbolOf(value: unknown): AssetSymbol {
34
+ const name = (typeof value === "object" && value ? (value as Asset).symbol : String(value)).toUpperCase();
35
+ if (name === "ETH" || name === "USDG") return name;
36
+ throw new CallsError("An asset is ETH or USDG.", "bad_asset");
37
+ }
38
+
39
+ const assetOf = (asset: Asset | AssetSymbol) => (typeof asset === "string" ? (assetSymbolOf(asset) === "ETH" ? ETH_ASSET : USDG_ASSET) : asset);
40
+
41
+ const USDG_AMOUNT = /^\d+(\.\d{1,6})?$|^\.\d{1,6}$/;
42
+
43
+ /** A plain decimal amount, "5" or "0.25", in base units of `asset`. Anything else is refused rather than guessed at. */
44
+ export function parseAmount(value: string, asset: Asset | AssetSymbol, what = "The amount"): bigint {
45
+ const { symbol, decimals } = assetOf(asset);
46
+ if (symbol === "ETH") return ethToWei(value, what);
47
+ if (!USDG_AMOUNT.test(value)) throw new CallsError(`${what} is an amount in USDG with up to six decimals, such as 5 or 0.25.`, "bad_amount");
48
+ const [whole = "", fraction = ""] = value.split(".");
49
+ return BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(fraction.padEnd(decimals, "0"));
50
+ }
51
+
52
+ /** Base units of `asset` as "5 USDG" or "0.001 ETH". */
53
+ export const formatAmount = (amount: bigint | string, asset: Asset | AssetSymbol) => {
54
+ const { symbol, decimals } = assetOf(asset);
55
+ return `${formatUnits(BigInt(amount), decimals)} ${symbol}`;
56
+ };
57
+
58
+ /**
59
+ * Whether a USDG write can go, from the wallet's balance and what it has already allowed the spender. `short` is what
60
+ * the wallet lacks, 0 when it holds enough. `approve` is the allowance to set first, which is exactly `amount`, or null
61
+ * when the allowance already covers it.
62
+ */
63
+ export function approvalFor(balance: bigint, allowance: bigint, amount: bigint): { approve: bigint | null; short: bigint } {
64
+ return { approve: allowance >= amount ? null : amount, short: balance >= amount ? 0n : amount - balance };
65
+ }
package/src/chain.ts CHANGED
@@ -9,6 +9,8 @@ export const CALLED_IT = "0x500855cA9F281A1383482399ADDd1651269BB866" as const;
9
9
  export const PREVIOUS_FACTORIES: readonly `0x${string}`[] = ["0xf1F8E31D084B516b62E5646C684F7e955E8dA378"];
10
10
  export const DEEDS = "0xD5Da523ee49CB7Fe855B0C6fa38707190A9D531F" as const;
11
11
  export const USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" as const;
12
+ /** The factory USDG Calls open on, from the `usdg` block of the deployment record. Null until it is deployed. */
13
+ export const USDG_FACTORY: `0x${string}` | null = "0x2FD41764Eb18B19F8095197C5FAdC56896736485";
12
14
  export const COUNCIL = "0x71b3F054cfc653d1BA6433b8EF6a5627fA5692db" as const;
13
15
 
14
16
  // The order Shipped's own services run: the official endpoint, then POKT, which also serves old state, then dRPC.
package/src/cli.ts CHANGED
@@ -3,31 +3,33 @@ import { readFileSync } from "node:fs";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { parseArgs } from "node:util";
5
5
  import { formatEther } from "viem";
6
+ import { assetSymbolOf, DEFAULT_MAX_STAKE_USDG, formatAmount, parseAmount, type Asset } from "./assets.js";
6
7
  import { createClient, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, prepareOpen, sideOf } from "./client.js";
7
8
  import { CallsError } from "./errors.js";
8
9
  import { ethToWei } from "./odds.js";
9
- import type { CallDetail, CallRow, Quote } from "./types.js";
10
+ import type { Approval, BonusQuote, CallDetail, CallRow, Quote } from "./types.js";
10
11
 
11
- const NOT_A_QUOTE = "--quote only works with bet and open. This command would send a transaction.";
12
+ const NOT_A_QUOTE = "--quote only works with bet, bonus and open. This command would send a transaction.";
12
13
  /** The ETH the next claim brings, and what of it goes on $SHIPPED. */
13
14
  const collecting = (a: { unclaimedTotal: string; cutTotal: string }) => {
14
15
  const cut = BigInt(a.cutTotal);
15
16
  return cut > 0n ? `${eth(BigInt(a.unclaimedTotal) - cut)} in ETH and ${eth(cut)} to $SHIPPED` : eth(a.unclaimedTotal);
16
17
  };
17
18
 
18
- const HELP = `calls: read and bet on Shipped Calls, ETH markets on whether a public claim holds, on Robinhood Chain.
19
+ const HELP = `calls: read and bet on Shipped Calls, markets in ETH or USDG on whether a public claim holds, on Robinhood Chain.
19
20
 
20
21
  Read, no wallet needed:
21
- calls list [--status open] [--type price] [--subject <handle>] [--sort closing|lopsided|pot|newest] [--limit 20] [--offset 0]
22
+ calls list [--status open] [--type price] [--asset eth|usdg] [--subject <handle>] [--sort closing|lopsided|pot|newest] [--limit 20] [--offset 0]
22
23
  calls get <address>
23
- calls quote <address> <holds|breaks> <eth>
24
- calls positions [<wallet>]
24
+ calls quote <address> <holds|breaks> <amount>
25
+ calls positions [<wallet>] [--asset eth|usdg]
25
26
  calls proof
26
27
  calls rounds [<market>]
27
28
  calls rounds history [<wallet>]
28
29
 
29
30
  Write, with CALLS_PRIVATE_KEY set:
30
- calls bet <address> <holds|breaks> <eth> [--quote] [--yes] [--max-stake <eth>]
31
+ calls bet <address> <holds|breaks> <amount> [--quote] [--yes] [--max-stake <amount>]
32
+ calls bonus <address> <usdg> [--quote] [--yes] [--max-stake <usdg>]
31
33
  calls claim <address> [--opener]
32
34
  calls rounds bet <market> <up|down> <eth> [--quote] [--yes] [--max-stake <eth>]
33
35
  calls rounds claim [<market>]
@@ -37,17 +39,24 @@ Write, with CALLS_PRIVATE_KEY set:
37
39
  [--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--max-bond <eth>] [--quote] [--yes]
38
40
  calls open --text <sentence> --bond-number <n> [--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--quote] [--yes]
39
41
 
40
- --quote With bet or open: show what would be sent and send nothing.
41
- --yes Skip the confirmation. Without a terminal to confirm in, a bet or an open needs it.
42
- --max-stake The most one bet may stake. 0.01 ETH unless set here or in CALLS_MAX_STAKE.
42
+ Amounts are in the Call's own asset: ETH on an ETH Call, USDG on a USDG Call. Gas is always ETH.
43
+ A USDG bet or bonus first approves the USDG factory for exactly that amount when its allowance is short, as a
44
+ transaction of its own. A bonus goes to the winners of a USDG Call, and back to its sponsors if nobody wins.
45
+
46
+ --quote With bet, bonus or open: show what would be sent and send nothing.
47
+ --yes Skip the confirmation. Without a terminal to confirm in, a bet, a bonus or an open needs it.
48
+ --max-stake The most one bet or bonus may put in, in the Call's asset. 0.01 ETH or 10 USDG unless set here
49
+ or in CALLS_MAX_STAKE and CALLS_MAX_STAKE_USDG.
43
50
  --max-bond The largest bond open may post. 0.02 ETH unless set.
44
51
  --json Answer in JSON. A failure is {"error": "...", "code": "..."} with a non-zero exit.
45
52
 
46
53
  Environment:
47
- CALLS_PRIVATE_KEY The wallet that signs. Reads never need it.
48
- CALLS_RPC_URL RPC endpoints, comma-separated, tried in order. A public list by default.
49
- CALLS_API_URL https://calls.shipped.bond by default.
50
- CALLS_MAX_STAKE The default for --max-stake, in ETH.
54
+ CALLS_PRIVATE_KEY The wallet that signs. Reads never need it.
55
+ CALLS_RPC_URL RPC endpoints, comma-separated, tried in order. A public list by default.
56
+ CALLS_API_URL https://calls.shipped.bond by default.
57
+ CALLS_MAX_STAKE The default for --max-stake on an ETH Call, in ETH.
58
+ CALLS_MAX_STAKE_USDG The default for --max-stake on a USDG Call, in USDG.
59
+ CALLS_USDG_FACTORY The factory USDG Calls open on, when this version does not name it.
51
60
 
52
61
  Details: https://calls.shipped.bond/agents
53
62
  `;
@@ -61,6 +70,7 @@ const FLAGS = {
61
70
  opener: { type: "boolean" },
62
71
  "max-stake": { type: "string" },
63
72
  "max-bond": { type: "string" },
73
+ asset: { type: "string" },
64
74
  status: { type: "string" },
65
75
  type: { type: "string" },
66
76
  subject: { type: "string" },
@@ -85,6 +95,7 @@ const CONTROL = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g;
85
95
  const clean = (s: string | null | undefined) => String(s ?? "").replace(CONTROL, "");
86
96
 
87
97
  const eth = (wei: string | bigint) => `${formatEther(BigInt(wei))} ETH`;
98
+ const money = (asset: Asset) => (amount: string | bigint) => formatAmount(amount, asset);
88
99
  const when = (unix: number) => `${new Date(unix * 1000).toISOString().slice(0, 16).replace("T", " ")} UTC`;
89
100
  const second = (unix: number) => `${new Date(unix * 1000).toISOString().slice(0, 19).replace("T", " ")} UTC`;
90
101
  const named = (side: string) => (side === "holds" ? "Holds" : "Breaks");
@@ -109,35 +120,69 @@ function specOf(value: string | undefined): Record<string, unknown> | undefined
109
120
  }
110
121
  }
111
122
 
112
- function clientFor(values: Values, env: NodeJS.ProcessEnv) {
113
- const cap = values["max-stake"] ?? env.CALLS_MAX_STAKE;
123
+ function clientFor(env: NodeJS.ProcessEnv) {
114
124
  return createClient({
115
125
  api: env.CALLS_API_URL || undefined,
116
126
  rpc: env.CALLS_RPC_URL || undefined,
117
127
  privateKey: env.CALLS_PRIVATE_KEY || undefined,
118
- maxStake: cap ? ethToWei(cap, "--max-stake") : DEFAULT_MAX_STAKE,
128
+ maxStake: env.CALLS_MAX_STAKE ? ethToWei(env.CALLS_MAX_STAKE, "CALLS_MAX_STAKE") : DEFAULT_MAX_STAKE,
129
+ maxStakeUsdg: env.CALLS_MAX_STAKE_USDG ? parseAmount(env.CALLS_MAX_STAKE_USDG, "USDG", "CALLS_MAX_STAKE_USDG") : DEFAULT_MAX_STAKE_USDG,
130
+ usdgFactory: (env.CALLS_USDG_FACTORY || undefined) as `0x${string}` | undefined,
119
131
  });
120
132
  }
121
133
 
134
+ /** --max-stake is in the Call's own asset, so it raises the cap for that asset only. */
135
+ function capsFor(values: Values, asset: Asset) {
136
+ const cap = values["max-stake"];
137
+ if (!cap) return {};
138
+ return asset.symbol === "ETH" ? { maxStake: parseAmount(cap, asset, "--max-stake") } : { maxStakeUsdg: parseAmount(cap, asset, "--max-stake") };
139
+ }
140
+
122
141
  const windowLine = ({ disputeWindow, priceDisputeWindow }: { disputeWindow: number | null; priceDisputeWindow?: number | null }) => {
123
142
  const hours = (disputeWindow ?? 0) / 3600;
124
143
  return priceDisputeWindow ? `${priceDisputeWindow / 3600} h on a Price Call, ${hours} h on a Post or contract-read Call` : `${hours} h`;
125
144
  };
126
145
 
127
146
  function rowLines(c: CallRow | CallDetail): string[] {
147
+ const m = money(c.asset);
128
148
  const odds = c.status === "open" ? `Holds ${c.odds.holdsMultiple ?? "-"}x, Breaks ${c.odds.breaksMultiple ?? "-"}x` : c.outcome ? `${named(c.outcome)} won` : c.status;
129
- return [`${c.address} ${c.status} ${c.type} closes ${when(c.closeAt)} pot ${eth(c.pools.total)} ${odds}`, ` ${clean(c.callText) || "(no sentence stored)"}`];
149
+ const bonus = c.bonus !== "0" ? ` bonus ${m(c.bonus)}` : "";
150
+ return [`${c.address} ${c.status} ${c.type} closes ${when(c.closeAt)} pot ${m(c.pools.total)}${bonus} ${odds}`, ` ${clean(c.callText) || "(no sentence stored)"}`];
130
151
  }
131
152
 
132
153
  function quoteLines(q: Quote, text?: string | null): string[] {
154
+ const m = money(q.asset);
133
155
  const lines = text ? [clean(text)] : [];
134
- lines.push(`${eth(q.amount)} on ${named(q.side)} pays ${eth(q.payout)} (${q.multiple}x) if ${named(q.side)} wins, with the pools as they stand.`);
135
- lines.push(`Pools after this bet: Holds ${eth(q.poolsAfter.holds)}, Breaks ${eth(q.poolsAfter.breaks)}. Later bets move the payout until betting closes.`);
136
- if (q.refund) lines.push(`The other side is empty. If it stays empty, every stake comes back and nobody wins.`);
156
+ lines.push(`${m(q.amount)} on ${named(q.side)} pays ${m(q.payout)} (${q.multiple}x) if ${named(q.side)} wins, with the pools as they stand.`);
157
+ if (q.bonus !== "0" && !q.refund) lines.push(`That counts this stake's share of the ${m(q.bonus)} bonus pot, which the winners split by stake.`);
158
+ lines.push(`Pools after this bet: Holds ${m(q.poolsAfter.holds)}, Breaks ${m(q.poolsAfter.breaks)}. Later bets move the payout until betting closes.`);
159
+ if (q.refund) lines.push(`The other side is empty. If it stays empty, every stake comes back and nobody wins.${q.bonus !== "0" ? " The bonus goes back to its sponsors." : ""}`);
137
160
  lines.push(q.bettingOpen ? `Betting closes ${when(q.closeAt)}.` : `Betting is closed on this Call (${q.status}).`);
138
161
  return lines;
139
162
  }
140
163
 
164
+ function bonusLines(q: BonusQuote, text?: string | null): string[] {
165
+ const m = money(q.asset);
166
+ const lines = text ? [clean(text)] : [];
167
+ lines.push(`${m(q.amount)} into the bonus pot takes it from ${m(q.bonus)} to ${m(q.bonusAfter)}.`);
168
+ lines.push("If the Call goes Final with stake on both sides, the winners share the pot by stake, with no fee on it. If it is voided or one side is empty, each sponsor takes back what they put in.");
169
+ lines.push("Adding to the pot buys no stake. To share in it, bet.");
170
+ lines.push(q.bettingOpen ? `The pot takes additions until betting closes, ${when(q.closeAt)}.` : `Betting is closed on this Call (${q.status}), and with it the pot.`);
171
+ return lines;
172
+ }
173
+
174
+ function approvalLines(a: Approval, asset: Asset, what: string): string[] {
175
+ const m = money(asset);
176
+ if (a.short !== "0") return [`This wallet holds ${m(a.balance)}, short of the ${m(a.amount)} this ${what} needs.`];
177
+ return a.approve ? [`First an approval: the USDG factory may take ${m(a.amount)} from this wallet. That is a transaction of its own, then the ${what}.`] : [`The USDG factory's allowance already covers this ${what}.`];
178
+ }
179
+
180
+ function mustHold(a: Approval | null, asset: Asset, what: string) {
181
+ if (a && a.short !== "0") throw new CallsError(`This wallet holds ${formatAmount(a.balance, asset)}, and this ${what} needs ${formatAmount(a.amount, asset)}. Nothing was sent.`, "insufficient_usdg");
182
+ }
183
+
184
+ const approvedLine = (tx: { approval: { hash: string; explorerUrl: string | null } | null }, amount: string) => (tx.approval ? [`Approved the USDG factory for ${amount}. ${tx.approval.explorerUrl ?? tx.approval.hash}`] : []);
185
+
141
186
  async function confirm(question: string, values: Values, command: string, extra: Record<string, unknown>): Promise<void> {
142
187
  if (values.yes) return;
143
188
  if (!process.stdin.isTTY) throw Object.assign(new CallsError(`Pass --yes to ${command}, or --quote to see it first. Nothing was sent.`, "needs_confirmation"), { extra });
@@ -158,12 +203,13 @@ async function textOf(client: ReturnType<typeof createClient>, address: string):
158
203
  type Answer = { json: unknown; lines: string[] };
159
204
 
160
205
  async function run(command: string | undefined, args: string[], values: Values, env: NodeJS.ProcessEnv): Promise<Answer> {
161
- const client = clientFor(values, env);
206
+ const client = clientFor(env);
162
207
  switch (command) {
163
208
  case "list": {
164
209
  const calls = await client.calls({
165
210
  status: values.status as never,
166
211
  type: values.type as never,
212
+ asset: values.asset ? assetSymbolOf(values.asset) : undefined,
167
213
  subject: values.subject,
168
214
  sort: values.sort as never,
169
215
  limit: values.limit ? Number(values.limit) : undefined,
@@ -183,43 +229,71 @@ async function run(command: string | undefined, args: string[], values: Values,
183
229
  throw error;
184
230
  }
185
231
  const lines = rowLines(call);
232
+ const m = money(call.asset);
186
233
  if (call.post?.url) lines.push(` Post: ${clean(call.post.url)}`);
187
- lines.push(` Deadline ${when(call.deadline)}. ${call.betCount} bet${call.betCount === 1 ? "" : "s"}. Opener ${call.opener}, bond ${eth(call.bond)}.`);
234
+ lines.push(` Deadline ${when(call.deadline)}. ${call.betCount} bet${call.betCount === 1 ? "" : "s"}. Opener ${call.opener}, bond ${m(call.bond)}.`);
235
+ if (call.asset.symbol !== "ETH") lines.push(` Staked in ${call.asset.symbol}, gas in ETH. Bonus pot ${m(call.bonus)}${call.bonuses.length ? ` from ${call.bonuses.length} addition${call.bonuses.length === 1 ? "" : "s"}` : ""}.`);
188
236
  if (call.evidence) lines.push(` Evidence: ${call.evidence.url}`);
189
237
  if (call.unresolvable) lines.push(` Can't settle as written. Anyone can void it from ${when(call.unresolvable.refundsAt)}, and every stake comes back.`);
190
238
  return { json: call, lines };
191
239
  }
192
240
  case "quote": {
193
- const usage = "calls quote <address> <holds|breaks> <eth>";
241
+ const usage = "calls quote <address> <holds|breaks> <amount>";
194
242
  const address = needs(args[0], usage);
195
243
  const side = sideOf(needs(args[1], usage));
196
- const amount = ethToWei(needs(args[2], usage), "The stake");
244
+ const raw = needs(args[2], usage);
245
+ const amount = parseAmount(raw, await client.assetOf(address), "The stake");
197
246
  const quote = await client.quote(address, side, amount);
198
247
  return { json: quote, lines: quoteLines(quote, await textOf(client, address)) };
199
248
  }
200
249
  case "bet": {
201
- const usage = "calls bet <address> <holds|breaks> <eth> [--quote] [--yes] [--max-stake <eth>]";
250
+ const usage = "calls bet <address> <holds|breaks> <amount> [--quote] [--yes] [--max-stake <amount>]";
202
251
  const address = needs(args[0], usage);
203
252
  const side = sideOf(needs(args[1], usage));
204
- const amount = ethToWei(needs(args[2], usage), "The stake");
253
+ const raw = needs(args[2], usage);
205
254
  if (!values.quote && !client.address) throw new CallsError("Set CALLS_PRIVATE_KEY to bet. --quote shows what a bet pays without a wallet.", "no_wallet");
255
+ const asset = await client.assetOf(address);
256
+ const m = money(asset);
257
+ const amount = parseAmount(raw, asset, "The stake");
258
+ const caps = capsFor(values, asset);
206
259
  const [quote, text] = await Promise.all([client.quote(address, side, amount), textOf(client, address)]);
207
- const lines = quoteLines(quote, text);
208
- if (values.quote) return { json: { quote }, lines };
260
+ const approval = asset.symbol === "USDG" && client.address ? await client.usdgApproval(amount) : null;
261
+ const lines = [...quoteLines(quote, text), ...(approval ? approvalLines(approval, asset, "bet") : [])];
262
+ if (values.quote) return { json: { quote, ...(approval && { approval }) }, lines };
263
+ mustHold(approval, asset, "bet");
264
+ if (!values.json) console.error(lines.join("\n"));
265
+ await confirm(approval?.approve ? `Approve ${m(amount)} to the USDG factory, then stake it on ${named(side)}?` : `Stake ${m(amount)} on ${named(side)}?`, values, "place this bet", { quote, ...(approval && { approval }) });
266
+ const tx = await client.bet(address, side, amount, caps);
267
+ return { json: { quote, tx }, lines: [...approvedLine(tx, m(amount)), `Bet placed: ${m(amount)} on ${named(side)}. ${tx.explorerUrl ?? tx.hash}`] };
268
+ }
269
+ case "bonus": {
270
+ const usage = "calls bonus <address> <usdg> [--quote] [--yes] [--max-stake <usdg>]";
271
+ const address = needs(args[0], usage);
272
+ const raw = needs(args[1], usage);
273
+ if (!values.quote && !client.address) throw new CallsError("Set CALLS_PRIVATE_KEY to add to a bonus pot. --quote shows what it does without a wallet.", "no_wallet");
274
+ const asset = await client.assetOf(address);
275
+ if (asset.symbol !== "USDG") throw new CallsError("Bonus pots are on USDG Calls only, and this Call is staked in ETH.", "not_usdg");
276
+ const m = money(asset);
277
+ const amount = parseAmount(raw, asset, "The bonus");
278
+ const [quote, text] = await Promise.all([client.bonusQuote(address, amount), textOf(client, address)]);
279
+ const approval = client.address ? await client.usdgApproval(amount) : null;
280
+ const lines = [...bonusLines(quote, text), ...(approval ? approvalLines(approval, asset, "bonus") : [])];
281
+ if (values.quote) return { json: { quote, ...(approval && { approval }) }, lines };
282
+ mustHold(approval, asset, "bonus");
209
283
  if (!values.json) console.error(lines.join("\n"));
210
- await confirm(`Stake ${eth(amount)} on ${named(side)}?`, values, "place this bet", { quote });
211
- const tx = await client.bet(address, side, amount);
212
- return { json: { quote, tx }, lines: [`Bet placed: ${eth(amount)} on ${named(side)}. ${tx.explorerUrl ?? tx.hash}`] };
284
+ await confirm(approval?.approve ? `Approve ${m(amount)} to the USDG factory, then add it to the bonus pot?` : `Add ${m(amount)} to the bonus pot?`, values, "add to this bonus pot", { quote, ...(approval && { approval }) });
285
+ const tx = await client.addBonus(address, amount, capsFor(values, asset));
286
+ return { json: { quote, tx }, lines: [...approvedLine(tx, m(amount)), `Added ${m(amount)} to the bonus pot${tx.bonus ? `, now ${m(tx.bonus)}` : ""}. ${tx.explorerUrl ?? tx.hash}`] };
213
287
  }
214
288
  case "claim": {
215
289
  if (values.quote) throw new CallsError(NOT_A_QUOTE, "usage");
216
290
  const address = needs(args[0], "calls claim <address> [--opener]");
217
291
  if (values.opener) {
218
292
  const tx = await client.claimOpener(address);
219
- return { json: tx, lines: [`Paid the opener ${tx.amount ? eth(tx.amount) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
293
+ return { json: tx, lines: [`Paid the opener ${tx.amount ? formatAmount(tx.amount, tx.asset) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
220
294
  }
221
295
  const tx = await client.claim(address);
222
- return { json: tx, lines: [`Claimed ${tx.amount ? eth(tx.amount) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
296
+ return { json: tx, lines: [`Claimed ${tx.amount ? formatAmount(tx.amount, tx.asset) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
223
297
  }
224
298
  case "open": {
225
299
  const usage = "calls open --text <sentence> --spec <json|@file> | --bond-number <n> [--yes]";
@@ -246,11 +320,15 @@ async function run(command: string | undefined, args: string[], values: Values,
246
320
  return { json: opened, lines: [`Opened ${opened.address}. Betting closes ${when(opened.closeAt)}. ${opened.explorerUrl ?? opened.hash}`] };
247
321
  }
248
322
  case "positions": {
249
- const [positions, rounds] = await Promise.all([client.positions(args[0]), client.rounds.history(args[0]).catch(() => null)]);
250
- const lines = [`${positions.address}${positions.balance == null ? "" : ` ${eth(positions.balance)}`}`];
251
- lines.push(...positions.positions.map((p) => ` ${p.call} Holds ${eth(p.holds)}, Breaks ${eth(p.breaks)}, pays ${eth(p.paysNow)} if its side wins`));
323
+ // One asset at a time, and Rounds is ETH, so it only joins the ETH read.
324
+ const asset = values.asset ? assetSymbolOf(values.asset) : "ETH";
325
+ const [positions, rounds] = await Promise.all([client.positions(args[0], { asset }), asset === "ETH" ? client.rounds.history(args[0]).catch(() => null) : null]);
326
+ const m = money(positions.asset);
327
+ const gas = asset !== "ETH" && positions.gas != null ? `, ${eth(positions.gas)} for gas` : "";
328
+ const lines = [`${positions.address}${positions.balance == null ? "" : ` ${m(positions.balance)}${gas}`}`];
329
+ lines.push(...positions.positions.map((p) => ` ${p.call} Holds ${m(p.holds)}, Breaks ${m(p.breaks)}, pays ${m(p.paysNow)} if its side wins`));
252
330
  const owed = positions.settled.filter((s) => s.owed && s.owed !== "0");
253
- lines.push(...owed.map((s) => ` ${s.call} ${eth(s.owed!)} to claim`));
331
+ lines.push(...owed.map((s) => ` ${s.call} ${m(s.owed!)} to claim`));
254
332
  const running = rounds?.rounds.filter((r) => r.outcome === null) ?? [];
255
333
  const inRounds = running.reduce((sum, r) => sum + BigInt(r.stake), 0n);
256
334
  if (running.length) lines.push(` Rounds: ${eth(inRounds)} in ${running.length} still running`);
@@ -270,6 +348,7 @@ async function run(command: string | undefined, args: string[], values: Values,
270
348
  const usage = "calls rounds bet <market> <up|down> <eth> [--quote] [--yes] [--max-stake <eth>]";
271
349
  const [market, side] = [needs(args[1], usage), needs(args[2], usage)];
272
350
  const amount = ethToWei(needs(args[3], usage), "The stake");
351
+ const cap = values["max-stake"] ? { maxStake: ethToWei(values["max-stake"], "--max-stake") } : {};
273
352
  if (!values.quote && !client.address) throw new CallsError("Set CALLS_PRIVATE_KEY to bet. --quote shows what a bet pays without a wallet.", "no_wallet");
274
353
  const quote = await client.rounds.quote(market, side, amount);
275
354
  const lines = [
@@ -280,7 +359,7 @@ async function run(command: string | undefined, args: string[], values: Values,
280
359
  if (values.quote) return { json: { quote }, lines };
281
360
  if (!values.json) console.error(lines.join("\n"));
282
361
  await confirm(`Stake ${eth(amount)} on ${quote.side}?`, values, "place this bet", { quote });
283
- const tx = await client.rounds.bet(market, side, amount);
362
+ const tx = await client.rounds.bet(market, side, amount, cap);
284
363
  return { json: { quote, tx }, lines: [`Bet placed: ${eth(amount)} on ${quote.market} ${quote.side}, round ${tx.epoch}. ${tx.explorerUrl ?? tx.hash}`] };
285
364
  }
286
365
  if (args[0] === "claim") {