Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ This is detected, not configured. It was tested on the fork with a Safe as the w

The app shows the deposit address only after it has checked the finished vault on chain. It runs the same checks every time you open a vault, and anybody can open any vault by address.

The address of your nth vault depends only on your wallet address and n. The app finds your vaults again on any device, without a server.
A wallet has one Chronobox. Its address depends only on the wallet address, and it is the same on every network: the Safe that the Safe proxy factory (`createProxyWithNonce`) makes from the 1 of 1 setup of your wallet, with the salt nonce `keccak256("zodiac-timebox:v1")`. The app finds it again on any device, without a server (`chronoboxOf` in `src/lib/chronobox.ts`).

### The optional guardian

Expand Down
29 changes: 25 additions & 4 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { ALERTS, AlertsPage } from "./ui/alerts.tsx";
import { CreatePage } from "./ui/create.tsx";
import { DevBar } from "./ui/devbar.tsx";
import { ByZodiac, Lockup } from "./ui/logo.tsx";
import { StartPage, vaultHref } from "./ui/start.tsx";
import { OpenPage, StartPage } from "./ui/start.tsx";
import { HomePage } from "./ui/home.tsx";
import { ImprintPage, LegalPage, PrivacyPage, TermsPage } from "./ui/legal.tsx";
import { TechnicalPage } from "./ui/technical.tsx";
import { StatesPage } from "./ui/states.tsx";
Expand All @@ -25,6 +26,7 @@ import { VaultPage } from "./ui/vault.tsx";
type Route =
| { page: "start" }
| { page: "new" }
| { page: "open" }
| { page: "technical" }
| { page: "privacy" }
| { page: "states" }
Expand All @@ -43,6 +45,7 @@ function parseRoute(hash: string): Route {
const path = hash.replace(/^#/, "");
if (path === "" || path === "/" || !path.startsWith("/")) return { page: "start" };
if (path === "/new") return { page: "new" };
if (path === "/open") return { page: "open" };
if (path === "/technical") return { page: "technical" };
if (path === "/privacy") return { page: "privacy" };
if (path === "/terms") return { page: "terms" };
Expand Down Expand Up @@ -204,7 +207,14 @@ export function App() {

let body;
if (route.page === "start") {
body = <StartPage session={session} chain={chain} connectOpen={connectOpen} onConnect={() => setConnectOpen(true)} />;
// A connected wallet sees its Chronobox, or the setup, right here. Without a wallet: the welcome.
body = session ? (
<HomePage key={`${session.account}:${session.chainId}`} session={session} chain={chain} />
) : (
<StartPage session={null} chain={chain} connectOpen={connectOpen} onConnect={() => setConnectOpen(true)} />
);
} else if (route.page === "open") {
body = <OpenPage chainId={chain?.id} />;
} else if (route.page === "technical") {
body = <TechnicalPage />;
} else if (route.page === "privacy") {
Expand Down Expand Up @@ -251,8 +261,9 @@ export function App() {
<CreatePage
session={session}
chain={chain}
onDone={(c, safe) => {
location.hash = vaultHref(c, safe);
onDone={() => {
// The wallet's one Chronobox is its start page.
location.hash = "#/";
}}
/>
);
Expand Down Expand Up @@ -300,6 +311,16 @@ export function App() {
<p class="mono">
<AddressText address={session.account} full />
</p>
{/* Any Chronobox by its address: one watched as a guardian, one on another network, one handed over. */}
<a
class="wallet-menu-link"
href="#/open"
onClick={() => {
if (walletChip.current) walletChip.current.open = false;
}}
>
Open a Chronobox by its address
</a>
<Button small onClick={disconnect}>
Disconnect
</Button>
Expand Down
20 changes: 20 additions & 0 deletions src/dev-accounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* The test accounts of the dev server: anvil's own ten, and the index of the Safe that the
* test wallet acts as in its "safe" kind. Shared by the test wallet (dev-wallet.ts) and the dev bar.
* Never part of a production build.
*/
export const ANVIL_ACCOUNTS = [
"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
"0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
"0x90F79bf6EB2c4f870365E785982E1f101E93b906",
"0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65",
"0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc",
"0x976EA74026E726554dB657fA54763abd0C3a0aa9",
"0x14dC79964da2C08b23698B3D3cc7Ca32193d9955",
"0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f",
"0xa0Ee7A142d267C1f36714E4a8F75612F20a79720",
] as const;

/** The test wallet's Safe (kind "safe") is the Safe of the anvil account at this salt index. */
export const SAFE_INDEX = 900;
15 changes: 1 addition & 14 deletions src/dev-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import { selector } from "./lib/abi.ts";
import { createTx, ownerBatchTx, predictSafe } from "./lib/chronobox.ts";
import { ANVIL_ACCOUNTS, SAFE_INDEX } from "./dev-accounts.ts";

// The wallet can switch between local forks: a fork of another network on 127.0.0.1:8546 is a second network.
// The choice stays over a reload, as in a real wallet.
Expand Down Expand Up @@ -40,20 +41,6 @@ const QUERY = new URLSearchParams(location.search);
const KIND: "plain" | "batch" | "safe" = QUERY.get("wallet") === "safe" || QUERY.get("safe") === "1" ? "safe" : QUERY.get("wallet") === "batch" ? "batch" : "plain";
const SAFE_MODE = KIND === "safe";
const BATCHES = KIND !== "plain";
const SAFE_INDEX = 900;

const ANVIL_ACCOUNTS = [
"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
"0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
"0x90F79bf6EB2c4f870365E785982E1f101E93b906",
"0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65",
"0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc",
"0x976EA74026E726554dB657fA54763abd0C3a0aa9",
"0x14dC79964da2C08b23698B3D3cc7Ca32193d9955",
"0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f",
"0xa0Ee7A142d267C1f36714E4a8F75612F20a79720",
] as const;

const ICON =
"data:image/svg+xml," +
Expand Down
34 changes: 19 additions & 15 deletions src/lib/chronobox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ const ROLES_TOPIC = {
const GUARD_SLOT = keccak(utf8("guard_manager.guard.address"));
const FALLBACK_SLOT = keccak(utf8("fallback_manager.handler.address"));

/** Base salt. The nth vault of a wallet uses SALT_BASE + n. */
/**
* Base salt. A wallet has one Chronobox: the Safe made with this salt nonce (index 0). Index n uses
* SALT_BASE + n; other indexes are left from a time when a wallet could have several.
*/
const SALT_BASE = toBigInt(keccak(utf8("zodiac-timebox:v1")));

export const TOPIC_TRANSACTION_ADDED = topic("TransactionAdded(uint256,bytes32,address,uint256,bytes,uint8)");
Expand Down Expand Up @@ -139,15 +142,27 @@ export function safeInitializer(wallet: Address): Hex {
}

/**
* The address of the nth Chronobox of a wallet. It depends only on the wallet
* and the index, and it is the same on every chain. The app can find a
* wallet's vaults again without a server.
* The address of the nth Safe of a wallet made with the Chronobox salt. It depends only on the
* wallet and the index, and it is the same on every chain. The app uses index 0 only: see `chronoboxOf`.
*/
export function predictSafe(wallet: Address, index: number): Address {
const salt = keccak(concat(keccak(safeInitializer(wallet)), uintWord(SALT_BASE + BigInt(index))));
return create2(CONTRACTS.safeProxyFactory, salt, SAFE_PROXY_INIT_CODE_HASH);
}

/**
* The one Chronobox of a wallet: the same address on every chain, found without a server.
* A Safe made by the Safe proxy factory with CREATE2, from the 1 of 1 setup of the wallet and the salt nonce SALT_BASE.
*/
export function chronoboxOf(wallet: Address): Address {
return predictSafe(wallet, 0);
}

/** Does the Chronobox of this wallet exist on the connected chain? */
export async function chronoboxExists(rpc: Rpc, wallet: Address): Promise<boolean> {
return size(await getCode(rpc, chronoboxOf(wallet))) > 0;
}

export function delayInitializer(safe: Address, cooldown: bigint, expiration: bigint): Hex {
const params = encode(["address", "address", "address", "uint256", "uint256"], [safe, safe, safe, cooldown, expiration]);
return call("setUp(bytes)", [params]);
Expand Down Expand Up @@ -1218,17 +1233,6 @@ export async function isHalfMade(rpc: Rpc, safe: Address, wallet: Address): Prom
return owners.length === 1 && sameAddress(owners[0], wallet);
}

/** Finds the vaults of a wallet on the connected chain. Stops at the first unused index. */
export async function discover(rpc: Rpc, wallet: Address, limit = 100): Promise<{ index: number; safe: Address }[]> {
const found: { index: number; safe: Address }[] = [];
for (let index = 0; index < limit; index++) {
const safe = predictSafe(wallet, index);
if (size(await getCode(rpc, safe)) === 0) break;
found.push({ index, safe });
}
return found;
}

// ---------------------------------------------------------------------------
// Queue
// ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function vaultsOf(wallet: Address): SavedVault[] {
return savedVaults().filter((v) => {
const matches = v.wallet
? sameAddress(v.wallet, wallet)
: (mine ??= Array.from({ length: 20 }, (_, index) => predictSafe(wallet, index))).some((safe) => sameAddress(safe, v.safe));
: (mine ??= [predictSafe(wallet, 0)]).some((safe) => sameAddress(safe, v.safe));
if (!matches) return false;
const key = `${v.chainId}:${v.safe.toLowerCase()}`;
if (seen.has(key)) return false;
Expand Down
24 changes: 24 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -3881,3 +3881,27 @@ img.token-badge.token-icon {
color: var(--muted);
font-size: 0.9rem;
}

/* Above the setup: which wallet has no Chronobox yet */
.home-none {
width: 100%;
max-width: 560px;
margin: 24px auto 0;
padding: 0 20px;
}

/* In the wallet menu: open any Chronobox by its address */
.wallet-menu-link {
display: block;
margin: 4px 0 10px;
color: var(--blue-text);
font-size: 0.9rem;
}

/* The end of the landing page: the way in once more, and the way to any Chronobox */
.start-end {
display: grid;
justify-items: center;
gap: 14px;
padding-top: 8px;
}
30 changes: 17 additions & 13 deletions src/ui/create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import {
MAX_COOLDOWN,
MIN_COOLDOWN,
createTx,
discover,
chronoboxExists,
chronoboxOf,
inspect,
isHalfMade,
lockTx,
nativeBalance,
predictRoles,
predictSafe,
safeFromReceipt,
sendAndWait,
setupCalls,
Expand Down Expand Up @@ -60,7 +60,8 @@ const PRESETS: { label: string; seconds: bigint }[] = [
*/
const RECEIVER: Address | null = CONTRIBUTION_RECEIVER ?? (__DEV__ ? "0x000000000000000000000000000000000000c0de" : null);

type Plan = { index: number; safe: Address; created: boolean };
/** `done`: the wallet's Chronobox is set up already. The setup has nothing to make, and the page goes to it. */
type Plan = { index: number; safe: Address; created: boolean; done?: boolean };
type StepId = "network" | "delay" | "promises" | "fund" | "review";
/**
* Where the setup stands: the id of a row on the working screen ("sign:3",
Expand Down Expand Up @@ -164,12 +165,11 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
* that a step which has landed is never sent again.
*/
const findPlan = async (): Promise<Plan> => {
const found = await discover(session.rpc, session.account);
// A Chronobox whose setup stopped after the first step comes first.
for (const vault of found) {
if (await isHalfMade(session.rpc, vault.safe, session.account)) return { index: vault.index, safe: vault.safe, created: true };
}
return { index: found.length, safe: predictSafe(session.account, found.length), created: false };
// A wallet has one Chronobox, at one address. It is not made yet, it stopped after its first step, or it is there.
const safe = chronoboxOf(session.account);
if (!(await chronoboxExists(session.rpc, session.account))) return { index: 0, safe, created: false };
if (await isHalfMade(session.rpc, safe, session.account)) return { index: 0, safe, created: true };
return { index: 0, safe, created: true, done: true };
};

useEffect(() => {
Expand All @@ -178,7 +178,12 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
setPlan(null);
setLoadError(null);
findPlan().then(
(next) => !stale && setPlan(next),
(next) => {
if (stale) return;
// The one Chronobox of this wallet is there already: there is nothing to set up.
if (next.done && !running.current) location.hash = "#/";
else setPlan(next);
},
(e) => !stale && setLoadError(errorText(e)),
);
return () => {
Expand Down Expand Up @@ -956,9 +961,8 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
Back
</button>
) : (
<a class="wiz-back" href="#/">
Close
</a>
// The setup is the start page of a wallet without a Chronobox: there is nothing to close it to.
<span class="wiz-back" aria-hidden="true" />
)}
<ol class="wiz-dots" aria-label={`Step ${step + 1} of ${steps.length}`}>
{steps.map((id, i) => (
Expand Down
67 changes: 64 additions & 3 deletions src/ui/devbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,49 @@
* the test wallet reads when the page loads. So a change loads the page again.
*/
import "../devbar.css";
import { useEffect, useState } from "preact/hooks";
import { chainById } from "../lib/chains.ts";
import { type Rpc, chronoboxOf, inspect, predictSafe, queueLength, readBalances } from "../lib/chronobox.ts";
import { shortAmount } from "../lib/format.ts";
import type { Address } from "../lib/hex.ts";

import { ANVIL_ACCOUNTS, SAFE_INDEX } from "../dev-accounts.ts";
import { assetsOf } from "./common.tsx";

/** The local fork, asked directly: the dev bar must not wait for, or disturb, the test wallet. */
const fork: Rpc = async (method, params = []) => {
const res = await fetch("http://127.0.0.1:8545", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
const out = (await res.json()) as { result?: unknown; error?: { message: string } };
if (out.error) throw new Error(out.error.message);
return out.result;
};

/**
* What an account's Chronobox is like on the fork, in a few words: none, a setup that stopped,
* empty, or what is locked in it, and how many withdrawals wait.
*/
async function stateOf(wallet: Address): Promise<string> {
const safe = chronoboxOf(wallet);
const code = (await fork("eth_getCode", [safe, "latest"])) as string;
if (!code || code === "0x") return "no Chronobox";
const inspection = await inspect(fork, safe);
if (inspection.state === "open") return "setup not finished";
if (inspection.state === "invalid" || inspection.state === "missing") return "Chronobox, needs a look";
const chain = chainById(1);
const assets = chain ? assetsOf(chain).filter((a) => a.main) : [];
const { balances } = await readBalances(fork, safe, assets);
const held = assets.map((a, i) => ({ a, b: balances[i] ?? 0n })).filter((h) => h.b > 0n);
const locked = held.length === 0 ? "empty" : `${held.map((h) => `${shortAmount(h.b, h.a.decimals, 2)} ${h.a.symbol}`).join(", ")} locked`;
const waiting = queueLength(inspection);
return `Chronobox, ${locked}${waiting > 0n ? `, ${waiting} waiting` : ""}`;
}

/** The address the test wallet acts as, for a choice in the list and the kind of wallet. */
function walletOf(choice: string, kind: string): Address | null {
const owner = choice.startsWith("0x") ? (choice as Address) : (ANVIL_ACCOUNTS[Number(choice)] as Address | undefined);
if (!owner) return null;
return kind === "safe" ? predictSafe(owner, SAFE_INDEX) : owner;
}

const KINDS = [
{ id: "plain", label: "Plain", hint: "An account without batching: one confirmation per step" },
Expand All @@ -36,6 +79,24 @@ export function DevBar() {
const params = new URLSearchParams(location.search);
const kind = params.get("wallet") ?? (params.get("safe") === "1" ? "safe" : "plain");
const account = params.get("as") ?? params.get("account") ?? "0";
// The state of every account's Chronobox, read from the fork when the bar opens.
const choices = [...ANVIL_ACCOUNTS.map((_, i) => String(i)), ...REAL.map((r) => r.address)];
const [states, setStates] = useState<Record<string, string>>({});
useEffect(() => {
let stale = false;
for (const choice of choices) {
const wallet = walletOf(choice, kind);
if (!wallet) continue;
stateOf(wallet).then(
(text) => !stale && setStates((all) => ({ ...all, [choice]: text })),
() => !stale && setStates((all) => ({ ...all, [choice]: "could not read" })),
);
}
return () => {
stale = true;
};
}, [kind]);
const named = (choice: string, base: string) => `${base} · ${states[choice] ?? "…"}`;
const go = (change: (next: URLSearchParams) => void) => {
const next = new URLSearchParams(location.search);
next.delete("safe");
Expand Down Expand Up @@ -69,16 +130,16 @@ export function DevBar() {
}}
>
<optgroup label="Anvil, test ETH only">
{Array.from({ length: 10 }, (_, i) => (
{ANVIL_ACCOUNTS.map((_, i) => (
<option value={String(i)} key={i}>
{i}
{named(String(i), kind === "safe" ? `Safe of ${i}` : String(i))}
</option>
))}
</optgroup>
<optgroup label="Real mainnet account, on the fork">
{REAL.map((r) => (
<option value={r.address} key={r.address}>
{r.label}
{named(r.address, kind === "safe" ? `Safe of ${r.label}` : r.label)}
</option>
))}
{account.startsWith("0x") && !REAL.some((r) => r.address === account) ? <option value={account}>{`${account.slice(0, 6)}…${account.slice(-4)}`}</option> : null}
Expand Down
Loading
Loading