@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/actions.js
DELETED
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
import { encodeAbiParameters, keccak256, pad } from "viem";
|
|
2
|
-
import { external, mortise } from "./addresses.js";
|
|
3
|
-
const poolKeyType = {
|
|
4
|
-
type: "tuple",
|
|
5
|
-
components: [
|
|
6
|
-
{ name: "currency0", type: "address" },
|
|
7
|
-
{ name: "currency1", type: "address" },
|
|
8
|
-
{ name: "fee", type: "uint24" },
|
|
9
|
-
{ name: "tickSpacing", type: "int24" },
|
|
10
|
-
{ name: "hooks", type: "address" },
|
|
11
|
-
],
|
|
12
|
-
};
|
|
13
|
-
const marketParamsType = {
|
|
14
|
-
type: "tuple",
|
|
15
|
-
components: [
|
|
16
|
-
{ name: "loanToken", type: "address" },
|
|
17
|
-
{ name: "collateralToken", type: "address" },
|
|
18
|
-
{ name: "oracle", type: "address" },
|
|
19
|
-
{ name: "irm", type: "address" },
|
|
20
|
-
{ name: "lltv", type: "uint256" },
|
|
21
|
-
],
|
|
22
|
-
};
|
|
23
|
-
/** The Uniswap v4 pool id, which is the market UniswapV4Adapter and UniswapV4LiquidityAdapter report. */
|
|
24
|
-
export function poolId(key) {
|
|
25
|
-
return keccak256(encodeAbiParameters([poolKeyType], [key]));
|
|
26
|
-
}
|
|
27
|
-
/** The Morpho Blue market id, which is the market MorphoBlueAdapter reports. */
|
|
28
|
-
export function morphoMarketId(m) {
|
|
29
|
-
return keccak256(encodeAbiParameters([marketParamsType], [m]));
|
|
30
|
-
}
|
|
31
|
-
/** Action data for every adapter, in exactly the layout each adapter's plan() decodes. */
|
|
32
|
-
export const actions = {
|
|
33
|
-
/** Exact-input swap on one Uniswap v3 pool; address(0) is ETH. The minimum is raised to the vault's floor. */
|
|
34
|
-
uniswapV3Swap: (a) => ({
|
|
35
|
-
adapter: mortise.uniswapV3,
|
|
36
|
-
data: encodeAbiParameters([{ type: "tuple", components: [{ name: "tokenIn", type: "address" }, { name: "tokenOut", type: "address" }, { name: "fee", type: "uint24" }, { name: "amountIn", type: "uint128" }, { name: "amountOutMinimum", type: "uint128" }] }], [a]),
|
|
37
|
-
}),
|
|
38
|
-
/** Exact-input swap on one Uniswap v4 pool, hook included. */
|
|
39
|
-
uniswapV4Swap: (a) => ({
|
|
40
|
-
adapter: mortise.uniswapV4,
|
|
41
|
-
data: encodeAbiParameters([poolKeyType, { type: "bool" }, { type: "uint128" }, { type: "uint128" }], [a.key, a.zeroForOne, a.amountIn, a.amountOutMinimum]),
|
|
42
|
-
}),
|
|
43
|
-
/** Supply or withdraw a Morpho Blue market's loan token; give either assets or shares, the other 0. */
|
|
44
|
-
morpho: (a) => ({
|
|
45
|
-
adapter: mortise.morphoBlue,
|
|
46
|
-
data: encodeAbiParameters([{ type: "uint8" }, marketParamsType, { type: "uint256" }, { type: "uint256" }], [a.op === "supply" ? 0 : 1, a.market, a.assets, a.shares]),
|
|
47
|
-
}),
|
|
48
|
-
/** Buy or sell a Pons V2 token on its bonding curve; amounts in the launch's pair token (or ETH) and the token. */
|
|
49
|
-
pons: (a) => ({
|
|
50
|
-
adapter: mortise.pons,
|
|
51
|
-
data: encodeAbiParameters([{ type: "bool" }, { type: "address" }, { type: "uint256" }, { type: "uint256" }], [a.side === "buy", a.token, a.amountIn, a.minOut]),
|
|
52
|
-
}),
|
|
53
|
-
/** Buy or sell through the Flap Portal (bonding curve, or the DEX after graduation). */
|
|
54
|
-
flap: (a) => ({
|
|
55
|
-
adapter: mortise.flap,
|
|
56
|
-
data: encodeAbiParameters([{ type: "address" }, { type: "address" }, { type: "uint256" }, { type: "uint256" }], [a.tokenIn, a.tokenOut, a.amountIn, a.minOut]),
|
|
57
|
-
}),
|
|
58
|
-
/** Deposit assets into, withdraw assets from, or redeem shares of a listed ERC-4626 vault. */
|
|
59
|
-
erc4626: (a) => ({
|
|
60
|
-
adapter: mortise.erc4626,
|
|
61
|
-
data: encodeAbiParameters([{ type: "uint8" }, { type: "address" }, { type: "uint256" }], [{ deposit: 0, withdraw: 1, redeem: 2 }[a.op], a.target, a.amount]),
|
|
62
|
-
}),
|
|
63
|
-
/** Send an ERC-20 to a recipient the owner listed for it (market: transferMarket(token, to)). */
|
|
64
|
-
transfer: (a) => ({
|
|
65
|
-
adapter: mortise.transfer,
|
|
66
|
-
data: encodeAbiParameters([{ type: "address" }, { type: "address" }, { type: "uint256" }], [a.token, a.to, a.amount]),
|
|
67
|
-
}),
|
|
68
|
-
/** Move a token or ETH (address(0)) to another vault of the family. */
|
|
69
|
-
familyTransfer: (a) => ({
|
|
70
|
-
adapter: mortise.familyTransfer,
|
|
71
|
-
data: encodeAbiParameters([{ type: "address" }, { type: "address" }, { type: "uint256" }], [a.token, a.to, a.amount]),
|
|
72
|
-
}),
|
|
73
|
-
/** Wrap ETH into WETH or unwrap it. */
|
|
74
|
-
weth: (a) => ({
|
|
75
|
-
adapter: mortise.weth,
|
|
76
|
-
data: encodeAbiParameters([{ type: "bool" }, { type: "uint256" }], [a.wrap, a.amount]),
|
|
77
|
-
}),
|
|
78
|
-
/** Bridge an ERC-20 through Across on a listed route; recipient and outputToken are bytes32. */
|
|
79
|
-
across: (b) => ({
|
|
80
|
-
adapter: mortise.across,
|
|
81
|
-
data: encodeAbiParameters([
|
|
82
|
-
{
|
|
83
|
-
type: "tuple",
|
|
84
|
-
components: [
|
|
85
|
-
{ name: "destinationChainId", type: "uint256" },
|
|
86
|
-
{ name: "recipient", type: "bytes32" },
|
|
87
|
-
{ name: "inputToken", type: "address" },
|
|
88
|
-
{ name: "outputToken", type: "bytes32" },
|
|
89
|
-
{ name: "minRate", type: "uint256" },
|
|
90
|
-
{ name: "inputAmount", type: "uint256" },
|
|
91
|
-
{ name: "outputAmount", type: "uint256" },
|
|
92
|
-
{ name: "quoteTimestamp", type: "uint32" },
|
|
93
|
-
{ name: "fillDeadline", type: "uint32" },
|
|
94
|
-
],
|
|
95
|
-
},
|
|
96
|
-
], [b]),
|
|
97
|
-
}),
|
|
98
|
-
/** Uniswap v3 positions: Mint and Increase take up to amount0/amount1; Decrease takes `liquidity`. */
|
|
99
|
-
uniswapV3Liquidity: (a) => {
|
|
100
|
-
let op;
|
|
101
|
-
let args;
|
|
102
|
-
if (a.op === "mint") {
|
|
103
|
-
op = 0;
|
|
104
|
-
args = encodeAbiParameters([{ type: "tuple", components: [{ name: "token0", type: "address" }, { name: "token1", type: "address" }, { name: "fee", type: "uint24" }, { name: "tickLower", type: "int24" }, { name: "tickUpper", type: "int24" }, { name: "amount0", type: "uint256" }, { name: "amount1", type: "uint256" }, { name: "amount0Min", type: "uint256" }, { name: "amount1Min", type: "uint256" }] }], [a]);
|
|
105
|
-
}
|
|
106
|
-
else if (a.op === "increase" || a.op === "decrease") {
|
|
107
|
-
op = a.op === "increase" ? 1 : 2;
|
|
108
|
-
args = encodeAbiParameters([{ type: "tuple", components: [{ name: "tokenId", type: "uint256" }, { name: "liquidity", type: "uint128" }, { name: "amount0", type: "uint256" }, { name: "amount1", type: "uint256" }, { name: "amount0Min", type: "uint256" }, { name: "amount1Min", type: "uint256" }] }], [a]);
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
op = a.op === "collect" ? 3 : 4;
|
|
112
|
-
args = encodeAbiParameters([{ type: "uint256" }], [a.tokenId]);
|
|
113
|
-
}
|
|
114
|
-
return { adapter: mortise.uniswapV3Liquidity, data: encodeAbiParameters([{ type: "uint8" }, { type: "bytes" }], [op, args]) };
|
|
115
|
-
},
|
|
116
|
-
/** Uniswap v4 positions: amounts are maximums for Mint and Increase, minimums for Decrease and Burn. */
|
|
117
|
-
uniswapV4Liquidity: (a) => {
|
|
118
|
-
let op;
|
|
119
|
-
let args;
|
|
120
|
-
if (a.op === "mint") {
|
|
121
|
-
op = 0;
|
|
122
|
-
args = encodeAbiParameters([{ type: "tuple", components: [{ name: "key", type: "tuple", components: poolKeyType.components }, { name: "tickLower", type: "int24" }, { name: "tickUpper", type: "int24" }, { name: "liquidity", type: "uint256" }, { name: "amount0", type: "uint128" }, { name: "amount1", type: "uint128" }] }], [a]);
|
|
123
|
-
}
|
|
124
|
-
else if (a.op !== "burn") {
|
|
125
|
-
op = a.op === "increase" ? 1 : 2;
|
|
126
|
-
args = encodeAbiParameters([{ type: "tuple", components: [{ name: "tokenId", type: "uint256" }, { name: "liquidity", type: "uint256" }, { name: "amount0", type: "uint128" }, { name: "amount1", type: "uint128" }] }], [a]);
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
op = 3;
|
|
130
|
-
args = encodeAbiParameters([{ type: "uint256" }, { type: "uint128" }, { type: "uint128" }], [a.tokenId, a.amount0Min, a.amount1Min]);
|
|
131
|
-
}
|
|
132
|
-
return { adapter: mortise.uniswapV4Liquidity, data: encodeAbiParameters([{ type: "uint8" }, { type: "bytes" }], [op, args]) };
|
|
133
|
-
},
|
|
134
|
-
};
|
|
135
|
-
// Lowercase, as bytes32 values come back from the chain.
|
|
136
|
-
const addressMarket = (a) => pad(a.toLowerCase(), { size: 32 });
|
|
137
|
-
const pairHash = (a, b) => keccak256(encodeAbiParameters([{ type: "address" }, { type: "address" }], [a, b]));
|
|
138
|
-
/**
|
|
139
|
-
* The market id each adapter reports, which the owner allows with gate.setMarket(adapter, market, true).
|
|
140
|
-
* Each one matches the adapter's plan(); the tests check them against the contracts.
|
|
141
|
-
*/
|
|
142
|
-
export const markets = {
|
|
143
|
-
/** The pool address from the official v3 factory (UniswapV3Adapter and UniswapV3LiquidityAdapter). */
|
|
144
|
-
uniswapV3Pool: (pool) => addressMarket(pool),
|
|
145
|
-
/** The PoolId (UniswapV4Adapter and UniswapV4LiquidityAdapter). */
|
|
146
|
-
uniswapV4Pool: (key) => poolId(key),
|
|
147
|
-
morpho: (m) => morphoMarketId(m),
|
|
148
|
-
/** The token's bonding curve. */
|
|
149
|
-
ponsCurve: (curve) => addressMarket(curve),
|
|
150
|
-
/** The pair, lower address first. */
|
|
151
|
-
flapPair: (a, b) => (BigInt(a) < BigInt(b) ? pairHash(a, b) : pairHash(b, a)),
|
|
152
|
-
erc4626: (target) => addressMarket(target),
|
|
153
|
-
/** Lets the transfer adapter send `token` to `to`. */
|
|
154
|
-
transfer: (token, to) => pairHash(token, to),
|
|
155
|
-
/** The token allowed to move inside the family. */
|
|
156
|
-
familyTransfer: (token) => addressMarket(token),
|
|
157
|
-
weth: () => addressMarket(external.weth),
|
|
158
|
-
acrossRoute: (r) => keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "bytes32" }, { type: "address" }, { type: "bytes32" }, { type: "uint256" }], [r.destinationChainId, r.recipient, r.inputToken, r.outputToken, r.minRate])),
|
|
159
|
-
};
|
package/dist/addresses.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { defineChain } from "viem";
|
|
2
|
-
/** Robinhood Chain mainnet. */
|
|
3
|
-
export const robinhood = defineChain({
|
|
4
|
-
id: 4663,
|
|
5
|
-
name: "Robinhood Chain",
|
|
6
|
-
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
7
|
-
rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } },
|
|
8
|
-
blockExplorers: { default: { name: "Blockscout", url: "https://robinhoodchain.blockscout.com" } },
|
|
9
|
-
});
|
|
10
|
-
/** Mortise contracts on Robinhood Chain, as in deployments/4663.json. */
|
|
11
|
-
export const mortise = {
|
|
12
|
-
rootValidator: "0xD10b7D017C00f078F4b39c348Ba50Af9422FC6cC",
|
|
13
|
-
gate: "0x5713DF62cFa2dACe935fc207543817dd6348b567",
|
|
14
|
-
setup: "0x0085085ce5771B03Fb0E9f4DbA802189cb9F9Dc5",
|
|
15
|
-
factory: "0xCbB00808600C62C008C9F6cd3b8A0b0a1374d3A8",
|
|
16
|
-
subVaults: "0x7d42FD334B2e342234eb47c0Caf4b3012260F81b",
|
|
17
|
-
signer: "0x4b26cb1c6f31d1749F741cC7dF5e25B4CbfF827a",
|
|
18
|
-
timelock: "0x45d02022232D78AA78716B837DDD63fb57Af40Be",
|
|
19
|
-
router: "0x34f6Da2b9EE2e97d77b0320B05A1584804f4D89d",
|
|
20
|
-
uniswapV3: "0x61DCf90FeE816EbD025766663cDF0598AE916f79",
|
|
21
|
-
uniswapV3Liquidity: "0x6581543E5b0b42E3dD066e1eF6AF4C6a60309aF2",
|
|
22
|
-
uniswapV4: "0x0A2C90C1CF8a827515971d9913E988f716DF73f6",
|
|
23
|
-
uniswapV4Liquidity: "0x0Af90790a50295D396408a71F9cCC7b49bF4ec19",
|
|
24
|
-
ponsTrader: "0x86775d6Ce307aAc55a42eB86612FC2b3aB55677a",
|
|
25
|
-
pons: "0x16Cb81C4C61FA7064D7325B8fA344E45833A391D",
|
|
26
|
-
flap: "0x869bb75F26D03a4B23952f1A29960bE015eE2bDa",
|
|
27
|
-
morphoBlue: "0xA972dF5d1196f5a0247de2d81fDAf801796C1D16",
|
|
28
|
-
erc4626: "0xD4d2827b2a8580bd6DbF2F0Bdcce239F795aAa61",
|
|
29
|
-
transfer: "0x9171159781C91133009EEfEb528397b256aEf347",
|
|
30
|
-
weth: "0xcb7EE95d267676Cc875a64A293A353604d497F30",
|
|
31
|
-
across: "0x3716d6CD2D06CEC9a1e9067eaEdD2D2F7467bD21",
|
|
32
|
-
familyTransfer: "0x398f4003F11197d70744D14423114D81280B5042",
|
|
33
|
-
dca: "0xC319309684725a0cF3F712F630A9e7c63ACE345a",
|
|
34
|
-
automation: "0x2aFf436334EbcafA4233363fcAf95bFE63219d7d",
|
|
35
|
-
rebalance: "0xe6e501a2A6422587E8c81813B805D52B4b4fFc57",
|
|
36
|
-
};
|
|
37
|
-
/** The block of the first Mortise deployment transaction, where log queries can start. */
|
|
38
|
-
export const deployBlock = 127492191n;
|
|
39
|
-
/** Contracts Mortise builds on. */
|
|
40
|
-
export const external = {
|
|
41
|
-
entryPoint: "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
|
|
42
|
-
safe7579: "0x7579d6Dd6F1e9F57729a59049174ed6Fd7fC0003",
|
|
43
|
-
weth: "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73",
|
|
44
|
-
permit2: "0x000000000022D473030F116dDEE9F6B43aC78BA3",
|
|
45
|
-
};
|
|
46
|
-
/** ETH, wherever Mortise takes a token address. */
|
|
47
|
-
export const ETH = "0x0000000000000000000000000000000000000000";
|
package/dist/agent.js
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { decodeEventLog, encodeFunctionData, keccak256 } from "viem";
|
|
2
|
-
import { adapterAbi, gateAbi } from "./abis.js";
|
|
3
|
-
import { mortise } from "./addresses.js";
|
|
4
|
-
/** What an adapter would do for an action: the market it needs and every call and token involved. */
|
|
5
|
-
export function planAction(client, vault, action) {
|
|
6
|
-
return client.readContract({ address: action.adapter, abi: adapterAbi, functionName: "plan", args: [vault, action.data] });
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* Runs the actions as the agent without sending anything, exactly as the Gate would, and returns each
|
|
10
|
-
* action's call results. Throws with the Gate's or adapter's error otherwise (see mortiseErrorName).
|
|
11
|
-
*/
|
|
12
|
-
export async function simulateActions(client, agent, vault, actions) {
|
|
13
|
-
const { result } = await client.simulateContract({ account: agent, address: mortise.gate, abi: gateAbi, functionName: "execute", args: [vault, actions] });
|
|
14
|
-
return result;
|
|
15
|
-
}
|
|
16
|
-
/** The transaction was mined and reverted. */
|
|
17
|
-
export class TransactionRevertedError extends Error {
|
|
18
|
-
transactionHash;
|
|
19
|
-
constructor(hash) {
|
|
20
|
-
super(`transaction ${hash} reverted`);
|
|
21
|
-
this.name = "TransactionRevertedError";
|
|
22
|
-
this.transactionHash = hash;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
/** Simulates, then sends the actions from the agent's own key, and returns the transaction hash at once. */
|
|
26
|
-
export async function sendActions(client, wallet, vault, actions, o = {}) {
|
|
27
|
-
const { request } = await client.simulateContract({ account: wallet.account, address: mortise.gate, abi: gateAbi, functionName: "execute", args: [vault, actions] });
|
|
28
|
-
return sendSigned(wallet, encodeFunctionData({ abi: gateAbi, functionName: "execute", args: request.args }), o);
|
|
29
|
-
}
|
|
30
|
-
/** Simulates, then sends the actions from the agent's own key and waits for them. The agent pays the gas. */
|
|
31
|
-
export async function executeActions(client, wallet, vault, actions) {
|
|
32
|
-
return actionReceipt(client, await sendActions(client, wallet, vault, actions));
|
|
33
|
-
}
|
|
34
|
-
/** Sends a trigger of an enabled module (the module decides who may trigger it, e.g. its keeper); returns the hash. */
|
|
35
|
-
export async function sendTrigger(client, wallet, vault, module, o = {}) {
|
|
36
|
-
const { request } = await client.simulateContract({ account: wallet.account, address: mortise.gate, abi: gateAbi, functionName: "trigger", args: [vault, module] });
|
|
37
|
-
return sendSigned(wallet, encodeFunctionData({ abi: gateAbi, functionName: "trigger", args: request.args }), o);
|
|
38
|
-
}
|
|
39
|
-
/** Runs what an enabled module proposes now and waits for it. */
|
|
40
|
-
export async function triggerModule(client, wallet, vault, module) {
|
|
41
|
-
return actionReceipt(client, await sendTrigger(client, wallet, vault, module));
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* With a local key the transaction is signed here, so its hash is known before it is broadcast: if the RPC then
|
|
45
|
-
* fails to answer, the caller still has the hash to check instead of sending again.
|
|
46
|
-
*/
|
|
47
|
-
async function sendSigned(wallet, data, o) {
|
|
48
|
-
if (wallet.account.type !== "local")
|
|
49
|
-
return wallet.sendTransaction({ to: mortise.gate, data });
|
|
50
|
-
const stopped = () => new Error("the send was stopped before the transaction went out");
|
|
51
|
-
const prepared = await wallet.prepareTransactionRequest({ to: mortise.gate, data });
|
|
52
|
-
if (o.shouldSend && !o.shouldSend())
|
|
53
|
-
throw stopped();
|
|
54
|
-
const signed = await wallet.signTransaction(prepared);
|
|
55
|
-
const hash = keccak256(signed);
|
|
56
|
-
// No await between this check and the start of the broadcast, so a stop can never land in between.
|
|
57
|
-
if (o.shouldSend && !o.shouldSend())
|
|
58
|
-
throw stopped();
|
|
59
|
-
o.onSigned?.(hash);
|
|
60
|
-
await wallet.sendRawTransaction({ serializedTransaction: signed });
|
|
61
|
-
return hash;
|
|
62
|
-
}
|
|
63
|
-
/** Waits for a Gate transaction and lists the actions it ran. Throws on revert or after `timeoutMs`. */
|
|
64
|
-
export async function actionReceipt(client, hash, timeoutMs = 180_000) {
|
|
65
|
-
const receipt = await client.waitForTransactionReceipt({ hash, timeout: timeoutMs });
|
|
66
|
-
if (receipt.status !== "success")
|
|
67
|
-
throw new TransactionRevertedError(hash);
|
|
68
|
-
const executed = [];
|
|
69
|
-
for (const log of receipt.logs) {
|
|
70
|
-
if (log.address.toLowerCase() !== mortise.gate.toLowerCase())
|
|
71
|
-
continue;
|
|
72
|
-
try {
|
|
73
|
-
const ev = decodeEventLog({ abi: gateAbi, data: log.data, topics: log.topics });
|
|
74
|
-
if (ev.eventName === "ActionExecuted")
|
|
75
|
-
executed.push({ adapter: ev.args.adapter, market: ev.args.market });
|
|
76
|
-
}
|
|
77
|
-
catch {
|
|
78
|
-
// Only ActionExecuted is reported.
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
return { transactionHash: hash, gasUsed: receipt.gasUsed, executed };
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* What an actor (an agent, or a module) may do in a vault right now: whether it is live, which adapters it may
|
|
85
|
-
* use and with which markets, and how much of each token is left under its caps in the current window.
|
|
86
|
-
*/
|
|
87
|
-
export async function permissions(client, vault, actor, q) {
|
|
88
|
-
const g = { address: mortise.gate, abi: gateAbi };
|
|
89
|
-
const [installed, live, until, paused, openFloor, block] = await Promise.all([
|
|
90
|
-
client.readContract({ ...g, functionName: "installed", args: [vault] }),
|
|
91
|
-
client.readContract({ ...g, functionName: "isAgent", args: [vault, actor] }),
|
|
92
|
-
client.readContract({ ...g, functionName: "agentUntil", args: [vault, actor] }),
|
|
93
|
-
client.readContract({ ...g, functionName: "isPaused", args: [vault] }),
|
|
94
|
-
client.readContract({ ...g, functionName: "hasOpenFloor", args: [vault, actor] }),
|
|
95
|
-
client.getBlock(),
|
|
96
|
-
]);
|
|
97
|
-
const adapters = await Promise.all(q.adapters.map(async (adapter) => ({
|
|
98
|
-
adapter,
|
|
99
|
-
canUse: await client.readContract({ ...g, functionName: "canUse", args: [vault, actor, adapter] }),
|
|
100
|
-
openMarkets: await client.readContract({ ...g, functionName: "hasOpenMarkets", args: [vault, actor, adapter] }),
|
|
101
|
-
})));
|
|
102
|
-
const now = block.timestamp;
|
|
103
|
-
const caps = await Promise.all(q.tokens.map(async (token) => {
|
|
104
|
-
const c = await client.readContract({ ...g, functionName: "cap", args: [vault, actor, token] });
|
|
105
|
-
const fresh = c.period === 0n || now >= c.windowStart + c.period;
|
|
106
|
-
const used = fresh ? 0n : c.used;
|
|
107
|
-
return { token, limit: c.limit, period: c.period, used, left: c.limit > used ? c.limit - used : 0n, resetsAt: fresh ? undefined : c.windowStart + c.period };
|
|
108
|
-
}));
|
|
109
|
-
const markets = await Promise.all((q.markets ?? []).map(async (m) => ({ ...m, allowed: await client.readContract({ ...g, functionName: "isMarket", args: [vault, m.adapter, m.market] }) })));
|
|
110
|
-
return { installed, live, until, paused, openFloor, adapters, caps, markets };
|
|
111
|
-
}
|
|
112
|
-
/** The floor the vault set for selling tokenIn for tokenOut, in raw tokenOut per 1e36 raw tokenIn (0 = none). */
|
|
113
|
-
export function minRate(client, vault, tokenIn, tokenOut) {
|
|
114
|
-
return client.readContract({ address: mortise.gate, abi: gateAbi, functionName: "minRate", args: [vault, tokenIn, tokenOut] });
|
|
115
|
-
}
|
package/dist/calls.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
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
|
-
};
|
package/dist/errors.js
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/modules.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
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
|
-
}
|