@shippedcalls/sdk 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +87 -2
- package/dist/abi.d.ts +1653 -0
- package/dist/abi.js +2135 -0
- package/dist/abi.js.map +1 -0
- package/dist/canonical.d.ts +2 -0
- package/dist/canonical.js +25 -0
- package/dist/canonical.js.map +1 -0
- package/dist/chain.d.ts +21 -0
- package/dist/chain.js +40 -0
- package/dist/chain.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +298 -0
- package/dist/cli.js.map +1 -0
- package/dist/client.d.ts +158 -0
- package/dist/client.js +419 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +51 -0
- package/dist/errors.js.map +1 -0
- package/dist/hashes.d.ts +12 -0
- package/dist/hashes.js +25 -0
- package/dist/hashes.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/odds.d.ts +43 -0
- package/dist/odds.js +73 -0
- package/dist/odds.js.map +1 -0
- package/dist/types.d.ts +417 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +32 -4
- package/skill/SKILL.md +60 -0
- package/skill/references/api.md +59 -0
- package/skill/references/funding.md +27 -0
- package/skill/references/settlement.md +45 -0
- package/skill/references/write-path.md +68 -0
- package/skill/scripts/calls.sh +3 -0
- package/src/abi.ts +2137 -0
- package/src/canonical.ts +24 -0
- package/src/chain.ts +43 -0
- package/src/cli.ts +291 -0
- package/src/client.ts +447 -0
- package/src/errors.ts +49 -0
- package/src/hashes.ts +32 -0
- package/src/index.ts +8 -0
- package/src/odds.ts +82 -0
- package/src/types.ts +305 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import { formatEther, getAddress, isAddress, parseEventLogs, type Abi, type Account, type Address, type Hash, type Transport, type TransactionReceipt } from "viem";
|
|
2
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
3
|
+
import { callAbi, factoryAbi } from "./abi.js";
|
|
4
|
+
import { hashJson } from "./canonical.js";
|
|
5
|
+
import { API_URL, CHAIN_ID, clientsFor, DEEDS, EXPLORER, FACTORY, PREVIOUS_FACTORIES, rpcEndpoints } from "./chain.js";
|
|
6
|
+
import { CallsError, describe } from "./errors.js";
|
|
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, OpenInput, Opened, Player, Positions, Prepared, Proof, Quote, RecentBet, Settlement, ShippedAgent, Stored, TapeItem, Tx } from "./types.js";
|
|
10
|
+
|
|
11
|
+
export interface ClientOptions {
|
|
12
|
+
/** The API's origin. https://calls.shipped.bond by default. */
|
|
13
|
+
api?: string;
|
|
14
|
+
/** One endpoint, a comma-separated list or an array, tried in order. A public list with fallback by default. */
|
|
15
|
+
rpc?: string | readonly string[];
|
|
16
|
+
/** A private key, or `account` for any viem account. Reads need neither. */
|
|
17
|
+
privateKey?: string;
|
|
18
|
+
account?: Account;
|
|
19
|
+
/** The most one bet may stake, wei. 0.01 ETH by default. */
|
|
20
|
+
maxStake?: bigint;
|
|
21
|
+
chainId?: number;
|
|
22
|
+
factory?: Address;
|
|
23
|
+
/** Earlier factories whose Calls this client still treats as Calls. The published ones unless `factory` is set. */
|
|
24
|
+
previousFactories?: readonly Address[];
|
|
25
|
+
fetch?: typeof fetch;
|
|
26
|
+
/** A viem transport in place of `rpc`. */
|
|
27
|
+
transport?: Transport;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const DEFAULT_MAX_STAKE = 10n ** 16n;
|
|
31
|
+
export const DEFAULT_MAX_BOND = MIN_OPENER_BOND;
|
|
32
|
+
|
|
33
|
+
const STATUS: readonly CallStatus[] = ["open", "settled", "disputed", "final", "voided"];
|
|
34
|
+
const TYPES: readonly CallType[] = ["posted", "onchain", "price", "deed"];
|
|
35
|
+
const SIDE_CODE = { holds: 1, breaks: 2 } as const;
|
|
36
|
+
const OUTCOME = [null, "holds", "breaks"] as const;
|
|
37
|
+
const SHELF_READS = 50;
|
|
38
|
+
|
|
39
|
+
const deedsCoreAbi = [
|
|
40
|
+
{
|
|
41
|
+
type: "function",
|
|
42
|
+
name: "core",
|
|
43
|
+
stateMutability: "view",
|
|
44
|
+
inputs: [{ name: "deedId", type: "uint256" }],
|
|
45
|
+
outputs: [
|
|
46
|
+
{ name: "creator", type: "address" },
|
|
47
|
+
{ name: "status", type: "uint8" },
|
|
48
|
+
{ name: "asset", type: "address" },
|
|
49
|
+
{ name: "deadline", type: "uint64" },
|
|
50
|
+
],
|
|
51
|
+
},
|
|
52
|
+
] as const;
|
|
53
|
+
const BOND_OPEN = 1;
|
|
54
|
+
|
|
55
|
+
export function sideOf(side: unknown): Side {
|
|
56
|
+
const name = String(side).toLowerCase();
|
|
57
|
+
if (name === "holds" || name === "1") return "holds";
|
|
58
|
+
if (name === "breaks" || name === "2") return "breaks";
|
|
59
|
+
throw new CallsError("Pick a side: holds or breaks.", "bad_side");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function addressOf(value: unknown, what = "Call"): Address {
|
|
63
|
+
if (typeof value === "string" && isAddress(value, { strict: false })) return getAddress(value);
|
|
64
|
+
throw new CallsError(`Use a ${what} address: 0x and 40 hex characters.`, "bad_address");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const query = (params: Record<string, unknown>) => {
|
|
68
|
+
const q = new URLSearchParams();
|
|
69
|
+
for (const [key, value] of Object.entries(params)) if (value != null && value !== "") q.set(key, String(value));
|
|
70
|
+
const text = q.toString();
|
|
71
|
+
return text ? `?${text}` : "";
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const toTx = (receipt: TransactionReceipt, chainId: number): Tx => ({
|
|
75
|
+
hash: receipt.transactionHash,
|
|
76
|
+
block: Number(receipt.blockNumber),
|
|
77
|
+
gasUsed: receipt.gasUsed.toString(),
|
|
78
|
+
fee: (receipt.gasUsed * receipt.effectiveGasPrice).toString(),
|
|
79
|
+
explorerUrl: chainId === CHAIN_ID ? `${EXPLORER}/tx/${receipt.transactionHash}` : null,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export function accountFromKey(privateKey: string): Account {
|
|
83
|
+
try {
|
|
84
|
+
return privateKeyToAccount((privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`) as Hash);
|
|
85
|
+
} catch {
|
|
86
|
+
throw new CallsError("That private key is not valid: 32 bytes of hex.", "bad_key");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Shipped's mainnet registry opened with a test bond, so its public bond numbers count from the one after it. */
|
|
91
|
+
export const bondIdOf = (number: number, chainId = CHAIN_ID) => number + (chainId === CHAIN_ID ? 2 : 1) - 1;
|
|
92
|
+
|
|
93
|
+
/** The hashes a Call opens with, computed here. `open` checks the API's against them before it spends anything. */
|
|
94
|
+
export function prepareOpen(input: OpenInput, chainId = CHAIN_ID): Prepared {
|
|
95
|
+
const bondNumber = input.bondNumber;
|
|
96
|
+
if (bondNumber != null && !(Number.isInteger(bondNumber) && bondNumber > 0)) throw new CallsError("A bond number is a positive whole number.", "bad_bond_number");
|
|
97
|
+
const spec = bondNumber != null ? { type: "deed", deedId: bondIdOf(bondNumber, chainId) } : input.spec;
|
|
98
|
+
if (!spec || typeof spec !== "object") throw new CallsError("Give the Call an evidence spec: see /v1/schemas/<type>.json.", "bad_spec");
|
|
99
|
+
const type = spec.type as CallType;
|
|
100
|
+
const callType = TYPES.indexOf(type);
|
|
101
|
+
if (callType < 0) throw new CallsError("The spec's type has to be posted, onchain, price or deed.", "bad_spec");
|
|
102
|
+
const bond = input.bond ?? MIN_OPENER_BOND;
|
|
103
|
+
const isBond = type === "deed";
|
|
104
|
+
const named = normalizeHandle(input.handle ?? (spec.handle as string | undefined) ?? "");
|
|
105
|
+
const handle = isBond ? "" : named || parsePostUrl(input.postUrl)?.handle || "";
|
|
106
|
+
if (input.postUrl && !parsePostUrl(input.postUrl)) throw new CallsError("Paste a link to a post on X.", "bad_post_url");
|
|
107
|
+
const postUrl = input.postUrl ? canonicalPostUrl(input.postUrl, named || undefined) : null;
|
|
108
|
+
return {
|
|
109
|
+
type,
|
|
110
|
+
callType,
|
|
111
|
+
spec: spec as Record<string, unknown>,
|
|
112
|
+
handle: handle || null,
|
|
113
|
+
postUrl,
|
|
114
|
+
bond: bond.toString(),
|
|
115
|
+
hashes: {
|
|
116
|
+
subject: isBond ? ZERO_HASH : subjectHash(handle),
|
|
117
|
+
postRef: postRefHash(postUrl),
|
|
118
|
+
callTextHash: callTextHash(input.callText),
|
|
119
|
+
evidenceSpec: specHash(spec),
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function createClient(options: ClientOptions = {}) {
|
|
125
|
+
const chainId = options.chainId ?? CHAIN_ID;
|
|
126
|
+
const factory = options.factory ?? FACTORY;
|
|
127
|
+
const factories = [factory, ...(options.previousFactories ?? (options.factory ? [] : PREVIOUS_FACTORIES))];
|
|
128
|
+
const origin = (options.api ?? API_URL).replace(/\/$/, "");
|
|
129
|
+
const account = options.account ?? (options.privateKey ? accountFromKey(options.privateKey) : undefined);
|
|
130
|
+
const { reads, writes } = clientsFor({ chainId, urls: rpcEndpoints(options.rpc), account, transport: options.transport });
|
|
131
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
132
|
+
const maxStake = options.maxStake ?? DEFAULT_MAX_STAKE;
|
|
133
|
+
let chainChecked = false;
|
|
134
|
+
|
|
135
|
+
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|
136
|
+
let res: Response;
|
|
137
|
+
try {
|
|
138
|
+
res = await doFetch(`${origin}${path}`, { signal: AbortSignal.timeout(20_000), ...init });
|
|
139
|
+
} catch {
|
|
140
|
+
throw new CallsError("Shipped Calls did not answer. Try again shortly.", "api_unavailable");
|
|
141
|
+
}
|
|
142
|
+
const body = (await res.json().catch(() => null)) as (T & { error?: string }) | null;
|
|
143
|
+
if (res.ok && body) return body;
|
|
144
|
+
throw new CallsError(body?.error ?? "Shipped Calls did not answer as expected. Try again shortly.", `api_${res.status}`, res.status);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const read = <T>(address: Address, abi: Abi, functionName: string, args: unknown[] = []) => reads.readContract({ address, abi, functionName, args } as never) as Promise<T>;
|
|
148
|
+
const callRead = <T>(address: Address, functionName: string, args: unknown[] = []) => read<T>(address, callAbi as Abi, functionName, args);
|
|
149
|
+
|
|
150
|
+
async function guarded<T>(work: () => Promise<T>): Promise<T> {
|
|
151
|
+
try {
|
|
152
|
+
return await work();
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw describe(error);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const isCall = async (address: Address) => (await Promise.all(factories.map((f) => read<boolean>(f, factoryAbi as Abi, "isCall", [address])))).some(Boolean);
|
|
159
|
+
|
|
160
|
+
async function mustBeCall(value: unknown): Promise<Address> {
|
|
161
|
+
const address = addressOf(value);
|
|
162
|
+
if (!(await isCall(address))) throw new CallsError("That address is not a Call of the Shipped Calls factory, so nothing was sent.", "not_a_call");
|
|
163
|
+
return address;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function wallet(): Account {
|
|
167
|
+
if (!account) throw new CallsError("Set a wallet to send this: CALLS_PRIVATE_KEY, or `privateKey` or `account` in code.", "no_wallet");
|
|
168
|
+
return account;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const walletOr = (value?: unknown) => (value ? addressOf(value, "wallet") : wallet().address);
|
|
172
|
+
|
|
173
|
+
async function assertChain() {
|
|
174
|
+
if (chainChecked) return;
|
|
175
|
+
const actual = await reads.getChainId();
|
|
176
|
+
if (actual !== chainId) throw new CallsError(`This RPC endpoint serves chain ${actual}, not chain ${chainId}.`, "wrong_chain");
|
|
177
|
+
chainChecked = true;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Simulates first, so a write the contract would refuse never reaches the chain and costs nothing. A quarter over
|
|
181
|
+
// the estimate, as Shipped's own services send.
|
|
182
|
+
async function send(params: { address: Address; abi: Abi; functionName: string; args?: unknown[]; value?: bigint }): Promise<TransactionReceipt> {
|
|
183
|
+
const from = wallet();
|
|
184
|
+
await assertChain();
|
|
185
|
+
const call = { ...params, account: from } as never;
|
|
186
|
+
const { request: simulated } = await reads.simulateContract(call);
|
|
187
|
+
const estimate = await reads.estimateContractGas(call);
|
|
188
|
+
const hash = await writes!.writeContract({ ...(simulated as object), gas: (estimate * 5n + 3n) / 4n } as never);
|
|
189
|
+
const receipt = await reads.waitForTransactionReceipt({ hash, pollingInterval: 1_000 });
|
|
190
|
+
if (receipt.status !== "success") throw new CallsError("The transaction failed onchain.", "reverted");
|
|
191
|
+
return receipt;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
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
|
+
|
|
196
|
+
async function chainQuote(address: Address, side: Side, amount: bigint): Promise<Quote> {
|
|
197
|
+
const [member, status, closeAt, holds, breaks, block] = await Promise.all([
|
|
198
|
+
isCall(address),
|
|
199
|
+
callRead<number>(address, "status").catch(() => null),
|
|
200
|
+
callRead<bigint>(address, "closeAt").catch(() => null),
|
|
201
|
+
callRead<bigint>(address, "pool", [1]).catch(() => null),
|
|
202
|
+
callRead<bigint>(address, "pool", [2]).catch(() => null),
|
|
203
|
+
reads.getBlock({ blockTag: "latest" }),
|
|
204
|
+
]);
|
|
205
|
+
if (!member) throw new CallsError("That address is not a Call of the Shipped Calls factory.", "not_a_call");
|
|
206
|
+
if (status == null || closeAt == null || holds == null || breaks == null) throw new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
|
|
207
|
+
const pools = { holds, breaks };
|
|
208
|
+
const q = quoteOf(pools, side, amount);
|
|
209
|
+
return {
|
|
210
|
+
call: address,
|
|
211
|
+
side,
|
|
212
|
+
amount: amount.toString(),
|
|
213
|
+
status: STATUS[status]!,
|
|
214
|
+
bettingOpen: status === 0 && block.timestamp < closeAt,
|
|
215
|
+
closeAt: Number(closeAt),
|
|
216
|
+
minBet: MIN_BET.toString(),
|
|
217
|
+
pools: { holds: holds.toString(), breaks: breaks.toString() },
|
|
218
|
+
poolsAfter: { holds: q.poolsAfter.holds.toString(), breaks: q.poolsAfter.breaks.toString() },
|
|
219
|
+
impliedBps: q.impliedBps,
|
|
220
|
+
impliedBpsAfter: q.impliedBpsAfter,
|
|
221
|
+
payout: q.payout.toString(),
|
|
222
|
+
profit: q.profit.toString(),
|
|
223
|
+
multiple: q.multiple,
|
|
224
|
+
refund: q.refund,
|
|
225
|
+
source: "chain",
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const client = {
|
|
230
|
+
/** The wallet this client signs with, if any. */
|
|
231
|
+
address: account?.address ?? null,
|
|
232
|
+
chainId,
|
|
233
|
+
factory,
|
|
234
|
+
|
|
235
|
+
// Reads from the API. It follows the chain by up to a minute; the chain reads below do not.
|
|
236
|
+
|
|
237
|
+
async calls(filters: { status?: CallStatus; type?: CallType; subject?: string; sort?: "closing" | "lopsided" | "pot" | "newest"; limit?: number; offset?: number } = {}): Promise<CallRow[]> {
|
|
238
|
+
return (await request<{ calls: CallRow[] }>(`/v1/calls${query(filters)}`)).calls;
|
|
239
|
+
},
|
|
240
|
+
call: async (address: string) => request<CallDetail>(`/v1/calls/${addressOf(address)}`),
|
|
241
|
+
/** The latest bets across every Call, or every bet on one Call with `call`. */
|
|
242
|
+
async bets({ call, limit }: { call?: string; limit?: number } = {}): Promise<RecentBet[] | CallDetail["bets"]> {
|
|
243
|
+
if (call) return (await client.call(call)).bets;
|
|
244
|
+
return (await request<{ bets: RecentBet[] }>(`/v1/bets/recent${query({ limit })}`)).bets;
|
|
245
|
+
},
|
|
246
|
+
async tape({ limit }: { limit?: number } = {}): Promise<TapeItem[]> {
|
|
247
|
+
return (await request<{ items: TapeItem[] }>(`/v1/tape${query({ limit })}`)).items;
|
|
248
|
+
},
|
|
249
|
+
leaderboard: (filters: { window?: "week" | "all"; board?: "profit" | "best" | "streak" | "openers"; limit?: number; me?: string } = {}) => request<Leaderboard>(`/v1/leaderboard${query(filters)}`),
|
|
250
|
+
player: async (address?: string) => request<Player>(`/v1/players/${walletOr(address)}`),
|
|
251
|
+
/** Shipped agents: name, rule and wallet. */
|
|
252
|
+
async agents(): Promise<ShippedAgent[]> {
|
|
253
|
+
return (await request<{ agents: ShippedAgent[] }>("/v1/agents")).agents;
|
|
254
|
+
},
|
|
255
|
+
proof: () => request<Proof>("/v1/proof"),
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* What `amount` wei on `side` pays with the pools as they stand. Reads the pools from the chain, and from the API if
|
|
259
|
+
* no endpoint answers. Later bets move the payout until betting closes.
|
|
260
|
+
*/
|
|
261
|
+
async quote(address: string, side: Side | string, amount: bigint): Promise<Quote> {
|
|
262
|
+
const call = addressOf(address);
|
|
263
|
+
const name = sideOf(side);
|
|
264
|
+
if (amount < MIN_BET) throw new CallsError("The minimum bet is 0.001 ETH.", "BetTooSmall");
|
|
265
|
+
try {
|
|
266
|
+
return await chainQuote(call, name, amount);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if (error instanceof CallsError && error.code !== "rpc_unavailable") throw error;
|
|
269
|
+
return request<Quote>(`/v1/calls/${call}/quote${query({ side: name, amount })}`);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
/** One wallet's open positions and settled Calls from the API, with its balance and what it can claim from the chain. */
|
|
274
|
+
async positions(address?: string): Promise<Positions> {
|
|
275
|
+
const who = walletOr(address);
|
|
276
|
+
const [player, balance] = await Promise.all([client.player(who), reads.getBalance({ address: who }).catch(() => null)]);
|
|
277
|
+
const settled = await Promise.all(
|
|
278
|
+
player.shelf.slice(0, SHELF_READS).map(async (row) => ({ ...row, owed: await client.payoutOf(row.call, who).then(String, () => null) })),
|
|
279
|
+
);
|
|
280
|
+
return { address: who, balance: balance == null ? null : balance.toString(), positions: player.positions, settled, week: player.week, all: player.all };
|
|
281
|
+
},
|
|
282
|
+
|
|
283
|
+
// Reads from the chain, current to the block.
|
|
284
|
+
|
|
285
|
+
isCall: (address: string) => guarded(() => isCall(addressOf(address))),
|
|
286
|
+
pool: (address: string, side: Side | string) => guarded(() => callRead<bigint>(addressOf(address), "pool", [SIDE_CODE[sideOf(side)]])),
|
|
287
|
+
status: (address: string) => guarded(async () => STATUS[await callRead<number>(addressOf(address), "status")]!),
|
|
288
|
+
/** Seconds this Call's result stays open to dispute after it settles. A Call of an earlier factory has no such read, and ran 24 hours. */
|
|
289
|
+
disputeWindow: (address: string) =>
|
|
290
|
+
guarded(async () => {
|
|
291
|
+
const call = addressOf(address);
|
|
292
|
+
try {
|
|
293
|
+
return Number(await callRead<bigint>(call, "disputeWindow"));
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if ((describe(error) as CallsError).code === "rpc_unavailable") throw error;
|
|
296
|
+
return (await callRead<number>(call, "callType")) === 3 ? 0 : DISPUTE_WINDOW;
|
|
297
|
+
}
|
|
298
|
+
}),
|
|
299
|
+
async odds(address: string) {
|
|
300
|
+
const [holds, breaks] = await Promise.all([client.pool(address, "holds"), client.pool(address, "breaks")]);
|
|
301
|
+
return { pools: { holds, breaks }, ...odds({ holds, breaks }) };
|
|
302
|
+
},
|
|
303
|
+
payoutOf: (address: string, who?: string) => guarded(() => callRead<bigint>(addressOf(address), "payoutOf", [walletOr(who)])),
|
|
304
|
+
stake: (address: string, side: Side | string, who?: string) => guarded(() => callRead<bigint>(addressOf(address), "stake", [walletOr(who), SIDE_CODE[sideOf(side)]])),
|
|
305
|
+
balance: (who?: string) => guarded(() => reads.getBalance({ address: walletOr(who) })),
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Stakes `amount` wei on `side`. Refuses an amount over `maxStake` and an address that is not one of the factory's
|
|
309
|
+
* Calls before anything goes out; simulates first, so a bet the contract would refuse costs nothing.
|
|
310
|
+
*/
|
|
311
|
+
async bet(address: string, side: Side | string, amount: bigint, { maxStake: cap = maxStake }: { maxStake?: bigint } = {}) {
|
|
312
|
+
const name = sideOf(side);
|
|
313
|
+
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");
|
|
314
|
+
return guarded(async () => {
|
|
315
|
+
const call = await mustBeCall(address);
|
|
316
|
+
// The API may be down; the chain still takes the bet, so its word only ever stops one.
|
|
317
|
+
const stored = await client.call(call).catch(() => null);
|
|
318
|
+
if (stored?.unresolvable) throw new CallsError(`Shipped can't settle this Call as written, so a stake here only comes back as a refund, from ${new Date(stored.unresolvable.refundsAt * 1000).toISOString()}. Nothing was sent.`, "unresolvable");
|
|
319
|
+
const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "bet", args: [SIDE_CODE[name]], value: amount });
|
|
320
|
+
const placed = eventOf<{ holdsPool: bigint; breaksPool: bigint }>(receipt, callAbi as Abi, "Bet");
|
|
321
|
+
return { ...toTx(receipt, chainId), call, side: name, amount: amount.toString(), pools: placed ? { holds: placed.holdsPool.toString(), breaks: placed.breaksPool.toString() } : null };
|
|
322
|
+
});
|
|
323
|
+
},
|
|
324
|
+
|
|
325
|
+
/** Collects winnings or a refund once the Call is Final or Voided. The money only ever goes to the wallet that sends this. */
|
|
326
|
+
claim: (address: string) =>
|
|
327
|
+
guarded(async () => {
|
|
328
|
+
const call = await mustBeCall(address);
|
|
329
|
+
const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "claim" });
|
|
330
|
+
const paid = eventOf<{ amount: bigint }>(receipt, callAbi as Abi, "Claimed");
|
|
331
|
+
return { ...toTx(receipt, chainId), call, amount: paid?.amount.toString() ?? null };
|
|
332
|
+
}),
|
|
333
|
+
|
|
334
|
+
/** Pays the opener's bond and fee share. Anyone can send it; the money only ever goes to the opener. */
|
|
335
|
+
claimOpener: (address: string) =>
|
|
336
|
+
guarded(async () => {
|
|
337
|
+
const call = await mustBeCall(address);
|
|
338
|
+
const receipt = await send({ address: call, abi: callAbi as Abi, functionName: "claimOpener" });
|
|
339
|
+
const paid = eventOf<{ opener: Address; amount: bigint }>(receipt, callAbi as Abi, "OpenerPaid");
|
|
340
|
+
return { ...toTx(receipt, chainId), call, opener: paid?.opener ?? null, amount: paid?.amount.toString() ?? null };
|
|
341
|
+
}),
|
|
342
|
+
|
|
343
|
+
/** Makes a Settled Call Final once its dispute window has passed. Anyone can send it. */
|
|
344
|
+
finalize: (address: string) =>
|
|
345
|
+
guarded(async () => {
|
|
346
|
+
const call = await mustBeCall(address);
|
|
347
|
+
return { ...toTx(await send({ address: call, abi: callAbi as Abi, functionName: "finalize" }), chainId), call };
|
|
348
|
+
}),
|
|
349
|
+
|
|
350
|
+
/** Disputes a settled result inside its window, posting the dispute bond (0.02 ETH). The court rules; the bond comes back if it flips the result. */
|
|
351
|
+
dispute: (address: string) =>
|
|
352
|
+
guarded(async () => {
|
|
353
|
+
const call = await mustBeCall(address);
|
|
354
|
+
const bond = await callRead<bigint>(call, "DISPUTE_BOND");
|
|
355
|
+
return { ...toTx(await send({ address: call, abi: callAbi as Abi, functionName: "dispute", value: bond }), chainId), call, bond: bond.toString() };
|
|
356
|
+
}),
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Opens a Call. Stores the sentence and spec with `POST /v1/calls` first, because Shipped settles from the stored
|
|
360
|
+
* spec, checks the API's hashes against its own, then sends `CallsFactory.open` with the bond.
|
|
361
|
+
*/
|
|
362
|
+
async open(input: OpenInput): Promise<Opened> {
|
|
363
|
+
const prepared = prepareOpen(input, chainId);
|
|
364
|
+
const bond = BigInt(prepared.bond);
|
|
365
|
+
const maxBond = input.maxBond ?? DEFAULT_MAX_BOND;
|
|
366
|
+
if (bond > maxBond) throw new CallsError(`A ${formatEther(bond)} ETH bond is over the ${formatEther(maxBond)} ETH limit. Raise the limit to post it.`, "over_max_bond");
|
|
367
|
+
wallet();
|
|
368
|
+
return guarded(async () => {
|
|
369
|
+
await assertChain();
|
|
370
|
+
const stored = await request<Stored>("/v1/calls", {
|
|
371
|
+
method: "POST",
|
|
372
|
+
headers: { "content-type": "application/json" },
|
|
373
|
+
body: JSON.stringify({
|
|
374
|
+
type: prepared.type,
|
|
375
|
+
callText: input.callText,
|
|
376
|
+
spec: prepared.spec,
|
|
377
|
+
...(prepared.handle ? { handle: prepared.handle } : {}),
|
|
378
|
+
...(input.postUrl ? { postUrl: input.postUrl } : {}),
|
|
379
|
+
...(input.postText ? { postText: input.postText } : {}),
|
|
380
|
+
...(prepared.type === "onchain" && input.deadline != null ? { deadline: input.deadline } : {}),
|
|
381
|
+
}),
|
|
382
|
+
});
|
|
383
|
+
const local = prepared.hashes;
|
|
384
|
+
if (stored.callType !== prepared.callType || stored.subject !== local.subject || stored.postRef !== local.postRef || stored.callTextHash !== local.callTextHash || stored.evidenceSpec !== local.evidenceSpec) {
|
|
385
|
+
throw new CallsError("The API answered other hashes than this Call hashes to, so nothing was sent. If it quotes a post, pass the author's handle.", "hash_mismatch");
|
|
386
|
+
}
|
|
387
|
+
const { closeAt, deadline } = await timesFor(prepared, stored, input);
|
|
388
|
+
const receipt = await send({
|
|
389
|
+
address: factory,
|
|
390
|
+
abi: [...(factoryAbi as Abi), ...(callAbi as Abi).filter((item) => item.type === "error")],
|
|
391
|
+
functionName: "open",
|
|
392
|
+
args: [local.subject, local.postRef, local.callTextHash, prepared.callType, BigInt(closeAt), BigInt(deadline), local.evidenceSpec, deedIdOf(prepared)],
|
|
393
|
+
value: bond,
|
|
394
|
+
});
|
|
395
|
+
const opened = eventOf<{ call: Address }>(receipt, factoryAbi as Abi, "CallOpened");
|
|
396
|
+
if (!opened) throw new CallsError("The transaction landed without a CallOpened event.", "no_event");
|
|
397
|
+
return { ...toTx(receipt, chainId), address: opened.call, callText: input.callText.trim(), closeAt, deadline, bond: prepared.bond, hashes: local };
|
|
398
|
+
});
|
|
399
|
+
},
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Checks a settlement: fetches the evidence record the API serves, hashes its canonical JSON and compares that and
|
|
403
|
+
* the record's outcome with the chain.
|
|
404
|
+
*/
|
|
405
|
+
async verifySettlement(address: string): Promise<Settlement> {
|
|
406
|
+
const call = addressOf(address);
|
|
407
|
+
return guarded(async () => {
|
|
408
|
+
const [statusCode, outcomeCode, evidenceHash] = await Promise.all([callRead<number>(call, "status"), callRead<number>(call, "outcome"), callRead<Hash>(call, "evidenceHash")]);
|
|
409
|
+
const status = STATUS[statusCode]!;
|
|
410
|
+
const outcome = OUTCOME[outcomeCode] ?? null;
|
|
411
|
+
const onChain = evidenceHash === ZERO_HASH ? null : evidenceHash;
|
|
412
|
+
const base = { call, status, outcome, evidenceHash: onChain, record: null };
|
|
413
|
+
if (status === "open") return { ...base, verified: null, note: "This Call has not been settled yet." };
|
|
414
|
+
if (status === "voided" && !onChain) return { ...base, verified: null, note: "This Call was voided: every stake comes back, and no evidence decides it." };
|
|
415
|
+
if (!onChain) return { ...base, verified: null, note: "A Call on a bond settles from the bond's final ruling, which the contract reads from Shipped's registry itself. There is no evidence hash to compare." };
|
|
416
|
+
const detail = await client.call(call);
|
|
417
|
+
if (!detail.evidenceHash) return { ...base, verified: null, note: "The API has not reached this settlement yet: it follows the chain by up to a minute. Try again shortly." };
|
|
418
|
+
if (!detail.evidence || detail.evidence.hash.toLowerCase() !== onChain.toLowerCase()) return { ...base, verified: false, note: "The API serves no evidence record for the hash onchain." };
|
|
419
|
+
const res = await doFetch(`${origin}${detail.evidence.url}`, { signal: AbortSignal.timeout(20_000) });
|
|
420
|
+
if (!res.ok) throw new CallsError("The API did not serve the evidence record.", `api_${res.status}`, res.status);
|
|
421
|
+
const parsed = (await res.json()) as { outcome: string; fetchedAt: number; source: unknown; redacted?: unknown };
|
|
422
|
+
const redacted = "redacted" in parsed;
|
|
423
|
+
const hash = redacted ? null : hashJson(parsed);
|
|
424
|
+
const facts = { url: `${origin}${detail.evidence.url}`, hash, outcome: parsed.outcome, fetchedAt: parsed.fetchedAt, source: parsed.source, redacted };
|
|
425
|
+
if (redacted) return { ...base, record: facts, verified: null, note: "A post in this record is no longer shown on X, so its text is left out and this copy cannot hash to the evidence hash onchain." };
|
|
426
|
+
const sameHash = hash!.toLowerCase() === onChain.toLowerCase();
|
|
427
|
+
const sameOutcome = String(parsed.outcome).toLowerCase() === outcome;
|
|
428
|
+
const verified = sameHash && sameOutcome;
|
|
429
|
+
return { ...base, record: facts, verified, note: verified ? "The record hashes to the evidence hash onchain and names the same outcome." : sameHash ? "The record hashes to the evidence hash onchain, but names another outcome than the chain." : "The record does not hash to the evidence hash onchain." };
|
|
430
|
+
});
|
|
431
|
+
},
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
async function timesFor(prepared: Prepared, stored: Stored, input: OpenInput) {
|
|
435
|
+
if (stored.suggested) return { deadline: stored.suggested.deadline, closeAt: Math.min(input.closeAt ?? stored.suggested.closeAt, stored.suggested.closeAt) };
|
|
436
|
+
const [, status, , bondDeadline] = await read<readonly [Address, number, Address, bigint]>(DEEDS, deedsCoreAbi as Abi, "core", [deedIdOf(prepared)]);
|
|
437
|
+
if (status !== BOND_OPEN) throw new CallsError("Calls can only be opened on an open Shipped bond.", "BadDeed");
|
|
438
|
+
const deadline = input.deadline ?? Number(bondDeadline);
|
|
439
|
+
return { deadline, closeAt: input.closeAt ?? deadline };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return client;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const deedIdOf = (prepared: Prepared) => (prepared.type === "deed" ? BigInt(prepared.spec.deedId as number | string) : 0n);
|
|
446
|
+
|
|
447
|
+
export type CallsClient = ReturnType<typeof createClient>;
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { BaseError, ContractFunctionExecutionError, ContractFunctionRevertedError, InsufficientFundsError } from "viem";
|
|
2
|
+
|
|
3
|
+
/** Every failure the SDK raises: one sentence to show, and a code to branch on. A revert's code is its error name. */
|
|
4
|
+
export class CallsError extends Error {
|
|
5
|
+
override name = "CallsError";
|
|
6
|
+
constructor(
|
|
7
|
+
message: string,
|
|
8
|
+
readonly code: string,
|
|
9
|
+
readonly status?: number,
|
|
10
|
+
) {
|
|
11
|
+
super(message);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const NOT_ENOUGH_ETH = "Not enough ETH to cover this and gas.";
|
|
16
|
+
|
|
17
|
+
// Keyed by error name, or by `function.error` where one revert means different things on different calls.
|
|
18
|
+
const REVERTS: Record<string, string> = {
|
|
19
|
+
"claim.TooEarly": "Nothing to claim until the Call is final.",
|
|
20
|
+
"finalize.TooEarly": "The dispute window is still open.",
|
|
21
|
+
BettingClosed: "Betting has closed on this Call.",
|
|
22
|
+
DeedSettled: "Betting has closed: the bond has been ruled on.",
|
|
23
|
+
BetTooSmall: "The minimum bet is 0.001 ETH.",
|
|
24
|
+
BadSide: "Pick Holds or Breaks.",
|
|
25
|
+
WrongStatus: "This Call has moved on. Read it again to see where it stands.",
|
|
26
|
+
WindowClosed: "The dispute window has closed.",
|
|
27
|
+
WrongBond: "The dispute bond has to match exactly.",
|
|
28
|
+
NothingToClaim: "Nothing to claim for this wallet.",
|
|
29
|
+
BondTooSmall: "The bond is below the 0.02 ETH minimum.",
|
|
30
|
+
BadWindow: "Betting has to close by the deadline, the deadline has to be within 180 days, and on a bond Call it can't be before the bond's own.",
|
|
31
|
+
BadDeed: "Calls can only be opened on an open Shipped bond.",
|
|
32
|
+
TooEarly: "It's too early for that. Check the times on the Call.",
|
|
33
|
+
IsDeedCall: "A Call on a bond settles from the bond's ruling.",
|
|
34
|
+
TransferFailed: "The payment could not be delivered to that address.",
|
|
35
|
+
InsufficientBalance: NOT_ENOUGH_ETH,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** One sentence for a failed read or write. RPC URLs can carry keys, so nothing from the transport is passed on. */
|
|
39
|
+
export function describe(error: unknown): CallsError {
|
|
40
|
+
if (error instanceof CallsError) return error;
|
|
41
|
+
if (!(error instanceof BaseError)) return new CallsError("The request did not go through.", "unknown");
|
|
42
|
+
if (error.walk((e) => e instanceof InsufficientFundsError) || /insufficient funds/i.test(error.message)) return new CallsError(NOT_ENOUGH_ETH, "insufficient_funds");
|
|
43
|
+
const revert = error.walk((e) => e instanceof ContractFunctionRevertedError) as ContractFunctionRevertedError | null;
|
|
44
|
+
const call = error.walk((e) => e instanceof ContractFunctionExecutionError) as ContractFunctionExecutionError | null;
|
|
45
|
+
const name = revert?.data?.errorName;
|
|
46
|
+
if (name) return new CallsError(REVERTS[`${call?.functionName}.${name}`] ?? REVERTS[name] ?? `The contract refused this: ${name}.`, name);
|
|
47
|
+
if (revert) return new CallsError("The contract refused this.", "reverted");
|
|
48
|
+
return new CallsError("Robinhood Chain did not answer on any RPC endpoint. Try again, or set CALLS_RPC_URL.", "rpc_unavailable");
|
|
49
|
+
}
|
package/src/hashes.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { keccak256, stringToBytes, type Hex } from "viem";
|
|
2
|
+
import { hashJson } from "./canonical.js";
|
|
3
|
+
|
|
4
|
+
export const ZERO_HASH = `0x${"0".repeat(64)}` as Hex;
|
|
5
|
+
|
|
6
|
+
const text = (s: string) => keccak256(stringToBytes(s));
|
|
7
|
+
|
|
8
|
+
export const normalizeHandle = (handle: string | null | undefined) => String(handle ?? "").trim().replace(/^@/, "").toLowerCase();
|
|
9
|
+
|
|
10
|
+
// The chain stores hashes of what the API keeps in full. These are the same rules the API and Shipped's settlement
|
|
11
|
+
// service use, so a Call opened here hashes to the row the API stored.
|
|
12
|
+
export const subjectHash = (handle: string | null | undefined) => (normalizeHandle(handle) ? text(normalizeHandle(handle)) : ZERO_HASH);
|
|
13
|
+
export const callTextHash = (callText: string) => text(String(callText).trim());
|
|
14
|
+
export const specHash = (spec: unknown) => hashJson(spec);
|
|
15
|
+
|
|
16
|
+
const POST_URL = /^(?:https?:\/\/)?(?:www\.|mobile\.)?(?:x\.com|twitter\.com)\/([A-Za-z0-9_]{1,15})\/status(?:es)?\/(\d+)/i;
|
|
17
|
+
|
|
18
|
+
export function parsePostUrl(url: string | null | undefined): { handle: string; id: string } | null {
|
|
19
|
+
const m = POST_URL.exec(String(url ?? "").trim());
|
|
20
|
+
return m ? { handle: m[1]!.toLowerCase(), id: m[2]! } : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// X serves a post under any handle in the path; `author`, when known, puts the real one there.
|
|
24
|
+
export function canonicalPostUrl(url: string | null | undefined, author?: string): string | null {
|
|
25
|
+
const post = parsePostUrl(url);
|
|
26
|
+
return post ? `https://x.com/${author ?? post.handle}/status/${post.id}` : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const postRefHash = (url: string | null | undefined) => {
|
|
30
|
+
const canon = canonicalPostUrl(url);
|
|
31
|
+
return canon ? text(canon) : ZERO_HASH;
|
|
32
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createClient, accountFromKey, bondIdOf, prepareOpen, 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";
|
|
3
|
+
export { callAbi, calledItAbi, factoryAbi } from "./abi.js";
|
|
4
|
+
export { canonical, hashJson } from "./canonical.js";
|
|
5
|
+
export { CallsError } from "./errors.js";
|
|
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";
|
|
8
|
+
export type * from "./types.js";
|
package/src/odds.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { parseEther } from "viem";
|
|
2
|
+
import { CallsError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export const RAKE_BPS = 400n;
|
|
5
|
+
export const MIN_BET = 10n ** 15n;
|
|
6
|
+
export const MIN_OPENER_BOND = 2n * 10n ** 16n;
|
|
7
|
+
/** Seconds. A Price Call has `PRICE_DISPUTE_WINDOW`; a bond Call has none. Every Call of an earlier factory has this one. */
|
|
8
|
+
export const DISPUTE_WINDOW = 24 * 3600;
|
|
9
|
+
export const PRICE_DISPUTE_WINDOW = 3600;
|
|
10
|
+
|
|
11
|
+
const ETH_AMOUNT = /^\d+(\.\d{1,18})?$|^\.\d{1,18}$/;
|
|
12
|
+
|
|
13
|
+
/** "0.001" to wei. Anything but a plain decimal amount of ETH is refused rather than guessed at. */
|
|
14
|
+
export function ethToWei(value: string, what = "The amount"): bigint {
|
|
15
|
+
if (!ETH_AMOUNT.test(value)) throw new CallsError(`${what} is an amount in ETH, such as 0.001.`, "bad_amount");
|
|
16
|
+
return parseEther(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type Side = "holds" | "breaks";
|
|
20
|
+
export interface Pools {
|
|
21
|
+
holds: bigint;
|
|
22
|
+
breaks: bigint;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function multiple(winners: bigint, losers: bigint): number | null {
|
|
26
|
+
if (winners === 0n) return losers === 0n ? 1 : null;
|
|
27
|
+
const paid = winners + (losers * (10000n - RAKE_BPS)) / 10000n;
|
|
28
|
+
return Number((paid * 10000n) / winners) / 10000;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 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
|
|
33
|
+
* would come back as if that side wins. A one-sided pot pays 1.0: winners get their stake back.
|
|
34
|
+
*/
|
|
35
|
+
export function odds({ holds, breaks }: Pools) {
|
|
36
|
+
const total = holds + breaks;
|
|
37
|
+
const holdsBps = total === 0n ? 0 : Number((holds * 10000n) / total);
|
|
38
|
+
return {
|
|
39
|
+
holdsBps,
|
|
40
|
+
breaksBps: total === 0n ? 0 : 10000 - holdsBps,
|
|
41
|
+
holdsMultiple: multiple(holds, breaks),
|
|
42
|
+
breaksMultiple: multiple(breaks, holds),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The contract's claim maths. A winning stake comes back with its share of the losing pool after the rake, floored on
|
|
48
|
+
* the whole stake an account has on that side; a pot with an empty side refunds every stake.
|
|
49
|
+
*/
|
|
50
|
+
export function payout(stake: bigint, side: Side, pools: Pools, outcome: Side): bigint {
|
|
51
|
+
if (stake <= 0n) return 0n;
|
|
52
|
+
if (pools.holds === 0n || pools.breaks === 0n) return stake;
|
|
53
|
+
if (side !== outcome) return 0n;
|
|
54
|
+
const losers = side === "holds" ? pools.breaks : pools.holds;
|
|
55
|
+
return stake + (stake * (losers - (losers * RAKE_BPS) / 10000n)) / pools[side];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Payout over stake, floored to two decimals. */
|
|
59
|
+
export const multipleOf = (paid: bigint, stake: bigint) => (stake > 0n ? Number((paid * 100n) / stake) / 100 : 0);
|
|
60
|
+
|
|
61
|
+
const shareOf = (pools: Pools, side: Side) => {
|
|
62
|
+
const total = pools.holds + pools.breaks;
|
|
63
|
+
return total === 0n ? null : Number((pools[side] * 10000n) / total);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* What `amount` on `side` pays if that side wins, with the pools as the bet leaves them. A parimutuel price is not
|
|
68
|
+
* fixed: this holds for the pools as they stand now, and later bets move it until betting closes.
|
|
69
|
+
*/
|
|
70
|
+
export function quoteOf(pools: Pools, side: Side, amount: bigint) {
|
|
71
|
+
const poolsAfter = { ...pools, [side]: pools[side] + amount } as Pools;
|
|
72
|
+
const paid = payout(amount, side, poolsAfter, side);
|
|
73
|
+
return {
|
|
74
|
+
poolsAfter,
|
|
75
|
+
impliedBps: shareOf(pools, side),
|
|
76
|
+
impliedBpsAfter: shareOf(poolsAfter, side)!,
|
|
77
|
+
payout: paid,
|
|
78
|
+
profit: paid - amount,
|
|
79
|
+
multiple: multipleOf(paid, amount),
|
|
80
|
+
refund: poolsAfter.holds === 0n || poolsAfter.breaks === 0n,
|
|
81
|
+
};
|
|
82
|
+
}
|