@mortiseagentvault/sdk 0.1.0 → 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/README.md +58 -4
- package/dist/THIRD_PARTY_NOTICES.txt +79 -0
- package/dist/abis.d.ts +3438 -0
- package/dist/actions.d.ts +255 -0
- package/dist/addresses.d.ts +21 -0
- package/dist/calls.d.ts +18 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4662 -10
- package/dist/modules.d.ts +14 -1
- package/dist/x402.d.ts +68 -0
- package/package.json +24 -7
- package/dist/abis.js +0 -28
- package/dist/actions.js +0 -159
- package/dist/addresses.js +0 -47
- package/dist/agent.js +0 -115
- package/dist/calls.js +0 -96
- package/dist/errors.js +0 -52
- package/dist/modules.js +0 -15
- package/dist/root.js +0 -104
- package/dist/userop.js +0 -425
- package/dist/vault.js +0 -117
package/dist/userop.js
DELETED
|
@@ -1,425 +0,0 @@
|
|
|
1
|
-
import { concat, decodeAbiParameters, decodeEventLog, decodeFunctionData, encodeAbiParameters, encodeFunctionData, numberToHex, pad, toHex, zeroAddress, } from "viem";
|
|
2
|
-
import { accountAbi, entryPointAbi, factoryAbi, safe7579Abi } from "./abis.js";
|
|
3
|
-
import { external, mortise } from "./addresses.js";
|
|
4
|
-
import { decodeMortiseError, revertData } from "./errors.js";
|
|
5
|
-
import { encodePasskeySignature, encodeRoot, encodeRootSignature } from "./root.js";
|
|
6
|
-
export const MODULE_TYPE = { validator: 1n, executor: 2n, fallback: 3n, hook: 4n };
|
|
7
|
-
/** ERC-7579 batch mode: call type 0x01, default exec type, no selector or payload. */
|
|
8
|
-
const BATCH_MODE = pad("0x01", { dir: "right", size: 32 });
|
|
9
|
-
/** The callData of a root userOp. */
|
|
10
|
-
const executionComponents = [
|
|
11
|
-
{ name: "target", type: "address" },
|
|
12
|
-
{ name: "value", type: "uint256" },
|
|
13
|
-
{ name: "callData", type: "bytes" },
|
|
14
|
-
];
|
|
15
|
-
export function encodeRootCall(c) {
|
|
16
|
-
if (c.kind === "execute") {
|
|
17
|
-
if (c.calls.length === 0)
|
|
18
|
-
throw new Error("nothing to execute");
|
|
19
|
-
const executions = encodeAbiParameters([{ type: "tuple[]", components: executionComponents }], [c.calls.map((x) => ({ target: x.to, value: x.value ?? 0n, callData: x.data ?? "0x" }))]);
|
|
20
|
-
return encodeFunctionData({ abi: accountAbi, functionName: "execute", args: [BATCH_MODE, executions] });
|
|
21
|
-
}
|
|
22
|
-
if (c.kind === "installModule") {
|
|
23
|
-
return encodeFunctionData({ abi: accountAbi, functionName: "installModule", args: [c.moduleType, c.module, c.initData] });
|
|
24
|
-
}
|
|
25
|
-
// Removing the root validator would lock the vault for good: the Safe's own owner is sealed.
|
|
26
|
-
if (c.moduleType === MODULE_TYPE.validator && c.module.toLowerCase() === mortise.rootValidator.toLowerCase()) {
|
|
27
|
-
throw new Error("refusing to remove the root validator: the vault would have no way in");
|
|
28
|
-
}
|
|
29
|
-
return encodeFunctionData({ abi: accountAbi, functionName: "uninstallModule", args: [c.moduleType, c.module, c.deInitData] });
|
|
30
|
-
}
|
|
31
|
-
const u128 = (v) => pad(toHex(v), { size: 16 });
|
|
32
|
-
export function packUserOp(op) {
|
|
33
|
-
return {
|
|
34
|
-
sender: op.sender,
|
|
35
|
-
nonce: op.nonce,
|
|
36
|
-
initCode: op.factory ? concat([op.factory, op.factoryData ?? "0x"]) : "0x",
|
|
37
|
-
callData: op.callData,
|
|
38
|
-
accountGasLimits: concat([u128(op.verificationGasLimit), u128(op.callGasLimit)]),
|
|
39
|
-
preVerificationGas: op.preVerificationGas,
|
|
40
|
-
gasFees: concat([u128(op.maxPriorityFeePerGas), u128(op.maxFeePerGas)]),
|
|
41
|
-
paymasterAndData: op.paymaster
|
|
42
|
-
? concat([
|
|
43
|
-
op.paymaster,
|
|
44
|
-
u128(op.paymasterVerificationGasLimit ?? 0n),
|
|
45
|
-
u128(op.paymasterPostOpGasLimit ?? 0n),
|
|
46
|
-
op.paymasterData ?? "0x",
|
|
47
|
-
])
|
|
48
|
-
: "0x",
|
|
49
|
-
signature: op.signature,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
/** The nonce of the vault's next root userOp: Safe7579 picks the validator from the nonce key. */
|
|
53
|
-
export async function rootNonce(client, vault) {
|
|
54
|
-
return client.readContract({
|
|
55
|
-
address: external.safe7579,
|
|
56
|
-
abi: safe7579Abi,
|
|
57
|
-
functionName: "getNonce",
|
|
58
|
-
args: [vault, mortise.rootValidator],
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
export async function userOpHash(client, op) {
|
|
62
|
-
return client.readContract({
|
|
63
|
-
address: external.entryPoint,
|
|
64
|
-
abi: entryPointAbi,
|
|
65
|
-
functionName: "getUserOpHash",
|
|
66
|
-
args: [packUserOp(op)],
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Runs the root call as the EntryPoint would, without a signature, and returns the gas it used. A revert here
|
|
71
|
-
* (for instance the timelock's NotScheduled) would also revert inside the userOp.
|
|
72
|
-
*/
|
|
73
|
-
export async function simulateRootCall(client, vault, callData) {
|
|
74
|
-
try {
|
|
75
|
-
await client.call({ account: external.entryPoint, to: vault, data: callData });
|
|
76
|
-
}
|
|
77
|
-
catch (err) {
|
|
78
|
-
throw await explainRootFailure(client, vault, callData, err);
|
|
79
|
-
}
|
|
80
|
-
return client.estimateGas({ account: external.entryPoint, to: vault, data: callData });
|
|
81
|
-
}
|
|
82
|
-
/** A root call that failed, with the reason Safe7579 hid behind ExecutionFailed when it can be recovered. */
|
|
83
|
-
export class RootCallError extends Error {
|
|
84
|
-
/** Where the failure came from: the vault's hook (such as the timelock), one call of the batch, or a module's install. */
|
|
85
|
-
source;
|
|
86
|
-
/** Index of the failing call in the batch, when source is "call". */
|
|
87
|
-
callIndex;
|
|
88
|
-
/** The revert data that carries the reason; decode it with decodeMortiseError. */
|
|
89
|
-
data;
|
|
90
|
-
constructor(message, source, data, cause, callIndex) {
|
|
91
|
-
super(message, { cause });
|
|
92
|
-
this.name = "RootCallError";
|
|
93
|
-
this.source = source;
|
|
94
|
-
this.data = data;
|
|
95
|
-
this.callIndex = callIndex;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Safe7579 runs the hook and every batch through Safe module calls and reverts with a bare ExecutionFailed, which
|
|
100
|
-
* drops the reason. This replays the hook's preCheck, then the batch call by call, as the vault, to find it.
|
|
101
|
-
*/
|
|
102
|
-
async function explainRootFailure(client, vault, callData, err) {
|
|
103
|
-
const data = revertData(err);
|
|
104
|
-
if (!data || decodeMortiseError(data)?.name !== "ExecutionFailed") {
|
|
105
|
-
return new RootCallError(`root call failed: ${describe(data)}`, "account", data, err);
|
|
106
|
-
}
|
|
107
|
-
const hook = await client.readContract({ address: vault, abi: safe7579Abi, functionName: "getActiveHook" });
|
|
108
|
-
if (hook !== zeroAddress) {
|
|
109
|
-
try {
|
|
110
|
-
// Safe7579 passes the account call with the EntryPoint appended as the sender.
|
|
111
|
-
const preCheck = encodeFunctionData({ abi: hookAbi, functionName: "preCheck", args: [external.entryPoint, 0n, concat([callData, external.entryPoint])] });
|
|
112
|
-
await client.call({ account: vault, to: hook, data: preCheck });
|
|
113
|
-
}
|
|
114
|
-
catch (hookErr) {
|
|
115
|
-
const hookData = revertData(hookErr);
|
|
116
|
-
return new RootCallError(`the vault's hook ${hook} refused the call: ${describe(hookData)}`, "hook", hookData, err);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
const decoded = decodeFunctionData({ abi: accountAbi, data: callData });
|
|
120
|
-
if (decoded.functionName === "installModule") {
|
|
121
|
-
// The data Safe7579 hands to onInstall for each module type; other types (such as multi-type installs)
|
|
122
|
-
// are not replayed, so a revert is never pinned on the wrong cause.
|
|
123
|
-
const [moduleType, module, initData] = decoded.args;
|
|
124
|
-
let moduleInitData;
|
|
125
|
-
if (moduleType === MODULE_TYPE.validator || moduleType === MODULE_TYPE.executor || moduleType === MODULE_TYPE.hook)
|
|
126
|
-
moduleInitData = initData;
|
|
127
|
-
else if (moduleType === MODULE_TYPE.fallback)
|
|
128
|
-
moduleInitData = decodeAbiParameters([{ type: "bytes4" }, { type: "bytes1" }, { type: "bytes" }], initData)[2];
|
|
129
|
-
else if (moduleType === 8n || moduleType === 9n)
|
|
130
|
-
moduleInitData = decodeAbiParameters([{ type: "uint256" }, { type: "bytes" }], initData)[1];
|
|
131
|
-
if (moduleInitData !== undefined) {
|
|
132
|
-
try {
|
|
133
|
-
await client.call({ account: vault, to: module, data: encodeFunctionData({ abi: moduleAbi, functionName: "onInstall", args: [moduleInitData] }) });
|
|
134
|
-
}
|
|
135
|
-
catch (installErr) {
|
|
136
|
-
const installData = revertData(installErr);
|
|
137
|
-
return new RootCallError(`${module} refused to install: ${describe(installData)}`, "install", installData, err);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
if (decoded.functionName === "execute") {
|
|
142
|
-
const [executions] = decodeAbiParameters([{ type: "tuple[]", components: executionComponents }], decoded.args[1]);
|
|
143
|
-
try {
|
|
144
|
-
const [block] = await client.simulateBlocks({
|
|
145
|
-
blocks: [{ calls: executions.map((e) => ({ account: vault, to: e.target, value: e.value, data: e.callData })) }],
|
|
146
|
-
});
|
|
147
|
-
const i = block?.calls.findIndex((c) => c.status === "failure") ?? -1;
|
|
148
|
-
if (i >= 0) {
|
|
149
|
-
const failed = block.calls[i];
|
|
150
|
-
const callErr = failed.error;
|
|
151
|
-
const callData_ = revertData(callErr) ?? (failed.data !== "0x" ? failed.data : undefined);
|
|
152
|
-
return new RootCallError(`call ${i} to ${executions[i].target} failed: ${describe(callData_)}`, "call", callData_, err, i);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
// The RPC may not support eth_simulateV1; the plain ExecutionFailed is all there is.
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
return new RootCallError("root call failed: ExecutionFailed (no reason recovered)", "account", data, err);
|
|
160
|
-
}
|
|
161
|
-
function describe(data) {
|
|
162
|
-
if (!data)
|
|
163
|
-
return "no revert data";
|
|
164
|
-
const d = decodeMortiseError(data);
|
|
165
|
-
if (!d)
|
|
166
|
-
return `unknown error ${data.slice(0, 10)}`;
|
|
167
|
-
return d.args.length ? `${d.name}(${d.args.map(String).join(", ")})` : d.name;
|
|
168
|
-
}
|
|
169
|
-
const moduleAbi = [
|
|
170
|
-
{ type: "function", name: "onInstall", inputs: [{ type: "bytes" }], outputs: [], stateMutability: "nonpayable" },
|
|
171
|
-
];
|
|
172
|
-
const hookAbi = [
|
|
173
|
-
{
|
|
174
|
-
type: "function",
|
|
175
|
-
name: "preCheck",
|
|
176
|
-
inputs: [{ type: "address" }, { type: "uint256" }, { type: "bytes" }],
|
|
177
|
-
outputs: [{ type: "bytes" }],
|
|
178
|
-
stateMutability: "nonpayable",
|
|
179
|
-
},
|
|
180
|
-
];
|
|
181
|
-
/** An ECDSA member signs the EIP-191 hash of the userOp hash. */
|
|
182
|
-
export function ecdsaRootSigner(index, account) {
|
|
183
|
-
return { index, sign: (hash) => account.signMessage({ message: { raw: hash } }) };
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Builds and signs a root userOp. The call is simulated first; the signatures cover every field, including gas
|
|
187
|
-
* and paymaster, so nothing is changed after signing.
|
|
188
|
-
*/
|
|
189
|
-
export async function buildRootOp(client, vault, call, o) {
|
|
190
|
-
const callData = encodeRootCall(call);
|
|
191
|
-
const exists = (await client.getCode({ address: vault }))?.length ? true : false;
|
|
192
|
-
let factory;
|
|
193
|
-
let factoryData;
|
|
194
|
-
if (!exists) {
|
|
195
|
-
if (!o.create)
|
|
196
|
-
throw new Error(`vault ${vault} does not exist; pass create to deploy it in this userOp`);
|
|
197
|
-
factory = mortise.factory;
|
|
198
|
-
factoryData = encodeFunctionData({ abi: factoryAbi, functionName: "createVault", args: [encodeRoot(o.root), o.create.salt] });
|
|
199
|
-
}
|
|
200
|
-
// Without code at the vault the call cannot be simulated, so a first userOp gets a fixed call gas limit.
|
|
201
|
-
const callGas = o.gas?.callGasLimit ?? (exists ? ((await simulateRootCall(client, vault, callData)) * 13n) / 10n + 50000n : 3000000n);
|
|
202
|
-
const block = await client.getBlock();
|
|
203
|
-
const base = block.baseFeePerGas ?? (await client.getGasPrice());
|
|
204
|
-
const op = {
|
|
205
|
-
sender: vault,
|
|
206
|
-
nonce: await rootNonce(client, vault),
|
|
207
|
-
factory,
|
|
208
|
-
factoryData,
|
|
209
|
-
callData,
|
|
210
|
-
callGasLimit: callGas,
|
|
211
|
-
verificationGasLimit: o.gas?.verificationGasLimit ?? (exists ? 800000n : 2500000n),
|
|
212
|
-
preVerificationGas: o.gas?.preVerificationGas ?? 100000n,
|
|
213
|
-
maxFeePerGas: o.gas?.maxFeePerGas ?? base * 2n + (o.gas?.maxPriorityFeePerGas ?? 0n),
|
|
214
|
-
maxPriorityFeePerGas: o.gas?.maxPriorityFeePerGas ?? 0n,
|
|
215
|
-
signature: "0x",
|
|
216
|
-
};
|
|
217
|
-
// The sponsor's fields go in before the bundler estimates, as their bytes and checks cost gas too; then the
|
|
218
|
-
// sponsor is asked again for fields over the final gas values (as ERC-7677's stub and final data).
|
|
219
|
-
if (o.paymaster && o.bundlerUrl)
|
|
220
|
-
Object.assign(op, await o.paymaster(op, { stub: true }));
|
|
221
|
-
if (o.bundlerUrl)
|
|
222
|
-
await applyBundlerGas(o.bundlerUrl, op, o.root, o.gas, o.signers.map((sg) => sg.index));
|
|
223
|
-
// The final fields are kept as returned: a verifying paymaster signs its own gas limits, so changing them
|
|
224
|
-
// here would break its signature. The bundler's estimates are already in the op it receives.
|
|
225
|
-
if (o.paymaster)
|
|
226
|
-
Object.assign(op, await o.paymaster(op, { stub: false }));
|
|
227
|
-
const hash = await userOpHash(client, op);
|
|
228
|
-
const sigs = await Promise.all(o.signers.map(async (s) => ({ index: s.index, signature: await s.sign(hash) })));
|
|
229
|
-
op.signature = encodeRootSignature(o.root, sigs);
|
|
230
|
-
return op;
|
|
231
|
-
}
|
|
232
|
-
/** A signature of the right shape that fails validation without reverting, for gas estimation only. */
|
|
233
|
-
/**
|
|
234
|
-
* A signature of the right shape for gas estimation, for the members that will sign (by index; the first
|
|
235
|
-
* `threshold` members when not given), so the estimate runs the same validation path as the real one.
|
|
236
|
-
*/
|
|
237
|
-
export function dummyRootSignature(root, signerIndices) {
|
|
238
|
-
const ecdsa = concat([pad("0xff", { size: 32 }), pad("0xff", { size: 32 }), "0x1b"]);
|
|
239
|
-
const passkey = encodePasskeySignature({
|
|
240
|
-
authenticatorData: pad("0x", { size: 37 }),
|
|
241
|
-
clientDataJSON: `{"type":"webauthn.get","challenge":"${"A".repeat(43)}","origin":"https://mortiseagentvault.xyz"}`,
|
|
242
|
-
r: 1n,
|
|
243
|
-
s: 1n,
|
|
244
|
-
});
|
|
245
|
-
const sigs = signingIndices(root, signerIndices).map((index) => ({ index, signature: root.members[index].type === "ecdsa" ? ecdsa : passkey }));
|
|
246
|
-
return encodeRootSignature(root, sigs);
|
|
247
|
-
}
|
|
248
|
-
function signingIndices(root, signerIndices) {
|
|
249
|
-
const all = signerIndices?.length ? [...new Set(signerIndices)].sort((a, b) => a - b) : root.members.map((_, i) => i);
|
|
250
|
-
return all.slice(0, root.threshold).filter((i) => i >= 0 && i < root.members.length);
|
|
251
|
-
}
|
|
252
|
-
async function applyBundlerGas(url, op, root, fixed, signerIndices) {
|
|
253
|
-
const est = await bundlerRpc(url, "eth_estimateUserOperationGas", [
|
|
254
|
-
// Rundler returns any limit the request already carries unchanged; 0 means "estimate it". So the limits
|
|
255
|
-
// go out as 0 unless the caller fixed them.
|
|
256
|
-
rpcUserOp({
|
|
257
|
-
...op,
|
|
258
|
-
signature: dummyRootSignature(root, signerIndices),
|
|
259
|
-
verificationGasLimit: fixed?.verificationGasLimit ?? 0n,
|
|
260
|
-
callGasLimit: fixed?.callGasLimit ?? 0n,
|
|
261
|
-
preVerificationGas: fixed?.preVerificationGas ?? 0n,
|
|
262
|
-
}),
|
|
263
|
-
external.entryPoint,
|
|
264
|
-
]);
|
|
265
|
-
const max = (a, b) => (a > b ? a : b);
|
|
266
|
-
// Paid in full, not metered: the estimate plus a margin for a price move before the op is sent.
|
|
267
|
-
if (fixed?.preVerificationGas === undefined)
|
|
268
|
-
op.preVerificationGas = (BigInt(est.preVerificationGas) * 12n) / 10n;
|
|
269
|
-
// A bundler rejects limits far above what the op uses (Rundler: under 40% of the verification limit used, as
|
|
270
|
-
// seen on Robinhood Chain), so the limits come from its estimate, not from fixed defaults. The estimate runs
|
|
271
|
-
// with the dummy signature, which costs less than the real one: measured on a mainnet fork, a real first
|
|
272
|
-
// member costs about 0.7k more (ECDSA) or 9.4k more (passkey), and the validator stops at the dummy's first
|
|
273
|
-
// member, so each further one adds about 8k (ECDSA) or 25k (passkey). The allowance covers that with room.
|
|
274
|
-
// The estimate also runs with fees at zero, so a vault that pays its own gas spends more than estimated on
|
|
275
|
-
// the prefund (about 46k more, seen between a vault's first and later userOps): 25k on top of Rundler's 30k.
|
|
276
|
-
const signing = signingIndices(root, signerIndices).map((i) => root.members[i]);
|
|
277
|
-
const allowance = signing.reduce((g, m, i) => g + (m.type === "ecdsa" ? (i === 0 ? 5000n : 15000n) : i === 0 ? 20000n : 40000n), 0n) + (op.paymaster ? 0n : 25000n);
|
|
278
|
-
if (fixed?.verificationGasLimit === undefined)
|
|
279
|
-
op.verificationGasLimit = (BigInt(est.verificationGasLimit) * 11n) / 10n + allowance;
|
|
280
|
-
if (fixed?.callGasLimit === undefined)
|
|
281
|
-
op.callGasLimit = (BigInt(est.callGasLimit) * 11n) / 10n;
|
|
282
|
-
// ERC-7677's final paymaster data carries no gas limits, so the bundler's estimates are kept here.
|
|
283
|
-
if (op.paymaster) {
|
|
284
|
-
if (est.paymasterVerificationGasLimit)
|
|
285
|
-
op.paymasterVerificationGasLimit = max(op.paymasterVerificationGasLimit ?? 0n, (BigInt(est.paymasterVerificationGasLimit) * 13n) / 10n);
|
|
286
|
-
if (est.paymasterPostOpGasLimit)
|
|
287
|
-
op.paymasterPostOpGasLimit = max(op.paymasterPostOpGasLimit ?? 0n, BigInt(est.paymasterPostOpGasLimit));
|
|
288
|
-
}
|
|
289
|
-
try {
|
|
290
|
-
// A little over the bundler's minimum, in case it moves between this call and the send.
|
|
291
|
-
const tip = (BigInt(await bundlerRpc(url, "rundler_maxPriorityFeePerGas", [])) * 105n) / 100n + 1n;
|
|
292
|
-
if (tip > op.maxPriorityFeePerGas) {
|
|
293
|
-
op.maxFeePerGas += tip - op.maxPriorityFeePerGas;
|
|
294
|
-
op.maxPriorityFeePerGas = tip;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
catch {
|
|
298
|
-
// A bundler without this method takes the fees as they are.
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
function readResult(logs, hash, tx) {
|
|
302
|
-
let result;
|
|
303
|
-
let revertReason;
|
|
304
|
-
for (const log of logs) {
|
|
305
|
-
if (log.address.toLowerCase() !== external.entryPoint.toLowerCase())
|
|
306
|
-
continue;
|
|
307
|
-
try {
|
|
308
|
-
const ev = decodeEventLog({ abi: entryPointAbi, data: log.data, topics: log.topics });
|
|
309
|
-
if (ev.eventName === "UserOperationEvent" && ev.args.userOpHash === hash) {
|
|
310
|
-
result = { userOpHash: hash, transactionHash: tx, success: ev.args.success, actualGasCost: ev.args.actualGasCost };
|
|
311
|
-
}
|
|
312
|
-
else if (ev.eventName === "UserOperationRevertReason" && ev.args.userOpHash === hash) {
|
|
313
|
-
revertReason = ev.args.revertReason;
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
catch {
|
|
317
|
-
// Other EntryPoint events are not needed here.
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
if (!result)
|
|
321
|
-
throw new Error(`no UserOperationEvent for ${hash} in ${tx}`);
|
|
322
|
-
return revertReason ? { ...result, revertReason } : result;
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Sends a signed userOp straight to the EntryPoint from an ordinary account, which acts as its own bundler and
|
|
326
|
-
* is paid the gas back by the vault (or the paymaster). No third-party bundler is needed.
|
|
327
|
-
*/
|
|
328
|
-
export async function sendUserOpDirect(client, wallet, op) {
|
|
329
|
-
const hash = await userOpHash(client, op);
|
|
330
|
-
const tx = await wallet.writeContract({
|
|
331
|
-
address: external.entryPoint,
|
|
332
|
-
abi: entryPointAbi,
|
|
333
|
-
functionName: "handleOps",
|
|
334
|
-
args: [[packUserOp(op)], wallet.account.address],
|
|
335
|
-
});
|
|
336
|
-
const receipt = await client.waitForTransactionReceipt({ hash: tx });
|
|
337
|
-
if (receipt.status !== "success")
|
|
338
|
-
throw new Error(`handleOps reverted in ${tx}`);
|
|
339
|
-
return readResult(receipt.logs, hash, tx);
|
|
340
|
-
}
|
|
341
|
-
function rpcUserOp(op) {
|
|
342
|
-
const q = (v) => numberToHex(v);
|
|
343
|
-
return {
|
|
344
|
-
sender: op.sender,
|
|
345
|
-
nonce: q(op.nonce),
|
|
346
|
-
...(op.factory ? { factory: op.factory, factoryData: op.factoryData ?? "0x" } : {}),
|
|
347
|
-
callData: op.callData,
|
|
348
|
-
callGasLimit: q(op.callGasLimit),
|
|
349
|
-
verificationGasLimit: q(op.verificationGasLimit),
|
|
350
|
-
preVerificationGas: q(op.preVerificationGas),
|
|
351
|
-
maxFeePerGas: q(op.maxFeePerGas),
|
|
352
|
-
maxPriorityFeePerGas: q(op.maxPriorityFeePerGas),
|
|
353
|
-
...(op.paymaster
|
|
354
|
-
? {
|
|
355
|
-
paymaster: op.paymaster,
|
|
356
|
-
paymasterVerificationGasLimit: q(op.paymasterVerificationGasLimit ?? 0n),
|
|
357
|
-
paymasterPostOpGasLimit: q(op.paymasterPostOpGasLimit ?? 0n),
|
|
358
|
-
paymasterData: op.paymasterData ?? "0x",
|
|
359
|
-
}
|
|
360
|
-
: {}),
|
|
361
|
-
signature: op.signature,
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
/** An error the bundler answered with, as opposed to one on the way to it. */
|
|
365
|
-
export class BundlerError extends Error {
|
|
366
|
-
code;
|
|
367
|
-
constructor(method, code, message) {
|
|
368
|
-
super(`${method}: ${message}`);
|
|
369
|
-
this.name = "BundlerError";
|
|
370
|
-
this.code = code;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
async function bundlerRpc(url, method, params) {
|
|
374
|
-
const res = await fetch(url, {
|
|
375
|
-
method: "POST",
|
|
376
|
-
headers: { "content-type": "application/json" },
|
|
377
|
-
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
378
|
-
signal: AbortSignal.timeout(30_000),
|
|
379
|
-
});
|
|
380
|
-
// Rate limits and server errors are on the way, whatever the body says.
|
|
381
|
-
if (res.status === 429 || res.status >= 500)
|
|
382
|
-
throw new Error(`${method}: HTTP ${res.status} from the bundler`);
|
|
383
|
-
const text = await res.text();
|
|
384
|
-
let body;
|
|
385
|
-
try {
|
|
386
|
-
body = JSON.parse(text);
|
|
387
|
-
}
|
|
388
|
-
catch {
|
|
389
|
-
throw new Error(`${method}: HTTP ${res.status} from the bundler`);
|
|
390
|
-
}
|
|
391
|
-
if (body.error)
|
|
392
|
-
throw new BundlerError(method, body.error.code, body.error.message);
|
|
393
|
-
if (!res.ok)
|
|
394
|
-
throw new BundlerError(method, res.status, `HTTP ${res.status}`);
|
|
395
|
-
return body.result;
|
|
396
|
-
}
|
|
397
|
-
/** Sends a signed userOp through an ERC-4337 bundler (for Robinhood Chain, Alchemy's) and waits for it. */
|
|
398
|
-
export async function sendUserOpToBundler(client, bundlerUrl, op, timeoutMs = 120_000) {
|
|
399
|
-
// The hash is known before sending, so a send whose answer is lost can still be polled. Sending the same op
|
|
400
|
-
// again is safe: its nonce lets it run only once.
|
|
401
|
-
const hash = await userOpHash(client, op);
|
|
402
|
-
try {
|
|
403
|
-
await bundlerRpc(bundlerUrl, "eth_sendUserOperation", [rpcUserOp(op), external.entryPoint]);
|
|
404
|
-
}
|
|
405
|
-
catch (err) {
|
|
406
|
-
throw Object.assign(new Error(`${err instanceof Error ? err.message : String(err)} (userOp ${hash})`, { cause: err }), { userOpHash: hash });
|
|
407
|
-
}
|
|
408
|
-
const deadline = Date.now() + timeoutMs;
|
|
409
|
-
while (Date.now() < deadline) {
|
|
410
|
-
// The userOp is already sent: a poll that fails on the way is retried until the deadline, while an
|
|
411
|
-
// answer from the bundler itself (such as a revoked key) ends the wait.
|
|
412
|
-
const r = await bundlerRpc(bundlerUrl, "eth_getUserOperationReceipt", [hash]).catch((e) => {
|
|
413
|
-
if (e instanceof BundlerError)
|
|
414
|
-
throw e;
|
|
415
|
-
return null;
|
|
416
|
-
});
|
|
417
|
-
if (r?.receipt) {
|
|
418
|
-
// The bundler may see the block before this client's RPC does.
|
|
419
|
-
const receipt = await client.waitForTransactionReceipt({ hash: r.receipt.transactionHash, timeout: Math.max(deadline - Date.now(), 30_000) });
|
|
420
|
-
return readResult(receipt.logs, hash, r.receipt.transactionHash);
|
|
421
|
-
}
|
|
422
|
-
await new Promise((f) => setTimeout(f, 2_000));
|
|
423
|
-
}
|
|
424
|
-
throw new Error(`userOp ${hash} not included within ${timeoutMs / 1000} s`);
|
|
425
|
-
}
|
package/dist/vault.js
DELETED
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import { erc20Abi as viemErc20Abi } from "viem";
|
|
2
|
-
import { factoryAbi, gateAbi, rootValidatorAbi, routerAbi, subVaultsAbi, timelockAbi } from "./abis.js";
|
|
3
|
-
import { ETH, external, mortise } from "./addresses.js";
|
|
4
|
-
import { encodeRoot } from "./root.js";
|
|
5
|
-
import { MODULE_TYPE } from "./userop.js";
|
|
6
|
-
import { accountAbi } from "./abis.js";
|
|
7
|
-
/** The address the vault for this root and salt has, whether or not it exists yet. */
|
|
8
|
-
export function predictVault(client, root, salt) {
|
|
9
|
-
return client.readContract({ address: mortise.factory, abi: factoryAbi, functionName: "predictVault", args: [encodeRoot(root), salt] });
|
|
10
|
-
}
|
|
11
|
-
/** Creates the vault in an ordinary transaction; anyone can pay for it. Returns its address. */
|
|
12
|
-
export async function createVault(client, wallet, root, salt) {
|
|
13
|
-
const vault = await predictVault(client, root, salt);
|
|
14
|
-
const hash = await wallet.writeContract({ address: mortise.factory, abi: factoryAbi, functionName: "createVault", args: [encodeRoot(root), salt] });
|
|
15
|
-
const receipt = await client.waitForTransactionReceipt({ hash });
|
|
16
|
-
if (receipt.status !== "success")
|
|
17
|
-
throw new Error(`createVault reverted in ${hash}`);
|
|
18
|
-
return vault;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Deposits through the deposit router, which takes the fee and counts the vault's limit. A plain transfer to
|
|
22
|
-
* the vault also works but is not counted and pays no fee. For a token, approves the router for the amount first.
|
|
23
|
-
*/
|
|
24
|
-
export async function deposit(client, wallet, vault, token, amount) {
|
|
25
|
-
if (token === ETH) {
|
|
26
|
-
const hash = await wallet.writeContract({ address: mortise.router, abi: routerAbi, functionName: "depositETH", args: [vault], value: amount });
|
|
27
|
-
await mustSucceed(client, hash);
|
|
28
|
-
return hash;
|
|
29
|
-
}
|
|
30
|
-
const approve = await wallet.writeContract({ address: token, abi: viemErc20Abi, functionName: "approve", args: [mortise.router, amount] });
|
|
31
|
-
await mustSucceed(client, approve);
|
|
32
|
-
const hash = await wallet.writeContract({ address: mortise.router, abi: routerAbi, functionName: "deposit", args: [vault, token, amount] });
|
|
33
|
-
await mustSucceed(client, hash);
|
|
34
|
-
return hash;
|
|
35
|
-
}
|
|
36
|
-
async function mustSucceed(client, hash) {
|
|
37
|
-
const r = await client.waitForTransactionReceipt({ hash });
|
|
38
|
-
if (r.status !== "success")
|
|
39
|
-
throw new Error(`transaction ${hash} reverted`);
|
|
40
|
-
}
|
|
41
|
-
/** What the router would take as fee and count toward the vault's limit for a deposit. */
|
|
42
|
-
export async function depositQuote(client, vault, token, amount) {
|
|
43
|
-
const [feeBps, capUsd, received] = await Promise.all([
|
|
44
|
-
client.readContract({ address: mortise.router, abi: routerAbi, functionName: "feeBps" }),
|
|
45
|
-
client.readContract({ address: mortise.router, abi: routerAbi, functionName: "capUsd" }),
|
|
46
|
-
client.readContract({ address: mortise.router, abi: routerAbi, functionName: "depositedUsd", args: [vault] }),
|
|
47
|
-
]);
|
|
48
|
-
const fee = (amount * feeBps) / 10000n;
|
|
49
|
-
const net = amount - fee;
|
|
50
|
-
// As the router counts it: the value of what reaches the vault, and only while a cap is set.
|
|
51
|
-
const usdValue = capUsd === 0n ? 0n : await client.readContract({ address: mortise.router, abi: routerAbi, functionName: "valueOf", args: [token, net] });
|
|
52
|
-
return { fee, net, usdValue, capUsd, receivedUsd: received, fitsCap: usdValue === 0n || received + usdValue <= capUsd };
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Guardian side of recovery: a guardian approves replacing the vault's root with `next`. Once the threshold of
|
|
56
|
-
* guardians approve the same root, the delay starts (RecoveryReady); the root can cancel it until then.
|
|
57
|
-
*/
|
|
58
|
-
export async function approveRecovery(client, guardian, vault, next) {
|
|
59
|
-
return send(client, guardian, "approveRecovery", [vault, encodeRoot(next)]);
|
|
60
|
-
}
|
|
61
|
-
/** Applies an approved recovery once its delay has passed; anyone may send it. */
|
|
62
|
-
export async function executeRecovery(client, wallet, vault, next) {
|
|
63
|
-
return send(client, wallet, "executeRecovery", [vault, encodeRoot(next)]);
|
|
64
|
-
}
|
|
65
|
-
async function send(client, wallet, functionName, args) {
|
|
66
|
-
const { request } = await client.simulateContract({ account: wallet.account, address: mortise.rootValidator, abi: rootValidatorAbi, functionName, args });
|
|
67
|
-
const hash = await wallet.writeContract(request);
|
|
68
|
-
const receipt = await client.waitForTransactionReceipt({ hash });
|
|
69
|
-
if (receipt.status !== "success")
|
|
70
|
-
throw new Error(`${functionName} reverted in ${hash}`);
|
|
71
|
-
return hash;
|
|
72
|
-
}
|
|
73
|
-
/** One look at a vault: its root, recovery, modules and pause state. */
|
|
74
|
-
export async function vaultStatus(client, vault) {
|
|
75
|
-
const code = await client.getCode({ address: vault });
|
|
76
|
-
if (!code || code === "0x")
|
|
77
|
-
return { exists: false, vault };
|
|
78
|
-
const [rootOf, guardians, paymasterOnly, gateInstalled, paused, pauser, hook, timelockDelay, liveParent, childCount, subVaultParent] = await Promise.all([
|
|
79
|
-
client.readContract({ address: mortise.rootValidator, abi: rootValidatorAbi, functionName: "rootOf", args: [vault] }),
|
|
80
|
-
client.readContract({ address: mortise.rootValidator, abi: rootValidatorAbi, functionName: "guardiansOf", args: [vault] }),
|
|
81
|
-
client.readContract({ address: mortise.rootValidator, abi: rootValidatorAbi, functionName: "isPaymasterOnly", args: [vault] }),
|
|
82
|
-
client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "installed", args: [vault] }),
|
|
83
|
-
client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "isPaused", args: [vault] }),
|
|
84
|
-
client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "pauser", args: [vault] }),
|
|
85
|
-
client.readContract({ address: vault, abi: [{ type: "function", name: "getActiveHook", inputs: [], outputs: [{ type: "address" }], stateMutability: "view" }], functionName: "getActiveHook" }),
|
|
86
|
-
client.readContract({ address: mortise.timelock, abi: timelockAbi, functionName: "delayOf", args: [vault] }),
|
|
87
|
-
client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "liveParent", args: [vault] }),
|
|
88
|
-
client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "childCount", args: [vault] }),
|
|
89
|
-
client.readContract({ address: mortise.subVaults, abi: subVaultsAbi, functionName: "parentOf", args: [vault] }),
|
|
90
|
-
]);
|
|
91
|
-
const [members, threshold] = rootOf;
|
|
92
|
-
const [guardianList, guardianThreshold, recoveryDelay] = guardians;
|
|
93
|
-
const isInstalled = (type, module) => client.readContract({ address: vault, abi: accountAbi, functionName: "isModuleInstalled", args: [type, module, "0x"] });
|
|
94
|
-
const [subVaults, signer] = await Promise.all([isInstalled(MODULE_TYPE.executor, mortise.subVaults), isInstalled(MODULE_TYPE.validator, mortise.signer)]);
|
|
95
|
-
const rootMembers = members.map((m) => m.keyType === 1 ? { type: "ecdsa", signer: m.signer } : { type: "passkey", x: m.x, y: m.y });
|
|
96
|
-
return {
|
|
97
|
-
exists: true,
|
|
98
|
-
vault,
|
|
99
|
-
root: { members: rootMembers, threshold: Number(threshold) },
|
|
100
|
-
recovery: { guardians: guardianList, threshold: guardianThreshold, delay: recoveryDelay },
|
|
101
|
-
paymasterOnly,
|
|
102
|
-
gate: { installed: gateInstalled, paused, pauser },
|
|
103
|
-
hook,
|
|
104
|
-
timelock: { installed: hook.toLowerCase() === mortise.timelock.toLowerCase(), delay: timelockDelay },
|
|
105
|
-
// `parent` is the Gate's family link (family transfers); `controller` is the sub-vault parent whose root
|
|
106
|
-
// runs this vault through MortiseSubVaults, set when the vault was created and kept after an unlink.
|
|
107
|
-
family: { parent: liveParent === ETH ? undefined : liveParent, controller: subVaultParent === ETH ? undefined : subVaultParent, children: childCount },
|
|
108
|
-
modules: { subVaults, signer },
|
|
109
|
-
ethBalance: await client.getBalance({ address: vault }),
|
|
110
|
-
entryPointDeposit: await client.readContract({
|
|
111
|
-
address: external.entryPoint,
|
|
112
|
-
abi: [{ type: "function", name: "balanceOf", inputs: [{ type: "address" }], outputs: [{ type: "uint256" }], stateMutability: "view" }],
|
|
113
|
-
functionName: "balanceOf",
|
|
114
|
-
args: [vault],
|
|
115
|
-
}),
|
|
116
|
-
};
|
|
117
|
-
}
|