Skip to content
Merged
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
21 changes: 20 additions & 1 deletion src/lib/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,11 @@ export async function sendBatch(
onWaiting?: () => void,
shouldStop?: () => boolean,
): Promise<{ blockNumber: bigint | null }> {
return waitForBatch(provider, await sendCalls(provider, account, chainId, calls), onWaiting, shouldStop);
}

/** Gives the calls to the wallet as one atomic batch. Returns the id of the batch. */
export async function sendCalls(provider: Provider, account: Address, chainId: number, calls: TxRequest[]): Promise<string> {
// A call that only sends ETH has no data. Wallets reject "0x" there, so the field is left out.
const list = calls.map((c) => ({ to: c.to, ...(c.data === "0x" ? {} : { data: c.data }), value: toQuantity(c.value ?? 0n) }));
const base = { from: account, chainId: toQuantity(chainId), calls: list };
Expand All @@ -272,6 +277,20 @@ export async function sendBatch(
}
const id = typeof result === "string" ? result : (result as { id?: string })?.id;
if (!id) throw new Error("Your wallet did not confirm that it took the request. Look in your wallet before you try again.");
return id;
}

/**
* Waits until the batch with this id is on chain. A batch that the wallet still
* holds is waited for again, not sent again: some wallets (Ambire) put a second
* request into the same transaction as the first.
*/
export async function waitForBatch(
provider: Provider,
id: string,
onWaiting?: () => void,
shouldStop?: () => boolean,
): Promise<{ blockNumber: bigint | null }> {
onWaiting?.();
const rpc = rpcOf(provider);
let misses = 0;
Expand Down Expand Up @@ -327,7 +346,7 @@ const REASONS: [RegExp, string][] = [
[/GS013/, "The Chronobox refused this step. Reload the page and look at its state before you try again."],
[/GS02[0-9]|GS03[0-9]/, "Your wallet is not allowed to do this with this Chronobox."],
[/not authorized|NotAuthorized|NoMembership|ConditionViolation/i, "Your wallet is not allowed to do this with this Chronobox."],
[/create2 call failed/i, "This Chronobox exists already. Reload the page."],
[/create2 call failed/i, "This Chronobox exists already, or your wallet has the setup twice in one request. Reject the request in your wallet, reload the page and start again."],
];

/** A short, plain message for an error that came from a wallet or an RPC. */
Expand Down
30 changes: 26 additions & 4 deletions src/ui/create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
slowAfterMs,
tokenBalance,
} from "../lib/chronobox.ts";
import { assertWallet, canBatch, errorText, isRejection, isTemporary, sendBatch, signTyped } from "../lib/wallet.ts";
import { assertWallet, canBatch, errorText, isRejection, isTemporary, sendCalls, signTyped, waitForBatch } from "../lib/wallet.ts";
import { AddressText, type Asset, assetsOf, Button, Choice, Notice, type Session, Tick, useBalancesState } from "./common.tsx";
import { DepositPanel } from "./deposit.tsx";
import { FundList } from "./fund.tsx";
Expand Down Expand Up @@ -134,6 +134,8 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
const [slow, setSlow] = useState(false);
const stop = useRef(false);
const running = useRef(false);
// The setup batch that the wallet may still hold after "Stop waiting". The next press waits for it again.
const pending = useRef<{ id: string; chainId: number; wallet: Address; safe: Address } | null>(null);

