@rhinestone/sdk 2.5.0 → 2.6.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.
Files changed (39) hide show
  1. package/dist/src/api/account.d.ts.map +1 -1
  2. package/dist/src/api/account.js +118 -0
  3. package/dist/src/api/compose-types.d.ts +7 -0
  4. package/dist/src/api/compose-types.d.ts.map +1 -1
  5. package/dist/src/clients/orchestrator/client.js +1 -1
  6. package/dist/src/clients/orchestrator/public.d.ts +8 -1
  7. package/dist/src/clients/orchestrator/public.d.ts.map +1 -1
  8. package/dist/src/clients/orchestrator/types.d.ts +6 -0
  9. package/dist/src/clients/orchestrator/types.d.ts.map +1 -1
  10. package/dist/src/config/account.d.ts +130 -6
  11. package/dist/src/config/account.d.ts.map +1 -1
  12. package/dist/src/index.d.ts +2 -2
  13. package/dist/src/index.d.ts.map +1 -1
  14. package/dist/src/modules/validators/permissions.d.ts +13 -0
  15. package/dist/src/modules/validators/permissions.d.ts.map +1 -1
  16. package/dist/src/modules/validators/permissions.js +140 -2
  17. package/dist/src/modules/validators/smart-sessions/resolve.d.ts.map +1 -1
  18. package/dist/src/modules/validators/smart-sessions/resolve.js +112 -13
  19. package/dist/src/modules/validators/smart-sessions/swap/fynd.d.ts +92 -0
  20. package/dist/src/modules/validators/smart-sessions/swap/fynd.d.ts.map +1 -0
  21. package/dist/src/modules/validators/smart-sessions/swap/fynd.js +101 -0
  22. package/dist/src/modules/validators/smart-sessions/swap/rhinestone.d.ts +147 -0
  23. package/dist/src/modules/validators/smart-sessions/swap/rhinestone.d.ts.map +1 -0
  24. package/dist/src/modules/validators/smart-sessions/swap/rhinestone.js +305 -0
  25. package/dist/src/modules/validators/smart-sessions/swap/rules.d.ts +73 -0
  26. package/dist/src/modules/validators/smart-sessions/swap/rules.d.ts.map +1 -0
  27. package/dist/src/modules/validators/smart-sessions/swap/rules.js +105 -0
  28. package/dist/src/modules/validators/smart-sessions/swap/scope.d.ts +31 -0
  29. package/dist/src/modules/validators/smart-sessions/swap/scope.d.ts.map +1 -0
  30. package/dist/src/modules/validators/smart-sessions/swap/scope.js +168 -0
  31. package/dist/src/modules/validators/smart-sessions/swap/zero-ex.d.ts +143 -0
  32. package/dist/src/modules/validators/smart-sessions/swap/zero-ex.d.ts.map +1 -0
  33. package/dist/src/modules/validators/smart-sessions/swap/zero-ex.js +164 -0
  34. package/dist/src/modules/validators/smart-sessions/types.d.ts +78 -0
  35. package/dist/src/modules/validators/smart-sessions/types.d.ts.map +1 -1
  36. package/dist/src/smart-sessions/index.d.ts +10 -5
  37. package/dist/src/smart-sessions/index.d.ts.map +1 -1
  38. package/dist/src/smart-sessions/index.js +6 -1
  39. package/package.json +1 -1
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Shared rule builders for swap-venue scoping.
3
+ *
4
+ * Venue modules describe *what* to pin; these turn that into policy rules with
5
+ * the security-relevant details (cumulative accumulation, zero native value)
6
+ * decided in exactly one place.
7
+ */
8
+ /**
9
+ * Pin a calldata word to an exact numeric value.
10
+ *
11
+ * Used for ABI *shape* words — array pointers, lengths, element offsets. Pinning
12
+ * those is what makes pinning anything inside a dynamic tail sound: without
13
+ * them a caller can re-lay-out the encoding so a fixed offset lands on a
14
+ * different word, and the rule silently validates the wrong bytes.
15
+ */
16
+ export function pinValue(calldataOffset, referenceValue) {
17
+ return { condition: 'equal', calldataOffset, referenceValue };
18
+ }
19
+ /** Pin a calldata word to an exact 32-byte value. */
20
+ export function pinWord(calldataOffset, referenceValue) {
21
+ return { condition: 'equal', calldataOffset, referenceValue };
22
+ }
23
+ /** Pin a calldata word to an exact address. */
24
+ export function pin(calldataOffset, referenceValue) {
25
+ return { condition: 'equal', calldataOffset, referenceValue };
26
+ }
27
+ /**
28
+ * Cap a swap's own sell amount, cumulatively across every call.
29
+ *
30
+ * `usageLimit` is what makes this cumulative: it sets `isLimited` + `usage.limit`
31
+ * on-chain, so the policy accumulates the observed value and reverts once the
32
+ * running total would exceed the cap.
33
+ *
34
+ * A bare comparison would be per-call, which is not enough. A reusable session
35
+ * could then run N swaps of `cap` each, and any allowance that already existed
36
+ * before the session was created is spent without the approve's spending-limit
37
+ * ever observing it.
38
+ */
39
+ export function cumulativeCap(calldataOffset, cap) {
40
+ return {
41
+ condition: 'lessThanOrEqual',
42
+ calldataOffset,
43
+ referenceValue: cap,
44
+ usageLimit: cap,
45
+ };
46
+ }
47
+ /**
48
+ * Wrap rules into the action's policy.
49
+ *
50
+ * `valueLimitPerUse: 0n` because the approve cap only bounds ERC-20 pulls —
51
+ * without it, a payable swap selector could still carry arbitrary native value
52
+ * through the router.
53
+ */
54
+ /** Every rule must hold, as a right-folded AND over the expression tree. */
55
+ function allOf(rules) {
56
+ return rules
57
+ .map((rule) => ({ type: 'rule', rule }))
58
+ .reduceRight((right, left) => ({ type: 'and', left, right }));
59
+ }
60
+ /**
61
+ * Wrap rules into the action's policy.
62
+ *
63
+ * `valueLimitPerUse: 0n` because the approve cap only bounds ERC-20 pulls —
64
+ * without it, a payable swap selector could still carry arbitrary native value
65
+ * through the router.
66
+ *
67
+ * UniversalActionPolicy while the rules fit its fixed 16-slot array, which is
68
+ * every venue except a fully-pinned wrapped route — those pin the shape words,
69
+ * both call targets, the approve and the nested exec, and run past 16. ArgPolicy
70
+ * takes a dynamic rule list, so it carries the overflow rather than forcing a
71
+ * pin to be dropped. Preferring the simpler policy keeps the common case on the
72
+ * contract it has always used.
73
+ */
74
+ const UNIVERSAL_ACTION_MAX_RULES = 16;
75
+ export function swapAction(target, selector, rules,
76
+ /**
77
+ * Mutually exclusive rule sets, at least one of which must hold — used when
78
+ * several venues authorise the SAME call but pin its tail to different
79
+ * aggregators. One on-chain action id cannot carry two policies, and dropping
80
+ * the pins to share it would authorise a tail neither venue named, so the
81
+ * alternatives become an OR instead.
82
+ */
83
+ alternatives = []) {
84
+ const usable = alternatives.filter((set) => set.length > 0);
85
+ const policy = usable.length > 0
86
+ ? {
87
+ type: 'arg-policy',
88
+ valueLimitPerUse: 0n,
89
+ expression: {
90
+ type: 'and',
91
+ left: allOf(rules),
92
+ right: usable
93
+ .map(allOf)
94
+ .reduce((left, right) => ({ type: 'or', left, right })),
95
+ },
96
+ }
97
+ : rules.length <= UNIVERSAL_ACTION_MAX_RULES
98
+ ? {
99
+ type: 'universal-action',
100
+ valueLimitPerUse: 0n,
101
+ rules: rules,
102
+ }
103
+ : { type: 'arg-policy', valueLimitPerUse: 0n, expression: allOf(rules) };
104
+ return { target, selector, policies: [policy] };
105
+ }
@@ -0,0 +1,31 @@
1
+ import type { FyndVenue, Permission, RhinestoneSwapVenue, ScopedAction, SwapScopeInput, SwapVenue, ZeroExVenue } from '../types.js';
2
+ import { type FyndChainId } from './fynd.js';
3
+ import { type ZeroExChainId } from './zero-ex.js';
4
+ /**
5
+ * Venue-scoped swap sessions (RHI-6286).
6
+ *
7
+ * A session scoped with `swap` may do exactly two things: approve the sell token
8
+ * to a listed venue's spender, and call that venue's swap entrypoint with the
9
+ * sell token, buy token and recipient pinned. Everything else reverts.
10
+ *
11
+ * Callers name venues (`zeroEx(...)`, `fynd()`); routers, selectors and calldata
12
+ * offsets live in the per-venue modules and never reach the public surface, so
13
+ * they stay patchable without a breaking change.
14
+ */
15
+ /**
16
+ * Venues valid on a given chain.
17
+ *
18
+ * Narrows `swap.via` by the session's chain id, so naming a venue that is not
19
+ * deployed there is a compile error rather than a revert at swap time.
20
+ */
21
+ export type SwapVenueFor<TChainId extends number> = number extends TChainId ? SwapVenue : RhinestoneSwapVenue | (TChainId extends ZeroExChainId ? ZeroExVenue : never) | (TChainId extends FyndChainId ? FyndVenue : never);
22
+ export interface ResolvedSwapScope {
23
+ readonly permissions: Permission[];
24
+ readonly actions: ScopedAction[];
25
+ }
26
+ /**
27
+ * Compile a `swap` scope into one merged approve permission plus one scoped
28
+ * action per venue.
29
+ */
30
+ export declare function resolveSwapScope(scope: SwapScopeInput, chainId: number, environment?: 'production' | 'development'): ResolvedSwapScope;
31
+ //# sourceMappingURL=scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../../../../../../modules/validators/smart-sessions/swap/scope.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EACV,mBAAmB,EAEnB,YAAY,EACZ,cAAc,EACd,SAAS,EACT,WAAW,EACZ,MAAM,UAAU,CAAA;AACjB,OAAO,EAAE,KAAK,WAAW,EAAa,MAAM,QAAQ,CAAA;AAGpD,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,WAAW,CAAA;AAE3D;;;;;;;;;;GAUG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,YAAY,CAAC,QAAQ,SAAS,MAAM,IAAI,MAAM,SAAS,QAAQ,GAMvE,SAAS,GAGL,mBAAmB,GACnB,CAAC,QAAQ,SAAS,aAAa,GAAG,WAAW,GAAG,KAAK,CAAC,GACtD,CAAC,QAAQ,SAAS,WAAW,GAAG,SAAS,GAAG,KAAK,CAAC,CAAA;AAE1D,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,WAAW,EAAE,UAAU,EAAE,CAAA;IAClC,QAAQ,CAAC,OAAO,EAAE,YAAY,EAAE,CAAA;CACjC;AAuDD;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,MAAM,EACf,WAAW,GAAE,YAAY,GAAG,aAA4B,GACvD,iBAAiB,CAqGnB"}
@@ -0,0 +1,168 @@
1
+ import { scopeFynd } from './fynd.js';
2
+ import { rhinestoneSwap, scopeRhinestone } from './rhinestone.js';
3
+ import { scopeZeroEx } from './zero-ex.js';
4
+ const erc20ApproveAbi = [
5
+ {
6
+ type: 'function',
7
+ name: 'approve',
8
+ stateMutability: 'nonpayable',
9
+ inputs: [
10
+ { name: 'spender', type: 'address' },
11
+ { name: 'amount', type: 'uint256' },
12
+ ],
13
+ outputs: [{ name: '', type: 'bool' }],
14
+ },
15
+ ];
16
+ /**
17
+ * One approve permission covering every venue's spender.
18
+ *
19
+ * Merged rather than one-per-venue because all venues pull the same sell token;
20
+ * a single action with a spender allowlist is cheaper to install and keeps the
21
+ * spending-limit a single shared counter instead of one budget per venue.
22
+ */
23
+ function approvePermission(scope, scopings) {
24
+ const spenders = [
25
+ ...new Set(scopings.flatMap((s) => s.approveSpenders.map((a) => a.toLowerCase()))),
26
+ ].map((s) => s);
27
+ return {
28
+ abi: erc20ApproveAbi,
29
+ address: scope.sell.token,
30
+ functions: {
31
+ approve: {
32
+ ...(scope.sell.maxTotal !== undefined
33
+ ? {
34
+ spendingLimit: {
35
+ token: scope.sell.token,
36
+ amount: scope.sell.maxTotal,
37
+ },
38
+ }
39
+ : {}),
40
+ params: {
41
+ spender: spenders.length === 1
42
+ ? { condition: 'equal', value: spenders[0] }
43
+ : { anyOf: spenders },
44
+ },
45
+ },
46
+ },
47
+ };
48
+ }
49
+ /**
50
+ * Compile a `swap` scope into one merged approve permission plus one scoped
51
+ * action per venue.
52
+ */
53
+ export function resolveSwapScope(scope, chainId, environment = 'production') {
54
+ // Default to the Swapper: it is the route the orchestrator emits for
55
+ // same-chain smart-account swaps, so a caller who just says "let this key
56
+ // swap A for B" gets a scope that actually matches the resulting ops.
57
+ const via = scope.via ?? [rhinestoneSwap()];
58
+ if (via.length === 0) {
59
+ throw new Error('swap.via must list at least one venue — an empty list would authorise nothing');
60
+ }
61
+ if (scope.sell.token.toLowerCase() === scope.buy.token.toLowerCase()) {
62
+ throw new Error(`swap.sell.token and swap.buy.token are the same address (${scope.sell.token})`);
63
+ }
64
+ const ctxFor = (venue) => ({
65
+ chainId,
66
+ environment,
67
+ sellToken: scope.sell.token,
68
+ buyToken: scope.buy.token,
69
+ recipient: scope.to,
70
+ // A venue-level cap wins over the scope-level one: `anySettler` demands its
71
+ // own `maxSpend` precisely because that venue needs a tighter bound than the
72
+ // session as a whole might carry.
73
+ cap: venue.maxSpend ?? scope.sell.maxTotal,
74
+ });
75
+ // Every aggregator venue is reachable two ways and the orchestrator picks:
76
+ // it wraps a route in the Swapper only when the Swapper can capture surplus,
77
+ // which depends on the direction AND the winning quoter, and that eligibility
78
+ // is orchestrator-side config that changes without the session knowing. So
79
+ // each venue authorises its direct call AND the wrapped one; authorising a
80
+ // single shape is how a session rejects the swap it was created for.
81
+ //
82
+ // The wrapped shape pins which aggregator may sit in the Swapper's `calls[]`.
83
+ // Two venues pinning DIFFERENT aggregators cannot share one Swapper action —
84
+ // so with more than one aggregator authorised the tail is left unpinned,
85
+ // which is the honest reading: either aggregator may fill it. The swap stays
86
+ // bound by the Swapper's own top-level tokenIn/tokenOut/recipient pins and
87
+ // the sell cap either way.
88
+ const routes = new Set(via.flatMap((venue) => venue.id === 'fynd'
89
+ ? ['fynd']
90
+ : venue.id === '0x'
91
+ ? ['zeroEx']
92
+ : []));
93
+ // A bare `rhinestoneSwap()` authorises any aggregator in the tail, so pinning
94
+ // it for the others would both contradict that venue and collide with it on
95
+ // the same Swapper action.
96
+ // A caller-written Swapper venue carries no route by construction — the
97
+ // routed shape is internal — so naming one authorises any aggregator.
98
+ const anyAggregatorAllowed = via.some((venue) => venue.id === 'rhinestone');
99
+ const sharedRoute = routes.size === 1 && !anyAggregatorAllowed ? [...routes][0] : undefined;
100
+ // More than one aggregator authorised: pin the tail to ANY ONE of them rather
101
+ // than to none. Sharing the Swapper action by dropping its route pins would
102
+ // authorise a tail neither venue named, which is broader than the scope.
103
+ const sharedRoutes = routes.size > 1 && !anyAggregatorAllowed ? [...routes] : undefined;
104
+ // The Settler the 0x venue already carries, so the wrapped half can pin the
105
+ // nested exec instead of dropping the one address that makes it bindable.
106
+ const zeroExSettler = via.flatMap((venue) => venue.id === '0x' && venue.settler !== undefined ? [venue.settler] : [])[0];
107
+ const wrappedVenue = () => {
108
+ const settler = zeroExSettler !== undefined ? { settler: zeroExSettler } : {};
109
+ if (sharedRoutes)
110
+ return { id: 'rhinestone', routes: sharedRoutes, ...settler };
111
+ if (sharedRoute) {
112
+ return {
113
+ id: 'rhinestone',
114
+ route: sharedRoute,
115
+ ...(sharedRoute === 'zeroEx' ? settler : {}),
116
+ };
117
+ }
118
+ return { id: 'rhinestone' };
119
+ };
120
+ const scopings = via.map((venue) => {
121
+ const ctx = ctxFor(venue);
122
+ if (venue.id === 'rhinestone')
123
+ return scopeRhinestone(venue, ctx);
124
+ const parts = [
125
+ venue.id === 'fynd' ? scopeFynd(ctx) : scopeZeroEx(venue, ctx),
126
+ scopeRhinestone(wrappedVenue(), ctx),
127
+ ];
128
+ return {
129
+ approveSpenders: parts.flatMap((p) => [...p.approveSpenders]),
130
+ actions: parts.flatMap((p) => [...p.actions]),
131
+ };
132
+ });
133
+ return {
134
+ permissions: [approvePermission(scope, scopings)],
135
+ actions: dedupeActions(scopings.flatMap((s) => [...s.actions])),
136
+ };
137
+ }
138
+ /**
139
+ * Collapse actions that different venues both authorise.
140
+ *
141
+ * Every aggregator venue covers the Swapper-wrapped shape as well as its direct
142
+ * one, so listing two of them yields the same (target, selector) twice. Those map to one on-chain action id, and the resolver rejects
143
+ * duplicates — reasonably, since two entries would silently overwrite each
144
+ * other's policies. Identical entries are safe to collapse; genuinely
145
+ * conflicting ones still throw, because picking a winner would silently
146
+ * loosen or tighten a rule the caller wrote.
147
+ */
148
+ function dedupeActions(actions) {
149
+ const byKey = new Map();
150
+ for (const action of actions) {
151
+ const key = `${action.target.toLowerCase()}|${action.selector.toLowerCase()}`;
152
+ const existing = byKey.get(key);
153
+ if (!existing) {
154
+ byKey.set(key, action);
155
+ continue;
156
+ }
157
+ if (JSON.stringify(existing, replaceBigInt) !==
158
+ JSON.stringify(action, replaceBigInt)) {
159
+ throw new Error(`Conflicting swap actions for ${action.target} ${action.selector}: ` +
160
+ 'two venues authorise the same call with different policies. Give ' +
161
+ 'them the same cap, or list only one.');
162
+ }
163
+ }
164
+ return [...byKey.values()];
165
+ }
166
+ function replaceBigInt(_key, value) {
167
+ return typeof value === 'bigint' ? value.toString() : value;
168
+ }
@@ -0,0 +1,143 @@
1
+ import { type Address } from 'viem';
2
+ import type { ZeroExVenue } from '../types.js';
3
+ import type { VenueContext, VenueScoping } from './rules.js';
4
+ /**
5
+ * 0x — Swap API v2, AllowanceHolder flow.
6
+ *
7
+ * Two calls per swap:
8
+ * 1. `approve(AllowanceHolder, amount)` on the sell token
9
+ * 2. `AllowanceHolder.exec(operator, token, amount, target, data)` — pulls the
10
+ * approved sell token and forwards `data` to the Settler.
11
+ *
12
+ * The split matters for scoping. `token` and `amount` are consumed by the
13
+ * AllowanceHolder itself, so pinning them is meaningful no matter what `target`
14
+ * is. `operator` and `target` decide who receives the pulled funds, and nothing
15
+ * on-chain requires them to be a Settler — leave them free and a compromised
16
+ * session key names its own contract.
17
+ */
18
+ /** Permanent across chains — 0x never rotates this. Verified deployed on Plasma. */
19
+ export declare const ZEROX_ALLOWANCE_HOLDER: Address;
20
+ /** Chains where 0x is an enabled quoter with a whitelisted Settler. */
21
+ export declare const ZEROX_CHAIN_IDS: readonly [1, 10, 56, 130, 137, 143, 146, 999, 4663, 8453, 9745, 42161, 43114, 57073];
22
+ export type ZeroExChainId = (typeof ZEROX_CHAIN_IDS)[number];
23
+ export declare const allowanceHolderAbi: readonly [{
24
+ readonly type: "function";
25
+ readonly name: "exec";
26
+ readonly stateMutability: "payable";
27
+ readonly inputs: readonly [{
28
+ readonly name: "operator";
29
+ readonly type: "address";
30
+ }, {
31
+ readonly name: "token";
32
+ readonly type: "address";
33
+ }, {
34
+ readonly name: "amount";
35
+ readonly type: "uint256";
36
+ }, {
37
+ readonly name: "target";
38
+ readonly type: "address";
39
+ }, {
40
+ readonly name: "data";
41
+ readonly type: "bytes";
42
+ }];
43
+ readonly outputs: readonly [{
44
+ readonly name: "result";
45
+ readonly type: "bytes";
46
+ }];
47
+ }];
48
+ export declare const ALLOWANCE_HOLDER_EXEC_SELECTOR: `0x${string}`;
49
+ /**
50
+ * 0x's Settler registry — an ERC-721 whose token owner IS the current Settler
51
+ * for that feature slot. Slot 2 is the taker-submitted Settler used by ordinary
52
+ * swaps.
53
+ *
54
+ * 0x redeploys the Settler every few weeks and moves the token, so there is no
55
+ * safe constant to bundle: any address baked into a release is correct only
56
+ * until the next rotation. Resolve with {@link resolveZeroExSettler} and pin the
57
+ * result, or use `anySettler` to trade the pin for longevity.
58
+ */
59
+ export declare const ZEROX_SETTLER_REGISTRY: Address;
60
+ export declare const ZEROX_SETTLER_FEATURE_ID = 2n;
61
+ export declare const zeroExSettlerRegistryAbi: readonly [{
62
+ readonly type: "function";
63
+ readonly name: "ownerOf";
64
+ readonly stateMutability: "view";
65
+ readonly inputs: readonly [{
66
+ readonly name: "tokenId";
67
+ readonly type: "uint256";
68
+ }];
69
+ readonly outputs: readonly [{
70
+ readonly name: "";
71
+ readonly type: "address";
72
+ }];
73
+ }];
74
+ /** Minimal structural client — avoids coupling this module to a viem client type. */
75
+ interface SettlerRegistryReader {
76
+ readContract(args: {
77
+ address: Address;
78
+ abi: typeof zeroExSettlerRegistryAbi;
79
+ functionName: 'ownerOf';
80
+ args: readonly [bigint];
81
+ }): Promise<Address>;
82
+ }
83
+ /**
84
+ * Read 0x's current Settler for this chain from the on-chain registry.
85
+ *
86
+ * Pin the result at session-enable time; do NOT re-resolve per swap. A session
87
+ * that looked the address up at use time would follow 0x's registry wherever it
88
+ * points, so a compromise of 0x's upgrade multisig could redirect every live
89
+ * session's approved funds. Pinned, the worst case of a rotation is that the
90
+ * session stops working until it is re-enabled.
91
+ *
92
+ * @param client - Any viem public client for the target chain.
93
+ */
94
+ export declare function resolveZeroExSettler(client: SettlerRegistryReader): Promise<Address>;
95
+ /**
96
+ * Pin 0x's Settler to a specific address.
97
+ *
98
+ * Pinning the inner `buyToken` / `recipient` is not a substitute for pinning
99
+ * `target`: those bytes only mean what their names say when the callee is
100
+ * genuinely a Settler.
101
+ */
102
+ export interface ZeroExPinnedOptions {
103
+ /** The Settler to pin. Get the current one with {@link resolveZeroExSettler}. */
104
+ settler: Address;
105
+ anySettler?: never;
106
+ maxSpend?: never;
107
+ }
108
+ /**
109
+ * Leave 0x's Settler unpinned so the session survives 0x's rotations.
110
+ *
111
+ * A deliberate security downgrade, which is why `maxSpend` is mandatory here:
112
+ * with `target` free, a compromised session key can redirect the AllowanceHolder
113
+ * pull to its own contract, and `maxSpend` is then the ONLY bound on what it
114
+ * takes. The blast radius becomes exactly `maxSpend`, never the account's whole
115
+ * balance.
116
+ *
117
+ * Prefer {@link ZeroExPinnedOptions} unless the session must outlive 0x's
118
+ * upgrade cadence (roughly every few weeks).
119
+ */
120
+ export interface ZeroExAnySettlerOptions {
121
+ anySettler: true;
122
+ /** Cumulative cap on sell-token spend across every swap in this session. */
123
+ maxSpend: bigint;
124
+ settler?: never;
125
+ }
126
+ /**
127
+ * Scope a session to 0x swaps, in whichever shape the orchestrator produces.
128
+ *
129
+ * Authorises BOTH the direct `AllowanceHolder.exec` call and the
130
+ * Swapper-wrapped one, and there is no way to narrow that. Whether a swap is
131
+ * wrapped is decided by `ENABLE_SWAPPER`, the account type, and whether the
132
+ * Swapper resolves on the chain — state that is read when the intent executes,
133
+ * not when the session is signed. Authorising one shape is how a session ends
134
+ * up rejecting the swap it was created for.
135
+ *
136
+ * Takes either a pinned `settler` or `anySettler` + `maxSpend`. There is
137
+ * deliberately no zero-argument form: a bundled Settler constant would be stale
138
+ * within weeks of the release that shipped it.
139
+ */
140
+ export declare function zeroEx(options: ZeroExPinnedOptions | ZeroExAnySettlerOptions): ZeroExVenue;
141
+ export declare function scopeZeroEx(venue: ZeroExVenue, ctx: VenueContext): VenueScoping;
142
+ export {};
143
+ //# sourceMappingURL=zero-ex.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zero-ex.d.ts","sourceRoot":"","sources":["../../../../../../modules/validators/smart-sessions/swap/zero-ex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,OAAO,EAAsB,MAAM,MAAM,CAAA;AAEjE,OAAO,KAAK,EAAkC,WAAW,EAAE,MAAM,UAAU,CAAA;AAC3E,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAGzD;;;;;;;;;;;;;GAaG;AAEH,oFAAoF;AACpF,eAAO,MAAM,sBAAsB,EAAE,OACS,CAAA;AAE9C,uEAAuE;AACvE,eAAO,MAAM,eAAe,sFAElB,CAAA;AAEV,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAA;AAE5D,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;EAcP,CAAA;AAExB,eAAO,MAAM,8BAA8B,eAE1C,CAAA;AAiCD;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAE,OACS,CAAA;AAE9C,eAAO,MAAM,wBAAwB,KAAK,CAAA;AAE1C,eAAO,MAAM,wBAAwB;;;;;;;;;;;;EAQb,CAAA;AAExB,qFAAqF;AACrF,UAAU,qBAAqB;IAC7B,YAAY,CAAC,IAAI,EAAE;QACjB,OAAO,EAAE,OAAO,CAAA;QAChB,GAAG,EAAE,OAAO,wBAAwB,CAAA;QACpC,YAAY,EAAE,SAAS,CAAA;QACvB,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,CAAA;KACxB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CACrB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,OAAO,CAAC,CAOlB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAClC,iFAAiF;IACjF,OAAO,EAAE,OAAO,CAAA;IAChB,UAAU,CAAC,EAAE,KAAK,CAAA;IAClB,QAAQ,CAAC,EAAE,KAAK,CAAA;CACjB;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,IAAI,CAAA;IAChB,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,KAAK,CAAA;CAChB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,MAAM,CACpB,OAAO,EAAE,mBAAmB,GAAG,uBAAuB,GACrD,WAAW,CAOb;AAED,wBAAgB,WAAW,CACzB,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,YAAY,GAChB,YAAY,CAsCd"}
@@ -0,0 +1,164 @@
1
+ import { toFunctionSelector } from 'viem';
2
+ import { namedParamOffsets } from '../../permissions.js';
3
+ import { cumulativeCap, pin, pinValue, swapAction } from './rules.js';
4
+ /**
5
+ * 0x — Swap API v2, AllowanceHolder flow.
6
+ *
7
+ * Two calls per swap:
8
+ * 1. `approve(AllowanceHolder, amount)` on the sell token
9
+ * 2. `AllowanceHolder.exec(operator, token, amount, target, data)` — pulls the
10
+ * approved sell token and forwards `data` to the Settler.
11
+ *
12
+ * The split matters for scoping. `token` and `amount` are consumed by the
13
+ * AllowanceHolder itself, so pinning them is meaningful no matter what `target`
14
+ * is. `operator` and `target` decide who receives the pulled funds, and nothing
15
+ * on-chain requires them to be a Settler — leave them free and a compromised
16
+ * session key names its own contract.
17
+ */
18
+ /** Permanent across chains — 0x never rotates this. Verified deployed on Plasma. */
19
+ export const ZEROX_ALLOWANCE_HOLDER = '0x0000000000001fF3684f28c67538d4D072C22734';
20
+ /** Chains where 0x is an enabled quoter with a whitelisted Settler. */
21
+ export const ZEROX_CHAIN_IDS = [
22
+ 1, 10, 56, 130, 137, 143, 146, 999, 4663, 8453, 9745, 42161, 43114, 57073,
23
+ ];
24
+ export const allowanceHolderAbi = [
25
+ {
26
+ type: 'function',
27
+ name: 'exec',
28
+ stateMutability: 'payable',
29
+ inputs: [
30
+ { name: 'operator', type: 'address' },
31
+ { name: 'token', type: 'address' },
32
+ { name: 'amount', type: 'uint256' },
33
+ { name: 'target', type: 'address' },
34
+ { name: 'data', type: 'bytes' },
35
+ ],
36
+ outputs: [{ name: 'result', type: 'bytes' }],
37
+ },
38
+ ];
39
+ export const ALLOWANCE_HOLDER_EXEC_SELECTOR = toFunctionSelector(allowanceHolderAbi[0]);
40
+ /** exec's own head offsets, derived from the ABI. */
41
+ const EXEC = namedParamOffsets(allowanceHolderAbi, 'exec');
42
+ /**
43
+ * Offsets of the Settler's slippage fields, measured in EXEC's calldata.
44
+ *
45
+ * These cannot come from an ABI: they live inside `exec.data`, which is opaque
46
+ * `bytes` as far as exec's own signature is concerned. They are stable anyway
47
+ * because the Settler's
48
+ * `execute((recipient, buyToken, minAmountOut) slippage, bytes[] actions, bytes32)`
49
+ * places the fixed-size slippage struct BEFORE the variable-length `actions`.
50
+ *
51
+ * Derivation: exec's `data` content begins at 192 (five head words + the length
52
+ * word), +4 for the inner selector = 196 for `recipient`, +32 = 228 for
53
+ * `buyToken`. Re-derive against a live 0x exec if 0x revs the Settler ABI.
54
+ */
55
+ /**
56
+ * `exec`'s `data` head word, and the canonical tail it must point at.
57
+ *
58
+ * The Settler offsets below are derived from `data` starting at 192, which only
59
+ * holds while this pointer says 160. Unpinned, a session key can aim `data`
60
+ * elsewhere and leave matching decoy words at 196/228 for the policy to read
61
+ * while the Settler decodes a different recipient. `rhinestone.ts` pins the
62
+ * equivalent `calls[]` shape words for the same reason.
63
+ */
64
+ const EXEC_DATA_POINTER_OFFSET = 128n;
65
+ const EXEC_DATA_POINTER = 160n;
66
+ const SETTLER_RECIPIENT_OFFSET = 196n;
67
+ const SETTLER_BUY_TOKEN_OFFSET = 228n;
68
+ /**
69
+ * 0x's Settler registry — an ERC-721 whose token owner IS the current Settler
70
+ * for that feature slot. Slot 2 is the taker-submitted Settler used by ordinary
71
+ * swaps.
72
+ *
73
+ * 0x redeploys the Settler every few weeks and moves the token, so there is no
74
+ * safe constant to bundle: any address baked into a release is correct only
75
+ * until the next rotation. Resolve with {@link resolveZeroExSettler} and pin the
76
+ * result, or use `anySettler` to trade the pin for longevity.
77
+ */
78
+ export const ZEROX_SETTLER_REGISTRY = '0x00000000000004533Fe15556B1E086BB1A72cEae';
79
+ export const ZEROX_SETTLER_FEATURE_ID = 2n;
80
+ export const zeroExSettlerRegistryAbi = [
81
+ {
82
+ type: 'function',
83
+ name: 'ownerOf',
84
+ stateMutability: 'view',
85
+ inputs: [{ name: 'tokenId', type: 'uint256' }],
86
+ outputs: [{ name: '', type: 'address' }],
87
+ },
88
+ ];
89
+ /**
90
+ * Read 0x's current Settler for this chain from the on-chain registry.
91
+ *
92
+ * Pin the result at session-enable time; do NOT re-resolve per swap. A session
93
+ * that looked the address up at use time would follow 0x's registry wherever it
94
+ * points, so a compromise of 0x's upgrade multisig could redirect every live
95
+ * session's approved funds. Pinned, the worst case of a rotation is that the
96
+ * session stops working until it is re-enabled.
97
+ *
98
+ * @param client - Any viem public client for the target chain.
99
+ */
100
+ export async function resolveZeroExSettler(client) {
101
+ return client.readContract({
102
+ address: ZEROX_SETTLER_REGISTRY,
103
+ abi: zeroExSettlerRegistryAbi,
104
+ functionName: 'ownerOf',
105
+ args: [ZEROX_SETTLER_FEATURE_ID],
106
+ });
107
+ }
108
+ /**
109
+ * Scope a session to 0x swaps, in whichever shape the orchestrator produces.
110
+ *
111
+ * Authorises BOTH the direct `AllowanceHolder.exec` call and the
112
+ * Swapper-wrapped one, and there is no way to narrow that. Whether a swap is
113
+ * wrapped is decided by `ENABLE_SWAPPER`, the account type, and whether the
114
+ * Swapper resolves on the chain — state that is read when the intent executes,
115
+ * not when the session is signed. Authorising one shape is how a session ends
116
+ * up rejecting the swap it was created for.
117
+ *
118
+ * Takes either a pinned `settler` or `anySettler` + `maxSpend`. There is
119
+ * deliberately no zero-argument form: a bundled Settler constant would be stale
120
+ * within weeks of the release that shipped it.
121
+ */
122
+ export function zeroEx(options) {
123
+ return {
124
+ id: '0x',
125
+ ...(options.settler !== undefined ? { settler: options.settler } : {}),
126
+ ...(options.anySettler ? { anySettler: true } : {}),
127
+ ...(options.maxSpend !== undefined ? { maxSpend: options.maxSpend } : {}),
128
+ };
129
+ }
130
+ export function scopeZeroEx(venue, ctx) {
131
+ // The union type rejects this at compile time, but a plain-JS caller or an
132
+ // `as any` reaches here with neither, and the rules below would then pin only
133
+ // the sell token — an unbounded AllowanceHolder path.
134
+ if (venue.settler === undefined && !venue.anySettler) {
135
+ throw new Error('zeroEx() requires either a pinned settler or anySettler + maxSpend: ' +
136
+ 'with neither, nothing bounds the operator, target or amount');
137
+ }
138
+ if (venue.anySettler && ctx.cap === undefined) {
139
+ throw new Error('zeroEx({ anySettler: true }) requires maxSpend: with the Settler ' +
140
+ 'unpinned it is the only bound on what a compromised session key can pull');
141
+ }
142
+ // Pinned from the scope, never from venue options — the sell token is a
143
+ // scope-level guarantee and must not depend on the caller restating it.
144
+ const rules = [
145
+ pin(EXEC.token, ctx.sellToken),
146
+ ];
147
+ if (venue.settler !== undefined) {
148
+ rules.push(pin(EXEC.operator, venue.settler));
149
+ rules.push(pin(EXEC.target, venue.settler));
150
+ // Before any offset inside `exec.data` can be trusted.
151
+ rules.push(pinValue(EXEC_DATA_POINTER_OFFSET, EXEC_DATA_POINTER));
152
+ rules.push(pin(SETTLER_BUY_TOKEN_OFFSET, ctx.buyToken));
153
+ rules.push(pin(SETTLER_RECIPIENT_OFFSET, ctx.recipient));
154
+ }
155
+ if (ctx.cap !== undefined) {
156
+ rules.push(cumulativeCap(EXEC.amount, ctx.cap));
157
+ }
158
+ return {
159
+ approveSpenders: [ZEROX_ALLOWANCE_HOLDER],
160
+ actions: [
161
+ swapAction(ZEROX_ALLOWANCE_HOLDER, ALLOWANCE_HOLDER_EXEC_SELECTOR, rules),
162
+ ],
163
+ };
164
+ }