@mortiseagentvault/sdk 0.0.0-stage → 0.1.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.
@@ -0,0 +1,70 @@
1
+ import { type Address, type Hex } from "viem";
2
+ import { type Root } from "./root.ts";
3
+ import { type Call, type RootCall } from "./userop.ts";
4
+ /**
5
+ * Settings of the vault's Gate. Each is a call the vault makes to the Gate, so it goes into a root userOp
6
+ * (or a sub-vault's exec). Rates are raw units of tokenOut per 1e36 raw units of tokenIn.
7
+ */
8
+ export declare const gate: {
9
+ /** `until` is a unix time in seconds; 0 removes the agent, NEVER keeps it. */
10
+ setAgent: (agent: Address, until: bigint) => Call;
11
+ setAdapterAccess: (actor: Address, adapter: Address, allowed: boolean) => Call;
12
+ setMarket: (adapter: Address, market: Hex, allowed: boolean) => Call;
13
+ /** `limit` in raw units of `token` (address(0) is ETH), per `period` seconds. */
14
+ setCap: (actor: Address, token: Address, limit: bigint, period: bigint) => Call;
15
+ setMinRate: (tokenIn: Address, tokenOut: Address, rate: bigint) => Call;
16
+ setOpenMarkets: (actor: Address, adapter: Address, open: boolean) => Call;
17
+ setOpenFloor: (actor: Address, open: boolean) => Call;
18
+ setModule: (module: Address, enabled: boolean, initState?: Hex) => Call;
19
+ setPauser: (pauser: Address) => Call;
20
+ pause: (vault: Address) => Call;
21
+ unpause: () => Call;
22
+ proposeParent: (parent: Address) => Call;
23
+ acceptChild: (child: Address) => Call;
24
+ unlink: (child: Address) => Call;
25
+ };
26
+ /** An agent that never expires. */
27
+ export declare const NEVER: bigint;
28
+ /** Rate helper: the least `out` raw units for `in_` raw units, in the Gate's per-1e36 unit, rounded up. */
29
+ export declare function rateOf(amountIn: bigint, minAmountOut: bigint): bigint;
30
+ /** The vault's root and its guardians. */
31
+ export declare const root: {
32
+ setRootKey: (next: Root) => Call;
33
+ /** Guardians who can replace the root after `delay` seconds (7 to 90 days); an empty list removes recovery. */
34
+ setGuardians: (guardians: Address[], threshold: bigint, delay: bigint) => Call;
35
+ cancelRecovery: () => Call;
36
+ setPaymasterOnly: (required: boolean) => Call;
37
+ };
38
+ /** The timelock hook: install, schedule and settings. */
39
+ export declare const timelock: {
40
+ /** Installs the hook. The root validator must already be in paymaster-only mode. */
41
+ install: (delay: number, destinations: Address[]) => RootCall;
42
+ /** Schedules a root call that the timelock would refuse now; it can run once, after the delay. */
43
+ schedule: (later: RootCall) => Call;
44
+ cancel: (later: RootCall) => Call;
45
+ cancelAll: () => Call;
46
+ setDelay: (delay: number) => Call;
47
+ setDestination: (destination: Address, allowed: boolean) => Call;
48
+ };
49
+ /** The timelock's id of a root call: the hash of its exact callData. */
50
+ export declare function opId(c: RootCall): Hex;
51
+ /** Sub-vaults: the parent installs the module once, then creates, runs and sweeps its sub-vaults. */
52
+ export declare const subVaults: {
53
+ install: () => RootCall;
54
+ create: (parent: Address, salt: bigint) => Call;
55
+ /** Runs `calls` as the sub-vault. */
56
+ exec: (child: Address, calls: Call[]) => Call;
57
+ /** Moves the sub-vault's whole balance of each token (address(0) is ETH) back to the parent. */
58
+ sweep: (child: Address, tokens: Address[]) => Call;
59
+ };
60
+ /** Message signing (ERC-1271 with ERC-7739): installed as validator and as static fallback for eip712Domain. */
61
+ export declare const signer: {
62
+ installValidator: () => RootCall;
63
+ /** Safe7579 fallback init data: selector, call type static (0xfe), then the module's own init data. */
64
+ installFallback: () => RootCall;
65
+ };
66
+ /** Moving funds out of the vault. */
67
+ export declare const funds: {
68
+ sendEth: (to: Address, amount: bigint) => Call;
69
+ sendToken: (token: Address, to: Address, amount: bigint) => Call;
70
+ };
package/dist/calls.js ADDED
@@ -0,0 +1,96 @@
1
+ import { encodeAbiParameters, encodeFunctionData, keccak256, maxUint64 } from "viem";
2
+ import { erc20Abi, gateAbi, rootValidatorAbi, subVaultsAbi, timelockAbi } from "./abis.js";
3
+ import { mortise } from "./addresses.js";
4
+ import { encodeRoot } from "./root.js";
5
+ import { encodeRootCall, MODULE_TYPE } from "./userop.js";
6
+ const call = (to, data, value = 0n) => ({ to, data, value });
7
+ /**
8
+ * Settings of the vault's Gate. Each is a call the vault makes to the Gate, so it goes into a root userOp
9
+ * (or a sub-vault's exec). Rates are raw units of tokenOut per 1e36 raw units of tokenIn.
10
+ */
11
+ export const gate = {
12
+ /** `until` is a unix time in seconds; 0 removes the agent, NEVER keeps it. */
13
+ setAgent: (agent, until) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setAgent", args: [agent, until] })),
14
+ setAdapterAccess: (actor, adapter, allowed) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setAdapterAccess", args: [actor, adapter, allowed] })),
15
+ setMarket: (adapter, market, allowed) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setMarket", args: [adapter, market, allowed] })),
16
+ /** `limit` in raw units of `token` (address(0) is ETH), per `period` seconds. */
17
+ setCap: (actor, token, limit, period) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setCap", args: [actor, token, limit, period] })),
18
+ setMinRate: (tokenIn, tokenOut, rate) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setMinRate", args: [tokenIn, tokenOut, rate] })),
19
+ setOpenMarkets: (actor, adapter, open) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setOpenMarkets", args: [actor, adapter, open] })),
20
+ setOpenFloor: (actor, open) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setOpenFloor", args: [actor, open] })),
21
+ setModule: (module, enabled, initState = "0x") => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setModule", args: [module, enabled, initState] })),
22
+ setPauser: (pauser) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "setPauser", args: [pauser] })),
23
+ pause: (vault) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "pause", args: [vault] })),
24
+ unpause: () => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "unpause" })),
25
+ proposeParent: (parent) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "proposeParent", args: [parent] })),
26
+ acceptChild: (child) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "acceptChild", args: [child] })),
27
+ unlink: (child) => call(mortise.gate, encodeFunctionData({ abi: gateAbi, functionName: "unlink", args: [child] })),
28
+ };
29
+ /** An agent that never expires. */
30
+ export const NEVER = maxUint64;
31
+ /** Rate helper: the least `out` raw units for `in_` raw units, in the Gate's per-1e36 unit, rounded up. */
32
+ export function rateOf(amountIn, minAmountOut) {
33
+ if (amountIn <= 0n)
34
+ throw new Error("amountIn must be positive");
35
+ return (minAmountOut * 10n ** 36n + amountIn - 1n) / amountIn;
36
+ }
37
+ /** The vault's root and its guardians. */
38
+ export const root = {
39
+ setRootKey: (next) => call(mortise.rootValidator, encodeFunctionData({ abi: rootValidatorAbi, functionName: "setRootKey", args: [encodeRoot(next)] })),
40
+ /** Guardians who can replace the root after `delay` seconds (7 to 90 days); an empty list removes recovery. */
41
+ setGuardians: (guardians, threshold, delay) => call(mortise.rootValidator, encodeFunctionData({ abi: rootValidatorAbi, functionName: "setGuardians", args: [guardians, threshold, delay] })),
42
+ cancelRecovery: () => call(mortise.rootValidator, encodeFunctionData({ abi: rootValidatorAbi, functionName: "cancelRecovery" })),
43
+ setPaymasterOnly: (required) => call(mortise.rootValidator, encodeFunctionData({ abi: rootValidatorAbi, functionName: "setPaymasterOnly", args: [required] })),
44
+ };
45
+ /** The timelock hook: install, schedule and settings. */
46
+ export const timelock = {
47
+ /** Installs the hook. The root validator must already be in paymaster-only mode. */
48
+ install: (delay, destinations) => ({
49
+ kind: "installModule",
50
+ moduleType: MODULE_TYPE.hook,
51
+ module: mortise.timelock,
52
+ initData: encodeAbiParameters([{ type: "uint32" }, { type: "address[]" }], [delay, destinations]),
53
+ }),
54
+ /** Schedules a root call that the timelock would refuse now; it can run once, after the delay. */
55
+ schedule: (later) => call(mortise.timelock, encodeFunctionData({ abi: timelockAbi, functionName: "schedule", args: [encodeRootCall(later)] })),
56
+ cancel: (later) => call(mortise.timelock, encodeFunctionData({ abi: timelockAbi, functionName: "cancel", args: [opId(later)] })),
57
+ cancelAll: () => call(mortise.timelock, encodeFunctionData({ abi: timelockAbi, functionName: "cancelAll" })),
58
+ setDelay: (delay) => call(mortise.timelock, encodeFunctionData({ abi: timelockAbi, functionName: "setDelay", args: [delay] })),
59
+ setDestination: (destination, allowed) => call(mortise.timelock, encodeFunctionData({ abi: timelockAbi, functionName: "setDestination", args: [destination, allowed] })),
60
+ };
61
+ /** The timelock's id of a root call: the hash of its exact callData. */
62
+ export function opId(c) {
63
+ return keccak256(encodeRootCall(c));
64
+ }
65
+ /** Sub-vaults: the parent installs the module once, then creates, runs and sweeps its sub-vaults. */
66
+ export const subVaults = {
67
+ install: () => ({ kind: "installModule", moduleType: MODULE_TYPE.executor, module: mortise.subVaults, initData: "0x" }),
68
+ create: (parent, salt) => call(mortise.subVaults, encodeFunctionData({ abi: subVaultsAbi, functionName: "createSubVault", args: [parent, salt] })),
69
+ /** Runs `calls` as the sub-vault. */
70
+ exec: (child, calls) => call(mortise.subVaults, encodeFunctionData({
71
+ abi: subVaultsAbi,
72
+ functionName: "exec",
73
+ args: [
74
+ child,
75
+ encodeAbiParameters([{ type: "tuple[]", components: [{ name: "target", type: "address" }, { name: "value", type: "uint256" }, { name: "callData", type: "bytes" }] }], [calls.map((c) => ({ target: c.to, value: c.value ?? 0n, callData: c.data ?? "0x" }))]),
76
+ ],
77
+ })),
78
+ /** Moves the sub-vault's whole balance of each token (address(0) is ETH) back to the parent. */
79
+ sweep: (child, tokens) => call(mortise.subVaults, encodeFunctionData({ abi: subVaultsAbi, functionName: "sweep", args: [child, tokens] })),
80
+ };
81
+ /** Message signing (ERC-1271 with ERC-7739): installed as validator and as static fallback for eip712Domain. */
82
+ export const signer = {
83
+ installValidator: () => ({ kind: "installModule", moduleType: MODULE_TYPE.validator, module: mortise.signer, initData: "0x" }),
84
+ /** Safe7579 fallback init data: selector, call type static (0xfe), then the module's own init data. */
85
+ installFallback: () => ({
86
+ kind: "installModule",
87
+ moduleType: MODULE_TYPE.fallback,
88
+ module: mortise.signer,
89
+ initData: encodeAbiParameters([{ type: "bytes4" }, { type: "bytes1" }, { type: "bytes" }], ["0x84b0196e", "0xfe", "0x"]),
90
+ }),
91
+ };
92
+ /** Moving funds out of the vault. */
93
+ export const funds = {
94
+ sendEth: (to, amount) => ({ to, value: amount, data: "0x" }),
95
+ sendToken: (token, to, amount) => call(token, encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: [to, amount] })),
96
+ };
@@ -0,0 +1,13 @@
1
+ import { type Hex } from "viem";
2
+ /** A contract error decoded from its revert data, or undefined when the data matches none of them. */
3
+ export declare function decodeMortiseError(data: Hex): {
4
+ name: string;
5
+ args: readonly unknown[];
6
+ } | undefined;
7
+ /**
8
+ * The revert data inside an error, if any. Checks the error's shape rather than its class, so it works when the
9
+ * error comes from another copy of viem than the SDK's own (an app that installs a different viem version).
10
+ */
11
+ export declare function revertData(err: unknown): Hex | undefined;
12
+ /** The Mortise error name behind a failed call, such as "CapExceeded", or undefined. */
13
+ export declare function mortiseErrorName(err: unknown): string | undefined;
package/dist/errors.js ADDED
@@ -0,0 +1,52 @@
1
+ import { decodeErrorResult } from "viem";
2
+ import * as abis from "./abis.js";
3
+ // Every error any Mortise contract, the EntryPoint or Safe7579 can raise, deduplicated by signature.
4
+ const errorAbi = (() => {
5
+ const seen = new Set();
6
+ const out = [];
7
+ for (const abi of Object.values(abis)) {
8
+ for (const item of abi) {
9
+ if (item.type !== "error")
10
+ continue;
11
+ const key = `${item.name}(${item.inputs.map((i) => i.type).join(",")})`;
12
+ if (seen.has(key))
13
+ continue;
14
+ seen.add(key);
15
+ out.push(item);
16
+ }
17
+ }
18
+ return out;
19
+ })();
20
+ /** A contract error decoded from its revert data, or undefined when the data matches none of them. */
21
+ export function decodeMortiseError(data) {
22
+ try {
23
+ const r = decodeErrorResult({ abi: errorAbi, data });
24
+ return { name: r.errorName, args: r.args ?? [] };
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /**
31
+ * The revert data inside an error, if any. Checks the error's shape rather than its class, so it works when the
32
+ * error comes from another copy of viem than the SDK's own (an app that installs a different viem version).
33
+ */
34
+ export function revertData(err) {
35
+ const hex = (v) => (typeof v === "string" && v.startsWith("0x") && v.length >= 10 ? v : undefined);
36
+ let found;
37
+ let e = err;
38
+ // A viem error nests the cause that carries the data; a RootCallError carries it itself.
39
+ for (let depth = 0; e && typeof e === "object" && depth < 20; depth++) {
40
+ const data = e.data;
41
+ found = hex(data) ?? hex(e.raw) ?? (data && typeof data === "object" ? hex(data.data) : undefined);
42
+ if (found)
43
+ return found;
44
+ e = e.cause;
45
+ }
46
+ return undefined;
47
+ }
48
+ /** The Mortise error name behind a failed call, such as "CapExceeded", or undefined. */
49
+ export function mortiseErrorName(err) {
50
+ const data = revertData(err);
51
+ return data ? decodeMortiseError(data)?.name : undefined;
52
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./abis.ts";
2
+ export * from "./addresses.ts";
3
+ export * from "./root.ts";
4
+ export * from "./userop.ts";
5
+ export * from "./calls.ts";
6
+ export * from "./actions.ts";
7
+ export * from "./agent.ts";
8
+ export * from "./vault.ts";
9
+ export * from "./modules.ts";
10
+ export * from "./errors.ts";
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./abis.js";
2
+ export * from "./addresses.js";
3
+ export * from "./root.js";
4
+ export * from "./userop.js";
5
+ export * from "./calls.js";
6
+ export * from "./actions.js";
7
+ export * from "./agent.js";
8
+ export * from "./vault.js";
9
+ export * from "./modules.js";
10
+ export * from "./errors.js";
@@ -0,0 +1,22 @@
1
+ import type { Address, ContractFunctionArgs, Hex, PublicClient } from "viem";
2
+ import { automationAbi, rebalanceAbi } from "./abis.ts";
3
+ import type { Action } from "./actions.ts";
4
+ /**
5
+ * Module states, built and checked by each module's own encoder so the SDK never re-implements the layout.
6
+ * Enable a module with gate.setModule(module, true, state), and give the module (as actor) adapter access,
7
+ * markets and caps like an agent.
8
+ */
9
+ export declare const moduleState: {
10
+ /** The same action every `interval` seconds, `runs` times from `firstAt`; only `keeper` may trigger it. */
11
+ dca: (client: PublicClient, a: {
12
+ action: Action;
13
+ keeper: Address;
14
+ interval: bigint;
15
+ firstAt: bigint;
16
+ runs: number;
17
+ }) => Promise<Hex>;
18
+ /** Up to eight tasks: scheduled, recurring or price-triggered actions, each run by its own keeper. */
19
+ automation: (client: PublicClient, tasks: ContractFunctionArgs<typeof automationAbi, "pure", "encodeTasks">[0]) => Promise<Hex>;
20
+ /** Token pairs kept near a target share of their Chainlink value. */
21
+ rebalance: (client: PublicClient, pairs: ContractFunctionArgs<typeof rebalanceAbi, "pure", "encodePairs">[0]) => Promise<Hex>;
22
+ };
@@ -0,0 +1,15 @@
1
+ import { automationAbi, dcaAbi, rebalanceAbi } from "./abis.js";
2
+ import { mortise } from "./addresses.js";
3
+ /**
4
+ * Module states, built and checked by each module's own encoder so the SDK never re-implements the layout.
5
+ * Enable a module with gate.setModule(module, true, state), and give the module (as actor) adapter access,
6
+ * markets and caps like an agent.
7
+ */
8
+ export const moduleState = {
9
+ /** The same action every `interval` seconds, `runs` times from `firstAt`; only `keeper` may trigger it. */
10
+ dca: (client, a) => client.readContract({ address: mortise.dca, abi: dcaAbi, functionName: "encodePlan", args: [a.action, a.keeper, a.interval, a.firstAt, a.runs] }),
11
+ /** Up to eight tasks: scheduled, recurring or price-triggered actions, each run by its own keeper. */
12
+ automation: (client, tasks) => client.readContract({ address: mortise.automation, abi: automationAbi, functionName: "encodeTasks", args: [tasks] }),
13
+ /** Token pairs kept near a target share of their Chainlink value. */
14
+ rebalance: (client, pairs) => client.readContract({ address: mortise.rebalance, abi: rebalanceAbi, functionName: "encodePairs", args: [pairs] }),
15
+ };
package/dist/root.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { type Address, type Hex } from "viem";
2
+ /** One key of a vault's root: an ECDSA signer or a WebAuthn passkey (P-256 public key). */
3
+ export type RootMember = {
4
+ type: "ecdsa";
5
+ signer: Address;
6
+ } | {
7
+ type: "passkey";
8
+ x: Hex;
9
+ y: Hex;
10
+ };
11
+ /** A vault's root: one to ten keys and how many of them must sign. */
12
+ export interface Root {
13
+ members: RootMember[];
14
+ threshold: number;
15
+ }
16
+ /** The bytes MortiseRootValidator takes as a root: abi.encode(Member[] members, uint256 threshold). */
17
+ export declare function encodeRoot(root: Root): Hex;
18
+ /** The hash guardians approve and RecoveryReady reports for a new root. */
19
+ export declare function rootHash(root: Root): Hex;
20
+ /**
21
+ * A passkey member's signature: abi.encode(WebAuthnAuth) as Solady's WebAuthn decodes it. The assertion must
22
+ * be over the hash being signed (the userOp hash) as its challenge, with user verification.
23
+ */
24
+ export declare function encodePasskeySignature(a: {
25
+ authenticatorData: Hex;
26
+ clientDataJSON: string;
27
+ r: bigint;
28
+ s: bigint;
29
+ }): Hex;
30
+ /** A one-key ECDSA root. */
31
+ export declare function singleKeyRoot(signer: Address): Root;
32
+ /**
33
+ * The signature MortiseRootValidator expects from a root. A one-key root takes that key's signature as is.
34
+ * A larger root takes abi.encode(MemberSignature[]) with strictly increasing member indices.
35
+ */
36
+ export declare function encodeRootSignature(root: Root, signatures: {
37
+ index: number;
38
+ signature: Hex;
39
+ }[]): Hex;
package/dist/root.js ADDED
@@ -0,0 +1,104 @@
1
+ import { encodeAbiParameters, keccak256 } from "viem";
2
+ const ZERO32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
3
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
4
+ const memberTuple = {
5
+ type: "tuple[]",
6
+ components: [
7
+ { name: "keyType", type: "uint8" },
8
+ { name: "signer", type: "address" },
9
+ { name: "x", type: "bytes32" },
10
+ { name: "y", type: "bytes32" },
11
+ ],
12
+ };
13
+ function toMember(m) {
14
+ return m.type === "ecdsa"
15
+ ? { keyType: 1, signer: m.signer, x: ZERO32, y: ZERO32 }
16
+ : { keyType: 2, signer: ZERO_ADDRESS, x: m.x, y: m.y };
17
+ }
18
+ /** The bytes MortiseRootValidator takes as a root: abi.encode(Member[] members, uint256 threshold). */
19
+ export function encodeRoot(root) {
20
+ const n = root.members.length;
21
+ if (n < 1 || n > 10)
22
+ throw new Error("a root has one to ten keys");
23
+ if (!Number.isInteger(root.threshold) || root.threshold < 1 || root.threshold > n) {
24
+ throw new Error("the threshold must be between 1 and the number of keys");
25
+ }
26
+ return encodeAbiParameters([memberTuple, { type: "uint256" }], [root.members.map(toMember), BigInt(root.threshold)]);
27
+ }
28
+ /** The hash guardians approve and RecoveryReady reports for a new root. */
29
+ export function rootHash(root) {
30
+ return keccak256(encodeRoot(root));
31
+ }
32
+ // P-256 group order; Solady's WebAuthn accepts only the low-s form.
33
+ const P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
34
+ /**
35
+ * A passkey member's signature: abi.encode(WebAuthnAuth) as Solady's WebAuthn decodes it. The assertion must
36
+ * be over the hash being signed (the userOp hash) as its challenge, with user verification.
37
+ */
38
+ export function encodePasskeySignature(a) {
39
+ // Byte offsets, as the contract reads them; string indices would count UTF-16 units instead.
40
+ const json = new TextEncoder().encode(a.clientDataJSON);
41
+ const challengeIndex = byteIndexOf(json, '"challenge":"');
42
+ const typeIndex = byteIndexOf(json, '"type":"');
43
+ if (challengeIndex < 0 || typeIndex < 0)
44
+ throw new Error("clientDataJSON has no challenge or type");
45
+ const s = a.s > P256_N / 2n ? P256_N - a.s : a.s;
46
+ return encodeAbiParameters([
47
+ {
48
+ type: "tuple",
49
+ components: [
50
+ { name: "authenticatorData", type: "bytes" },
51
+ { name: "clientDataJSON", type: "string" },
52
+ { name: "challengeIndex", type: "uint256" },
53
+ { name: "typeIndex", type: "uint256" },
54
+ { name: "r", type: "bytes32" },
55
+ { name: "s", type: "bytes32" },
56
+ ],
57
+ },
58
+ ], [
59
+ {
60
+ authenticatorData: a.authenticatorData,
61
+ clientDataJSON: a.clientDataJSON,
62
+ challengeIndex: BigInt(challengeIndex),
63
+ typeIndex: BigInt(typeIndex),
64
+ r: `0x${a.r.toString(16).padStart(64, "0")}`,
65
+ s: `0x${s.toString(16).padStart(64, "0")}`,
66
+ },
67
+ ]);
68
+ }
69
+ function byteIndexOf(haystack, needle) {
70
+ const n = new TextEncoder().encode(needle);
71
+ outer: for (let i = 0; i + n.length <= haystack.length; i++) {
72
+ for (let j = 0; j < n.length; j++)
73
+ if (haystack[i + j] !== n[j])
74
+ continue outer;
75
+ return i;
76
+ }
77
+ return -1;
78
+ }
79
+ /** A one-key ECDSA root. */
80
+ export function singleKeyRoot(signer) {
81
+ return { members: [{ type: "ecdsa", signer }], threshold: 1 };
82
+ }
83
+ /**
84
+ * The signature MortiseRootValidator expects from a root. A one-key root takes that key's signature as is.
85
+ * A larger root takes abi.encode(MemberSignature[]) with strictly increasing member indices.
86
+ */
87
+ export function encodeRootSignature(root, signatures) {
88
+ if (root.members.length === 1) {
89
+ const only = signatures[0];
90
+ if (signatures.length !== 1 || !only || only.index !== 0)
91
+ throw new Error("a one-key root takes one signature");
92
+ return only.signature;
93
+ }
94
+ const sorted = [...signatures].sort((a, b) => a.index - b.index);
95
+ sorted.forEach((s, i) => {
96
+ if (s.index < 0 || s.index >= root.members.length)
97
+ throw new Error(`no root member ${s.index}`);
98
+ if (i > 0 && sorted[i - 1].index === s.index)
99
+ throw new Error(`member ${s.index} signed twice`);
100
+ });
101
+ if (sorted.length < root.threshold)
102
+ throw new Error(`the root needs ${root.threshold} signatures`);
103
+ return encodeAbiParameters([{ type: "tuple[]", components: [{ name: "index", type: "uint256" }, { name: "signature", type: "bytes" }] }], [sorted.map((s) => ({ index: BigInt(s.index), signature: s.signature }))]);
104
+ }
@@ -0,0 +1,151 @@
1
+ import { type Account, type Address, type Chain, type Hex, type PublicClient, type Transport, type WalletClient } from "viem";
2
+ import { type Root } from "./root.ts";
3
+ /** One call the vault makes. */
4
+ export interface Call {
5
+ to: Address;
6
+ value?: bigint;
7
+ data?: Hex;
8
+ }
9
+ /** What a root userOp asks the vault to do. The root validator accepts only these three account functions. */
10
+ export type RootCall = {
11
+ kind: "execute";
12
+ calls: Call[];
13
+ } | {
14
+ kind: "installModule";
15
+ moduleType: bigint;
16
+ module: Address;
17
+ initData: Hex;
18
+ } | {
19
+ kind: "uninstallModule";
20
+ moduleType: bigint;
21
+ module: Address;
22
+ deInitData: Hex;
23
+ };
24
+ export declare const MODULE_TYPE: {
25
+ readonly validator: 1n;
26
+ readonly executor: 2n;
27
+ readonly fallback: 3n;
28
+ readonly hook: 4n;
29
+ };
30
+ export declare function encodeRootCall(c: RootCall): Hex;
31
+ /** EntryPoint v0.7 PackedUserOperation. */
32
+ export interface PackedUserOperation {
33
+ sender: Address;
34
+ nonce: bigint;
35
+ initCode: Hex;
36
+ callData: Hex;
37
+ accountGasLimits: Hex;
38
+ preVerificationGas: bigint;
39
+ gasFees: Hex;
40
+ paymasterAndData: Hex;
41
+ signature: Hex;
42
+ }
43
+ /** The unpacked fields a userOp is built from. */
44
+ export interface UserOperation {
45
+ sender: Address;
46
+ nonce: bigint;
47
+ factory?: Address;
48
+ factoryData?: Hex;
49
+ callData: Hex;
50
+ callGasLimit: bigint;
51
+ verificationGasLimit: bigint;
52
+ preVerificationGas: bigint;
53
+ maxFeePerGas: bigint;
54
+ maxPriorityFeePerGas: bigint;
55
+ paymaster?: Address;
56
+ paymasterVerificationGasLimit?: bigint;
57
+ paymasterPostOpGasLimit?: bigint;
58
+ paymasterData?: Hex;
59
+ signature: Hex;
60
+ }
61
+ export declare function packUserOp(op: UserOperation): PackedUserOperation;
62
+ /** The nonce of the vault's next root userOp: Safe7579 picks the validator from the nonce key. */
63
+ export declare function rootNonce(client: PublicClient, vault: Address): Promise<bigint>;
64
+ export declare function userOpHash(client: PublicClient, op: UserOperation): Promise<Hex>;
65
+ /**
66
+ * Runs the root call as the EntryPoint would, without a signature, and returns the gas it used. A revert here
67
+ * (for instance the timelock's NotScheduled) would also revert inside the userOp.
68
+ */
69
+ export declare function simulateRootCall(client: PublicClient, vault: Address, callData: Hex): Promise<bigint>;
70
+ /** A root call that failed, with the reason Safe7579 hid behind ExecutionFailed when it can be recovered. */
71
+ export declare class RootCallError extends Error {
72
+ /** Where the failure came from: the vault's hook (such as the timelock), one call of the batch, or a module's install. */
73
+ readonly source: "hook" | "call" | "install" | "account";
74
+ /** Index of the failing call in the batch, when source is "call". */
75
+ readonly callIndex: number | undefined;
76
+ /** The revert data that carries the reason; decode it with decodeMortiseError. */
77
+ readonly data: Hex | undefined;
78
+ constructor(message: string, source: "hook" | "call" | "install" | "account", data: Hex | undefined, cause: unknown, callIndex?: number);
79
+ }
80
+ /** A key that signs root userOps: its index in the root and how it signs a userOp hash. */
81
+ export interface RootKeySigner {
82
+ index: number;
83
+ sign(userOpHash: Hex): Promise<Hex>;
84
+ }
85
+ /** An ECDSA member signs the EIP-191 hash of the userOp hash. */
86
+ export declare function ecdsaRootSigner(index: number, account: {
87
+ signMessage(a: {
88
+ message: {
89
+ raw: Hex;
90
+ };
91
+ }): Promise<Hex>;
92
+ }): RootKeySigner;
93
+ /** Fields a gas sponsor adds; see ERC-4337 v0.7. */
94
+ export interface PaymasterFields {
95
+ paymaster: Address;
96
+ paymasterVerificationGasLimit: bigint;
97
+ paymasterPostOpGasLimit: bigint;
98
+ paymasterData: Hex;
99
+ }
100
+ export interface RootOpOptions {
101
+ /** The vault's root, to encode the signatures in the format it expects. */
102
+ root: Root;
103
+ signers: RootKeySigner[];
104
+ /** Creates the vault in the same userOp when it does not exist yet. */
105
+ create?: {
106
+ salt: bigint;
107
+ };
108
+ /**
109
+ * Asked for paymaster fields; required when the vault is in paymaster-only mode. With a bundler it is asked
110
+ * twice, as ERC-7677's pm_getPaymasterStubData and pm_getPaymasterData: `stub: true` before the gas estimate,
111
+ * for fields that need not validate, then `stub: false` over the final gas values.
112
+ */
113
+ paymaster?: (op: UserOperation, phase: {
114
+ stub: boolean;
115
+ }) => Promise<PaymasterFields>;
116
+ /** When set, gas and the priority fee come from this bundler's estimates (never lower than the SDK's own). */
117
+ bundlerUrl?: string;
118
+ /** Overrides for the gas fields. */
119
+ gas?: Partial<Pick<UserOperation, "callGasLimit" | "verificationGasLimit" | "preVerificationGas" | "maxFeePerGas" | "maxPriorityFeePerGas">>;
120
+ }
121
+ /**
122
+ * Builds and signs a root userOp. The call is simulated first; the signatures cover every field, including gas
123
+ * and paymaster, so nothing is changed after signing.
124
+ */
125
+ export declare function buildRootOp(client: PublicClient, vault: Address, call: RootCall, o: RootOpOptions): Promise<UserOperation>;
126
+ /** A signature of the right shape that fails validation without reverting, for gas estimation only. */
127
+ /**
128
+ * A signature of the right shape for gas estimation, for the members that will sign (by index; the first
129
+ * `threshold` members when not given), so the estimate runs the same validation path as the real one.
130
+ */
131
+ export declare function dummyRootSignature(root: Root, signerIndices?: number[]): Hex;
132
+ /** The outcome of a userOp, read from the EntryPoint's events. */
133
+ export interface UserOpResult {
134
+ userOpHash: Hex;
135
+ transactionHash: Hex;
136
+ success: boolean;
137
+ actualGasCost: bigint;
138
+ revertReason?: Hex;
139
+ }
140
+ /**
141
+ * Sends a signed userOp straight to the EntryPoint from an ordinary account, which acts as its own bundler and
142
+ * is paid the gas back by the vault (or the paymaster). No third-party bundler is needed.
143
+ */
144
+ export declare function sendUserOpDirect(client: PublicClient, wallet: WalletClient<Transport, Chain, Account>, op: UserOperation): Promise<UserOpResult>;
145
+ /** An error the bundler answered with, as opposed to one on the way to it. */
146
+ export declare class BundlerError extends Error {
147
+ readonly code: number;
148
+ constructor(method: string, code: number, message: string);
149
+ }
150
+ /** Sends a signed userOp through an ERC-4337 bundler (for Robinhood Chain, Alchemy's) and waits for it. */
151
+ export declare function sendUserOpToBundler(client: PublicClient, bundlerUrl: string, op: UserOperation, timeoutMs?: number): Promise<UserOpResult>;