useEffect(() => {
let stale = false;
Expand Down Expand Up @@ -381,6 +383,8 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
let target = plan.safe;
// True from the moment a request goes to the wallet. After that, the chain says what happened, not an error.
let asked = false;
// True when this press waited for a request sent by an earlier press.
let resumed = false;
try {
let now = await findPlan();
setPlan(now);
Expand All @@ -395,7 +399,16 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
const stayed: Line[] = [];
let later: Chosen[] = [];

if (batch) {
const last = pending.current;
if (last && !(last.chainId === chain.id && sameAddress(last.wallet, session.account) && sameAddress(last.safe, now.safe) && !now.created)) pending.current = null;
if (batch && pending.current) {
// The wallet still has the first request. A second one could end up in the same transaction and make it fail.
asked = true;
await waitForBatch(session.wallet.provider, pending.current.id, () => setProgress("waiting"), () => stop.current);
pending.current = null;
// The amounts of that first request may differ from the ones chosen now.
resumed = true;
} else if (batch) {
const held = await nativeBalance(session.rpc, session.account);
// A contribution that nothing can pay is left out. It never stops the setup.
const parts = splitContribution(money.map((d) => toPick(d, true)), confirmedGive, held, 0n) ?? splitContribution(money.map((d) => toPick(d, true)), null, held, 0n)!;
Expand All @@ -411,7 +424,10 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
inside = money.map((d, i) => line(d, parts.stays[i]));
if (parts.from !== "none") gave = giveText;
asked = true;
await sendBatch(session.wallet.provider, session.account, chain.id, calls, () => setProgress("waiting"), () => stop.current);
const id = await sendCalls(session.wallet.provider, session.account, chain.id, calls);
pending.current = { id, chainId: chain.id, wallet: session.account, safe: now.safe };
await waitForBatch(session.wallet.provider, id, () => setProgress("waiting"), () => stop.current);
pending.current = null;
} else {
if (!now.created) {
setProgress("create");
Expand Down Expand Up @@ -503,8 +519,11 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
open = false;
}
}
if (resumed) return finish(target, state, null, [], money.length > 0);
return finish(target, state, inside, stayed);
} catch (e) {
// Only "Stop waiting" leaves the request with the wallet. After any other end, the next press may send again.
if (!stop.current) pending.current = null;
if (asked && !isRejection(e)) {
// Something may have reached the chain all the same. Look before saying that it failed.
setProgress("check");
Expand Down Expand Up @@ -650,7 +669,10 @@ export function CreatePage(props: { session: Session; chain: Chain | undefined;
>
Stop waiting
</button>
<p class="wiz-note">That does not undo anything. This page then looks at the chain and shows where your setup stands.</p>
<p class="wiz-note">
That does not undo anything. This page then looks at the chain and shows where your setup stands. If you try again, the page waits for the
same request in your wallet. It does not send a second one.
</p>
</div>
) : null}
</Screen>
Expand Down
13 changes: 12 additions & 1 deletion test/wallet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { test } from "node:test";
import { parseUnits, plainNumber } from "../src/lib/format.ts";
import { Replaced, StoppedWaiting, changeWalletTx, sendAndWait } from "../src/lib/chronobox.ts";
import { CHAINS, CONTRACTS } from "../src/lib/chains.ts";
import { BatchUnknown, type Provider, RpcTimeout, WalletMoved, assertWallet, errorText, isRejection, isTemporary, rpcOf, sendBatch, switchChain } from "../src/lib/wallet.ts";
import { BatchUnknown, type Provider, RpcTimeout, WalletMoved, assertWallet, errorText, isRejection, isTemporary, rpcOf, sendBatch, switchChain, waitForBatch } from "../src/lib/wallet.ts";

const A = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8";
const B = "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC";
Expand Down Expand Up @@ -197,6 +197,17 @@ test("a batch is not sent twice, and an unknown outcome is not called a failure"
assert.equal(sent.atomicRequired, true);
});

test("a batch the wallet still holds is waited for, not sent again", async () => {
const wallet = provider({
wallet_sendCalls: () => ({ id: "0xfirst" }),
wallet_getCallsStatus: ([id]) => (id === "0xfirst" ? { status: 200, receipts: [{ blockNumber: "0x2", status: "0x1" }] } : null),
});
assert.deepEqual(await waitForBatch(wallet, "0xfirst"), { blockNumber: 2n });
assert.equal(wallet.calls.filter((m) => m === "wallet_sendCalls").length, 0);
// "Stop waiting" leaves the batch with the wallet.
await assert.rejects(waitForBatch(provider({ wallet_getCallsStatus: () => ({ status: 100 }) }), "0xfirst", undefined, () => true), BatchUnknown);
});

test("errors reach the person in plain words", () => {
const plain = (code: number | undefined, message: string) => errorText(code === undefined ? new Error(message) : rpcError(code, message));
assert.match(plain(4001, "MetaMask Tx Signature: User denied transaction signature."), /You rejected/);
Expand Down
Loading