@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/README.md +73 -15
- package/dist/abi.d.ts +1328 -0
- package/dist/abi.js +1703 -0
- package/dist/abi.js.map +1 -1
- package/dist/assets.d.ts +34 -0
- package/dist/assets.js +48 -0
- package/dist/assets.js.map +1 -0
- package/dist/chain.d.ts +2 -0
- package/dist/chain.js +2 -0
- package/dist/chain.js.map +1 -1
- package/dist/cli.js +121 -38
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +90 -17
- package/dist/client.js +276 -69
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +16 -3
- 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 +54 -7
- package/dist/jobs.js +112 -26
- package/dist/jobs.js.map +1 -1
- package/dist/odds.d.ts +7 -6
- package/dist/odds.js +13 -12
- package/dist/odds.js.map +1 -1
- package/dist/types.d.ts +90 -30
- package/package.json +3 -3
- package/skill/SKILL.md +24 -14
- package/skill/references/api.md +30 -12
- package/skill/references/funding.md +4 -2
- package/skill/references/jobs.md +1 -1
- package/skill/references/settlement.md +5 -2
- package/skill/references/write-path.md +30 -2
- package/skill/scripts/calls.sh +1 -1
- package/src/abi.ts +1705 -0
- package/src/assets.ts +65 -0
- package/src/chain.ts +2 -0
- package/src/cli.ts +118 -39
- package/src/client.ts +291 -71
- package/src/errors.ts +18 -3
- package/src/index.ts +4 -3
- package/src/jobs.ts +111 -24
- package/src/odds.ts +13 -12
- package/src/types.ts +77 -26
package/src/jobs.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getAddress, isAddress, parseAbi, zeroAddress, zeroHash, type Abi, type Account, type Address, type Hash, type Hex, type PublicClient, type TransactionReceipt } from "viem";
|
|
1
|
+
import { getAddress, isAddress, parseAbi, toEventSelector, zeroAddress, zeroHash, type Abi, type Account, type Address, type Hash, type Hex, type PublicClient, type TransactionReceipt } from "viem";
|
|
2
2
|
import { CHAIN_ID, COUNCIL, DEEDS, USDG } from "./chain.js";
|
|
3
3
|
import { CallsError, RECEIPT_UNKNOWN } from "./errors.js";
|
|
4
4
|
import type { Tx } from "./types.js";
|
|
@@ -6,7 +6,8 @@ import type { Tx } from "./types.js";
|
|
|
6
6
|
// A job is a Shipped bond the worker opens and the client funds. The bond's paid side belongs to whoever opens it, so
|
|
7
7
|
// the worker has to; the milestone carries a tag with the agreed amount, so anyone can tell a job from a bond and see
|
|
8
8
|
// what it is meant to hold. The worker writes every term, which is why `check` exists and `fund` refuses to pay into
|
|
9
|
-
// anything it fails.
|
|
9
|
+
// anything it fails. A worker's bond is locked when the job opens, or with `bondAfterFunding` after the client has
|
|
10
|
+
// funded the amount, through `postBond`.
|
|
10
11
|
|
|
11
12
|
export const USDG_DECIMALS = 6;
|
|
12
13
|
export const MAX_TITLE = 96;
|
|
@@ -24,9 +25,10 @@ export const DEFAULT_MAX_JOB_FUND = 25_000_000n;
|
|
|
24
25
|
|
|
25
26
|
const LEAD_SLACK = 60;
|
|
26
27
|
const BPS = 10_000;
|
|
28
|
+
const BPS_UNITS = 10_000n;
|
|
27
29
|
const STATUS_OPEN = 1;
|
|
28
30
|
const STATUS_SETTLED = 4;
|
|
29
|
-
const ERC721_TRANSFER = "
|
|
31
|
+
const ERC721_TRANSFER = toEventSelector("Transfer(address,address,uint256)");
|
|
30
32
|
const TAG = /\n\n\[shipped-job:1 amount=(\d+) bond=(\d+)\]$/;
|
|
31
33
|
|
|
32
34
|
export const deedsAbi = parseAbi([
|
|
@@ -42,6 +44,7 @@ export const deedsAbi = parseAbi([
|
|
|
42
44
|
"function getDeed(uint256 deedId) view returns (Deed)",
|
|
43
45
|
"function owed(address account, address asset) view returns (uint256)",
|
|
44
46
|
"function timeline(uint256 deedId) view returns (uint64 deadline, uint64 verifierEnd, uint64 backupEnd, uint64 defaultAt, uint64 appealEnd, uint64 panelEnd)",
|
|
47
|
+
"event Funded(uint256 indexed deedId, address indexed from, uint256 amount, uint256 balance)",
|
|
45
48
|
"error AssetNotAllowed()",
|
|
46
49
|
"error CreationIsPaused()",
|
|
47
50
|
"error InvalidDeadline()",
|
|
@@ -120,8 +123,12 @@ export interface OpenJobInput {
|
|
|
120
123
|
reviewWindow?: number;
|
|
121
124
|
/** Paid to the reviewer from the job when its ruling stands, USDG units. 0.25 USDG at least for the council. */
|
|
122
125
|
reviewerFee?: bigint;
|
|
123
|
-
/** What the worker locks on its own side. It is lost to the client if the job
|
|
126
|
+
/** What the worker locks on its own side. It is lost to the client if the job is rejected or the worker gives up. */
|
|
124
127
|
workerBond?: bigint;
|
|
128
|
+
/** Opens with nothing locked; the worker posts `workerBond` with `postBond` once the client has funded the amount. */
|
|
129
|
+
bondAfterFunding?: boolean;
|
|
130
|
+
/** A silent reviewer returns the amount to the client and the bond to the worker, less Shipped's fee on the bond. */
|
|
131
|
+
silenceReturnsBond?: boolean;
|
|
125
132
|
}
|
|
126
133
|
|
|
127
134
|
/** What the client agreed to, for `check` and `fund` to compare against what the worker actually opened. */
|
|
@@ -136,8 +143,16 @@ export interface JobAgreement {
|
|
|
136
143
|
notAfter?: number;
|
|
137
144
|
/** The largest reviewer fee the client accepts, USDG units. A tenth of the amount by default. */
|
|
138
145
|
maxReviewerFee?: bigint;
|
|
139
|
-
/** The least the worker must have locked, USDG units. */
|
|
146
|
+
/** The least the worker must have locked, USDG units. With `bondAfterFunding`, exactly the bond the job must name. */
|
|
140
147
|
minWorkerBond?: bigint;
|
|
148
|
+
/**
|
|
149
|
+
* You fund the amount alone, and the worker's bond follows it. Name the bond in `minWorkerBond` as well: without it
|
|
150
|
+
* `check` and `fund` refuse the job (`bond_not_agreed`), since the job's own bond would set what silence leaves the
|
|
151
|
+
* worker. The type does not require it, so that code written for 0.5.0 against this interface still compiles.
|
|
152
|
+
*/
|
|
153
|
+
bondAfterFunding?: boolean;
|
|
154
|
+
/** A silent reviewer may return the worker's bond to it: the job may pay the worker the bond's share of the escrow. */
|
|
155
|
+
silenceReturnsBond?: boolean;
|
|
141
156
|
}
|
|
142
157
|
|
|
143
158
|
export interface JobProblem {
|
|
@@ -145,7 +160,8 @@ export interface JobProblem {
|
|
|
145
160
|
message: string;
|
|
146
161
|
}
|
|
147
162
|
|
|
148
|
-
|
|
163
|
+
/** `awaiting_bond`: the job holds the client's amount and not yet the worker's bond. */
|
|
164
|
+
export type JobState = "awaiting_funds" | "awaiting_bond" | "in_progress" | "in_review" | "refundable" | "ruled" | "paid" | "partly_paid" | "refunded";
|
|
149
165
|
|
|
150
166
|
export interface Job {
|
|
151
167
|
id: string;
|
|
@@ -163,7 +179,7 @@ export interface Job {
|
|
|
163
179
|
escrow: string;
|
|
164
180
|
funded: boolean;
|
|
165
181
|
deadline: number;
|
|
166
|
-
/** When anyone can
|
|
182
|
+
/** When anyone can settle the job at its default split if the reviewer has stayed silent. */
|
|
167
183
|
refundableAt: number;
|
|
168
184
|
state: JobState;
|
|
169
185
|
}
|
|
@@ -199,6 +215,18 @@ export function readJobTag(milestone: string): { brief: string; amount: bigint;
|
|
|
199
215
|
return { brief: milestone.slice(0, match.index), amount: BigInt(match[1]!), bond: BigInt(match[2]!) };
|
|
200
216
|
}
|
|
201
217
|
|
|
218
|
+
/**
|
|
219
|
+
* The default split, in basis points of the escrow, under which a silent reviewer returns the amount to the client and
|
|
220
|
+
* the bond to the worker. The registry rounds the worker's share down, so this is the largest split whose share is at
|
|
221
|
+
* most the bond: the client always gets its whole amount back, and the worker its bond less at most 0.01% of the
|
|
222
|
+
* escrow, which goes to the client.
|
|
223
|
+
*/
|
|
224
|
+
export function silenceSplit(amount: bigint, bond: bigint): number {
|
|
225
|
+
if (bond <= 0n || amount < 0n) return 0;
|
|
226
|
+
const bps = (BPS_UNITS * (bond + 1n) - 1n) / (amount + bond);
|
|
227
|
+
return Number(bps < BPS_UNITS ? bps : BPS_UNITS);
|
|
228
|
+
}
|
|
229
|
+
|
|
202
230
|
/** The registry's bond number on Shipped's site. */
|
|
203
231
|
export const bondNumberOf = (id: bigint | number, chainId = CHAIN_ID) => Number(id) - (chainId === CHAIN_ID ? 1 : 0);
|
|
204
232
|
|
|
@@ -242,7 +270,7 @@ export function jobTerms(input: OpenJobInput, { worker, now }: { worker: string;
|
|
|
242
270
|
check: zeroAddress,
|
|
243
271
|
checkData: "0x",
|
|
244
272
|
refundTo: client,
|
|
245
|
-
defaultRemainderBps: 0,
|
|
273
|
+
defaultRemainderBps: input.silenceReturnsBond ? silenceSplit(input.amount, bond) : 0,
|
|
246
274
|
refundCapBps: 0,
|
|
247
275
|
allowPartial: false,
|
|
248
276
|
verifierGrace: reviewWindow,
|
|
@@ -273,16 +301,25 @@ export function checkJob(deed: ChainDeed, agreement: JobAgreement, { client, now
|
|
|
273
301
|
|
|
274
302
|
if (!same(t.refundTo, client)) add("refund_elsewhere", `A failed job pays ${t.refundTo}, not you.`);
|
|
275
303
|
if (agreement.worker && !same(deed.creator, addressOf(agreement.worker, "worker"))) add("wrong_worker", `The job was opened by ${deed.creator}, not the worker you agreed with.`);
|
|
276
|
-
|
|
304
|
+
// The split is a share of whatever the job holds, so it is bounded by the bond the client agreed to, not the tag's.
|
|
305
|
+
const silence = agreement.silenceReturnsBond ? silenceSplit(tag.amount, agreement.minWorkerBond ?? tag.bond) : 0;
|
|
306
|
+
if (t.defaultRemainderBps > silence) add("pays_on_silence", agreement.silenceReturnsBond ? "The job pays the worker more than its bond if the reviewer stays silent." : "The job pays the worker if the reviewer stays silent. It has to refund you.");
|
|
277
307
|
if (t.check !== zeroAddress) add("has_check", "The job can be released by an on-chain check instead of the reviewer.");
|
|
278
308
|
if (t.allowPartial) add("allows_partial", "The reviewer can split this job between you and the worker.");
|
|
279
309
|
if (!same(t.asset, USDG)) add("wrong_asset", "The job is not held in USDG.");
|
|
280
310
|
|
|
281
311
|
if (tag.amount !== agreement.amount) add("wrong_amount", `The job asks for ${usdg(tag.amount)}, not the ${usdg(agreement.amount)} you agreed.`);
|
|
282
312
|
const minBond = agreement.minWorkerBond ?? 0n;
|
|
283
|
-
if (
|
|
284
|
-
|
|
285
|
-
|
|
313
|
+
if (agreement.bondAfterFunding) {
|
|
314
|
+
// Nothing is locked until the client funds, so the job names exactly the agreed bond: a bigger one would raise the
|
|
315
|
+
// share of the amount a silent reviewer leaves the worker should the bond never come. The agreement has to name it.
|
|
316
|
+
if (agreement.minWorkerBond === undefined) add("bond_not_agreed", "Name the bond you agreed in minWorkerBond: with the bond to follow, the job's own bond would set what silence leaves the worker.");
|
|
317
|
+
else if (tag.bond !== agreement.minWorkerBond) add("bond_not_agreed", `The job names a bond of ${usdg(tag.bond)}, not the ${usdg(agreement.minWorkerBond)} agreed.`);
|
|
318
|
+
} else {
|
|
319
|
+
if (tag.bond < minBond) add("bond_too_small", `The worker's bond is ${usdg(tag.bond)}, under the ${usdg(minBond)} you asked for.`);
|
|
320
|
+
if (deed.balance < tag.bond) add("bond_missing", "The worker has not locked the bond the job names.");
|
|
321
|
+
if (deed.balance >= tag.amount + tag.bond) add("already_funded", "This job already holds its full amount.");
|
|
322
|
+
}
|
|
286
323
|
|
|
287
324
|
const maxFee = agreement.maxReviewerFee ?? agreement.amount / MAX_REVIEWER_SHARE_DIVISOR;
|
|
288
325
|
if (t.verifierFee > maxFee) add("fee_too_high", `The reviewer's fee is ${usdg(t.verifierFee)}, over the ${usdg(maxFee)} you accept.`);
|
|
@@ -290,6 +327,8 @@ export function checkJob(deed: ChainDeed, agreement: JobAgreement, { client, now
|
|
|
290
327
|
const deadline = Number(t.deadline);
|
|
291
328
|
if (deadline <= now + MIN_LEAD) add("deadline_too_soon", "The deadline is too close for the work to be done.");
|
|
292
329
|
if (agreement.notAfter != null && deadline > agreement.notAfter) add("deadline_too_late", "The deadline is later than you agreed.");
|
|
330
|
+
// Last, so a job that both holds its amount and differs from the agreement is reported for the difference first.
|
|
331
|
+
if (agreement.bondAfterFunding && deed.balance >= tag.amount) add("already_funded", "This job already holds its amount.");
|
|
293
332
|
return problems;
|
|
294
333
|
}
|
|
295
334
|
|
|
@@ -298,7 +337,7 @@ export function jobStateOf(deed: ChainDeed, refundableAt: number, now: number):
|
|
|
298
337
|
if (deed.status !== STATUS_OPEN) return "ruled";
|
|
299
338
|
const tag = readJobTag(deed.terms.milestone);
|
|
300
339
|
if (now > refundableAt) return "refundable";
|
|
301
|
-
if (tag && deed.balance < tag.amount + tag.bond) return "awaiting_funds";
|
|
340
|
+
if (tag && deed.balance < tag.amount + tag.bond) return deed.balance >= tag.amount ? "awaiting_bond" : "awaiting_funds";
|
|
302
341
|
return now <= Number(deed.terms.deadline) ? "in_progress" : "in_review";
|
|
303
342
|
}
|
|
304
343
|
|
|
@@ -337,13 +376,21 @@ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFun
|
|
|
337
376
|
reads.readContract({ address: USDG, abi: erc20Abi as Abi, functionName: "allowance", args: [owner, registry] } as never) as Promise<bigint>,
|
|
338
377
|
]);
|
|
339
378
|
if (balance < amount) throw new CallsError(`This wallet holds ${usdg(balance)}, and this needs ${usdg(amount)}.`, "insufficient_usdg");
|
|
340
|
-
if (allowance
|
|
379
|
+
if (allowance >= amount) return false;
|
|
380
|
+
await send({ address: USDG, abi: erc20Abi as Abi, functionName: "approve", args: [registry, amount] });
|
|
381
|
+
return true;
|
|
341
382
|
}
|
|
342
383
|
|
|
343
384
|
const cap = (amount: bigint, limit: bigint) => {
|
|
344
385
|
if (amount > limit) throw new CallsError(`This would lock ${usdg(amount)}, over the ${usdg(limit)} limit. Raise maxFund only on your operator's word.`, "over_cap");
|
|
345
386
|
};
|
|
346
387
|
|
|
388
|
+
/** The allowance a write gave is not left standing for money that did not go in. */
|
|
389
|
+
const unapprove = () => send({ address: USDG, abi: erc20Abi as Abi, functionName: "approve", args: [registry, 0n] }).catch(() => {});
|
|
390
|
+
|
|
391
|
+
/** Jobs whose bond this client is posting now. */
|
|
392
|
+
const posting = new Set<string>();
|
|
393
|
+
|
|
347
394
|
return {
|
|
348
395
|
/** One job as the chain has it. */
|
|
349
396
|
get: (jobId: unknown): Promise<Job> =>
|
|
@@ -377,15 +424,15 @@ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFun
|
|
|
377
424
|
};
|
|
378
425
|
}),
|
|
379
426
|
|
|
380
|
-
/** Worker: opens the job
|
|
427
|
+
/** Worker: opens the job, locking its bond now unless `bondAfterFunding`. Hand the id to the client to fund. */
|
|
381
428
|
open: (input: OpenJobInput, { maxFund: limit = maxFund }: { maxFund?: bigint } = {}): Promise<JobTx> =>
|
|
382
429
|
guarded(async () => {
|
|
383
430
|
const worker = wallet().address;
|
|
384
431
|
const terms = jobTerms(input, { worker, now: await timeOnChain() });
|
|
385
|
-
const
|
|
386
|
-
cap(
|
|
387
|
-
if (
|
|
388
|
-
const receipt = await write("create", [terms,
|
|
432
|
+
const deposit = input.bondAfterFunding ? 0n : (input.workerBond ?? 0n);
|
|
433
|
+
cap(deposit, limit);
|
|
434
|
+
if (deposit > 0n) await approveUpTo(deposit);
|
|
435
|
+
const receipt = await write("create", [terms, deposit]);
|
|
389
436
|
// The registry mints the paid side as token id * 2, from the zero address, in the same transaction.
|
|
390
437
|
const minted = receipt.logs.find((log) => same(log.address, registry) && log.topics[0] === ERC721_TRANSFER && BigInt(log.topics[1] ?? 1) === 0n);
|
|
391
438
|
if (!minted?.topics[3]) throw new CallsError(`Transaction ${receipt.transactionHash} landed but its job id could not be read.`, RECEIPT_UNKNOWN);
|
|
@@ -401,7 +448,7 @@ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFun
|
|
|
401
448
|
return { ok: problems.length === 0, problems };
|
|
402
449
|
}),
|
|
403
450
|
|
|
404
|
-
/** Client: locks the agreed amount, and only if the job passes `check`. */
|
|
451
|
+
/** Client: locks the agreed amount, and only if the job passes `check`. With `bondAfterFunding`, the amount alone. */
|
|
405
452
|
fund: (jobId: unknown, agreement: JobAgreement, { maxFund: limit = maxFund }: { maxFund?: bigint } = {}): Promise<JobTx & { amount: string }> =>
|
|
406
453
|
guarded(async () => {
|
|
407
454
|
const id = idOf(jobId);
|
|
@@ -409,10 +456,47 @@ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFun
|
|
|
409
456
|
const [{ deed, tag }, now] = await Promise.all([jobAt(id), timeOnChain()]);
|
|
410
457
|
const problems = checkJob(deed, { ...agreement, client }, { client, now });
|
|
411
458
|
if (problems.length > 0) throw new CallsError(`Not funded. ${problems.map((p) => p.message).join(" ")}`, problems[0]!.code);
|
|
412
|
-
const amount = tag.amount + tag.bond - deed.balance;
|
|
459
|
+
const amount = agreement.bondAfterFunding ? tag.amount : tag.amount + tag.bond - deed.balance;
|
|
413
460
|
cap(amount, limit);
|
|
414
|
-
await approveUpTo(amount);
|
|
415
|
-
|
|
461
|
+
const approved = await approveUpTo(amount);
|
|
462
|
+
try {
|
|
463
|
+
return { id: id.toString(), amount: amount.toString(), tx: toTx(await write("fund", [id, amount])) };
|
|
464
|
+
} catch (error) {
|
|
465
|
+
if (approved) await unapprove();
|
|
466
|
+
throw error;
|
|
467
|
+
}
|
|
468
|
+
}),
|
|
469
|
+
|
|
470
|
+
/** Worker: locks the bond the job names, once the job holds the client's amount and not yet the bond. */
|
|
471
|
+
postBond: (jobId: unknown, { maxFund: limit = maxFund }: { maxFund?: bigint } = {}): Promise<JobTx & { amount: string }> =>
|
|
472
|
+
guarded(async () => {
|
|
473
|
+
const id = idOf(jobId);
|
|
474
|
+
const key = id.toString();
|
|
475
|
+
// One post per job: a second while the first is under way, or while a transaction of this wallet is still
|
|
476
|
+
// pending, could lock the bond twice.
|
|
477
|
+
if (posting.has(key)) throw new CallsError("This wallet is already posting this job's bond. Read the job before posting it again.", "bond_pending");
|
|
478
|
+
posting.add(key);
|
|
479
|
+
try {
|
|
480
|
+
const { deed, tag } = await jobAt(id);
|
|
481
|
+
const owner = wallet().address;
|
|
482
|
+
if (!same(deed.creator, owner)) throw new CallsError("Only the worker who opened the job posts its bond.", "not_worker");
|
|
483
|
+
if (deed.status !== STATUS_OPEN) throw new CallsError("This job is no longer open.", "not_open");
|
|
484
|
+
if (tag.bond === 0n) throw new CallsError("This job names no bond.", "no_bond");
|
|
485
|
+
if (deed.balance < tag.amount) throw new CallsError("The client has not funded the job's amount yet. Post the bond once it has.", "not_funded");
|
|
486
|
+
if (deed.balance >= tag.amount + tag.bond) throw new CallsError("This job already holds its amount and the bond.", "already_funded");
|
|
487
|
+
const [mined, pending] = await Promise.all([reads.getTransactionCount({ address: owner, blockTag: "latest" }), reads.getTransactionCount({ address: owner, blockTag: "pending" })]);
|
|
488
|
+
if (pending > mined) throw new CallsError("This wallet has a transaction still pending. Once it lands, read the job before posting the bond again.", "bond_pending");
|
|
489
|
+
cap(tag.bond, limit);
|
|
490
|
+
const approved = await approveUpTo(tag.bond);
|
|
491
|
+
try {
|
|
492
|
+
return { id: key, amount: tag.bond.toString(), tx: toTx(await write("fund", [id, tag.bond])) };
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (approved) await unapprove();
|
|
495
|
+
throw error;
|
|
496
|
+
}
|
|
497
|
+
} finally {
|
|
498
|
+
posting.delete(key);
|
|
499
|
+
}
|
|
416
500
|
}),
|
|
417
501
|
|
|
418
502
|
/** Worker or reviewer: points at what was delivered. */
|
|
@@ -443,7 +527,10 @@ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFun
|
|
|
443
527
|
return { id: id.toString(), tx: toTx(await write("concede", [id, reason])) };
|
|
444
528
|
}),
|
|
445
529
|
|
|
446
|
-
/**
|
|
530
|
+
/**
|
|
531
|
+
* Anyone: the reviewer stayed silent past its window, so the job settles at its default split. The client gets
|
|
532
|
+
* everything, or with `silenceReturnsBond` the amount while the worker gets its bond back.
|
|
533
|
+
*/
|
|
447
534
|
refund: (jobId: unknown): Promise<JobTx> =>
|
|
448
535
|
guarded(async () => {
|
|
449
536
|
const id = idOf(jobId);
|
package/src/odds.ts
CHANGED
|
@@ -36,37 +36,38 @@ export interface Pools {
|
|
|
36
36
|
breaks: bigint;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
function multiple(winners: bigint, losers: bigint): number | null {
|
|
39
|
+
function multiple(winners: bigint, losers: bigint, bonus: bigint): number | null {
|
|
40
40
|
if (winners === 0n) return losers === 0n ? 1 : null;
|
|
41
|
-
const paid = winners + (losers * (10000n - RAKE_BPS)) / 10000n;
|
|
41
|
+
const paid = winners + (losers * (10000n - RAKE_BPS)) / 10000n + (losers === 0n ? 0n : bonus);
|
|
42
42
|
return Number((paid * 10000n) / winners) / 10000;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
46
|
* Each side's share of the pot in bps, 0 on an empty pot as the contract's `odds()` does, and what one unit staked now
|
|
47
|
-
* would come back as if that side wins. A one-sided pot pays 1.0: winners get their stake
|
|
47
|
+
* would come back as if that side wins, with any bonus shared on top. A one-sided pot pays 1.0: winners get their stake
|
|
48
|
+
* back and the bonus goes back to its sponsors.
|
|
48
49
|
*/
|
|
49
|
-
export function odds({ holds, breaks }: Pools) {
|
|
50
|
+
export function odds({ holds, breaks }: Pools, bonus = 0n) {
|
|
50
51
|
const total = holds + breaks;
|
|
51
52
|
const holdsBps = total === 0n ? 0 : Number((holds * 10000n) / total);
|
|
52
53
|
return {
|
|
53
54
|
holdsBps,
|
|
54
55
|
breaksBps: total === 0n ? 0 : 10000 - holdsBps,
|
|
55
|
-
holdsMultiple: multiple(holds, breaks),
|
|
56
|
-
breaksMultiple: multiple(breaks, holds),
|
|
56
|
+
holdsMultiple: multiple(holds, breaks, bonus),
|
|
57
|
+
breaksMultiple: multiple(breaks, holds, bonus),
|
|
57
58
|
};
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
/**
|
|
61
|
-
* The contract's claim maths. A winning stake comes back with its share of the losing pool after the rake
|
|
62
|
-
* the whole stake an account has on that side; a pot with an empty side refunds every stake.
|
|
62
|
+
* The contract's claim maths. A winning stake comes back with its share of the losing pool after the rake and of the
|
|
63
|
+
* bonus, floored on the whole stake an account has on that side; a pot with an empty side refunds every stake.
|
|
63
64
|
*/
|
|
64
|
-
export function payout(stake: bigint, side: Side, pools: Pools, outcome: Side): bigint {
|
|
65
|
+
export function payout(stake: bigint, side: Side, pools: Pools, outcome: Side, bonus = 0n): bigint {
|
|
65
66
|
if (stake <= 0n) return 0n;
|
|
66
67
|
if (pools.holds === 0n || pools.breaks === 0n) return stake;
|
|
67
68
|
if (side !== outcome) return 0n;
|
|
68
69
|
const losers = side === "holds" ? pools.breaks : pools.holds;
|
|
69
|
-
return stake + (stake * (losers - (losers * RAKE_BPS) / 10000n)) / pools[side];
|
|
70
|
+
return stake + (stake * (losers - (losers * RAKE_BPS) / 10000n + bonus)) / pools[side];
|
|
70
71
|
}
|
|
71
72
|
|
|
72
73
|
/** Payout over stake, floored to two decimals. */
|
|
@@ -81,9 +82,9 @@ const shareOf = (pools: Pools, side: Side) => {
|
|
|
81
82
|
* What `amount` on `side` pays if that side wins, with the pools as the bet leaves them. A parimutuel price is not
|
|
82
83
|
* fixed: this holds for the pools as they stand now, and later bets move it until betting closes.
|
|
83
84
|
*/
|
|
84
|
-
export function quoteOf(pools: Pools, side: Side, amount: bigint) {
|
|
85
|
+
export function quoteOf(pools: Pools, side: Side, amount: bigint, bonus = 0n) {
|
|
85
86
|
const poolsAfter = { ...pools, [side]: pools[side] + amount } as Pools;
|
|
86
|
-
const paid = payout(amount, side, poolsAfter, side);
|
|
87
|
+
const paid = payout(amount, side, poolsAfter, side, bonus);
|
|
87
88
|
return {
|
|
88
89
|
poolsAfter,
|
|
89
90
|
impliedBps: shareOf(pools, side),
|
package/src/types.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import type { Address, Hash, Hex } from "viem";
|
|
2
|
+
import type { Asset, AssetSymbol } from "./assets.js";
|
|
2
3
|
import type { Side } from "./odds.js";
|
|
3
4
|
|
|
4
|
-
// The API's answers as served: amounts are
|
|
5
|
-
// case: some routes checksum them and some
|
|
5
|
+
// The API's answers as served: amounts are base units of the Call's asset as decimal strings (wei on an ETH Call,
|
|
6
|
+
// millionths on a USDG Call), times unix seconds. Compare addresses without case: some routes checksum them and some
|
|
7
|
+
// lowercase them. GET /v1/openapi.json is the full description.
|
|
6
8
|
|
|
7
9
|
export type CallStatus = "open" | "settled" | "disputed" | "final" | "voided";
|
|
8
10
|
export type CallType = "posted" | "onchain" | "price" | "deed";
|
|
9
11
|
export type Wei = string;
|
|
12
|
+
/** Base units of the Call's own asset, as a decimal string: wei for ETH, millionths for USDG. */
|
|
13
|
+
export type Units = string;
|
|
10
14
|
|
|
11
15
|
export interface Post {
|
|
12
16
|
id: string | null;
|
|
@@ -36,9 +40,14 @@ export interface CallSummary {
|
|
|
36
40
|
closeAt: number;
|
|
37
41
|
deadline: number;
|
|
38
42
|
openedAt: number;
|
|
39
|
-
|
|
43
|
+
/** What the Call is staked in. Every amount on it is in base units of this asset. */
|
|
44
|
+
asset: Asset;
|
|
45
|
+
bond: Units;
|
|
46
|
+
/** The bonus pot sponsors added, shared by the winners on top of the losing pool. Always "0" on an ETH Call. */
|
|
47
|
+
bonus: Units;
|
|
40
48
|
deedId: string | null;
|
|
41
|
-
|
|
49
|
+
/** `eth` is the pot in ETH, null on a USDG Call; `amount` is the pot in whole units of the Call's asset. */
|
|
50
|
+
pools: { holds: Units; breaks: Units; total: Units; eth: number | null; amount: number };
|
|
42
51
|
odds: { holdsBps: number; breaksBps: number; holdsMultiple: number | null; breaksMultiple: number | null; lopsided: number };
|
|
43
52
|
betCount: number;
|
|
44
53
|
outcome: Side | null;
|
|
@@ -54,7 +63,7 @@ export interface CallSummary {
|
|
|
54
63
|
export interface CallRow extends CallSummary {
|
|
55
64
|
spark: number[];
|
|
56
65
|
change1h: number;
|
|
57
|
-
recentStake:
|
|
66
|
+
recentStake: Units;
|
|
58
67
|
recentBets15: number;
|
|
59
68
|
}
|
|
60
69
|
|
|
@@ -63,9 +72,9 @@ export interface Bet {
|
|
|
63
72
|
logIndex: number;
|
|
64
73
|
bettor: Address;
|
|
65
74
|
side: Side;
|
|
66
|
-
amount:
|
|
67
|
-
holdsPool:
|
|
68
|
-
breaksPool:
|
|
75
|
+
amount: Units;
|
|
76
|
+
holdsPool: Units;
|
|
77
|
+
breaksPool: Units;
|
|
69
78
|
block: number;
|
|
70
79
|
at: number;
|
|
71
80
|
tag: Tag;
|
|
@@ -79,20 +88,22 @@ export interface CallDetail extends CallSummary {
|
|
|
79
88
|
evidence: { hash: Hash; url: string; matchesChain: boolean | null } | null;
|
|
80
89
|
settledBy: Address | null;
|
|
81
90
|
disputer: Address | null;
|
|
82
|
-
disputeBond:
|
|
91
|
+
disputeBond: Units | null;
|
|
83
92
|
disputedAt: number | null;
|
|
84
93
|
resolvedAt: number | null;
|
|
85
|
-
winnersPool:
|
|
86
|
-
losersPool:
|
|
87
|
-
rake:
|
|
88
|
-
openerPaid:
|
|
89
|
-
treasuryPaid:
|
|
94
|
+
winnersPool: Units | null;
|
|
95
|
+
losersPool: Units | null;
|
|
96
|
+
rake: Units | null;
|
|
97
|
+
openerPaid: Units | null;
|
|
98
|
+
treasuryPaid: Units | null;
|
|
90
99
|
openerAtFault: boolean | null;
|
|
91
100
|
reasonHash: Hash | null;
|
|
92
101
|
openedBlock: number;
|
|
93
102
|
openedTx: Hash;
|
|
94
103
|
unresolvable: { reason: string; refundsAt: number } | null;
|
|
95
104
|
bets: Bet[];
|
|
105
|
+
/** Every addition to the bonus pot, newest first. Empty on an ETH Call. */
|
|
106
|
+
bonuses: { txHash: Hash; logIndex: number; sponsor: Address; amount: Units; bonus: Units; block: number; at: number }[];
|
|
96
107
|
records: { tokenId: number; account: Address; collection: Address | null; txHash: Hash; block: number; at: number }[] | null;
|
|
97
108
|
}
|
|
98
109
|
|
|
@@ -102,11 +113,13 @@ export interface RecentBet {
|
|
|
102
113
|
callAddress: Address;
|
|
103
114
|
bettor: Address;
|
|
104
115
|
side: Side;
|
|
105
|
-
amount:
|
|
116
|
+
amount: Units;
|
|
117
|
+
/** What the Call is staked in, and so what `amount` and `pools` are in. */
|
|
118
|
+
asset: AssetSymbol;
|
|
106
119
|
block: number;
|
|
107
120
|
at: number;
|
|
108
121
|
callTextHash: Hash;
|
|
109
|
-
pools: { holds:
|
|
122
|
+
pools: { holds: Units; breaks: Units };
|
|
110
123
|
tag: Tag;
|
|
111
124
|
}
|
|
112
125
|
|
|
@@ -203,18 +216,22 @@ export interface Proof {
|
|
|
203
216
|
export interface Quote {
|
|
204
217
|
call: Address;
|
|
205
218
|
side: Side;
|
|
206
|
-
amount:
|
|
219
|
+
amount: Units;
|
|
220
|
+
/** What the Call is staked in. Every amount in the quote is in base units of it. */
|
|
221
|
+
asset: Asset;
|
|
222
|
+
/** The bonus pot counted in `payout`. "0" on an ETH Call. */
|
|
223
|
+
bonus: Units;
|
|
207
224
|
status: CallStatus;
|
|
208
225
|
bettingOpen: boolean;
|
|
209
226
|
closeAt: number;
|
|
210
|
-
minBet:
|
|
211
|
-
pools: { holds:
|
|
212
|
-
poolsAfter: { holds:
|
|
227
|
+
minBet: Units;
|
|
228
|
+
pools: { holds: Units; breaks: Units };
|
|
229
|
+
poolsAfter: { holds: Units; breaks: Units };
|
|
213
230
|
impliedBps: number | null;
|
|
214
231
|
impliedBpsAfter: number;
|
|
215
|
-
/** If this side wins, with the pools as the bet leaves them. Later bets move it until betting closes. */
|
|
216
|
-
payout:
|
|
217
|
-
profit:
|
|
232
|
+
/** If this side wins, with the pools as the bet leaves them and its share of any bonus. Later bets move it until betting closes. */
|
|
233
|
+
payout: Units;
|
|
234
|
+
profit: Units;
|
|
218
235
|
multiple: number;
|
|
219
236
|
/** The other side is empty. If it stays empty every stake comes back and nobody wins. */
|
|
220
237
|
refund: boolean;
|
|
@@ -297,15 +314,49 @@ export interface Settlement {
|
|
|
297
314
|
|
|
298
315
|
export interface Positions {
|
|
299
316
|
address: Address;
|
|
300
|
-
/** The
|
|
301
|
-
|
|
317
|
+
/** The asset these positions are staked in. ETH unless asked for another; no figure adds one asset to another. */
|
|
318
|
+
asset: Asset;
|
|
319
|
+
/** The wallet's balance of `asset` on the chain, or null when no endpoint answered. */
|
|
320
|
+
balance: Units | null;
|
|
321
|
+
/** The wallet's ETH, which pays the gas whatever the stake is in. On an ETH read it is `balance`. */
|
|
322
|
+
gas: Wei | null;
|
|
302
323
|
positions: Player["positions"];
|
|
303
324
|
/** Newest 50 Final and Voided Calls, each with what `claim()` pays now (`owed`, null when no endpoint answered). */
|
|
304
|
-
settled: (Player["shelf"][number] & { owed:
|
|
325
|
+
settled: (Player["shelf"][number] & { owed: Units | null })[];
|
|
305
326
|
week: Player["week"];
|
|
306
327
|
all: Player["all"];
|
|
307
328
|
}
|
|
308
329
|
|
|
330
|
+
/** What a USDG write needs from the wallet before it goes, read from the chain. */
|
|
331
|
+
export interface Approval {
|
|
332
|
+
token: Address;
|
|
333
|
+
/** The contract the wallet lets take its USDG: the USDG factory for a bet or a bonus, the Call for a dispute. */
|
|
334
|
+
spender: Address;
|
|
335
|
+
owner: Address;
|
|
336
|
+
balance: Units;
|
|
337
|
+
allowance: Units;
|
|
338
|
+
amount: Units;
|
|
339
|
+
/** The allowance to set first, exactly `amount`, or null when the allowance already covers it. A separate transaction. */
|
|
340
|
+
approve: Units | null;
|
|
341
|
+
/** How much USDG the wallet lacks. "0" when it holds enough. */
|
|
342
|
+
short: Units;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** What adding to a USDG Call's bonus pot does, with the pot as it stands. */
|
|
346
|
+
export interface BonusQuote {
|
|
347
|
+
call: Address;
|
|
348
|
+
asset: Asset;
|
|
349
|
+
amount: Units;
|
|
350
|
+
status: CallStatus;
|
|
351
|
+
bettingOpen: boolean;
|
|
352
|
+
closeAt: number;
|
|
353
|
+
pools: { holds: Units; breaks: Units };
|
|
354
|
+
bonus: Units;
|
|
355
|
+
bonusAfter: Units;
|
|
356
|
+
/** What this wallet has put in the pot so far, or null without a wallet. */
|
|
357
|
+
sponsored: Units | null;
|
|
358
|
+
}
|
|
359
|
+
|
|
309
360
|
export type RoundOutcome = "up" | "down" | "refunded";
|
|
310
361
|
export type RoundSide = "up" | "down";
|
|
311
362
|
|