@shippedcalls/sdk 0.2.0 → 0.3.1
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/README.md +12 -0
- package/dist/abi.d.ts +1061 -0
- package/dist/abi.js +1363 -0
- package/dist/abi.js.map +1 -1
- package/dist/cli.js +87 -4
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +68 -1
- package/dist/client.js +132 -6
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +11 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/odds.d.ts +4 -0
- package/dist/odds.js +13 -0
- package/dist/odds.js.map +1 -1
- package/dist/types.d.ts +128 -0
- package/package.json +1 -1
- package/skill/SKILL.md +9 -2
- package/skill/references/api.md +7 -1
- package/skill/references/rounds.md +56 -0
- package/skill/references/write-path.md +4 -0
- package/skill/scripts/calls.sh +1 -1
- package/src/abi.ts +1364 -0
- package/src/cli.ts +76 -4
- package/src/client.ts +133 -7
- package/src/errors.ts +13 -0
- package/src/index.ts +4 -4
- package/src/odds.ts +14 -0
- package/src/types.ts +80 -0
package/src/cli.ts
CHANGED
|
@@ -8,6 +8,13 @@ import { CallsError } from "./errors.js";
|
|
|
8
8
|
import { ethToWei } from "./odds.js";
|
|
9
9
|
import type { CallDetail, CallRow, Quote } from "./types.js";
|
|
10
10
|
|
|
11
|
+
const NOT_A_QUOTE = "--quote only works with bet and open. This command would send a transaction.";
|
|
12
|
+
/** The ETH the next claim brings, and what of it goes on $SHIPPED. */
|
|
13
|
+
const collecting = (a: { unclaimedTotal: string; cutTotal: string }) => {
|
|
14
|
+
const cut = BigInt(a.cutTotal);
|
|
15
|
+
return cut > 0n ? `${eth(BigInt(a.unclaimedTotal) - cut)} in ETH and ${eth(cut)} to $SHIPPED` : eth(a.unclaimedTotal);
|
|
16
|
+
};
|
|
17
|
+
|
|
11
18
|
const HELP = `calls: read and bet on Shipped Calls, ETH markets on whether a public claim holds, on Robinhood Chain.
|
|
12
19
|
|
|
13
20
|
Read, no wallet needed:
|
|
@@ -16,15 +23,21 @@ Read, no wallet needed:
|
|
|
16
23
|
calls quote <address> <holds|breaks> <eth>
|
|
17
24
|
calls positions [<wallet>]
|
|
18
25
|
calls proof
|
|
26
|
+
calls rounds [<market>]
|
|
27
|
+
calls rounds history [<wallet>]
|
|
19
28
|
|
|
20
29
|
Write, with CALLS_PRIVATE_KEY set:
|
|
21
30
|
calls bet <address> <holds|breaks> <eth> [--quote] [--yes] [--max-stake <eth>]
|
|
22
31
|
calls claim <address> [--opener]
|
|
32
|
+
calls rounds bet <market> <up|down> <eth> [--quote] [--yes] [--max-stake <eth>]
|
|
33
|
+
calls rounds claim [<market>]
|
|
34
|
+
calls rounds plain-wins <on|off>
|
|
35
|
+
calls rounds limit <eth>
|
|
23
36
|
calls open --text <sentence> --spec <json|@file> [--handle <x handle>] [--post-url <url>] [--post-text <text>]
|
|
24
37
|
[--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--max-bond <eth>] [--quote] [--yes]
|
|
25
38
|
calls open --text <sentence> --bond-number <n> [--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--quote] [--yes]
|
|
26
39
|
|
|
27
|
-
--quote
|
|
40
|
+
--quote With bet or open: show what would be sent and send nothing.
|
|
28
41
|
--yes Skip the confirmation. Without a terminal to confirm in, a bet or an open needs it.
|
|
29
42
|
--max-stake The most one bet may stake. 0.01 ETH unless set here or in CALLS_MAX_STAKE.
|
|
30
43
|
--max-bond The largest bond open may post. 0.02 ETH unless set.
|
|
@@ -73,6 +86,7 @@ const clean = (s: string | null | undefined) => String(s ?? "").replace(CONTROL,
|
|
|
73
86
|
|
|
74
87
|
const eth = (wei: string | bigint) => `${formatEther(BigInt(wei))} ETH`;
|
|
75
88
|
const when = (unix: number) => `${new Date(unix * 1000).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
89
|
+
const second = (unix: number) => `${new Date(unix * 1000).toISOString().slice(0, 19).replace("T", " ")} UTC`;
|
|
76
90
|
const named = (side: string) => (side === "holds" ? "Holds" : "Breaks");
|
|
77
91
|
|
|
78
92
|
function unixOf(value: string | undefined, what: string): number | undefined {
|
|
@@ -198,6 +212,7 @@ async function run(command: string | undefined, args: string[], values: Values,
|
|
|
198
212
|
return { json: { quote, tx }, lines: [`Bet placed: ${eth(amount)} on ${named(side)}. ${tx.explorerUrl ?? tx.hash}`] };
|
|
199
213
|
}
|
|
200
214
|
case "claim": {
|
|
215
|
+
if (values.quote) throw new CallsError(NOT_A_QUOTE, "usage");
|
|
201
216
|
const address = needs(args[0], "calls claim <address> [--opener]");
|
|
202
217
|
if (values.opener) {
|
|
203
218
|
const tx = await client.claimOpener(address);
|
|
@@ -231,13 +246,69 @@ async function run(command: string | undefined, args: string[], values: Values,
|
|
|
231
246
|
return { json: opened, lines: [`Opened ${opened.address}. Betting closes ${when(opened.closeAt)}. ${opened.explorerUrl ?? opened.hash}`] };
|
|
232
247
|
}
|
|
233
248
|
case "positions": {
|
|
234
|
-
const positions = await client.positions(args[0]);
|
|
249
|
+
const [positions, rounds] = await Promise.all([client.positions(args[0]), client.rounds.history(args[0]).catch(() => null)]);
|
|
235
250
|
const lines = [`${positions.address}${positions.balance == null ? "" : ` ${eth(positions.balance)}`}`];
|
|
236
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`));
|
|
237
252
|
const owed = positions.settled.filter((s) => s.owed && s.owed !== "0");
|
|
238
253
|
lines.push(...owed.map((s) => ` ${s.call} ${eth(s.owed!)} to claim`));
|
|
239
|
-
|
|
240
|
-
|
|
254
|
+
const running = rounds?.rounds.filter((r) => r.outcome === null) ?? [];
|
|
255
|
+
const inRounds = running.reduce((sum, r) => sum + BigInt(r.stake), 0n);
|
|
256
|
+
if (running.length) lines.push(` Rounds: ${eth(inRounds)} in ${running.length} still running`);
|
|
257
|
+
if (rounds?.unclaimedRounds) lines.push(` Rounds: ${rounds.unclaimedRounds} to collect, ${collecting(rounds)} in the next claim. Run calls rounds claim.`);
|
|
258
|
+
if (!positions.positions.length && !owed.length && !running.length && !rounds?.unclaimedRounds) lines.push(" No open positions and nothing to claim.");
|
|
259
|
+
return { json: { ...positions, rounds: rounds && { running, unclaimedRounds: rounds.unclaimedRounds, unclaimedTotal: rounds.unclaimedTotal } }, lines };
|
|
260
|
+
}
|
|
261
|
+
case "rounds": {
|
|
262
|
+
if (args[0] === "history") {
|
|
263
|
+
const history = await client.rounds.history(args[1]);
|
|
264
|
+
const lines = [`${history.wallet}: ${history.wins}-${history.losses}, streak ${history.streak.current}, best ${history.streak.best}. ${history.unclaimedRounds} to collect, ${collecting(history)} in the next claim.`];
|
|
265
|
+
const result = (r: (typeof history.rounds)[number]) => (r.outcome === null ? "not decided yet" : r.outcome === "refunded" ? "refunded" : r.won ? `won, paid ${eth(r.payout!)}` : `lost, ${eth(r.payout ?? "0")} back`);
|
|
266
|
+
lines.push(...history.rounds.slice(0, 10).map((r) => ` ${r.market} ${r.epoch} ${r.up ? "Up" : "Down"} ${eth(r.stake)}: ${result(r)}`));
|
|
267
|
+
return { json: history, lines };
|
|
268
|
+
}
|
|
269
|
+
if (args[0] === "bet") {
|
|
270
|
+
const usage = "calls rounds bet <market> <up|down> <eth> [--quote] [--yes] [--max-stake <eth>]";
|
|
271
|
+
const [market, side] = [needs(args[1], usage), needs(args[2], usage)];
|
|
272
|
+
const amount = ethToWei(needs(args[3], usage), "The stake");
|
|
273
|
+
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
|
+
const quote = await client.rounds.quote(market, side, amount);
|
|
275
|
+
const lines = [
|
|
276
|
+
`${quote.market} ${quote.side} in round ${quote.epoch}: ${eth(quote.inPlay)} of your ${eth(amount)} is matched with the pools as they stand. A win pays ${eth(quote.payout)}, and whatever isn't matched comes back either way. Bets stop ${second(quote.cutoffAt)}.`,
|
|
277
|
+
...(quote.refund ? ["Nobody is on the other side yet. Close to the lock a Shipped agent may match up to 0.005 ETH of it. If nobody takes it, the stake comes back."] : []),
|
|
278
|
+
...(quote.refused ? [`This bet would be refused: ${quote.refused.message}`] : []),
|
|
279
|
+
];
|
|
280
|
+
if (values.quote) return { json: { quote }, lines };
|
|
281
|
+
if (!values.json) console.error(lines.join("\n"));
|
|
282
|
+
await confirm(`Stake ${eth(amount)} on ${quote.side}?`, values, "place this bet", { quote });
|
|
283
|
+
const tx = await client.rounds.bet(market, side, amount);
|
|
284
|
+
return { json: { quote, tx }, lines: [`Bet placed: ${eth(amount)} on ${quote.market} ${quote.side}, round ${tx.epoch}. ${tx.explorerUrl ?? tx.hash}`] };
|
|
285
|
+
}
|
|
286
|
+
if (args[0] === "claim") {
|
|
287
|
+
if (values.quote) throw new CallsError(NOT_A_QUOTE, "usage");
|
|
288
|
+
const tx = await client.rounds.claim(args[1]);
|
|
289
|
+
return { json: tx, lines: [`Collected ${eth(tx.amount)} from ${tx.rounds} ${tx.rounds === 1 ? "round" : "rounds"}, ${tx.left} left.${tx.cut === "0" ? "" : ` ${eth(tx.cut)} bought $SHIPPED.`} ${tx.explorerUrl ?? tx.hash}`] };
|
|
290
|
+
}
|
|
291
|
+
if (args[0] === "plain-wins") {
|
|
292
|
+
if (values.quote) throw new CallsError(NOT_A_QUOTE, "usage");
|
|
293
|
+
const setting = needs(args[1], "calls rounds plain-wins <on|off>");
|
|
294
|
+
if (setting !== "on" && setting !== "off") throw new CallsError("Usage: calls rounds plain-wins <on|off>", "usage");
|
|
295
|
+
const tx = await client.rounds.setPlainWins(setting === "on");
|
|
296
|
+
return { json: tx, lines: [`${setting === "on" ? "Every win now pays in ETH, with no card and no $SHIPPED buy." : "A win that earns a card now mints it, and 10% of its profit buys $SHIPPED."} ${tx.explorerUrl ?? tx.hash}`] };
|
|
297
|
+
}
|
|
298
|
+
if (args[0] === "limit") {
|
|
299
|
+
if (values.quote) throw new CallsError(NOT_A_QUOTE, "usage");
|
|
300
|
+
const cap = ethToWei(needs(args[1], "calls rounds limit <eth>"), "The limit");
|
|
301
|
+
const tx = await client.rounds.setLimit(cap);
|
|
302
|
+
return { json: tx, lines: [`Asked for a daily limit of ${cap === 0n ? "none" : eth(cap)}. Lowering it applies at once; raising or removing it takes 24 hours. ${tx.explorerUrl ?? tx.hash}`] };
|
|
303
|
+
}
|
|
304
|
+
if (args[0]) {
|
|
305
|
+
const market = await client.rounds.state(args[0]);
|
|
306
|
+
return { json: market, lines: [`${market.market} round ${market.betting.epoch}: Up ${eth(market.betting.up)}, Down ${eth(market.betting.down)}. Bets stop ${second(market.betting.cutoffAt)}.${market.open ? "" : " Rounds isn't taking bets right now."}`] };
|
|
307
|
+
}
|
|
308
|
+
const floor = await client.rounds.markets();
|
|
309
|
+
const lines = floor.markets.map((m) => `${m.market} round ${m.betting.epoch}: Up ${eth(m.betting.up)}, Down ${eth(m.betting.down)}. Bets stop ${second(m.betting.cutoffAt)}.`);
|
|
310
|
+
if (!floor.open) lines.push("Rounds isn't taking bets right now.");
|
|
311
|
+
return { json: floor, lines };
|
|
241
312
|
}
|
|
242
313
|
case "proof": {
|
|
243
314
|
const proof = await client.proof();
|
|
@@ -245,6 +316,7 @@ async function run(command: string | undefined, args: string[], values: Values,
|
|
|
245
316
|
lines.push(...proof.contracts.map((c) => ` ${c.name}: ${c.address}${c.sourcify === "exact_match" ? ", source published, exact match" : ""}`));
|
|
246
317
|
if (proof.rules.minBet) lines.push(`Minimum bet ${eth(proof.rules.minBet)}. Fee ${(proof.rules.rakeBps ?? 0) / 100}% of the losing pool. Dispute window ${windowLine(proof.rules)}.`);
|
|
247
318
|
if (proof.activity) lines.push(`${proof.activity.opened} Calls opened, ${eth(proof.activity.staked)} staked, ${eth(proof.activity.paidOut)} paid out.`);
|
|
319
|
+
if (proof.rounds) lines.push(`Rounds: prices checked by Pyth at ${proof.rounds.oracle}, guarded by ${proof.rounds.guardian.address}.`);
|
|
248
320
|
if (proof.agents.length) lines.push(`Shipped agents: ${proof.agents.map((a) => a.name).join(", ")}.`);
|
|
249
321
|
return { json: proof, lines };
|
|
250
322
|
}
|
package/src/client.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { formatEther, getAddress, isAddress, parseEventLogs, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
|
|
1
|
+
import { formatEther, getAddress, isAddress, parseEventLogs, stringToHex, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
|
|
2
2
|
import { privateKeyToAccount } from "viem/accounts";
|
|
3
|
-
import { callAbi, factoryAbi } from "./abi.js";
|
|
3
|
+
import { callAbi, factoryAbi, roundsAbi } from "./abi.js";
|
|
4
4
|
import { hashJson } from "./canonical.js";
|
|
5
5
|
import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, rpcEndpoints } from "./chain.js";
|
|
6
|
-
import { CallsError, describe } from "./errors.js";
|
|
6
|
+
import { CallsError, describe, RECEIPT_UNKNOWN, revertLine } from "./errors.js";
|
|
7
7
|
import { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
|
|
8
|
-
import { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, odds, quoteOf, type Side } from "./odds.js";
|
|
9
|
-
import type { CallDetail, CallRow, CallStatus, CallType, Leaderboard,
|
|
8
|
+
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
10
|
|
|
11
11
|
export interface ClientOptions {
|
|
12
12
|
/** The API's origin. https://calls.shipped.bond by default. */
|
|
@@ -52,6 +52,22 @@ const deedsCoreAbi = [
|
|
|
52
52
|
] as const;
|
|
53
53
|
const BOND_OPEN = 1;
|
|
54
54
|
|
|
55
|
+
export function roundSideOf(side: unknown): RoundSide {
|
|
56
|
+
const name = String(side).toLowerCase();
|
|
57
|
+
if (name === "up" || name === "down") return name;
|
|
58
|
+
throw new CallsError("Pick a side: up or down.", "bad_side");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function marketOf(market: unknown): string {
|
|
62
|
+
const name = String(market).toUpperCase();
|
|
63
|
+
if (!/^[A-Z0-9]{2,8}$/.test(name)) throw new CallsError("A market is a symbol such as ETH.", "bad_market");
|
|
64
|
+
return name;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const marketId = (market: string) => stringToHex(market, { size: 32 });
|
|
68
|
+
/** One transaction collects at most this many rounds; the rest wait for the next claim. */
|
|
69
|
+
const CLAIM_BATCH = 40;
|
|
70
|
+
|
|
55
71
|
export function sideOf(side: unknown): Side {
|
|
56
72
|
const name = String(side).toLowerCase();
|
|
57
73
|
if (name === "holds" || name === "1") return "holds";
|
|
@@ -168,7 +184,11 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
168
184
|
return account;
|
|
169
185
|
}
|
|
170
186
|
|
|
171
|
-
const walletOr = (value?: unknown) =>
|
|
187
|
+
const walletOr = (value?: unknown) => {
|
|
188
|
+
if (value) return addressOf(value, "wallet");
|
|
189
|
+
if (!account) throw new CallsError("Name a wallet, or set CALLS_PRIVATE_KEY.", "no_wallet");
|
|
190
|
+
return account.address;
|
|
191
|
+
};
|
|
172
192
|
|
|
173
193
|
async function assertChain() {
|
|
174
194
|
if (chainChecked) return;
|
|
@@ -186,11 +206,26 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
186
206
|
const { request: simulated } = await reads.simulateContract(call);
|
|
187
207
|
const estimate = await reads.estimateContractGas(call);
|
|
188
208
|
const hash = await writes!.writeContract({ ...(simulated as object), gas: (estimate * 5n + 3n) / 4n } as never);
|
|
189
|
-
|
|
209
|
+
// Once there is a hash, a failed read says nothing about the transaction: calling that a failure invites paying twice.
|
|
210
|
+
const receipt = await reads.waitForTransactionReceipt({ hash, pollingInterval: 1_000 }).catch(() => {
|
|
211
|
+
throw new CallsError(`Transaction ${hash} was sent and its receipt could not be read. Check it before sending this again.`, RECEIPT_UNKNOWN);
|
|
212
|
+
});
|
|
190
213
|
if (receipt.status !== "success") throw new CallsError("The transaction failed onchain.", "reverted");
|
|
191
214
|
return receipt;
|
|
192
215
|
}
|
|
193
216
|
|
|
217
|
+
const weiOf = (amount: unknown) => {
|
|
218
|
+
if (typeof amount !== "bigint" || amount <= 0n) throw new CallsError("An amount is wei, as a bigint above zero.", "bad_amount");
|
|
219
|
+
return amount;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const roundState = (market: string) => {
|
|
223
|
+
const name = marketOf(market);
|
|
224
|
+
return request<RoundsMarket & { open: boolean }>(`/v1/rounds/${name}`).catch((error: CallsError) => {
|
|
225
|
+
throw error.status === 404 ? new CallsError(`Rounds has no ${name} market.`, "UnknownMarket") : error;
|
|
226
|
+
});
|
|
227
|
+
};
|
|
228
|
+
|
|
194
229
|
const eventOf = <T>(receipt: TransactionReceipt, abi: Abi, eventName: string) => (parseEventLogs({ abi, logs: receipt.logs, eventName } as never) as unknown as { args: T }[])[0]?.args;
|
|
195
230
|
|
|
196
231
|
async function chainQuote(address: Address, side: Side, amount: bigint): Promise<Quote> {
|
|
@@ -322,6 +357,97 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
322
357
|
});
|
|
323
358
|
},
|
|
324
359
|
|
|
360
|
+
/** Five minutes, up or down. The contract's address comes from the API, so a new deployment needs no new client. */
|
|
361
|
+
rounds: {
|
|
362
|
+
/** Every market's round taking bets, the round running and its latest results, in one read. */
|
|
363
|
+
markets: () => request<RoundsFloor>("/v1/rounds"),
|
|
364
|
+
state: roundState,
|
|
365
|
+
/**
|
|
366
|
+
* What `amount` wei does on a side, with the pools as they stand, before any card's cut. `inPlay` is the part that's
|
|
367
|
+
* matched; the rest comes back win or lose. `payout` is what comes back on a win. Later bets move both until the lock.
|
|
368
|
+
* `refund` means nobody is on the other side yet. `refused` names what would stop this bet. Sends nothing.
|
|
369
|
+
*/
|
|
370
|
+
async quote(market: string, side: RoundSide | string, amount: bigint) {
|
|
371
|
+
weiOf(amount);
|
|
372
|
+
const name = marketOf(market);
|
|
373
|
+
const chosen = roundSideOf(side);
|
|
374
|
+
const [floor, history] = await Promise.all([request<RoundsFloor>("/v1/rounds"), account ? request<RoundsAccount>(`/v1/accounts/${account.address}/rounds`).catch(() => null) : null]);
|
|
375
|
+
const betting = floor.markets.find((m) => m.market === name)?.betting;
|
|
376
|
+
if (!betting) throw new CallsError(`Rounds has no ${name} market.`, "UnknownMarket");
|
|
377
|
+
const [mine, other] = chosen === "up" ? [betting.up, betting.down] : [betting.down, betting.up];
|
|
378
|
+
const payout = roundPayout(amount, BigInt(mine), BigInt(other));
|
|
379
|
+
const held = history?.rounds.find((r) => r.market === name && r.epoch === betting.epoch);
|
|
380
|
+
const refusal =
|
|
381
|
+
!floor.open ? "rounds_closed"
|
|
382
|
+
: floor.now >= betting.cutoffAt ? "TooLate"
|
|
383
|
+
: amount < BigInt(floor.minBet) ? "BelowMinimum"
|
|
384
|
+
: held && held.up !== (chosen === "up") ? "OtherSide"
|
|
385
|
+
: BigInt(held?.stake ?? 0) + amount > BigInt(floor.maxStake) ? "OverStakeCap"
|
|
386
|
+
: null;
|
|
387
|
+
return {
|
|
388
|
+
market: name,
|
|
389
|
+
side: chosen,
|
|
390
|
+
amount: amount.toString(),
|
|
391
|
+
inPlay: roundInPlay(amount, BigInt(mine), BigInt(other)).toString(),
|
|
392
|
+
open: floor.open,
|
|
393
|
+
epoch: betting.epoch,
|
|
394
|
+
cutoffAt: betting.cutoffAt,
|
|
395
|
+
payout: payout.toString(),
|
|
396
|
+
profit: (payout - amount).toString(),
|
|
397
|
+
multiple: multipleOf(payout, amount),
|
|
398
|
+
refund: BigInt(other) === 0n,
|
|
399
|
+
refused: refusal && { code: refusal, message: refusal === "rounds_closed" ? "Rounds isn't taking bets right now." : revertLine(refusal) },
|
|
400
|
+
};
|
|
401
|
+
},
|
|
402
|
+
/** With `plain` on, every win pays in ETH: no card and no $SHIPPED buy. */
|
|
403
|
+
setPlainWins: (plain = true) =>
|
|
404
|
+
guarded(async () => {
|
|
405
|
+
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
406
|
+
return toTx(await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "setPlainWins", args: [plain] }), chainId);
|
|
407
|
+
}),
|
|
408
|
+
/** The wallet's own daily stake limit in wei, 0 for none. Lowering applies at once; raising or removing takes 24 hours. */
|
|
409
|
+
setLimit: (cap: bigint) =>
|
|
410
|
+
guarded(async () => {
|
|
411
|
+
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
412
|
+
return toTx(await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "setLimit", args: [cap] }), chainId);
|
|
413
|
+
}),
|
|
414
|
+
/** A wallet's streak, today's stake and profit, what it can collect, its daily limit and its latest rounds. */
|
|
415
|
+
history: (who?: string) => guarded(() => request<RoundsAccount>(`/v1/accounts/${walletOr(who)}/rounds`)),
|
|
416
|
+
|
|
417
|
+
/** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while rounds aren't being priced. */
|
|
418
|
+
async bet(market: string, side: RoundSide | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
|
|
419
|
+
weiOf(amount);
|
|
420
|
+
const name = marketOf(market);
|
|
421
|
+
const chosen = roundSideOf(side);
|
|
422
|
+
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");
|
|
423
|
+
return guarded(async () => {
|
|
424
|
+
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
425
|
+
if (!floor.markets.some((m) => m.market === name)) throw new CallsError(`Rounds has no ${name} market.`, "UnknownMarket");
|
|
426
|
+
if (!floor.open) throw new CallsError("Rounds isn't taking bets right now, so nothing was sent.", "rounds_closed");
|
|
427
|
+
const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "bet", args: [marketId(name), chosen === "up"], value: amount });
|
|
428
|
+
const placed = eventOf<{ epoch: bigint; upPool: bigint; downPool: bigint }>(receipt, roundsAbi as Abi, "Bet");
|
|
429
|
+
return { ...toTx(receipt, chainId), market: name, epoch: placed ? Number(placed.epoch) : null, side: chosen, amount: amount.toString(), pools: placed ? { up: placed.upPool.toString(), down: placed.downPool.toString() } : null };
|
|
430
|
+
});
|
|
431
|
+
},
|
|
432
|
+
|
|
433
|
+
/** Collects what this wallet is owed: every market, one market, or the epochs named, oldest first. `amount` is the ETH that reached the wallet; `cut` is what bought $SHIPPED for it. The money only ever goes to the wallet that sends this. */
|
|
434
|
+
claim: (market?: string, epochs?: readonly number[]) =>
|
|
435
|
+
guarded(async () => {
|
|
436
|
+
const only = market ? marketOf(market) : null;
|
|
437
|
+
const [floor, account] = await Promise.all([request<RoundsFloor>("/v1/rounds"), request<RoundsAccount>(`/v1/accounts/${wallet().address}/rounds`)]);
|
|
438
|
+
if (only && !floor.markets.some((m) => m.market === only)) throw new CallsError(`Rounds has no ${only} market.`, "UnknownMarket");
|
|
439
|
+
const owed = account.unclaimed.filter((o) => (!only || o.market === only) && (!epochs || epochs.includes(o.epoch)));
|
|
440
|
+
if (!owed.length && account.unclaimedRounds > account.unclaimed.length) throw new CallsError("This wallet has older rounds to collect first. Claim without naming a market or epochs.", "NothingToClaim");
|
|
441
|
+
if (!owed.length) throw new CallsError("Nothing to claim for this wallet.", "NothingToClaim");
|
|
442
|
+
const batch = owed.slice(0, CLAIM_BATCH);
|
|
443
|
+
const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "claim", args: [batch.map((o) => marketId(o.market)), batch.map((o) => BigInt(o.epoch))] });
|
|
444
|
+
const paid = parseEventLogs({ abi: roundsAbi as Abi, logs: receipt.logs, eventName: "Claimed" } as never) as unknown as { args: { amount: bigint } }[];
|
|
445
|
+
const card = eventOf<{ cut: bigint; paid: boolean }>(receipt, roundsAbi as Abi, "CardCut");
|
|
446
|
+
const cut = card?.paid ? card.cut : 0n;
|
|
447
|
+
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() };
|
|
448
|
+
}),
|
|
449
|
+
},
|
|
450
|
+
|
|
325
451
|
/** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
|
|
326
452
|
claim: (address: string) =>
|
|
327
453
|
guarded(async () => {
|
package/src/errors.ts
CHANGED
|
@@ -12,6 +12,9 @@ export class CallsError extends Error {
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
/** The transaction went out and may have landed. Don't send it again without checking. */
|
|
16
|
+
export const RECEIPT_UNKNOWN = "receipt_unknown";
|
|
17
|
+
|
|
15
18
|
export const NOT_ENOUGH_ETH = "Not enough ETH to cover this and gas.";
|
|
16
19
|
|
|
17
20
|
// Keyed by error name, or by `function.error` where one revert means different things on different calls.
|
|
@@ -33,9 +36,19 @@ const REVERTS: Record<string, string> = {
|
|
|
33
36
|
IsDeedCall: "A Call on a bond settles from the bond's ruling.",
|
|
34
37
|
TransferFailed: "The payment could not be delivered to that address.",
|
|
35
38
|
InsufficientBalance: NOT_ENOUGH_ETH,
|
|
39
|
+
TooLate: "Betting has closed on this round. The next one opens at the lock, within ten seconds.",
|
|
40
|
+
BelowMinimum: "The minimum bet is 0.001 ETH.",
|
|
41
|
+
OverStakeCap: "One wallet can stake up to 0.5 ETH in a round.",
|
|
42
|
+
OverDailyLimit: "This would take the wallet past the daily limit it set for itself.",
|
|
43
|
+
OtherSide: "This wallet is already on the other side of this round.",
|
|
44
|
+
MarketPaused: "This market isn't taking bets right now.",
|
|
45
|
+
UnknownMarket: "Rounds has no such market.",
|
|
46
|
+
GasTooLow: "This win's card needs more gas. Send at least the estimate.",
|
|
36
47
|
};
|
|
37
48
|
|
|
38
49
|
/** One sentence for a failed read or write. RPC URLs can carry keys, so nothing from the transport is passed on. */
|
|
50
|
+
export const revertLine = (name: string) => REVERTS[name] ?? `The contract would refuse this: ${name}.`;
|
|
51
|
+
|
|
39
52
|
export function describe(error: unknown): CallsError {
|
|
40
53
|
if (error instanceof CallsError) return error;
|
|
41
54
|
if (!(error instanceof BaseError)) return new CallsError("The request did not go through.", "unknown");
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { createClient, accountFromKey, bondIdOf, prepareOpen, sideOf, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, type CallsClient, type ClientOptions } from "./client.js";
|
|
1
|
+
export { createClient, accountFromKey, bondIdOf, prepareOpen, roundSideOf, sideOf, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, type CallsClient, type ClientOptions } from "./client.js";
|
|
2
2
|
export { API_URL, CALLED_IT, CHAIN_ID, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints } from "./chain.js";
|
|
3
|
-
export { callAbi, calledItAbi, factoryAbi } from "./abi.js";
|
|
3
|
+
export { callAbi, calledItAbi, factoryAbi, roundsAbi } from "./abi.js";
|
|
4
4
|
export { canonical, hashJson } from "./canonical.js";
|
|
5
|
-
export { CallsError } from "./errors.js";
|
|
5
|
+
export { CallsError, RECEIPT_UNKNOWN } from "./errors.js";
|
|
6
6
|
export { callTextHash, canonicalPostUrl, normalizeHandle, parsePostUrl, postRefHash, specHash, subjectHash, ZERO_HASH } from "./hashes.js";
|
|
7
|
-
export { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, PRICE_DISPUTE_WINDOW, RAKE_BPS, ethToWei, multipleOf, odds, payout, quoteOf, type Pools, type Side } from "./odds.js";
|
|
7
|
+
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
8
|
export type * from "./types.js";
|
package/src/odds.ts
CHANGED
|
@@ -16,6 +16,20 @@ export function ethToWei(value: string, what = "The amount"): bigint {
|
|
|
16
16
|
return parseEther(value);
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/** How much of a stake plays, counted into the pools: only matched stake does, and the rest comes back win or lose. */
|
|
20
|
+
export function roundInPlay(stake: bigint, side: bigint, other: bigint): bigint {
|
|
21
|
+
const winning = side + stake;
|
|
22
|
+
return (stake * (winning < other ? winning : other)) / winning;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a stake in a round pays if its side wins, counted into the pools, at the fee of a wallet that doesn't hold $SHIPPED: 3% of what plays. */
|
|
26
|
+
export function roundPayout(stake: bigint, side: bigint, other: bigint): bigint {
|
|
27
|
+
if (other === 0n) return stake;
|
|
28
|
+
const winning = side + stake;
|
|
29
|
+
const matched = winning < other ? winning : other;
|
|
30
|
+
return (stake * (winning + matched - (2n * matched * 300n) / 10000n)) / winning;
|
|
31
|
+
}
|
|
32
|
+
|
|
19
33
|
export type Side = "holds" | "breaks";
|
|
20
34
|
export interface Pools {
|
|
21
35
|
holds: bigint;
|
package/src/types.ts
CHANGED
|
@@ -194,6 +194,8 @@ export interface Proof {
|
|
|
194
194
|
};
|
|
195
195
|
activity: { opened: number; final: number; disputed: number; voided: number; staked: Wei; paidOut: Wei; asOf: { block: number; at: number } | null } | null;
|
|
196
196
|
software: Record<string, unknown>;
|
|
197
|
+
/** Who holds the keys of Rounds, or null while it isn't running. */
|
|
198
|
+
rounds: { guardian: { address: Address; kind: string | null }; oracle: Address } | null;
|
|
197
199
|
readAt: number;
|
|
198
200
|
agents: ShippedAgent[];
|
|
199
201
|
}
|
|
@@ -303,3 +305,81 @@ export interface Positions {
|
|
|
303
305
|
week: Player["week"];
|
|
304
306
|
all: Player["all"];
|
|
305
307
|
}
|
|
308
|
+
|
|
309
|
+
export type RoundOutcome = "up" | "down" | "refunded";
|
|
310
|
+
export type RoundSide = "up" | "down";
|
|
311
|
+
|
|
312
|
+
export interface RoundPools {
|
|
313
|
+
epoch: number;
|
|
314
|
+
lockAt: number;
|
|
315
|
+
closeAt: number;
|
|
316
|
+
up: Wei;
|
|
317
|
+
down: Wei;
|
|
318
|
+
bets: number;
|
|
319
|
+
/** What a winning stake gets back per unit at these pools, its unmatched part included, floored to hundredths; null while either side is empty. */
|
|
320
|
+
upPays: number | null;
|
|
321
|
+
downPays: number | null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export interface RoundResult {
|
|
325
|
+
market: string;
|
|
326
|
+
epoch: number;
|
|
327
|
+
outcome: RoundOutcome;
|
|
328
|
+
lockPrice: string | null;
|
|
329
|
+
closePrice: string | null;
|
|
330
|
+
up: Wei;
|
|
331
|
+
down: Wei;
|
|
332
|
+
pool: Wei;
|
|
333
|
+
rake: Wei;
|
|
334
|
+
pays: number | null;
|
|
335
|
+
decidedAt: number;
|
|
336
|
+
lockAt: number;
|
|
337
|
+
closeAt: number;
|
|
338
|
+
txHash: Hash;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export interface RoundsMarket {
|
|
342
|
+
market: string;
|
|
343
|
+
symbol: string;
|
|
344
|
+
price: string | null;
|
|
345
|
+
betting: RoundPools & { opensAt: number; cutoffAt: number };
|
|
346
|
+
running: RoundPools & { lockPrice: string | null };
|
|
347
|
+
last: RoundResult[];
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export interface RoundsFloor {
|
|
351
|
+
now: number;
|
|
352
|
+
/** False while rounds aren't being priced. A bet then would wait out the hour and refund, so the client refuses it. */
|
|
353
|
+
open: boolean;
|
|
354
|
+
contract: Address;
|
|
355
|
+
interval: number;
|
|
356
|
+
cutoff: number;
|
|
357
|
+
minBet: Wei;
|
|
358
|
+
maxStake: Wei;
|
|
359
|
+
rakeBps: number;
|
|
360
|
+
terms: { holdToken: Address; holdMin: Wei; holderRakeBps: number; cards: Address; cardCutBps: number; cardStreak: number; maxCardCut: Wei } | null;
|
|
361
|
+
markets: RoundsMarket[];
|
|
362
|
+
feed: { market: string; epoch: number; wallet: Address; agent: string | null; up: boolean; amount: Wei; at: number; txHash: Hash }[];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export interface RoundsAccount {
|
|
366
|
+
wallet: Address;
|
|
367
|
+
streak: { current: number; best: number };
|
|
368
|
+
profitToday: Wei;
|
|
369
|
+
stakedToday: Wei;
|
|
370
|
+
played: number;
|
|
371
|
+
wins: number;
|
|
372
|
+
losses: number;
|
|
373
|
+
/** The oldest rounds this wallet can collect, which is what one claim takes. `amount` is what collecting credits; `cut` of it buys $SHIPPED for the wallet when `card` is true. */
|
|
374
|
+
unclaimed: { market: string; epoch: number; amount: Wei; cut: Wei; streak: number; card: boolean }[];
|
|
375
|
+
/** Every round this wallet can collect, listed or not. */
|
|
376
|
+
unclaimedRounds: number;
|
|
377
|
+
unclaimedTotal: Wei;
|
|
378
|
+
cutTotal: Wei;
|
|
379
|
+
shippedBought: Wei;
|
|
380
|
+
holds: boolean;
|
|
381
|
+
plainWins: boolean;
|
|
382
|
+
rounds: { market: string; epoch: number; up: boolean; stake: Wei; outcome: RoundOutcome | null; won: boolean | null; payout: Wei | null; card: number | null; lockAt: number; closeAt: number }[];
|
|
383
|
+
/** The daily cap this wallet set for itself on chain, or null when no endpoint answered. */
|
|
384
|
+
limit: { cap: Wei; pendingCap: Wei; pendingAt: number; spentToday: Wei } | null;
|
|
385
|
+
}
|