@shippedcalls/sdk 0.3.0 → 0.4.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/README.md +42 -2
- package/dist/abi.d.ts +264 -0
- package/dist/abi.js +342 -0
- package/dist/abi.js.map +1 -1
- package/dist/chain.d.ts +2 -0
- package/dist/chain.js +2 -0
- package/dist/chain.js.map +1 -1
- package/dist/cli.js +87 -4
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +57 -3
- package/dist/client.js +86 -9
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +22 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/jobs.d.ts +588 -0
- package/dist/jobs.js +347 -0
- package/dist/jobs.js.map +1 -0
- 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 +9 -2
- package/skill/references/api.md +6 -1
- package/skill/references/jobs.md +30 -0
- 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/chain.ts +2 -0
- package/src/cli.ts +76 -4
- package/src/client.ts +88 -9
- package/src/errors.ts +24 -1
- package/src/index.ts +4 -3
- package/src/jobs.ts +467 -0
- package/src/odds.ts +14 -0
- package/src/types.ts +14 -6
package/src/client.ts
CHANGED
|
@@ -3,9 +3,10 @@ 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
|
+
import { createJobs, DEFAULT_MAX_JOB_FUND } from "./jobs.js";
|
|
9
10
|
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
11
|
|
|
11
12
|
export interface ClientOptions {
|
|
@@ -18,6 +19,8 @@ export interface ClientOptions {
|
|
|
18
19
|
account?: Account;
|
|
19
20
|
/** The most one bet may stake, wei. 0.01 ETH by default. */
|
|
20
21
|
maxStake?: bigint;
|
|
22
|
+
/** The most one job call may lock, USDG units. 25 USDG by default. */
|
|
23
|
+
maxJobFund?: bigint;
|
|
21
24
|
chainId?: number;
|
|
22
25
|
factory?: Address;
|
|
23
26
|
/** Earlier factories whose Calls this client still treats as Calls. The published ones unless `factory` is set. */
|
|
@@ -184,7 +187,11 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
184
187
|
return account;
|
|
185
188
|
}
|
|
186
189
|
|
|
187
|
-
const walletOr = (value?: unknown) =>
|
|
190
|
+
const walletOr = (value?: unknown) => {
|
|
191
|
+
if (value) return addressOf(value, "wallet");
|
|
192
|
+
if (!account) throw new CallsError("Name a wallet, or set CALLS_PRIVATE_KEY.", "no_wallet");
|
|
193
|
+
return account.address;
|
|
194
|
+
};
|
|
188
195
|
|
|
189
196
|
async function assertChain() {
|
|
190
197
|
if (chainChecked) return;
|
|
@@ -202,11 +209,26 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
202
209
|
const { request: simulated } = await reads.simulateContract(call);
|
|
203
210
|
const estimate = await reads.estimateContractGas(call);
|
|
204
211
|
const hash = await writes!.writeContract({ ...(simulated as object), gas: (estimate * 5n + 3n) / 4n } as never);
|
|
205
|
-
|
|
212
|
+
// Once there is a hash, a failed read says nothing about the transaction: calling that a failure invites paying twice.
|
|
213
|
+
const receipt = await reads.waitForTransactionReceipt({ hash, pollingInterval: 1_000 }).catch(() => {
|
|
214
|
+
throw new CallsError(`Transaction ${hash} was sent and its receipt could not be read. Check it before sending this again.`, RECEIPT_UNKNOWN);
|
|
215
|
+
});
|
|
206
216
|
if (receipt.status !== "success") throw new CallsError("The transaction failed onchain.", "reverted");
|
|
207
217
|
return receipt;
|
|
208
218
|
}
|
|
209
219
|
|
|
220
|
+
const weiOf = (amount: unknown) => {
|
|
221
|
+
if (typeof amount !== "bigint" || amount <= 0n) throw new CallsError("An amount is wei, as a bigint above zero.", "bad_amount");
|
|
222
|
+
return amount;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const roundState = (market: string) => {
|
|
226
|
+
const name = marketOf(market);
|
|
227
|
+
return request<RoundsMarket & { open: boolean }>(`/v1/rounds/${name}`).catch((error: CallsError) => {
|
|
228
|
+
throw error.status === 404 ? new CallsError(`Rounds has no ${name} market.`, "UnknownMarket") : error;
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
|
|
210
232
|
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
233
|
|
|
212
234
|
async function chainQuote(address: Address, side: Side, amount: bigint): Promise<Quote> {
|
|
@@ -248,6 +270,9 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
248
270
|
chainId,
|
|
249
271
|
factory,
|
|
250
272
|
|
|
273
|
+
/** Hold payment until the work is accepted: the worker opens a job, the client funds it, a named reviewer releases it. */
|
|
274
|
+
jobs: createJobs({ reads, chainId, send, guarded, wallet, toTx: (receipt) => toTx(receipt, chainId), maxFund: options.maxJobFund ?? DEFAULT_MAX_JOB_FUND }),
|
|
275
|
+
|
|
251
276
|
// Reads from the API. It follows the chain by up to a minute; the chain reads below do not.
|
|
252
277
|
|
|
253
278
|
async calls(filters: { status?: CallStatus; type?: CallType; subject?: string; sort?: "closing" | "lopsided" | "pot" | "newest"; limit?: number; offset?: number } = {}): Promise<CallRow[]> {
|
|
@@ -342,36 +367,90 @@ export function createClient(options: ClientOptions = {}) {
|
|
|
342
367
|
rounds: {
|
|
343
368
|
/** Every market's round taking bets, the round running and its latest results, in one read. */
|
|
344
369
|
markets: () => request<RoundsFloor>("/v1/rounds"),
|
|
345
|
-
state:
|
|
370
|
+
state: roundState,
|
|
371
|
+
/**
|
|
372
|
+
* What `amount` wei does on a side, with the pools as they stand, before any card's cut. `inPlay` is the part that's
|
|
373
|
+
* matched; the rest comes back win or lose. `payout` is what comes back on a win. Later bets move both until the lock.
|
|
374
|
+
* `refund` means nobody is on the other side yet. `refused` names what would stop this bet. Sends nothing.
|
|
375
|
+
*/
|
|
376
|
+
async quote(market: string, side: RoundSide | string, amount: bigint) {
|
|
377
|
+
weiOf(amount);
|
|
378
|
+
const name = marketOf(market);
|
|
379
|
+
const chosen = roundSideOf(side);
|
|
380
|
+
const [floor, history] = await Promise.all([request<RoundsFloor>("/v1/rounds"), account ? request<RoundsAccount>(`/v1/accounts/${account.address}/rounds`).catch(() => null) : null]);
|
|
381
|
+
const betting = floor.markets.find((m) => m.market === name)?.betting;
|
|
382
|
+
if (!betting) throw new CallsError(`Rounds has no ${name} market.`, "UnknownMarket");
|
|
383
|
+
const [mine, other] = chosen === "up" ? [betting.up, betting.down] : [betting.down, betting.up];
|
|
384
|
+
const payout = roundPayout(amount, BigInt(mine), BigInt(other));
|
|
385
|
+
const held = history?.rounds.find((r) => r.market === name && r.epoch === betting.epoch);
|
|
386
|
+
const refusal =
|
|
387
|
+
!floor.open ? "rounds_closed"
|
|
388
|
+
: floor.now >= betting.cutoffAt ? "TooLate"
|
|
389
|
+
: amount < BigInt(floor.minBet) ? "BelowMinimum"
|
|
390
|
+
: held && held.up !== (chosen === "up") ? "OtherSide"
|
|
391
|
+
: BigInt(held?.stake ?? 0) + amount > BigInt(floor.maxStake) ? "OverStakeCap"
|
|
392
|
+
: null;
|
|
393
|
+
return {
|
|
394
|
+
market: name,
|
|
395
|
+
side: chosen,
|
|
396
|
+
amount: amount.toString(),
|
|
397
|
+
inPlay: roundInPlay(amount, BigInt(mine), BigInt(other)).toString(),
|
|
398
|
+
open: floor.open,
|
|
399
|
+
epoch: betting.epoch,
|
|
400
|
+
cutoffAt: betting.cutoffAt,
|
|
401
|
+
payout: payout.toString(),
|
|
402
|
+
profit: (payout - amount).toString(),
|
|
403
|
+
multiple: multipleOf(payout, amount),
|
|
404
|
+
refund: BigInt(other) === 0n,
|
|
405
|
+
refused: refusal && { code: refusal, message: refusal === "rounds_closed" ? "Rounds isn't taking bets right now." : revertLine(refusal) },
|
|
406
|
+
};
|
|
407
|
+
},
|
|
408
|
+
/** With `plain` on, every win pays in ETH: no card and no $SHIPPED buy. */
|
|
409
|
+
setPlainWins: (plain = true) =>
|
|
410
|
+
guarded(async () => {
|
|
411
|
+
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
412
|
+
return toTx(await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "setPlainWins", args: [plain] }), chainId);
|
|
413
|
+
}),
|
|
414
|
+
/** The wallet's own daily stake limit in wei, 0 for none. Lowering applies at once; raising or removing takes 24 hours. */
|
|
415
|
+
setLimit: (cap: bigint) =>
|
|
416
|
+
guarded(async () => {
|
|
417
|
+
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
418
|
+
return toTx(await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "setLimit", args: [cap] }), chainId);
|
|
419
|
+
}),
|
|
346
420
|
/** A wallet's streak, today's stake and profit, what it can collect, its daily limit and its latest rounds. */
|
|
347
421
|
history: (who?: string) => guarded(() => request<RoundsAccount>(`/v1/accounts/${walletOr(who)}/rounds`)),
|
|
348
422
|
|
|
349
|
-
/** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while
|
|
423
|
+
/** Stakes `amount` wei on the round now taking bets. Refuses an amount over `maxStake`, and refuses while rounds aren't being priced. */
|
|
350
424
|
async bet(market: string, side: RoundSide | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
|
|
425
|
+
weiOf(amount);
|
|
351
426
|
const name = marketOf(market);
|
|
352
427
|
const chosen = roundSideOf(side);
|
|
353
428
|
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
429
|
return guarded(async () => {
|
|
355
430
|
const floor = await request<RoundsFloor>("/v1/rounds");
|
|
356
431
|
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
|
|
432
|
+
if (!floor.open) throw new CallsError("Rounds isn't taking bets right now, so nothing was sent.", "rounds_closed");
|
|
358
433
|
const receipt = await send({ address: floor.contract, abi: roundsAbi as Abi, functionName: "bet", args: [marketId(name), chosen === "up"], value: amount });
|
|
359
434
|
const placed = eventOf<{ epoch: bigint; upPool: bigint; downPool: bigint }>(receipt, roundsAbi as Abi, "Bet");
|
|
360
435
|
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
436
|
});
|
|
362
437
|
},
|
|
363
438
|
|
|
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. */
|
|
439
|
+
/** 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
440
|
claim: (market?: string, epochs?: readonly number[]) =>
|
|
366
441
|
guarded(async () => {
|
|
367
442
|
const only = market ? marketOf(market) : null;
|
|
368
443
|
const [floor, account] = await Promise.all([request<RoundsFloor>("/v1/rounds"), request<RoundsAccount>(`/v1/accounts/${wallet().address}/rounds`)]);
|
|
444
|
+
if (only && !floor.markets.some((m) => m.market === only)) throw new CallsError(`Rounds has no ${only} market.`, "UnknownMarket");
|
|
369
445
|
const owed = account.unclaimed.filter((o) => (!only || o.market === only) && (!epochs || epochs.includes(o.epoch)));
|
|
446
|
+
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
447
|
if (!owed.length) throw new CallsError("Nothing to claim for this wallet.", "NothingToClaim");
|
|
371
448
|
const batch = owed.slice(0, CLAIM_BATCH);
|
|
372
449
|
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
450
|
const paid = parseEventLogs({ abi: roundsAbi as Abi, logs: receipt.logs, eventName: "Claimed" } as never) as unknown as { args: { amount: bigint } }[];
|
|
374
|
-
|
|
451
|
+
const card = eventOf<{ cut: bigint; paid: boolean }>(receipt, roundsAbi as Abi, "CardCut");
|
|
452
|
+
const cut = card?.paid ? card.cut : 0n;
|
|
453
|
+
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
454
|
}),
|
|
376
455
|
},
|
|
377
456
|
|
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,36 @@ 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.",
|
|
47
|
+
"rule.TooEarly": "Before the deadline a reviewer can only accept.",
|
|
48
|
+
"rule.WindowClosed": "The reviewer's window has closed. Anyone can now refund the client.",
|
|
49
|
+
"settleDefault.TooEarly": "The reviewer's window is still open.",
|
|
50
|
+
"fund.NotOpen": "This job has already been ruled on.",
|
|
51
|
+
NotVerifier: "Only the reviewer named in the job can rule on it.",
|
|
52
|
+
NotCreator: "Only the worker who opened the job can do that.",
|
|
53
|
+
NotPoster: "Only the worker or the reviewer can post evidence.",
|
|
54
|
+
NotOpen: "This job has already been ruled on.",
|
|
55
|
+
NothingOwed: "Nothing to collect for this wallet.",
|
|
56
|
+
UnknownDeed: "There is no job with that id.",
|
|
57
|
+
InvalidVerifier: "The reviewer has to be a different wallet from the worker.",
|
|
58
|
+
InvalidRefund: "The client has to be a different wallet from the worker.",
|
|
59
|
+
InvalidDeadline: "The deadline has to be at least ten minutes away and within three years.",
|
|
60
|
+
InvalidWindow: "The review window has to be between one hour and 60 days.",
|
|
61
|
+
InvalidEvidence: "Evidence is a link of up to 2,048 bytes.",
|
|
62
|
+
AssetNotAllowed: "The registry does not hold that token.",
|
|
63
|
+
CreationIsPaused: "The registry is not opening new jobs right now.",
|
|
43
64
|
};
|
|
44
65
|
|
|
45
66
|
/** One sentence for a failed read or write. RPC URLs can carry keys, so nothing from the transport is passed on. */
|
|
67
|
+
export const revertLine = (name: string) => REVERTS[name] ?? `The contract would refuse this: ${name}.`;
|
|
68
|
+
|
|
46
69
|
export function describe(error: unknown): CallsError {
|
|
47
70
|
if (error instanceof CallsError) return error;
|
|
48
71
|
if (!(error instanceof BaseError)) return new CallsError("The request did not go through.", "unknown");
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export { createClient, accountFromKey, bondIdOf, prepareOpen, roundSideOf, sideOf, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, type CallsClient, type ClientOptions } from "./client.js";
|
|
2
|
-
export { API_URL, CALLED_IT, CHAIN_ID, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints } from "./chain.js";
|
|
2
|
+
export { API_URL, CALLED_IT, CHAIN_ID, COUNCIL, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, RPC_URLS, rpcEndpoints, USDG } 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";
|
|
9
|
+
export { bondNumberOf, checkJob, COUNCIL_MIN_FEE, DEFAULT_MAX_JOB_FUND, DEFAULT_REVIEW_WINDOW, jobMilestone, jobStateOf, jobTerms, readJobTag, usdgToUnits, type ChainDeed, type Job, type JobAgreement, type JobProblem, type JobsClient, type JobState, type JobTerms, type JobTx, type OpenJobInput } from "./jobs.js";
|