@shippedcalls/sdk 0.3.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 +11 -2
- package/dist/abi.d.ts +264 -0
- package/dist/abi.js +342 -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 +30 -3
- package/dist/client.js +83 -9
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +5 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- 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 +31 -8
- package/package.json +1 -1
- package/skill/SKILL.md +8 -2
- package/skill/references/api.md +6 -1
- package/skill/references/rounds.md +16 -7
- package/skill/references/write-path.md +4 -0
- package/skill/scripts/calls.sh +1 -1
- package/src/abi.ts +342 -0
- package/src/cli.ts +76 -4
- package/src/client.ts +82 -9
- package/src/errors.ts +7 -1
- package/src/index.ts +2 -2
- package/src/odds.ts +14 -0
- package/src/types.ts +14 -6
package/src/client.ts
CHANGED
|
@@ -3,9 +3,9 @@ import { privateKeyToAccount } from "viem/accounts";
|
|
|
3
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";
|
|
8
|
+
import { DISPUTE_WINDOW, MIN_BET, MIN_OPENER_BOND, multipleOf, odds, quoteOf, roundInPlay, roundPayout, type Side } from "./odds.js";
|
|
9
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 {
|
|
@@ -184,7 +184,11 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
184
184
|
return account;
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
-
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
|
+
};
|
|
188
192
|
|
|
189
193
|
async function assertChain() {
|
|
190
194
|
if (chainChecked) return;
|
|
@@ -202,11 +206,26 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
202
206
|
const { request: simulated } = await reads.simulateContract(call);
|
|
203
207
|
const estimate = await reads.estimateContractGas(call);
|
|
204
208
|
const hash = await writes!.writeContract({ ...(simulated as object), gas: (estimate * 5n + 3n) / 4n } as never);
|
|
205
|
-
|
|
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
|
+
});
|
|
206
213
|
if (receipt.status !== "success") throw new CallsError("The transaction failed onchain.", "reverted");
|
|
207
214
|
return receipt;
|
|
208
215
|
}
|
|
209
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
|
+
|
|
210
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;
|
|
211
230
|
|
|
212
231
|
async function chainQuote(address: Address, side: Side, amount: bigint): Promise<Quote> {
|
|
@@ -342,36 +361,90 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
342
361
|
rounds: {
|
|
343
362
|
/** Every market's round taking bets, the round running and its latest results, in one read. */
|
|
344
363
|
markets: () => request<RoundsFloor>("/v1/rounds"),
|
|
345
|
-
state:
|
|
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
|
+
}),
|
|
346
414
|
/** A wallet's streak, today's stake and profit, what it can collect, its daily limit and its latest rounds. */
|
|
347
415
|
history: (who?: string) => guarded(() => request<RoundsAccount>(`/v1/accounts/${walletOr(who)}/rounds`)),
|
|
348
416
|
|
|
349
|
-
/** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while
|
|
417
|
+
/** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while rounds aren't being priced. */
|
|
350
418
|
async bet(market: string, side: RoundSide | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
|
|
419
|
+
weiOf(amount);
|
|
351
420
|
const name = marketOf(market);
|
|
352
421
|
const chosen = roundSideOf(side);
|
|
353
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");
|
|
354
423
|
return guarded(async () => {
|
|
355
424
|
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
356
425
|
if (!floor.markets.some((m) => m.market === name)) throw new CallsError(`Rounds has no ${name} market.`, "UnknownMarket");
|
|
357
|
-
if (!floor.open) throw new CallsError("Rounds
|
|
426
|
+
if (!floor.open) throw new CallsError("Rounds isn't taking bets right now, so nothing was sent.", "rounds_closed");
|
|
358
427
|
const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "bet", args: [marketId(name), chosen === "up"], value: amount });
|
|
359
428
|
const placed = eventOf<{ epoch: bigint; upPool: bigint; downPool: bigint }>(receipt, roundsAbi as Abi, "Bet");
|
|
360
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 };
|
|
361
430
|
});
|
|
362
431
|
},
|
|
363
432
|
|
|
364
|
-
/** Collects what this wallet is owed: every market, one market, or the epochs named. The money only ever goes to the wallet that sends this. */
|
|
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. */
|
|
365
434
|
claim: (market?: string, epochs?: readonly number[]) =>
|
|
366
435
|
guarded(async () => {
|
|
367
436
|
const only = market ? marketOf(market) : null;
|
|
368
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");
|
|
369
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");
|
|
370
441
|
if (!owed.length) throw new CallsError("Nothing to claim for this wallet.", "NothingToClaim");
|
|
371
442
|
const batch = owed.slice(0, CLAIM_BATCH);
|
|
372
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))] });
|
|
373
444
|
const paid = parseEventLogs({ abi: roundsAbi as Abi, logs: receipt.logs, eventName: "Claimed" } as never) as unknown as { args: { amount: bigint } }[];
|
|
374
|
-
|
|
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() };
|
|
375
448
|
}),
|
|
376
449
|
},
|
|
377
450
|
|
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,16 +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,
|
|
36
|
-
TooLate: "Betting has closed on this round. The next one
|
|
39
|
+
TooLate: "Betting has closed on this round. The next one opens at the lock, within ten seconds.",
|
|
37
40
|
BelowMinimum: "The minimum bet is 0.001 ETH.",
|
|
38
41
|
OverStakeCap: "One wallet can stake up to 0.5 ETH in a round.",
|
|
39
42
|
OverDailyLimit: "This would take the wallet past the daily limit it set for itself.",
|
|
40
43
|
OtherSide: "This wallet is already on the other side of this round.",
|
|
41
44
|
MarketPaused: "This market isn't taking bets right now.",
|
|
42
45
|
UnknownMarket: "Rounds has no such market.",
|
|
46
|
+
GasTooLow: "This win's card needs more gas. Send at least the estimate.",
|
|
43
47
|
};
|
|
44
48
|
|
|
45
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
|
+
|
|
46
52
|
export function describe(error: unknown): CallsError {
|
|
47
53
|
if (error instanceof CallsError) return error;
|
|
48
54
|
if (!(error instanceof BaseError)) return new CallsError("The request did not go through.", "unknown");
|
package/src/index.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { createClient, accountFromKey, bondIdOf, prepareOpen, roundSideOf, sideO
|
|
|
2
2
|
export { API_URL, CALLED_IT, CHAIN_ID, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints } from "./chain.js";
|
|
3
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
|
}
|
|
@@ -314,7 +316,7 @@ export interface RoundPools {
|
|
|
314
316
|
up: Wei;
|
|
315
317
|
down: Wei;
|
|
316
318
|
bets: number;
|
|
317
|
-
/** What a winning stake
|
|
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. */
|
|
318
320
|
upPays: number | null;
|
|
319
321
|
downPays: number | null;
|
|
320
322
|
}
|
|
@@ -333,8 +335,6 @@ export interface RoundResult {
|
|
|
333
335
|
decidedAt: number;
|
|
334
336
|
lockAt: number;
|
|
335
337
|
closeAt: number;
|
|
336
|
-
/** The public candles anyone can open to check the two prices. */
|
|
337
|
-
candles: { lock: string; close: string };
|
|
338
338
|
txHash: Hash;
|
|
339
339
|
}
|
|
340
340
|
|
|
@@ -349,7 +349,7 @@ export interface RoundsMarket {
|
|
|
349
349
|
|
|
350
350
|
export interface RoundsFloor {
|
|
351
351
|
now: number;
|
|
352
|
-
/** False while
|
|
352
|
+
/** False while rounds aren't being priced. A bet then would wait out the hour and refund, so the client refuses it. */
|
|
353
353
|
open: boolean;
|
|
354
354
|
contract: Address;
|
|
355
355
|
interval: number;
|
|
@@ -357,6 +357,7 @@ export interface RoundsFloor {
|
|
|
357
357
|
minBet: Wei;
|
|
358
358
|
maxStake: Wei;
|
|
359
359
|
rakeBps: number;
|
|
360
|
+
terms: { holdToken: Address; holdMin: Wei; holderRakeBps: number; cards: Address; cardCutBps: number; cardStreak: number; maxCardCut: Wei } | null;
|
|
360
361
|
markets: RoundsMarket[];
|
|
361
362
|
feed: { market: string; epoch: number; wallet: Address; agent: string | null; up: boolean; amount: Wei; at: number; txHash: Hash }[];
|
|
362
363
|
}
|
|
@@ -369,9 +370,16 @@ export interface RoundsAccount {
|
|
|
369
370
|
played: number;
|
|
370
371
|
wins: number;
|
|
371
372
|
losses: number;
|
|
372
|
-
|
|
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;
|
|
373
377
|
unclaimedTotal: Wei;
|
|
374
|
-
|
|
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 }[];
|
|
375
383
|
/** The daily cap this wallet set for itself on chain, or null when no endpoint answered. */
|
|
376
384
|
limit: { cap: Wei; pendingCap: Wei; pendingAt: number; spentToday: Wei } | null;
|
|
377
385
|
}
|