@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,173 @@
1
+ import { type Address, type Hex } from "viem";
2
+ /** One step for the Gate: an adapter and its input. */
3
+ export interface Action {
4
+ adapter: Address;
5
+ data: Hex;
6
+ }
7
+ /** Uniswap v4 PoolKey; address(0) is native ETH. */
8
+ export interface PoolKey {
9
+ currency0: Address;
10
+ currency1: Address;
11
+ fee: number;
12
+ tickSpacing: number;
13
+ hooks: Address;
14
+ }
15
+ /** Morpho Blue MarketParams. */
16
+ export interface MarketParams {
17
+ loanToken: Address;
18
+ collateralToken: Address;
19
+ oracle: Address;
20
+ irm: Address;
21
+ lltv: bigint;
22
+ }
23
+ /** The Uniswap v4 pool id, which is the market UniswapV4Adapter and UniswapV4LiquidityAdapter report. */
24
+ export declare function poolId(key: PoolKey): Hex;
25
+ /** The Morpho Blue market id, which is the market MorphoBlueAdapter reports. */
26
+ export declare function morphoMarketId(m: MarketParams): Hex;
27
+ /** Action data for every adapter, in exactly the layout each adapter's plan() decodes. */
28
+ export declare const actions: {
29
+ /** Exact-input swap on one Uniswap v3 pool; address(0) is ETH. The minimum is raised to the vault's floor. */
30
+ uniswapV3Swap: (a: {
31
+ tokenIn: Address;
32
+ tokenOut: Address;
33
+ fee: number;
34
+ amountIn: bigint;
35
+ amountOutMinimum: bigint;
36
+ }) => Action;
37
+ /** Exact-input swap on one Uniswap v4 pool, hook included. */
38
+ uniswapV4Swap: (a: {
39
+ key: PoolKey;
40
+ zeroForOne: boolean;
41
+ amountIn: bigint;
42
+ amountOutMinimum: bigint;
43
+ }) => Action;
44
+ /** Supply or withdraw a Morpho Blue market's loan token; give either assets or shares, the other 0. */
45
+ morpho: (a: {
46
+ op: "supply" | "withdraw";
47
+ market: MarketParams;
48
+ assets: bigint;
49
+ shares: bigint;
50
+ }) => Action;
51
+ /** Buy or sell a Pons V2 token on its bonding curve; amounts in the launch's pair token (or ETH) and the token. */
52
+ pons: (a: {
53
+ side: "buy" | "sell";
54
+ token: Address;
55
+ amountIn: bigint;
56
+ minOut: bigint;
57
+ }) => Action;
58
+ /** Buy or sell through the Flap Portal (bonding curve, or the DEX after graduation). */
59
+ flap: (a: {
60
+ tokenIn: Address;
61
+ tokenOut: Address;
62
+ amountIn: bigint;
63
+ minOut: bigint;
64
+ }) => Action;
65
+ /** Deposit assets into, withdraw assets from, or redeem shares of a listed ERC-4626 vault. */
66
+ erc4626: (a: {
67
+ op: "deposit" | "withdraw" | "redeem";
68
+ target: Address;
69
+ amount: bigint;
70
+ }) => Action;
71
+ /** Send an ERC-20 to a recipient the owner listed for it (market: transferMarket(token, to)). */
72
+ transfer: (a: {
73
+ token: Address;
74
+ to: Address;
75
+ amount: bigint;
76
+ }) => Action;
77
+ /** Move a token or ETH (address(0)) to another vault of the family. */
78
+ familyTransfer: (a: {
79
+ token: Address;
80
+ to: Address;
81
+ amount: bigint;
82
+ }) => Action;
83
+ /** Wrap ETH into WETH or unwrap it. */
84
+ weth: (a: {
85
+ wrap: boolean;
86
+ amount: bigint;
87
+ }) => Action;
88
+ /** Bridge an ERC-20 through Across on a listed route; recipient and outputToken are bytes32. */
89
+ across: (b: {
90
+ destinationChainId: bigint;
91
+ recipient: Hex;
92
+ inputToken: Address;
93
+ outputToken: Hex;
94
+ minRate: bigint;
95
+ inputAmount: bigint;
96
+ outputAmount: bigint;
97
+ quoteTimestamp: number;
98
+ fillDeadline: number;
99
+ }) => Action;
100
+ /** Uniswap v3 positions: Mint and Increase take up to amount0/amount1; Decrease takes `liquidity`. */
101
+ uniswapV3Liquidity: (a: {
102
+ op: "mint";
103
+ token0: Address;
104
+ token1: Address;
105
+ fee: number;
106
+ tickLower: number;
107
+ tickUpper: number;
108
+ amount0: bigint;
109
+ amount1: bigint;
110
+ amount0Min: bigint;
111
+ amount1Min: bigint;
112
+ } | {
113
+ op: "increase" | "decrease";
114
+ tokenId: bigint;
115
+ liquidity: bigint;
116
+ amount0: bigint;
117
+ amount1: bigint;
118
+ amount0Min: bigint;
119
+ amount1Min: bigint;
120
+ } | {
121
+ op: "collect" | "burn";
122
+ tokenId: bigint;
123
+ }) => Action;
124
+ /** Uniswap v4 positions: amounts are maximums for Mint and Increase, minimums for Decrease and Burn. */
125
+ uniswapV4Liquidity: (a: {
126
+ op: "mint";
127
+ key: PoolKey;
128
+ tickLower: number;
129
+ tickUpper: number;
130
+ liquidity: bigint;
131
+ amount0: bigint;
132
+ amount1: bigint;
133
+ } | {
134
+ op: "increase" | "decrease";
135
+ tokenId: bigint;
136
+ liquidity: bigint;
137
+ amount0: bigint;
138
+ amount1: bigint;
139
+ } | {
140
+ op: "burn";
141
+ tokenId: bigint;
142
+ amount0Min: bigint;
143
+ amount1Min: bigint;
144
+ }) => Action;
145
+ };
146
+ /**
147
+ * The market id each adapter reports, which the owner allows with gate.setMarket(adapter, market, true).
148
+ * Each one matches the adapter's plan(); the tests check them against the contracts.
149
+ */
150
+ export declare const markets: {
151
+ /** The pool address from the official v3 factory (UniswapV3Adapter and UniswapV3LiquidityAdapter). */
152
+ uniswapV3Pool: (pool: Address) => `0x${string}`;
153
+ /** The PoolId (UniswapV4Adapter and UniswapV4LiquidityAdapter). */
154
+ uniswapV4Pool: (key: PoolKey) => `0x${string}`;
155
+ morpho: (m: MarketParams) => `0x${string}`;
156
+ /** The token's bonding curve. */
157
+ ponsCurve: (curve: Address) => `0x${string}`;
158
+ /** The pair, lower address first. */
159
+ flapPair: (a: Address, b: Address) => `0x${string}`;
160
+ erc4626: (target: Address) => `0x${string}`;
161
+ /** Lets the transfer adapter send `token` to `to`. */
162
+ transfer: (token: Address, to: Address) => `0x${string}`;
163
+ /** The token allowed to move inside the family. */
164
+ familyTransfer: (token: Address) => `0x${string}`;
165
+ weth: () => `0x${string}`;
166
+ acrossRoute: (r: {
167
+ destinationChainId: bigint;
168
+ recipient: Hex;
169
+ inputToken: Address;
170
+ outputToken: Hex;
171
+ minRate: bigint;
172
+ }) => `0x${string}`;
173
+ };
@@ -0,0 +1,159 @@
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
+ };
@@ -0,0 +1,41 @@
1
+ import { type Address, type Chain } from "viem";
2
+ /** Robinhood Chain mainnet. */
3
+ export declare const robinhood: Chain;
4
+ /** Mortise contracts on Robinhood Chain, as in deployments/4663.json. */
5
+ export declare const mortise: {
6
+ readonly rootValidator: "0xD10b7D017C00f078F4b39c348Ba50Af9422FC6cC";
7
+ readonly gate: "0x5713DF62cFa2dACe935fc207543817dd6348b567";
8
+ readonly setup: "0x0085085ce5771B03Fb0E9f4DbA802189cb9F9Dc5";
9
+ readonly factory: "0xCbB00808600C62C008C9F6cd3b8A0b0a1374d3A8";
10
+ readonly subVaults: "0x7d42FD334B2e342234eb47c0Caf4b3012260F81b";
11
+ readonly signer: "0x4b26cb1c6f31d1749F741cC7dF5e25B4CbfF827a";
12
+ readonly timelock: "0x45d02022232D78AA78716B837DDD63fb57Af40Be";
13
+ readonly router: "0x34f6Da2b9EE2e97d77b0320B05A1584804f4D89d";
14
+ readonly uniswapV3: "0x61DCf90FeE816EbD025766663cDF0598AE916f79";
15
+ readonly uniswapV3Liquidity: "0x6581543E5b0b42E3dD066e1eF6AF4C6a60309aF2";
16
+ readonly uniswapV4: "0x0A2C90C1CF8a827515971d9913E988f716DF73f6";
17
+ readonly uniswapV4Liquidity: "0x0Af90790a50295D396408a71F9cCC7b49bF4ec19";
18
+ readonly ponsTrader: "0x86775d6Ce307aAc55a42eB86612FC2b3aB55677a";
19
+ readonly pons: "0x16Cb81C4C61FA7064D7325B8fA344E45833A391D";
20
+ readonly flap: "0x869bb75F26D03a4B23952f1A29960bE015eE2bDa";
21
+ readonly morphoBlue: "0xA972dF5d1196f5a0247de2d81fDAf801796C1D16";
22
+ readonly erc4626: "0xD4d2827b2a8580bd6DbF2F0Bdcce239F795aAa61";
23
+ readonly transfer: "0x9171159781C91133009EEfEb528397b256aEf347";
24
+ readonly weth: "0xcb7EE95d267676Cc875a64A293A353604d497F30";
25
+ readonly across: "0x3716d6CD2D06CEC9a1e9067eaEdD2D2F7467bD21";
26
+ readonly familyTransfer: "0x398f4003F11197d70744D14423114D81280B5042";
27
+ readonly dca: "0xC319309684725a0cF3F712F630A9e7c63ACE345a";
28
+ readonly automation: "0x2aFf436334EbcafA4233363fcAf95bFE63219d7d";
29
+ readonly rebalance: "0xe6e501a2A6422587E8c81813B805D52B4b4fFc57";
30
+ };
31
+ /** The block of the first Mortise deployment transaction, where log queries can start. */
32
+ export declare const deployBlock = 127492191n;
33
+ /** Contracts Mortise builds on. */
34
+ export declare const external: {
35
+ readonly entryPoint: "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
36
+ readonly safe7579: "0x7579d6Dd6F1e9F57729a59049174ed6Fd7fC0003";
37
+ readonly weth: "0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73";
38
+ readonly permit2: "0x000000000022D473030F116dDEE9F6B43aC78BA3";
39
+ };
40
+ /** ETH, wherever Mortise takes a token address. */
41
+ export declare const ETH: Address;
@@ -0,0 +1,47 @@
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";
@@ -0,0 +1,91 @@
1
+ import { type Account, type Address, type Chain, type Hex, type PublicClient, type Transport, type WalletClient } from "viem";
2
+ import type { Action } from "./actions.ts";
3
+ type Wallet = WalletClient<Transport, Chain, Account>;
4
+ /** What an adapter would do for an action: the market it needs and every call and token involved. */
5
+ export declare function planAction(client: PublicClient, vault: Address, action: Action): Promise<{
6
+ market: `0x${string}`;
7
+ calls: readonly {
8
+ target: `0x${string}`;
9
+ value: bigint;
10
+ callData: `0x${string}`;
11
+ }[];
12
+ tokens: readonly `0x${string}`[];
13
+ isSwap: boolean;
14
+ swapIn: `0x${string}`;
15
+ swapOut: `0x${string}`;
16
+ }>;
17
+ /**
18
+ * Runs the actions as the agent without sending anything, exactly as the Gate would, and returns each
19
+ * action's call results. Throws with the Gate's or adapter's error otherwise (see mortiseErrorName).
20
+ */
21
+ export declare function simulateActions(client: PublicClient, agent: Address, vault: Address, actions: Action[]): Promise<readonly (readonly `0x${string}`[])[]>;
22
+ export interface ActionReceipt {
23
+ transactionHash: Hex;
24
+ gasUsed: bigint;
25
+ executed: {
26
+ adapter: Address;
27
+ market: Hex;
28
+ }[];
29
+ }
30
+ /**
31
+ * Hooks into a send. `shouldSend` is asked right before signing and again right before broadcasting; false
32
+ * stops the send, so nothing goes out. `onSigned` gets the hash just before the broadcast starts.
33
+ */
34
+ export interface SendOptions {
35
+ shouldSend?: () => boolean;
36
+ onSigned?: (hash: Hex) => void;
37
+ }
38
+ /** The transaction was mined and reverted. */
39
+ export declare class TransactionRevertedError extends Error {
40
+ readonly transactionHash: Hex;
41
+ constructor(hash: Hex);
42
+ }
43
+ /** Simulates, then sends the actions from the agent's own key, and returns the transaction hash at once. */
44
+ export declare function sendActions(client: PublicClient, wallet: Wallet, vault: Address, actions: Action[], o?: SendOptions): Promise<Hex>;
45
+ /** Simulates, then sends the actions from the agent's own key and waits for them. The agent pays the gas. */
46
+ export declare function executeActions(client: PublicClient, wallet: Wallet, vault: Address, actions: Action[]): Promise<ActionReceipt>;
47
+ /** Sends a trigger of an enabled module (the module decides who may trigger it, e.g. its keeper); returns the hash. */
48
+ export declare function sendTrigger(client: PublicClient, wallet: Wallet, vault: Address, module: Address, o?: SendOptions): Promise<Hex>;
49
+ /** Runs what an enabled module proposes now and waits for it. */
50
+ export declare function triggerModule(client: PublicClient, wallet: Wallet, vault: Address, module: Address): Promise<ActionReceipt>;
51
+ /** Waits for a Gate transaction and lists the actions it ran. Throws on revert or after `timeoutMs`. */
52
+ export declare function actionReceipt(client: PublicClient, hash: Hex, timeoutMs?: number): Promise<ActionReceipt>;
53
+ /**
54
+ * What an actor (an agent, or a module) may do in a vault right now: whether it is live, which adapters it may
55
+ * use and with which markets, and how much of each token is left under its caps in the current window.
56
+ */
57
+ export declare function permissions(client: PublicClient, vault: Address, actor: Address, q: {
58
+ adapters: Address[];
59
+ tokens: Address[];
60
+ markets?: {
61
+ adapter: Address;
62
+ market: Hex;
63
+ }[];
64
+ }): Promise<{
65
+ installed: boolean;
66
+ live: boolean;
67
+ until: bigint;
68
+ paused: boolean;
69
+ openFloor: boolean;
70
+ adapters: {
71
+ adapter: `0x${string}`;
72
+ canUse: boolean;
73
+ openMarkets: boolean;
74
+ }[];
75
+ caps: {
76
+ token: `0x${string}`;
77
+ limit: bigint;
78
+ period: bigint;
79
+ used: bigint;
80
+ left: bigint;
81
+ resetsAt: bigint | undefined;
82
+ }[];
83
+ markets: {
84
+ allowed: boolean;
85
+ adapter: Address;
86
+ market: Hex;
87
+ }[];
88
+ }>;
89
+ /** The floor the vault set for selling tokenIn for tokenOut, in raw tokenOut per 1e36 raw tokenIn (0 = none). */
90
+ export declare function minRate(client: PublicClient, vault: Address, tokenIn: Address, tokenOut: Address): Promise<bigint>;
91
+ export {};
package/dist/agent.js ADDED
@@ -0,0 +1,115 @@
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
+ }