@zodiaceco/sdk 2.0.0 → 2.1.1

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,357 @@
1
+ import { Permission } from "zodiac-roles-sdk";
2
+ import { Address, ApplyConstellationPayload, ChainId } from "@zodiaceco/api-types";
3
+ import { allow } from "defi-kit/eth";
4
+ import { UUID } from "crypto";
5
+
6
+ //#region src/types.d.ts
7
+ type ApiNewRolesSpec = Extract<ApplyConstellationPayload['specification'][number], {
8
+ type: 'ROLES';
9
+ nonce: string;
10
+ }>;
11
+ /** A role definition in the API's serialized format (bigints as template literal strings). */
12
+ /** An allowance definition in the API's serialized format (bigints as template literal strings). */
13
+ type ApiAllowanceSpec = Extract<NonNullable<ApiNewRolesSpec['allowances']>, readonly any[]>[number];
14
+ /** Recursively converts `${bigint}` template literal strings to `bigint`. */
15
+ type RealBigints<T> = T extends `${bigint}` ? bigint : T extends readonly (infer U)[] ? RealBigints<U>[] : T extends Record<string, any> ? { [K in keyof T]: RealBigints<T[K]> } : T;
16
+ /** A role definition with bigint fields as actual bigints. */
17
+ /** An allowance definition with bigint fields as actual bigints. */
18
+ type AllowanceSpec = RealBigints<ApiAllowanceSpec>;
19
+ //#endregion
20
+ //#region src/constellation.d.ts
21
+ /**
22
+ * A role definition keyed by role name. Entries describe what the role may do —
23
+ * parameters and labels, never compiled permissions. They are expanded into
24
+ * `{ targets, annotations }` when the constellation is deployed, so that a
25
+ * stored revision always compiles through the current compilers.
26
+ */
27
+ type RoleDef = {
28
+ members: readonly AddressOrRef[];
29
+ permissions: readonly PermissionEntry[];
30
+ };
31
+ type User = {
32
+ id: UUID;
33
+ fullName: string;
34
+ personalSafes: Record<number, {
35
+ address: Lowercase<Address>;
36
+ active: boolean;
37
+ }>;
38
+ };
39
+ type Account = {
40
+ id: UUID;
41
+ label: string;
42
+ address: Lowercase<Address>;
43
+ chain: ChainId; /** True for accounts promoted to a workspace vault. */
44
+ vault: boolean;
45
+ };
46
+ /**
47
+ * Accounts grouped by node type within a workspace. Per-type maps keep
48
+ * bracket-accessor namespaces separate: a SAFE and a ROLES mod sharing a
49
+ * label don't collide, and `eth.safe[...]` IntelliSense doesn't suggest
50
+ * ROLES mod labels (and vice versa).
51
+ */
52
+ type WorkspaceAccounts = {
53
+ workspaceId: UUID;
54
+ workspaceName: string;
55
+ safes: Readonly<Record<string, Account>>;
56
+ rolesMods: Readonly<Record<string, Account>>;
57
+ delays: Readonly<Record<string, Account>>;
58
+ };
59
+ /** Shape of the codegen data produced by `zodiac pull-org`. */
60
+ type CodegenData = {
61
+ users: Readonly<Record<string, User>>;
62
+ accounts: Readonly<Record<string, WorkspaceAccounts>>;
63
+ };
64
+ type GeneratedCodegen = ZodiacGeneratedCodegen extends CodegenData ? ZodiacGeneratedCodegen : CodegenData;
65
+ type ConstellationOpts<C extends CodegenData> = {
66
+ /** Workspace to scope accounts and roles to. */workspace: keyof C['accounts'] & string; /** Human-readable label for this constellation. */
67
+ label: string; /** Target chain for all nodes in this constellation. */
68
+ chain: ChainId;
69
+ };
70
+ type ConstellationInternalOpts<C extends CodegenData> = {
71
+ /** Injected codegen data (used for testing). */codegen?: C;
72
+ };
73
+ type Prettify<T> = { readonly [K in keyof T]: T[K] } & {};
74
+ type SafeEntries<C extends CodegenData, W extends keyof C['accounts']> = C['accounts'][W]['safes'];
75
+ type RolesEntries<C extends CodegenData, W extends keyof C['accounts']> = C['accounts'][W]['rolesMods'];
76
+ type NodeType = 'SAFE' | 'ROLES' | 'DELAY';
77
+ /** A reference to a node used in `owners`, `modules`, `target`, etc. */
78
+ type NodeRef = Readonly<{
79
+ type: NodeType;
80
+ label: string;
81
+ chain: ChainId;
82
+ }>;
83
+ /** A blockchain address (checksummed or lowercase) or a reference to another
84
+ * node in the constellation. Values are normalized to lowercase before being
85
+ * sent to the API. */
86
+ type AddressOrRef = Address | NodeRef;
87
+ type NodeBase = Readonly<{
88
+ /** Human-readable identifier, unique within the constellation. */label: string; /** Chain the node is deployed on. */
89
+ chain: ChainId;
90
+ /** Set for existing nodes (from codegen or bound by address), absent for new
91
+ * nodes. Accepts checksummed or lowercase; normalized to lowercase on push. */
92
+ address?: Address; /** Deployment nonce — required for new nodes, optional for existing. */
93
+ nonce?: bigint;
94
+ }>;
95
+ /** A safe node spec — existing vault ref or new safe with required config. */
96
+ type SafeNode = NodeBase & Readonly<{
97
+ /** Discriminator identifying this node as a Safe. */type: 'SAFE'; /** Number of owner signatures required to execute a transaction. */
98
+ threshold: number; /** Safe owner addresses or node references. */
99
+ owners: readonly (string | NodeRef)[]; /** Module addresses or node references enabled on the safe. */
100
+ modules?: readonly (string | NodeRef)[]; /** Whether this safe shall appear as a vault in the workspace. @default false */
101
+ vault?: boolean;
102
+ }>;
103
+ /** A roles modifier node spec — existing vault ref or new roles with modifier config. */
104
+ type RolesNode = NodeBase & Readonly<{
105
+ /** Discriminator identifying this node as a Roles modifier. */type: 'ROLES'; /** The safe that this roles modifier controls. */
106
+ target?: AddressOrRef; /** The account that is allowed to update the configuration of the Roles mod. */
107
+ owner?: AddressOrRef; /** The account that calls will be executed from. */
108
+ avatar?: AddressOrRef; /** MultiSend contract addresses for batched transactions. */
109
+ multisend?: readonly Address[];
110
+ /** Role definitions configured on this modifier. Pass `null` for a key to
111
+ * clear that role; unmentioned roles are left untouched. */
112
+ roles?: Record<string, RoleDef | null>;
113
+ /** Spending allowances configured on this modifier, keyed by name. Pass
114
+ * `null` for a key to clear that allowance; unmentioned allowances are
115
+ * left untouched. */
116
+ allowances?: Record<string, AllowanceSpec | null>;
117
+ }>;
118
+ /** Any complete node that can be passed to `push()`. */
119
+ type ConstellationNode = SafeNode | RolesNode;
120
+ type NewSafeProps = {
121
+ /** Deployment nonce for CREATE2 address derivation. */nonce: bigint; /** Number of owner signatures required to execute a transaction. */
122
+ threshold: number; /** Safe owner addresses or node references. */
123
+ owners: readonly AddressOrRef[]; /** Module addresses or node references to enable on the safe. */
124
+ modules?: readonly AddressOrRef[]; /** Whether this safe is a workspace vault. @default false */
125
+ vault?: boolean;
126
+ };
127
+ /** Configuration shared by both ways of declaring a roles modifier. */
128
+ type RolesConfig = {
129
+ /** The safe that this roles modifier controls. Defaults to the new safe with the same label, when one exists. */target?: AddressOrRef; /** The account that calls will be executed from. Defaults to `target` value */
130
+ avatar?: AddressOrRef; /** The account that is allowed to update the configuration of the Roles Mod. Defaults to `target` value */
131
+ owner?: AddressOrRef; /** MultiSend contract addresses for batched transactions. Defaults to `['0x38869bf66a61cf6bdb996a6ae40d5853fd43b526', '0x9641d764fc13c8b624c04430c7356c1c7c8102e2']` */
132
+ multisend?: readonly Address[];
133
+ /** Role definitions to configure on this modifier. Pass `null` for a key to
134
+ * clear that role; unmentioned roles are left untouched. */
135
+ roles?: Record<string, RoleDef | null>;
136
+ /** Spending allowances to configure on this modifier, keyed by name. Pass
137
+ * `null` for a key to clear that allowance; unmentioned allowances are
138
+ * left untouched. */
139
+ allowances?: Record<string, AllowanceSpec | null>;
140
+ };
141
+ /** Declare a brand-new roles modifier (address derived via CREATE2 from `nonce`). */
142
+ type NewRolesByNonce = RolesConfig & {
143
+ /** Deployment nonce for CREATE2 address derivation. */nonce: bigint;
144
+ };
145
+ /** Bind to a roles modifier already deployed on-chain at a known address, to
146
+ * reconfigure its roles/allowances. Use this for mods not (yet) imported into
147
+ * the workspace — pass the address instead of a deployment `nonce`. */
148
+ type ExistingRolesByAddress = RolesConfig & {
149
+ /** Address of the existing Roles mod to bind to and reconfigure. */address: Address;
150
+ };
151
+ type NewRolesProps = NewRolesByNonce | ExistingRolesByAddress;
152
+ type ExistingNodeAccessor<Type extends string, K extends string, E, Ch extends ChainId, NP extends Record<string, any>> = Readonly<Prettify<E & {
153
+ type: Type;
154
+ label: K;
155
+ chain: Ch;
156
+ }>> & (<O extends { [P in Exclude<keyof E & string, 'id' | 'label'>]?: any } & Partial<NP> = {}>(overrides?: { [P in Exclude<keyof E & string, 'id' | 'label'>]?: any } & Partial<NP> & O) => Readonly<Prettify<Omit<E, keyof O> & O & Partial<NP> & {
157
+ type: Type;
158
+ label: K;
159
+ chain: Ch;
160
+ }>>);
161
+ type NewNodeAccessor<Type extends string, Ch extends ChainId, NP extends Record<string, any>> = Readonly<Prettify<{
162
+ type: Type;
163
+ label: string;
164
+ chain: Ch;
165
+ }>> & (<P extends NP>(props: P) => Readonly<Prettify<P & {
166
+ type: Type;
167
+ label: string;
168
+ chain: Ch;
169
+ }>>);
170
+ type EntityAccessor<Type extends string, Entries extends Record<string, any>, Ch extends ChainId = ChainId, NP extends Record<string, any> = Record<string, any>> = { readonly [K in keyof Entries & string]: ExistingNodeAccessor<Type, K, Entries[K], Ch, NP> } & {
171
+ readonly [key: string]: NewNodeAccessor<Type, Ch, NP>;
172
+ };
173
+ type UserAccessor<C extends CodegenData, Ch extends number> = { readonly [K in keyof C['users'] & string]: C['users'][K]['personalSafes'][Ch]['address'] };
174
+ type ConstellationResult<C extends CodegenData, W extends keyof C['accounts'] = keyof C['accounts'], Ch extends ChainId = ChainId> = {
175
+ /** Access existing safes by label or create new ones with a new label.
176
+ * Only SAFE-typed accounts are suggested in IntelliSense. */
177
+ safe: EntityAccessor<'SAFE', SafeEntries<C, W>, Ch, NewSafeProps>;
178
+ /** Access existing roles modifiers by label or create new ones with a
179
+ * new label. Only ROLES-typed accounts are suggested in IntelliSense. */
180
+ roles: EntityAccessor<'ROLES', RolesEntries<C, W>, Ch, NewRolesProps>; /** Resolve a user's personal safe address on the constellation's chain. */
181
+ user: UserAccessor<C, Ch>;
182
+ };
183
+ /** @internal */
184
+ /**
185
+ * Creates a constellation scoped to a workspace and chain.
186
+ *
187
+ * Use bracket access to reference existing accounts (vaults and other
188
+ * applied constellation nodes) or define new ones:
189
+ * ```ts
190
+ * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })
191
+ *
192
+ * const dao = eth.safe['GG DAO'] // existing account ref
193
+ * const roles = eth.roles['GG DAO'] // existing roles ref
194
+ * const newSafe = eth.safe['New Safe']({ nonce: 0n, threshold: 2, owners: [...], modules: [...] })
195
+ * ```
196
+ */
197
+ declare function constellation<const C extends CodegenData = GeneratedCodegen, const W extends keyof C['accounts'] & string = keyof C['accounts'] & string, const Ch extends ChainId = ChainId>(opts: ConstellationOpts<C> & {
198
+ workspace: W;
199
+ chain: Ch;
200
+ }, internal?: ConstellationInternalOpts<C>): ConstellationResult<C, W, Ch>;
201
+ //#endregion
202
+ //#region src/permissionEntries.d.ts
203
+ /**
204
+ * An allowance key. Authored as a plain label, the way a role key is, and
205
+ * encoded to bytes32 when the constellation is deployed. An already-encoded
206
+ * key still works — `encodeKey` passes 32-byte hex through unchanged.
207
+ */
208
+ type AllowanceKey = string;
209
+ type SwapEntry = {
210
+ label: string;
211
+ action: {
212
+ type: 'swap';
213
+ sell: Address[];
214
+ buy: Address[];
215
+ };
216
+ };
217
+ type TransferEntry = {
218
+ label: string;
219
+ action: {
220
+ type: 'transfer';
221
+ tokens: Address[];
222
+ to: Address[];
223
+ bridge?: {
224
+ chain: ChainId;
225
+ to: Address[];
226
+ receive: Address[];
227
+ }[];
228
+ allowance?: AllowanceKey;
229
+ };
230
+ };
231
+ /**
232
+ * A permission's target, written either as an address or as another node in the
233
+ * same constellation.
234
+ *
235
+ * A policy is usually pushed alongside the accounts it governs, so the address
236
+ * a permission points at often does not exist yet. Naming the node instead
237
+ * sends a reference, and the address is substituted once it is derived at
238
+ * deploy — the same way a node is named as an owner, a module or an avatar.
239
+ *
240
+ * `NodeRef` for the same reason those fields use it: an uninvoked accessor is
241
+ * a forward reference to a node, and is how two nodes that need each other are
242
+ * written. It carries the label a reference resolves by without being a
243
+ * complete node.
244
+ */
245
+ type PermissionTarget = `0x${string}` | NodeRef;
246
+ type WithNodeTarget<P> = P extends {
247
+ targetAddress: `0x${string}`;
248
+ } ? Omit<P, 'targetAddress'> & {
249
+ targetAddress: PermissionTarget;
250
+ } : P;
251
+ /** A `zodiac-roles-sdk` permission that may name a node as its target. */
252
+ type ConstellationPermission = WithNodeTarget<Permission>;
253
+ type LabelledPermissions = {
254
+ label: string;
255
+ permissions: ConstellationPermission[];
256
+ };
257
+ type DeFiKitEntry = {
258
+ label: string;
259
+ defiKit: {
260
+ protocol: string;
261
+ verb: string;
262
+ params: Record<string, DeFiKitParamValue>;
263
+ };
264
+ };
265
+ type DeFiKitParamValue = string | number | boolean | readonly (string | number | boolean)[] | null | undefined;
266
+ /**
267
+ * One entry of a role's `permissions`. A bare permission stays valid, but every
268
+ * labelled form names something the app can show as a single card.
269
+ */
270
+ type PermissionEntry = ConstellationPermission | LabelledPermissions | SwapEntry | TransferEntry | DeFiKitEntry;
271
+ /** A role's full permission list — the type `permissions.ts` files satisfy. */
272
+ type Permissions = readonly PermissionEntry[];
273
+ //#endregion
274
+ //#region src/actions.d.ts
275
+ /**
276
+ * Allows signing CoW orders selling any of `sell` for any of `buy`. The
277
+ * parameters are compiled into permissions when the constellation is deployed,
278
+ * never here — a stored revision that carried its own copy would go stale as
279
+ * soon as the compiler changed.
280
+ */
281
+ declare const swap: ({
282
+ label,
283
+ sell,
284
+ buy
285
+ }: SwapParams) => SwapEntry;
286
+ /**
287
+ * Allows transferring any of `tokens` to any of `to` on the role's own chain,
288
+ * and — through `bridge` — to recipients on other chains over Across. Both are
289
+ * optional on their own; a transfer names at least one recipient somewhere.
290
+ */
291
+ declare const transfer: ({
292
+ label,
293
+ tokens,
294
+ to,
295
+ bridge,
296
+ allowance
297
+ }: TransferParams) => TransferEntry;
298
+ /**
299
+ * A labelled bag of `allow`-kit permissions — the code-side counterpart of the
300
+ * app's Custom action, for everything the other action types don't cover. It
301
+ * takes plain permissions, not other actions.
302
+ */
303
+ declare const custom: ({
304
+ label,
305
+ permissions
306
+ }: CustomParams) => LabelledPermissions;
307
+ /**
308
+ * The DeFi Kit allow kit — same protocol, verb and parameter surface, plus a
309
+ * `label`. A DeFi Kit entry is nothing but its annotation: the permissions are
310
+ * fetched from the annotation's uri at deploy, so nothing is fetched here.
311
+ *
312
+ * Protocols and parameters are typed against the Ethereum kit, the widest of
313
+ * the chains DeFi Kit serves. Values that only exist on another chain still
314
+ * type-check; the API validates them when the annotation is resolved.
315
+ */
316
+ declare const defikit: DeFiKit;
317
+ type SwapParams = {
318
+ /** Names the action in the app. Never reaches the chain. */label: string; /** Tokens the role may sell. */
319
+ sell: readonly Address[]; /** Tokens the role may buy. */
320
+ buy: readonly Address[];
321
+ };
322
+ type TransferParams = {
323
+ /** Names the action in the app. Never reaches the chain. */label: string; /** Tokens the role may transfer. Use the zero address for the native token. */
324
+ tokens: readonly Address[];
325
+ /** Addresses the role may transfer to on the role's own chain. A node stands
326
+ * for its address, so only nodes that already have one — an account from your
327
+ * codegen, or one bound by address — can be named here. */
328
+ to?: readonly Recipient[]; /** Destinations on other chains, bridged over Across. */
329
+ bridge?: readonly BridgeTarget[];
330
+ /** Allowance capping what may be sent. Pass the allowance declared on the
331
+ * roles modifier, or its key. */
332
+ allowance?: AllowanceSpec | AllowanceKey;
333
+ };
334
+ type CustomParams = {
335
+ /** Names the action in the app. Never reaches the chain. */label: string;
336
+ permissions: readonly ConstellationPermission[];
337
+ };
338
+ /** An address, or a node that already knows the address it lives at. */
339
+ type Recipient = Address | {
340
+ readonly address: Address;
341
+ readonly chain?: ChainId;
342
+ };
343
+ type BridgeTarget = {
344
+ /** The destination chain. Inferred from the recipients when they are nodes. */chain?: ChainId; /** Addresses the role may bridge to on the destination chain. */
345
+ to: readonly Recipient[]; /** Tokens the role may receive on the destination chain. */
346
+ receive: readonly Address[];
347
+ };
348
+ type EthereumKit = typeof allow;
349
+ type DeFiKit = { readonly [Protocol in keyof EthereumKit]: { readonly [Verb in keyof EthereumKit[Protocol]]: DeFiKitVerb<EthereumKit[Protocol][Verb]> } };
350
+ type DeFiKitVerb<Verb> = Verb extends ((params: infer Params) => unknown) ? (params: Params & {
351
+ label: string;
352
+ }) => DeFiKitEntry : (params: {
353
+ label: string;
354
+ }) => DeFiKitEntry;
355
+ //#endregion
356
+ export { PermissionEntry as a, ConstellationNode as c, transfer as i, constellation as l, defikit as n, PermissionTarget as o, swap as r, Permissions as s, custom as t };
357
+ //# sourceMappingURL=actions-vTsHy73w.d.mts.map
@@ -1,2 +1,2 @@
1
- import { i as transfer, n as defikit, o as PermissionEntry, r as swap, s as Permissions, t as custom } from "./actions-DS5XoMiq.mjs";
2
- export { PermissionEntry, Permissions, custom, defikit, swap, transfer };
1
+ import { a as PermissionEntry, i as transfer, n as defikit, o as PermissionTarget, r as swap, s as Permissions, t as custom } from "./actions-vTsHy73w.mjs";
2
+ export { PermissionEntry, PermissionTarget, Permissions, custom, defikit, swap, transfer };
@@ -1 +1 @@
1
- {"version":3,"file":"actions.mjs","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { allow as ethereumKit } from 'defi-kit/eth'\nimport type { Permission } from 'zodiac-roles-sdk'\nimport { recipientChains } from './permissionEntries'\nimport type {\n AllowanceKey,\n DeFiKitEntry,\n LabelledPermissions,\n PermissionEntry,\n SwapEntry,\n TransferEntry,\n} from './permissionEntries'\nimport type { AllowanceSpec } from './types'\n\nexport type { PermissionEntry }\nexport type { Permissions } from './permissionEntries'\n\n/**\n * Allows signing CoW orders selling any of `sell` for any of `buy`. The\n * parameters are compiled into permissions when the constellation is deployed,\n * never here — a stored revision that carried its own copy would go stale as\n * soon as the compiler changed.\n */\nexport const swap = ({ label, sell, buy }: SwapParams): SwapEntry => ({\n label,\n action: { type: 'swap', sell: [...sell], buy: [...buy] },\n})\n\n/**\n * Allows transferring any of `tokens` to any of `to` on the role's own chain,\n * and — through `bridge` — to recipients on other chains over Across. Both are\n * optional on their own; a transfer names at least one recipient somewhere.\n */\nexport const transfer = ({\n label,\n tokens,\n to = [],\n bridge = [],\n allowance,\n}: TransferParams): TransferEntry => {\n const entry: TransferEntry = {\n label,\n action: {\n type: 'transfer',\n tokens: [...tokens],\n to: to.map(toAddress),\n ...(bridge.length > 0 && { bridge: bridge.map(toBridgeTarget) }),\n ...(allowance != null && { allowance: allowanceKey(allowance) }),\n },\n }\n\n // Remember which chains the `to` nodes live on so push() can refuse a\n // recipient from another chain. Symbol-keyed: never serialized.\n const chains = to.flatMap((recipient) =>\n typeof recipient === 'string' || recipient.chain == null\n ? []\n : [recipient.chain]\n )\n\n if (chains.length > 0) {\n Object.defineProperty(entry, recipientChains, {\n value: chains,\n enumerable: false,\n })\n }\n\n return entry\n}\n\n/**\n * A labelled bag of `allow`-kit permissions — the code-side counterpart of the\n * app's Custom action, for everything the other action types don't cover. It\n * takes plain permissions, not other actions.\n */\nexport const custom = ({\n label,\n permissions,\n}: CustomParams): LabelledPermissions => ({\n label,\n permissions: [...permissions],\n})\n\n/**\n * The DeFi Kit allow kit — same protocol, verb and parameter surface, plus a\n * `label`. A DeFi Kit entry is nothing but its annotation: the permissions are\n * fetched from the annotation's uri at deploy, so nothing is fetched here.\n *\n * Protocols and parameters are typed against the Ethereum kit, the widest of\n * the chains DeFi Kit serves. Values that only exist on another chain still\n * type-check; the API validates them when the annotation is resolved.\n */\nexport const defikit: DeFiKit = new Proxy({} as DeFiKit, {\n get: (_, protocol: string) =>\n new Proxy(\n {},\n {\n get:\n (_, verb: string) =>\n ({ label, ...params }: { label: string }) => ({\n label,\n defiKit: { protocol, verb, params },\n }),\n }\n ),\n})\n\nconst allowanceKey = (allowance: AllowanceSpec | AllowanceKey) =>\n typeof allowance === 'string' ? allowance : allowance.key\n\nconst toAddress = (recipient: Recipient): Address =>\n typeof recipient === 'string' ? recipient : recipient.address\n\n/**\n * A node knows the chain it lives on, so a bridge target written with nodes\n * needs no `chain` of its own. Naming one anyway is allowed — a plain address\n * carries no chain — but a node that disagrees with it is a mistake worth\n * catching here rather than at deploy.\n */\nconst toBridgeTarget = ({ chain, to, receive }: BridgeTarget) => ({\n chain: destinationChain(chain, to),\n to: to.map(toAddress),\n receive: [...receive],\n})\n\nconst destinationChain = (\n chain: ChainId | undefined,\n recipients: readonly Recipient[]\n): ChainId => {\n let destination = chain\n\n for (const recipient of recipients) {\n if (typeof recipient === 'string' || recipient.chain == null) {\n continue\n }\n\n if (destination != null && destination !== recipient.chain) {\n throw new Error(\n `A bridge target has one destination, but this one spans chains \"${destination}\" and \"${recipient.chain}\"`\n )\n }\n\n destination = recipient.chain\n }\n\n if (destination == null) {\n throw new Error(\n 'A bridge target needs a `chain` unless its recipients are nodes that know one'\n )\n }\n\n return destination\n}\n\ntype SwapParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n /** Tokens the role may sell. */\n sell: readonly Address[]\n /** Tokens the role may buy. */\n buy: readonly Address[]\n}\n\ntype TransferParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n /** Tokens the role may transfer. Use the zero address for the native token. */\n tokens: readonly Address[]\n /** Addresses the role may transfer to on the role's own chain. A node stands\n * for its address, so only nodes that already have one — an account from your\n * codegen, or one bound by address — can be named here. */\n to?: readonly Recipient[]\n /** Destinations on other chains, bridged over Across. */\n bridge?: readonly BridgeTarget[]\n /** Allowance capping what may be sent. Pass the allowance declared on the\n * roles modifier, or its key. */\n allowance?: AllowanceSpec | AllowanceKey\n}\n\ntype CustomParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n permissions: readonly Permission[]\n}\n\n/** An address, or a node that already knows the address it lives at. */\ntype Recipient =\n | Address\n | { readonly address: Address; readonly chain?: ChainId }\n\ntype BridgeTarget = {\n /** The destination chain. Inferred from the recipients when they are nodes. */\n chain?: ChainId\n /** Addresses the role may bridge to on the destination chain. */\n to: readonly Recipient[]\n /** Tokens the role may receive on the destination chain. */\n receive: readonly Address[]\n}\n\ntype EthereumKit = typeof ethereumKit\n\ntype DeFiKit = {\n readonly [Protocol in keyof EthereumKit]: {\n readonly [Verb in keyof EthereumKit[Protocol]]: DeFiKitVerb<\n EthereumKit[Protocol][Verb]\n >\n }\n}\n\ntype DeFiKitVerb<Verb> = Verb extends (params: infer Params) => unknown\n ? (params: Params & { label: string }) => DeFiKitEntry\n : (params: { label: string }) =>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IAAI,UAAU;CACrB,SAAS,CAAC,GAAG,QAAQ;CACtB;AAED,MAAM,oBACJ,OACA,eACY;CACZ,IAAI,cAAc;AAElB,MAAK,MAAM,aAAa,YAAY;AAClC,MAAI,OAAO,cAAc,YAAY,UAAU,SAAS,KACtD;AAGF,MAAI,eAAe,QAAQ,gBAAgB,UAAU,MACnD,OAAM,IAAI,MACR,mEAAmE,YAAY,SAAS,UAAU,MAAM,GACzG;AAGH,gBAAc,UAAU;;AAG1B,KAAI,eAAe,KACjB,OAAM,IAAI,MACR,gFACD;AAGH,QAAO"}
1
+ {"version":3,"file":"actions.mjs","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { allow as ethereumKit } from 'defi-kit/eth'\nimport { recipientChains } from './permissionEntries'\nimport type {\n AllowanceKey,\n ConstellationPermission,\n DeFiKitEntry,\n LabelledPermissions,\n PermissionEntry,\n PermissionTarget,\n SwapEntry,\n TransferEntry,\n} from './permissionEntries'\nimport type { AllowanceSpec } from './types'\n\nexport type { PermissionEntry, PermissionTarget }\nexport type { Permissions } from './permissionEntries'\n\n/**\n * Allows signing CoW orders selling any of `sell` for any of `buy`. The\n * parameters are compiled into permissions when the constellation is deployed,\n * never here — a stored revision that carried its own copy would go stale as\n * soon as the compiler changed.\n */\nexport const swap = ({ label, sell, buy }: SwapParams): SwapEntry => ({\n label,\n action: { type: 'swap', sell: [...sell], buy: [...buy] },\n})\n\n/**\n * Allows transferring any of `tokens` to any of `to` on the role's own chain,\n * and — through `bridge` — to recipients on other chains over Across. Both are\n * optional on their own; a transfer names at least one recipient somewhere.\n */\nexport const transfer = ({\n label,\n tokens,\n to = [],\n bridge = [],\n allowance,\n}: TransferParams): TransferEntry => {\n const entry: TransferEntry = {\n label,\n action: {\n type: 'transfer',\n tokens: [...tokens],\n to: to.map(toAddress),\n ...(bridge.length > 0 && { bridge: bridge.map(toBridgeTarget) }),\n ...(allowance != null && { allowance: allowanceKey(allowance) }),\n },\n }\n\n // Remember which chains the `to` nodes live on so push() can refuse a\n // recipient from another chain. Symbol-keyed: never serialized.\n const chains = to.flatMap((recipient) =>\n typeof recipient === 'string' || recipient.chain == null\n ? []\n : [recipient.chain]\n )\n\n if (chains.length > 0) {\n Object.defineProperty(entry, recipientChains, {\n value: chains,\n enumerable: false,\n })\n }\n\n return entry\n}\n\n/**\n * A labelled bag of `allow`-kit permissions — the code-side counterpart of the\n * app's Custom action, for everything the other action types don't cover. It\n * takes plain permissions, not other actions.\n */\nexport const custom = ({\n label,\n permissions,\n}: CustomParams): LabelledPermissions => ({\n label,\n permissions: [...permissions],\n})\n\n/**\n * The DeFi Kit allow kit — same protocol, verb and parameter surface, plus a\n * `label`. A DeFi Kit entry is nothing but its annotation: the permissions are\n * fetched from the annotation's uri at deploy, so nothing is fetched here.\n *\n * Protocols and parameters are typed against the Ethereum kit, the widest of\n * the chains DeFi Kit serves. Values that only exist on another chain still\n * type-check; the API validates them when the annotation is resolved.\n */\nexport const defikit: DeFiKit = new Proxy({} as DeFiKit, {\n get: (_, protocol: string) =>\n new Proxy(\n {},\n {\n get:\n (_, verb: string) =>\n ({ label, ...params }: { label: string }) => ({\n label,\n defiKit: { protocol, verb, params },\n }),\n }\n ),\n})\n\nconst allowanceKey = (allowance: AllowanceSpec | AllowanceKey) =>\n typeof allowance === 'string' ? allowance : allowance.key\n\nconst toAddress = (recipient: Recipient): Address =>\n typeof recipient === 'string' ? recipient : recipient.address\n\n/**\n * A node knows the chain it lives on, so a bridge target written with nodes\n * needs no `chain` of its own. Naming one anyway is allowed — a plain address\n * carries no chain — but a node that disagrees with it is a mistake worth\n * catching here rather than at deploy.\n */\nconst toBridgeTarget = ({ chain, to, receive }: BridgeTarget) => ({\n chain: destinationChain(chain, to),\n to: to.map(toAddress),\n receive: [...receive],\n})\n\nconst destinationChain = (\n chain: ChainId | undefined,\n recipients: readonly Recipient[]\n): ChainId => {\n let destination = chain\n\n for (const recipient of recipients) {\n if (typeof recipient === 'string' || recipient.chain == null) {\n continue\n }\n\n if (destination != null && destination !== recipient.chain) {\n throw new Error(\n `A bridge target has one destination, but this one spans chains \"${destination}\" and \"${recipient.chain}\"`\n )\n }\n\n destination = recipient.chain\n }\n\n if (destination == null) {\n throw new Error(\n 'A bridge target needs a `chain` unless its recipients are nodes that know one'\n )\n }\n\n return destination\n}\n\ntype SwapParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n /** Tokens the role may sell. */\n sell: readonly Address[]\n /** Tokens the role may buy. */\n buy: readonly Address[]\n}\n\ntype TransferParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n /** Tokens the role may transfer. Use the zero address for the native token. */\n tokens: readonly Address[]\n /** Addresses the role may transfer to on the role's own chain. A node stands\n * for its address, so only nodes that already have one — an account from your\n * codegen, or one bound by address — can be named here. */\n to?: readonly Recipient[]\n /** Destinations on other chains, bridged over Across. */\n bridge?: readonly BridgeTarget[]\n /** Allowance capping what may be sent. Pass the allowance declared on the\n * roles modifier, or its key. */\n allowance?: AllowanceSpec | AllowanceKey\n}\n\ntype CustomParams = {\n /** Names the action in the app. Never reaches the chain. */\n label: string\n permissions: readonly ConstellationPermission[]\n}\n\n/** An address, or a node that already knows the address it lives at. */\ntype Recipient =\n | Address\n | { readonly address: Address; readonly chain?: ChainId }\n\ntype BridgeTarget = {\n /** The destination chain. Inferred from the recipients when they are nodes. */\n chain?: ChainId\n /** Addresses the role may bridge to on the destination chain. */\n to: readonly Recipient[]\n /** Tokens the role may receive on the destination chain. */\n receive: readonly Address[]\n}\n\ntype EthereumKit = typeof ethereumKit\n\ntype DeFiKit = {\n readonly [Protocol in keyof EthereumKit]: {\n readonly [Verb in keyof EthereumKit[Protocol]]: DeFiKitVerb<\n EthereumKit[Protocol][Verb]\n >\n }\n}\n\ntype DeFiKitVerb<Verb> = Verb extends (params: infer Params) => unknown\n ? (params: Params & { label: string }) => DeFiKitEntry\n : (params: { label: string }) => DeFiKitEntry\n"],"mappings":";;;;;;;;A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AG,QAAQ;CACtB;AAED,MAAM,oBACJ,OACA,eACY;CACZ,IAAI,cAAc;AAElB,MAAK,MAAM,aAAa,YAAY;AAClC,MAAI,OAAO,cAAc,YAAY,UAAU,SAAS,KACtD;AAGF,MAAI,eAAe,QAAQ,gBAAgB,UAAU,MACnD,OAAM,IAAI,MACR,mEAAmE,YAAY,SAAS,UAAU,MAAM,GACzG;AAGH,gBAAc,UAAU;;AAG1B,KAAI,eAAe,KACjB,OAAM,IAAI,MACR,gFACD;AAGH,QAAO"}
package/dist/index.d.mts CHANGED
@@ -1,192 +1,10 @@
1
1
  /// <reference path="./zodiac-os-codegen.d.ts" />
2
- import { a as AllowanceSpec, o as PermissionEntry, s as Permissions } from "./actions-DS5XoMiq.mjs";
2
+ import { a as PermissionEntry, c as ConstellationNode, l as constellation, s as Permissions } from "./actions-vTsHy73w.mjs";
3
3
  import { a as EVERYTHING, c as Scoping, i as ConditionFunction, l as TargetPermission, n as ChainPrefix, o as FunctionPermission, s as Options, u as buildAllowKit } from "./index-CnH26Z_A.mjs";
4
4
  import { Annotation, Permission, PermissionSet, c, encodeKey, forAll } from "zodiac-roles-sdk";
5
- import { Address, ApplyConstellationPayload, ApplyConstellationResult, ChainId, ListAccountsResult, ListUsersResult, ResolveConstellationPayload, ResolveConstellationResult } from "@zodiaceco/api-types";
5
+ import { ApplyConstellationPayload, ApplyConstellationResult, ListAccountsResult, ListUsersResult, ResolveConstellationPayload, ResolveConstellationResult } from "@zodiaceco/api-types";
6
6
  import { UUID } from "crypto";
7
7
 
8
- //#region src/constellation.d.ts
9
- /**
10
- * A role definition keyed by role name. Entries describe what the role may do —
11
- * parameters and labels, never compiled permissions. They are expanded into
12
- * `{ targets, annotations }` when the constellation is deployed, so that a
13
- * stored revision always compiles through the current compilers.
14
- */
15
- type RoleDef = {
16
- members: readonly AddressOrRef[];
17
- permissions: readonly PermissionEntry[];
18
- };
19
- type User = {
20
- id: UUID;
21
- fullName: string;
22
- personalSafes: Record<number, {
23
- address: Lowercase<Address>;
24
- active: boolean;
25
- }>;
26
- };
27
- type Account = {
28
- id: UUID;
29
- label: string;
30
- address: Lowercase<Address>;
31
- chain: ChainId; /** True for accounts promoted to a workspace vault. */
32
- vault: boolean;
33
- };
34
- /**
35
- * Accounts grouped by node type within a workspace. Per-type maps keep
36
- * bracket-accessor namespaces separate: a SAFE and a ROLES mod sharing a
37
- * label don't collide, and `eth.safe[...]` IntelliSense doesn't suggest
38
- * ROLES mod labels (and vice versa).
39
- */
40
- type WorkspaceAccounts = {
41
- workspaceId: UUID;
42
- workspaceName: string;
43
- safes: Readonly<Record<string, Account>>;
44
- rolesMods: Readonly<Record<string, Account>>;
45
- delays: Readonly<Record<string, Account>>;
46
- };
47
- /** Shape of the codegen data produced by `zodiac pull-org`. */
48
- type CodegenData = {
49
- users: Readonly<Record<string, User>>;
50
- accounts: Readonly<Record<string, WorkspaceAccounts>>;
51
- };
52
- type GeneratedCodegen = ZodiacGeneratedCodegen extends CodegenData ? ZodiacGeneratedCodegen : CodegenData;
53
- type ConstellationOpts<C extends CodegenData> = {
54
- /** Workspace to scope accounts and roles to. */workspace: keyof C['accounts'] & string; /** Human-readable label for this constellation. */
55
- label: string; /** Target chain for all nodes in this constellation. */
56
- chain: ChainId;
57
- };
58
- type ConstellationInternalOpts<C extends CodegenData> = {
59
- /** Injected codegen data (used for testing). */codegen?: C;
60
- };
61
- type Prettify<T> = { readonly [K in keyof T]: T[K] } & {};
62
- type SafeEntries<C extends CodegenData, W extends keyof C['accounts']> = C['accounts'][W]['safes'];
63
- type RolesEntries<C extends CodegenData, W extends keyof C['accounts']> = C['accounts'][W]['rolesMods'];
64
- type NodeType = 'SAFE' | 'ROLES' | 'DELAY';
65
- /** A reference to a node used in `owners`, `modules`, `target`, etc. */
66
- type NodeRef = Readonly<{
67
- type: NodeType;
68
- label: string;
69
- chain: ChainId;
70
- }>;
71
- /** A blockchain address (checksummed or lowercase) or a reference to another
72
- * node in the constellation. Values are normalized to lowercase before being
73
- * sent to the API. */
74
- type AddressOrRef = Address | NodeRef;
75
- type NodeBase = Readonly<{
76
- /** Human-readable identifier, unique within the constellation. */label: string; /** Chain the node is deployed on. */
77
- chain: ChainId;
78
- /** Set for existing nodes (from codegen or bound by address), absent for new
79
- * nodes. Accepts checksummed or lowercase; normalized to lowercase on push. */
80
- address?: Address; /** Deployment nonce — required for new nodes, optional for existing. */
81
- nonce?: bigint;
82
- }>;
83
- /** A safe node spec — existing vault ref or new safe with required config. */
84
- type SafeNode = NodeBase & Readonly<{
85
- /** Discriminator identifying this node as a Safe. */type: 'SAFE'; /** Number of owner signatures required to execute a transaction. */
86
- threshold: number; /** Safe owner addresses or node references. */
87
- owners: readonly (string | NodeRef)[]; /** Module addresses or node references enabled on the safe. */
88
- modules?: readonly (string | NodeRef)[]; /** Whether this safe shall appear as a vault in the workspace. @default false */
89
- vault?: boolean;
90
- }>;
91
- /** A roles modifier node spec — existing vault ref or new roles with modifier config. */
92
- type RolesNode = NodeBase & Readonly<{
93
- /** Discriminator identifying this node as a Roles modifier. */type: 'ROLES'; /** The safe that this roles modifier controls. */
94
- target?: AddressOrRef; /** The account that is allowed to update the configuration of the Roles mod. */
95
- owner?: AddressOrRef; /** The account that calls will be executed from. */
96
- avatar?: AddressOrRef; /** MultiSend contract addresses for batched transactions. */
97
- multisend?: readonly Address[];
98
- /** Role definitions configured on this modifier. Pass `null` for a key to
99
- * clear that role; unmentioned roles are left untouched. */
100
- roles?: Record<string, RoleDef | null>;
101
- /** Spending allowances configured on this modifier, keyed by name. Pass
102
- * `null` for a key to clear that allowance; unmentioned allowances are
103
- * left untouched. */
104
- allowances?: Record<string, AllowanceSpec | null>;
105
- }>;
106
- /** Any complete node that can be passed to `push()`. */
107
- type ConstellationNode = SafeNode | RolesNode;
108
- type NewSafeProps = {
109
- /** Deployment nonce for CREATE2 address derivation. */nonce: bigint; /** Number of owner signatures required to execute a transaction. */
110
- threshold: number; /** Safe owner addresses or node references. */
111
- owners: readonly AddressOrRef[]; /** Module addresses or node references to enable on the safe. */
112
- modules?: readonly AddressOrRef[]; /** Whether this safe is a workspace vault. @default false */
113
- vault?: boolean;
114
- };
115
- /** Configuration shared by both ways of declaring a roles modifier. */
116
- type RolesConfig = {
117
- /** The safe that this roles modifier controls. Defaults to the new safe with the same label, when one exists. */target?: AddressOrRef; /** The account that calls will be executed from. Defaults to `target` value */
118
- avatar?: AddressOrRef; /** The account that is allowed to update the configuration of the Roles Mod. Defaults to `target` value */
119
- owner?: AddressOrRef; /** MultiSend contract addresses for batched transactions. Defaults to `['0x38869bf66a61cf6bdb996a6ae40d5853fd43b526', '0x9641d764fc13c8b624c04430c7356c1c7c8102e2']` */
120
- multisend?: readonly Address[];
121
- /** Role definitions to configure on this modifier. Pass `null` for a key to
122
- * clear that role; unmentioned roles are left untouched. */
123
- roles?: Record<string, RoleDef | null>;
124
- /** Spending allowances to configure on this modifier, keyed by name. Pass
125
- * `null` for a key to clear that allowance; unmentioned allowances are
126
- * left untouched. */
127
- allowances?: Record<string, AllowanceSpec | null>;
128
- };
129
- /** Declare a brand-new roles modifier (address derived via CREATE2 from `nonce`). */
130
- type NewRolesByNonce = RolesConfig & {
131
- /** Deployment nonce for CREATE2 address derivation. */nonce: bigint;
132
- };
133
- /** Bind to a roles modifier already deployed on-chain at a known address, to
134
- * reconfigure its roles/allowances. Use this for mods not (yet) imported into
135
- * the workspace — pass the address instead of a deployment `nonce`. */
136
- type ExistingRolesByAddress = RolesConfig & {
137
- /** Address of the existing Roles mod to bind to and reconfigure. */address: Address;
138
- };
139
- type NewRolesProps = NewRolesByNonce | ExistingRolesByAddress;
140
- type ExistingNodeAccessor<Type extends string, K extends string, E, Ch extends ChainId, NP extends Record<string, any>> = Readonly<Prettify<E & {
141
- type: Type;
142
- label: K;
143
- chain: Ch;
144
- }>> & (<O extends { [P in Exclude<keyof E & string, 'id' | 'label'>]?: any } & Partial<NP> = {}>(overrides?: { [P in Exclude<keyof E & string, 'id' | 'label'>]?: any } & Partial<NP> & O) => Readonly<Prettify<Omit<E, keyof O> & O & Partial<NP> & {
145
- type: Type;
146
- label: K;
147
- chain: Ch;
148
- }>>);
149
- type NewNodeAccessor<Type extends string, Ch extends ChainId, NP extends Record<string, any>> = Readonly<Prettify<{
150
- type: Type;
151
- label: string;
152
- chain: Ch;
153
- }>> & (<P extends NP>(props: P) => Readonly<Prettify<P & {
154
- type: Type;
155
- label: string;
156
- chain: Ch;
157
- }>>);
158
- type EntityAccessor<Type extends string, Entries extends Record<string, any>, Ch extends ChainId = ChainId, NP extends Record<string, any> = Record<string, any>> = { readonly [K in keyof Entries & string]: ExistingNodeAccessor<Type, K, Entries[K], Ch, NP> } & {
159
- readonly [key: string]: NewNodeAccessor<Type, Ch, NP>;
160
- };
161
- type UserAccessor<C extends CodegenData, Ch extends number> = { readonly [K in keyof C['users'] & string]: C['users'][K]['personalSafes'][Ch]['address'] };
162
- type ConstellationResult<C extends CodegenData, W extends keyof C['accounts'] = keyof C['accounts'], Ch extends ChainId = ChainId> = {
163
- /** Access existing safes by label or create new ones with a new label.
164
- * Only SAFE-typed accounts are suggested in IntelliSense. */
165
- safe: EntityAccessor<'SAFE', SafeEntries<C, W>, Ch, NewSafeProps>;
166
- /** Access existing roles modifiers by label or create new ones with a
167
- * new label. Only ROLES-typed accounts are suggested in IntelliSense. */
168
- roles: EntityAccessor<'ROLES', RolesEntries<C, W>, Ch, NewRolesProps>; /** Resolve a user's personal safe address on the constellation's chain. */
169
- user: UserAccessor<C, Ch>;
170
- };
171
- /** @internal */
172
- /**
173
- * Creates a constellation scoped to a workspace and chain.
174
- *
175
- * Use bracket access to reference existing accounts (vaults and other
176
- * applied constellation nodes) or define new ones:
177
- * ```ts
178
- * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })
179
- *
180
- * const dao = eth.safe['GG DAO'] // existing account ref
181
- * const roles = eth.roles['GG DAO'] // existing roles ref
182
- * const newSafe = eth.safe['New Safe']({ nonce: 0n, threshold: 2, owners: [...], modules: [...] })
183
- * ```
184
- */
185
- declare function constellation<const C extends CodegenData = GeneratedCodegen, const W extends keyof C['accounts'] & string = keyof C['accounts'] & string, const Ch extends ChainId = ChainId>(opts: ConstellationOpts<C> & {
186
- workspace: W;
187
- chain: Ch;
188
- }, internal?: ConstellationInternalOpts<C>): ConstellationResult<C, W, Ch>;
189
- //#endregion
190
8
  //#region src/api.d.ts
191
9
  type Options$1 = {
192
10
  workspace?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/constellation.ts","../src/push.ts"],"sourcesContent":["/// <reference path=\"./zodiac-os-codegen.d.ts\" />\nimport type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { PermissionEntry } from './actions'\nimport type { AllowanceSpec } from './types'\nimport { createRequire } from 'module'\nimport { resolveZodiacDir } from './paths'\nimport { UUID } from 'crypto'\n\n/**\n * A role definition keyed by role name. Entries describe what the role may do —\n * parameters and labels, never compiled permissions. They are expanded into\n * `{ targets, annotations }` when the constellation is deployed, so that a\n * stored revision always compiles through the current compilers.\n */\nexport type RoleDef = {\n members: readonly AddressOrRef[]\n permissions: readonly PermissionEntry[]\n}\n\ntype User = {\n id: UUID\n fullName: string\n personalSafes: Record<\n number,\n { address: Lowercase<Address>; active: boolean }\n >\n}\n\ntype Account = {\n id: UUID\n label: string\n address: Lowercase<Address>\n chain: ChainId\n /** True for accounts promoted to a workspace vault. */\n vault: boolean\n}\n\n/**\n * Accounts grouped by node type within a workspace. Per-type maps keep\n * bracket-accessor namespaces separate: a SAFE and a ROLES mod sharing a\n * label don't collide, and `eth.safe[...]` IntelliSense doesn't suggest\n * ROLES mod labels (and vice versa).\n */\ntype WorkspaceAccounts = {\n workspaceId: UUID\n workspaceName: string\n safes: Readonly<Record<string, Account>>\n rolesMods: Readonly<Record<string, Account>>\n delays: Readonly<Record<string, Account>>\n}\n\n/** Shape of the codegen data produced by `zodiac pull-org`. */\nexport type CodegenData = {\n users: Readonly<Record<string, User>>\n accounts: Readonly<Record<string, WorkspaceAccounts>>\n}\n\n// If `pull-org` has been run, the consumer's `.zodiac/index.d.ts` augments\n// `ZodiacGeneratedCodegen` with literal `users`/`accounts` shapes. Otherwise\n// the interface is empty and we fall back to the wide `CodegenData`.\ntype GeneratedCodegen = ZodiacGeneratedCodegen extends CodegenData\n ? ZodiacGeneratedCodegen\n : CodegenData\n\ntype ConstellationOpts<C extends CodegenData> = {\n /** Workspace to scope accounts and roles to. */\n workspace: keyof C['accounts'] & string\n /** Human-readable label for this constellation. */\n label: string\n /** Target chain for all nodes in this constellation. */\n chain: ChainId\n}\n\ntype ConstellationInternalOpts<C extends CodegenData> = {\n /** Injected codegen data (used for testing). */\n codegen?: C\n}\n\ntype Prettify<T> = { readonly [K in keyof T]: T[K] } & {}\n\ntype SafeEntries<\n C extends CodegenData,\n W extends keyof C['accounts'],\n> = C['accounts'][W]['safes']\n\ntype RolesEntries<\n C extends CodegenData,\n W extends keyof C['accounts'],\n> = C['accounts'][W]['rolesMods']\n\ntype NodeType = 'SAFE' | 'ROLES' | 'DELAY'\n\n/** A reference to a node used in `owners`, `modules`, `target`, etc. */\ntype NodeRef = Readonly<{ type: NodeType; label: string; chain: ChainId }>\n\n/** A blockchain address (checksummed or lowercase) or a reference to another\n * node in the constellation. Values are normalized to lowercase before being\n * sent to the API. */\ntype AddressOrRef = Address | NodeRef\n\ntype NodeBase = Readonly<{\n /** Human-readable identifier, unique within the constellation. */\n label: string\n /** Chain the node is deployed on. */\n chain: ChainId\n /** Set for existing nodes (from codegen or bound by address), absent for new\n * nodes. Accepts checksummed or lowercase; normalized to lowercase on push. */\n address?: Address\n /** Deployment nonce — required for new nodes, optional for existing. */\n nonce?: bigint\n}>\n\n/** A safe node spec — existing vault ref or new safe with required config. */\nexport type SafeNode = NodeBase &\n Readonly<{\n /** Discriminator identifying this node as a Safe. */\n type: 'SAFE'\n /** Number of owner signatures required to execute a transaction. */\n threshold: number\n /** Safe owner addresses or node references. */\n owners: readonly (string | NodeRef)[]\n /** Module addresses or node references enabled on the safe. */\n modules?: readonly (string | NodeRef)[]\n /** Whether this safe shall appear as a vault in the workspace. @default false */\n vault?: boolean\n }>\n\n/** A roles modifier node spec — existing vault ref or new roles with modifier config. */\nexport type RolesNode = NodeBase &\n Readonly<{\n /** Discriminator identifying this node as a Roles modifier. */\n type: 'ROLES'\n /** The safe that this roles modifier controls. */\n target?: AddressOrRef\n /** The account that is allowed to update the configuration of the Roles mod. */\n owner?: AddressOrRef\n /** The account that calls will be executed from. */\n avatar?: AddressOrRef\n /** MultiSend contract addresses for batched transactions. */\n multisend?: readonly Address[]\n /** Role definitions configured on this modifier. Pass `null` for a key to\n * clear that role; unmentioned roles are left untouched. */\n roles?: Record<string, RoleDef | null>\n /** Spending allowances configured on this modifier, keyed by name. Pass\n * `null` for a key to clear that allowance; unmentioned allowances are\n * left untouched. */\n allowances?: Record<string, AllowanceSpec | null>\n }>\n\n/** Any complete node that can be passed to `push()`. */\nexport type ConstellationNode = SafeNode | RolesNode\nexport type ConstellationNodeInternal = ConstellationNode & {\n _constellation: ConstellationMeta\n}\n\ntype NewSafeProps = {\n /** Deployment nonce for CREATE2 address derivation. */\n nonce: bigint\n /** Number of owner signatures required to execute a transaction. */\n threshold: number\n /** Safe owner addresses or node references. */\n owners: readonly AddressOrRef[]\n /** Module addresses or node references to enable on the safe. */\n modules?: readonly AddressOrRef[]\n /** Whether this safe is a workspace vault. @default false */\n vault?: boolean\n}\n\n/** Configuration shared by both ways of declaring a roles modifier. */\ntype RolesConfig = {\n /** The safe that this roles modifier controls. Defaults to the new safe with the same label, when one exists. */\n target?: AddressOrRef\n /** The account that calls will be executed from. Defaults to `target` value */\n avatar?: AddressOrRef\n /** The account that is allowed to update the configuration of the Roles Mod. Defaults to `target` value */\n owner?: AddressOrRef\n /** MultiSend contract addresses for batched transactions. Defaults to `['0x38869bf66a61cf6bdb996a6ae40d5853fd43b526', '0x9641d764fc13c8b624c04430c7356c1c7c8102e2']` */\n multisend?: readonly Address[]\n /** Role definitions to configure on this modifier. Pass `null` for a key to\n * clear that role; unmentioned roles are left untouched. */\n roles?: Record<string, RoleDef | null>\n /** Spending allowances to configure on this modifier, keyed by name. Pass\n * `null` for a key to clear that allowance; unmentioned allowances are\n * left untouched. */\n allowances?: Record<string, AllowanceSpec | null>\n}\n\n/** Declare a brand-new roles modifier (address derived via CREATE2 from `nonce`). */\ntype NewRolesByNonce = RolesConfig & {\n /** Deployment nonce for CREATE2 address derivation. */\n nonce: bigint\n}\n\n/** Bind to a roles modifier already deployed on-chain at a known address, to\n * reconfigure its roles/allowances. Use this for mods not (yet) imported into\n * the workspace — pass the address instead of a deployment `nonce`. */\ntype ExistingRolesByAddress = RolesConfig & {\n /** Address of the existing Roles mod to bind to and reconfigure. */\n address: Address\n}\n\ntype NewRolesProps = NewRolesByNonce | ExistingRolesByAddress\n\ntype ExistingNodeAccessor<\n Type extends string,\n K extends string,\n E,\n Ch extends ChainId,\n NP extends Record<string, any>,\n> = Readonly<Prettify<E & { type: Type; label: K; chain: Ch }>> &\n (<\n O extends {\n [P in Exclude<keyof E & string, 'id' | 'label'>]?: any\n } & Partial<NP> = {},\n >(\n overrides?: {\n [P in Exclude<keyof E & string, 'id' | 'label'>]?: any\n } & Partial<NP> &\n O\n ) => Readonly<\n Prettify<\n Omit<E, keyof O> & O & Partial<NP> & { type: Type; label: K; chain: Ch }\n >\n >)\n\ntype NewNodeAccessor<\n Type extends string,\n Ch extends ChainId,\n NP extends Record<string, any>,\n> = Readonly<Prettify<{ type: Type; label: string; chain: Ch }>> &\n (<P extends NP>(\n props: P\n ) => Readonly<Prettify<P & { type: Type; label: string; chain: Ch }>>)\n\ntype EntityAccessor<\n Type extends string,\n Entries extends Record<string, any>,\n Ch extends ChainId = ChainId,\n NP extends Record<string, any> = Record<string, any>,\n> = {\n readonly [K in keyof Entries & string]: ExistingNodeAccessor<\n Type,\n K,\n Entries[K],\n Ch,\n NP\n >\n} & {\n readonly [key: string]: NewNodeAccessor<Type, Ch, NP>\n}\n\ntype UserAccessor<C extends CodegenData, Ch extends number> = {\n readonly [K in keyof C['users'] &\n string]: C['users'][K]['personalSafes'][Ch]['address']\n}\n\ntype ConstellationResult<\n C extends CodegenData,\n W extends keyof C['accounts'] = keyof C['accounts'],\n Ch extends ChainId = ChainId,\n> = {\n /** Access existing safes by label or create new ones with a new label.\n * Only SAFE-typed accounts are suggested in IntelliSense. */\n safe: EntityAccessor<'SAFE', SafeEntries<C, W>, Ch, NewSafeProps>\n /** Access existing roles modifiers by label or create new ones with a\n * new label. Only ROLES-typed accounts are suggested in IntelliSense. */\n roles: EntityAccessor<'ROLES', RolesEntries<C, W>, Ch, NewRolesProps>\n /** Resolve a user's personal safe address on the constellation's chain. */\n user: UserAccessor<C, Ch>\n}\n\n/** @internal */\nexport type ConstellationMeta = {\n label: string\n chain: ChainId\n workspaceId: UUID\n}\n\nfunction loadCodegen(): CodegenData {\n const require = createRequire(import.meta.url)\n return require(resolveZodiacDir()) as CodegenData\n}\n\n/**\n * Creates a constellation scoped to a workspace and chain.\n *\n * Use bracket access to reference existing accounts (vaults and other\n * applied constellation nodes) or define new ones:\n * ```ts\n * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })\n *\n * const dao = eth.safe['GG DAO'] // existing account ref\n * const roles = eth.roles['GG DAO'] // existing roles ref\n * const newSafe = eth.safe['New Safe']({ nonce: 0n, threshold: 2, owners: [...], modules: [...] })\n * ```\n */\nexport function constellation<\n const C extends CodegenData = GeneratedCodegen,\n const W extends keyof C['accounts'] & string = keyof C['accounts'] & string,\n const Ch extends ChainId = ChainId,\n>(\n opts: ConstellationOpts<C> & { workspace: W; chain: Ch },\n internal?: ConstellationInternalOpts<C>\n): ConstellationResult<C, W, Ch> {\n const codegen: CodegenData = internal?.codegen ?? loadCodegen()\n\n const ws = codegen.accounts[opts.workspace]\n const safesByLabel: Record<string, Account> = {}\n const rolesByLabel: Record<string, Account> = {}\n if (ws) {\n for (const [label, account] of Object.entries(ws.safes)) {\n safesByLabel[label] = account\n }\n for (const [label, account] of Object.entries(ws.rolesMods)) {\n rolesByLabel[label] = account\n }\n }\n\n const meta: ConstellationMeta = {\n label: opts.label,\n chain: opts.chain,\n workspaceId: (ws?.workspaceId ?? '') as UUID,\n }\n\n function makeNodeRef(\n data: Record<string, any>\n ): Readonly<Record<string, any>> {\n return Object.freeze({\n ...data,\n chain: opts.chain,\n _constellation: meta,\n })\n }\n\n function entityAccessor(\n registry: Record<string, Record<string, any>>,\n type: string\n ) {\n const cache = new Map<string, Record<string, any>>()\n return new Proxy({} as Record<string, any>, {\n get(_target: any, name: string) {\n if (typeof name !== 'string') return undefined\n const cached = cache.get(name)\n if (cached) return cached\n const existing = registry[name]\n // Bracket-access keys in the generated codegen carry a\n // ` (0xChecksummed…)` suffix when multiple workspace accounts share\n // a label. The label sent in the push spec should be the clean\n // original, so prefer `existing.label` when it's available.\n const specLabel: string = existing?.label ?? name\n const fn = (overrides?: Record<string, any>) =>\n makeNodeRef({\n type,\n ...(existing || {}),\n ...overrides,\n label: specLabel,\n })\n Object.assign(fn, {\n type,\n ...(existing || {}),\n label: specLabel,\n chain: opts.chain,\n _constellation: meta,\n })\n cache.set(name, fn)\n return fn\n },\n })\n }\n\n function userAccessor() {\n return new Proxy(\n {},\n {\n get(_target: any, name: string) {\n const user = codegen.users[name]\n if (!user) throw new Error(`Unknown user: ${name}`)\n const personalSafe = user.personalSafes[opts.chain]\n if (!personalSafe) {\n throw new Error(\n `User ${name} has no personal safe on chain ${opts.chain}`\n )\n }\n return personalSafe.address\n },\n }\n )\n }\n\n const safe = entityAccessor(safesByLabel, 'SAFE')\n const roles = entityAccessor(rolesByLabel, 'ROLES')\n\n return {\n safe,\n roles,\n user: userAccessor(),\n } as ConstellationResult<C, W, Ch>\n}\n","import type {\n ApplyConstellationPayload,\n ApplyConstellationResult,\n ChainId,\n} from '@zodiaceco/api-types'\nimport { invariant } from '@epic-web/invariant'\nimport {\n assertRecipientChains,\n isDeFiKitEntry,\n toAnnotation,\n} from './permissionEntries'\nimport { ApiClient } from './api'\nimport type {\n ConstellationMeta,\n ConstellationNode,\n ConstellationNodeInternal,\n RoleDef,\n} from './constellation'\n\ntype PushOpts = {\n /** API client instance. Defaults to a client configured from environment variables. */\n api?: ApiClient\n}\n\n/**\n * Resolves node references and pushes the constellation specification to the API.\n *\n *\n * ```ts\n * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })\n * const dao = eth.safe['GG DAO']\n * const roles = eth.roles['New Roles']({ nonce: 0n, target: dao, owner: dao, avatar: dao })\n *\n * await push([dao, roles])\n * ```\n */\nexport async function push(\n nodes: ConstellationNode[] | { [key: string]: ConstellationNode },\n opts?: PushOpts\n): Promise<ApplyConstellationResult[]> {\n const api = opts?.api ?? new ApiClient()\n const refs = deriveRefs(nodes)\n\n // Group nodes by constellation (multiple constellations can be applied with a single call)\n const groups = new Map<\n string,\n { meta: ConstellationMeta; nodes: ConstellationNodeInternal[] }\n >()\n\n for (const node of refs.byIdentity.keys()) {\n const meta = node._constellation\n invariant(\n meta,\n `Node \"${node.label}\" is not associated with a constellation`\n )\n const key = `${meta.workspaceId}:${meta.chain}:${meta.label}`\n let group = groups.get(key)\n if (!group) {\n group = { meta, nodes: [] }\n groups.set(key, group)\n }\n group.nodes.push(node)\n }\n\n const results: ApplyConstellationResult[] = []\n for (const { meta, nodes: groupNodes } of groups.values()) {\n const specification = groupNodes.map((n) => nodeToSpec(n, refs))\n const result = await api.applyConstellation(meta.workspaceId, {\n label: meta.label,\n chain: meta.chain,\n specification,\n })\n results.push(result)\n }\n\n return results\n}\n\ntype RefsIndex = {\n byIdentity: Map<ConstellationNodeInternal, string>\n byLabel: Map<string, string>\n}\n\nfunction labelKey(node: ConstellationNodeInternal): string {\n return `${node._constellation.workspaceId}:${node.type}:${node.label}`\n}\n\nfunction deriveRefs(\n nodes: ConstellationNode[] | { [key: string]: ConstellationNode }\n): RefsIndex {\n const byIdentity = new Map<ConstellationNodeInternal, string>()\n const byLabel = new Map<string, string>()\n\n const register = (node: ConstellationNodeInternal, ref: string) => {\n byIdentity.set(node, ref)\n byLabel.set(labelKey(node), ref)\n }\n\n if (Array.isArray(nodes)) {\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]\n invariant(\n isConstellationNode(node),\n `unexpected node input at index: ${i}`\n )\n register(node, `${i}`)\n }\n } else {\n for (const [key, node] of Object.entries(nodes)) {\n invariant(\n isConstellationNode(node),\n `unexpected node input under key: ${key}`\n )\n register(node, key)\n }\n }\n\n return { byIdentity, byLabel }\n}\n\nfunction nodeToSpec(\n node: ConstellationNodeInternal,\n refs: RefsIndex\n): ApplyConstellationPayload['specification'][number] {\n const { id, _constellation, ...rest } = node as Record<string, any>\n const spec: Record<string, any> = {}\n\n for (const [key, value] of Object.entries(rest)) {\n if (node.type === 'ROLES' && key === 'roles' && value != null) {\n spec.roles = describeRoles(\n value as Record<string, RoleDef | null>,\n node.chain,\n refs\n )\n continue\n }\n spec[key] = resolveRefs(value, refs)\n }\n\n spec.ref = refs.byIdentity.get(node)\n invariant(spec.ref != null, 'ref not found')\n\n return stringifyBigints(\n spec\n ) as ApplyConstellationPayload['specification'][number]\n}\n\n/**\n * Entries travel to the API as they were written — parameters and labels — and\n * are compiled when the constellation is deployed. Only a DeFi Kit entry is\n * rendered here, into the annotation uri that names the chain it was written\n * for; the permissions behind it are fetched from that uri at deploy.\n */\nfunction describeRoles(\n roles: Record<string, RoleDef | null>,\n chain: ChainId,\n refs: RefsIndex\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(roles).map(([key, def]) => {\n if (def == null) {\n return [key, null] as const\n }\n\n return [\n key,\n {\n key,\n members: resolveRefs(def.members, refs),\n permissions: def.permissions.map((entry) => {\n assertRecipientChains(entry, chain)\n\n return resolveRefs(\n isDeFiKitEntry(entry)\n ? { label: entry.label, annotation: toAnnotation(entry, chain) }\n : entry,\n refs\n )\n }),\n },\n ] as const\n })\n )\n}\n\nfunction resolveRefs(value: unknown, refs: RefsIndex): unknown {\n if (isConstellationNode(value)) {\n const ref = refs.byIdentity.get(value) ?? refs.byLabel.get(labelKey(value))\n invariant(\n ref != null,\n `Node \"${value.label}\" is referenced but not included in the push() call`\n )\n return `$${ref}`\n }\n\n if (Array.isArray(value)) {\n return value.map((v) => resolveRefs(v, refs))\n }\n\n if (typeof value === 'object' && value !== null) {\n const resolved: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n resolved[k] = resolveRefs(v, refs)\n }\n return resolved\n }\n\n // API expects lowercase addresses\n if (typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value)) {\n return value.toLowerCase()\n }\n\n return value\n}\n\nfunction stringifyBigints(value: unknown): unknown {\n if (typeof value === 'bigint') {\n return value.toString()\n }\n\n if (Array.isArray(value)) {\n return value.map(stringifyBigints)\n }\n\n if (typeof value === 'object' && value !== null) {\n const result: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n result[k] = stringifyBigints(v)\n }\n return result\n }\n\n return value\n}\n\nfunction isConstellationNode(\n value: unknown\n): value is ConstellationNodeInternal {\n if (typeof value === 'function' || typeof value === 'object') {\n const obj = value as any\n return (\n obj != null &&\n typeof obj.type === 'string' &&\n typeof obj.chain === 'number' &&\n typeof obj._constellation === 'object'\n )\n }\n return false\n}\n"],"mappings":";;;;;;;AAsRA,SAAS,cAA2B;AAElC,QADgB,cAAc,OAAO,KAAK,IAAI,CAC/B,kBAAkB,CAAC;;;;;;;;;;;;;;;AAgBpC,SAAgB,cAKd,MACA,UAC+B;CAC/B,MAAM,UAAuB,UAAU,WAAW,aAAa;CAE/D,MAAM,KAAK,QAAQ,SAAS,KAAK;CACjC,MAAM,eAAwC,EAAE;CAChD,MAAM,eAAwC,EAAE;AAChD,KAAI,IAAI;AACN,OAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,GAAG,MAAM,CACrD,cAAa,SAAS;AAExB,OAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,GAAG,UAAU,CACzD,cAAa,S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AAM,YAAY,GAAG,KAAK,CAAC;AAG/C,KAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,MAAM,WAAoC,EAAE;AAC5C,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,CACxC,UAAS,KAAK,YAAY,GAAG,KAAK;AAEpC,SAAO;;AAIT,KAAI,OAAO,UAAU,YAAY,sBAAsB,KAAK,MAAM,CAChE,QAAO,MAAM,aAAa;AAG5B,QAAO;;AAGT,SAAS,iBAAiB,OAAyB;AACjD,KAAI,OAAO,UAAU,SACnB,QAAO,MAAM,UAAU;AAGzB,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,iBAAiB;AAGpC,KAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,CACxC,QAAO,KAAK,iBAAiB,EAAE;AAEjC,SAAO;;AAGT,QAAO;;AAGT,SAAS,oBACP,OACoC;AACpC,KAAI,OAAO,UAAU,cAAc,OAAO,UAAU,UAAU;EAC5D,MAAM,MAAM;AACZ,SACE,OAAO,QACP,OAAO,IAAI,SAAS,YACpB,OAAO,IAAI,UAAU,YACrB,OAAO,IAAI,mBAAmB;;AAGlC,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/constellation.ts","../src/push.ts"],"sourcesContent":["/// <reference path=\"./zodiac-os-codegen.d.ts\" />\nimport type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { PermissionEntry } from './actions'\nimport type { AllowanceSpec } from './types'\nimport { createRequire } from 'module'\nimport { resolveZodiacDir } from './paths'\nimport { UUID } from 'crypto'\n\n/**\n * A role definition keyed by role name. Entries describe what the role may do —\n * parameters and labels, never compiled permissions. They are expanded into\n * `{ targets, annotations }` when the constellation is deployed, so that a\n * stored revision always compiles through the current compilers.\n */\nexport type RoleDef = {\n members: readonly AddressOrRef[]\n permissions: readonly PermissionEntry[]\n}\n\ntype User = {\n id: UUID\n fullName: string\n personalSafes: Record<\n number,\n { address: Lowercase<Address>; active: boolean }\n >\n}\n\ntype Account = {\n id: UUID\n label: string\n address: Lowercase<Address>\n chain: ChainId\n /** True for accounts promoted to a workspace vault. */\n vault: boolean\n}\n\n/**\n * Accounts grouped by node type within a workspace. Per-type maps keep\n * bracket-accessor namespaces separate: a SAFE and a ROLES mod sharing a\n * label don't collide, and `eth.safe[...]` IntelliSense doesn't suggest\n * ROLES mod labels (and vice versa).\n */\ntype WorkspaceAccounts = {\n workspaceId: UUID\n workspaceName: string\n safes: Readonly<Record<string, Account>>\n rolesMods: Readonly<Record<string, Account>>\n delays: Readonly<Record<string, Account>>\n}\n\n/** Shape of the codegen data produced by `zodiac pull-org`. */\nexport type CodegenData = {\n users: Readonly<Record<string, User>>\n accounts: Readonly<Record<string, WorkspaceAccounts>>\n}\n\n// If `pull-org` has been run, the consumer's `.zodiac/index.d.ts` augments\n// `ZodiacGeneratedCodegen` with literal `users`/`accounts` shapes. Otherwise\n// the interface is empty and we fall back to the wide `CodegenData`.\ntype GeneratedCodegen = ZodiacGeneratedCodegen extends CodegenData\n ? ZodiacGeneratedCodegen\n : CodegenData\n\ntype ConstellationOpts<C extends CodegenData> = {\n /** Workspace to scope accounts and roles to. */\n workspace: keyof C['accounts'] & string\n /** Human-readable label for this constellation. */\n label: string\n /** Target chain for all nodes in this constellation. */\n chain: ChainId\n}\n\ntype ConstellationInternalOpts<C extends CodegenData> = {\n /** Injected codegen data (used for testing). */\n codegen?: C\n}\n\ntype Prettify<T> = { readonly [K in keyof T]: T[K] } & {}\n\ntype SafeEntries<\n C extends CodegenData,\n W extends keyof C['accounts'],\n> = C['accounts'][W]['safes']\n\ntype RolesEntries<\n C extends CodegenData,\n W extends keyof C['accounts'],\n> = C['accounts'][W]['rolesMods']\n\ntype NodeType = 'SAFE' | 'ROLES' | 'DELAY'\n\n/** A reference to a node used in `owners`, `modules`, `target`, etc. */\nexport type NodeRef = Readonly<{\n type: NodeType\n label: string\n chain: ChainId\n}>\n\n/** A blockchain address (checksummed or lowercase) or a reference to another\n * node in the constellation. Values are normalized to lowercase before being\n * sent to the API. */\ntype AddressOrRef = Address | NodeRef\n\ntype NodeBase = Readonly<{\n /** Human-readable identifier, unique within the constellation. */\n label: string\n /** Chain the node is deployed on. */\n chain: ChainId\n /** Set for existing nodes (from codegen or bound by address), absent for new\n * nodes. Accepts checksummed or lowercase; normalized to lowercase on push. */\n address?: Address\n /** Deployment nonce — required for new nodes, optional for existing. */\n nonce?: bigint\n}>\n\n/** A safe node spec — existing vault ref or new safe with required config. */\nexport type SafeNode = NodeBase &\n Readonly<{\n /** Discriminator identifying this node as a Safe. */\n type: 'SAFE'\n /** Number of owner signatures required to execute a transaction. */\n threshold: number\n /** Safe owner addresses or node references. */\n owners: readonly (string | NodeRef)[]\n /** Module addresses or node references enabled on the safe. */\n modules?: readonly (string | NodeRef)[]\n /** Whether this safe shall appear as a vault in the workspace. @default false */\n vault?: boolean\n }>\n\n/** A roles modifier node spec — existing vault ref or new roles with modifier config. */\nexport type RolesNode = NodeBase &\n Readonly<{\n /** Discriminator identifying this node as a Roles modifier. */\n type: 'ROLES'\n /** The safe that this roles modifier controls. */\n target?: AddressOrRef\n /** The account that is allowed to update the configuration of the Roles mod. */\n owner?: AddressOrRef\n /** The account that calls will be executed from. */\n avatar?: AddressOrRef\n /** MultiSend contract addresses for batched transactions. */\n multisend?: readonly Address[]\n /** Role definitions configured on this modifier. Pass `null` for a key to\n * clear that role; unmentioned roles are left untouched. */\n roles?: Record<string, RoleDef | null>\n /** Spending allowances configured on this modifier, keyed by name. Pass\n * `null` for a key to clear that allowance; unmentioned allowances are\n * left untouched. */\n allowances?: Record<string, AllowanceSpec | null>\n }>\n\n/** Any complete node that can be passed to `push()`. */\nexport type ConstellationNode = SafeNode | RolesNode\nexport type ConstellationNodeInternal = ConstellationNode & {\n _constellation: ConstellationMeta\n}\n\ntype NewSafeProps = {\n /** Deployment nonce for CREATE2 address derivation. */\n nonce: bigint\n /** Number of owner signatures required to execute a transaction. */\n threshold: number\n /** Safe owner addresses or node references. */\n owners: readonly AddressOrRef[]\n /** Module addresses or node references to enable on the safe. */\n modules?: readonly AddressOrRef[]\n /** Whether this safe is a workspace vault. @default false */\n vault?: boolean\n}\n\n/** Configuration shared by both ways of declaring a roles modifier. */\ntype RolesConfig = {\n /** The safe that this roles modifier controls. Defaults to the new safe with the same label, when one exists. */\n target?: AddressOrRef\n /** The account that calls will be executed from. Defaults to `target` value */\n avatar?: AddressOrRef\n /** The account that is allowed to update the configuration of the Roles Mod. Defaults to `target` value */\n owner?: AddressOrRef\n /** MultiSend contract addresses for batched transactions. Defaults to `['0x38869bf66a61cf6bdb996a6ae40d5853fd43b526', '0x9641d764fc13c8b624c04430c7356c1c7c8102e2']` */\n multisend?: readonly Address[]\n /** Role definitions to configure on this modifier. Pass `null` for a key to\n * clear that role; unmentioned roles are left untouched. */\n roles?: Record<string, RoleDef | null>\n /** Spending allowances to configure on this modifier, keyed by name. Pass\n * `null` for a key to clear that allowance; unmentioned allowances are\n * left untouched. */\n allowances?: Record<string, AllowanceSpec | null>\n}\n\n/** Declare a brand-new roles modifier (address derived via CREATE2 from `nonce`). */\ntype NewRolesByNonce = RolesConfig & {\n /** Deployment nonce for CREATE2 address derivation. */\n nonce: bigint\n}\n\n/** Bind to a roles modifier already deployed on-chain at a known address, to\n * reconfigure its roles/allowances. Use this for mods not (yet) imported into\n * the workspace — pass the address instead of a deployment `nonce`. */\ntype ExistingRolesByAddress = RolesConfig & {\n /** Address of the existing Roles mod to bind to and reconfigure. */\n address: Address\n}\n\ntype NewRolesProps = NewRolesByNonce | ExistingRolesByAddress\n\ntype ExistingNodeAccessor<\n Type extends string,\n K extends string,\n E,\n Ch extends ChainId,\n NP extends Record<string, any>,\n> = Readonly<Prettify<E & { type: Type; label: K; chain: Ch }>> &\n (<\n O extends {\n [P in Exclude<keyof E & string, 'id' | 'label'>]?: any\n } & Partial<NP> = {},\n >(\n overrides?: {\n [P in Exclude<keyof E & string, 'id' | 'label'>]?: any\n } & Partial<NP> &\n O\n ) => Readonly<\n Prettify<\n Omit<E, keyof O> & O & Partial<NP> & { type: Type; label: K; chain: Ch }\n >\n >)\n\ntype NewNodeAccessor<\n Type extends string,\n Ch extends ChainId,\n NP extends Record<string, any>,\n> = Readonly<Prettify<{ type: Type; label: string; chain: Ch }>> &\n (<P extends NP>(\n props: P\n ) => Readonly<Prettify<P & { type: Type; label: string; chain: Ch }>>)\n\ntype EntityAccessor<\n Type extends string,\n Entries extends Record<string, any>,\n Ch extends ChainId = ChainId,\n NP extends Record<string, any> = Record<string, any>,\n> = {\n readonly [K in keyof Entries & string]: ExistingNodeAccessor<\n Type,\n K,\n Entries[K],\n Ch,\n NP\n >\n} & {\n readonly [key: string]: NewNodeAccessor<Type, Ch, NP>\n}\n\ntype UserAccessor<C extends CodegenData, Ch extends number> = {\n readonly [K in keyof C['users'] &\n string]: C['users'][K]['personalSafes'][Ch]['address']\n}\n\ntype ConstellationResult<\n C extends CodegenData,\n W extends keyof C['accounts'] = keyof C['accounts'],\n Ch extends ChainId = ChainId,\n> = {\n /** Access existing safes by label or create new ones with a new label.\n * Only SAFE-typed accounts are suggested in IntelliSense. */\n safe: EntityAccessor<'SAFE', SafeEntries<C, W>, Ch, NewSafeProps>\n /** Access existing roles modifiers by label or create new ones with a\n * new label. Only ROLES-typed accounts are suggested in IntelliSense. */\n roles: EntityAccessor<'ROLES', RolesEntries<C, W>, Ch, NewRolesProps>\n /** Resolve a user's personal safe address on the constellation's chain. */\n user: UserAccessor<C, Ch>\n}\n\n/** @internal */\nexport type ConstellationMeta = {\n label: string\n chain: ChainId\n workspaceId: UUID\n}\n\nfunction loadCodegen(): CodegenData {\n const require = createRequire(import.meta.url)\n return require(resolveZodiacDir()) as CodegenData\n}\n\n/**\n * Creates a constellation scoped to a workspace and chain.\n *\n * Use bracket access to reference existing accounts (vaults and other\n * applied constellation nodes) or define new ones:\n * ```ts\n * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })\n *\n * const dao = eth.safe['GG DAO'] // existing account ref\n * const roles = eth.roles['GG DAO'] // existing roles ref\n * const newSafe = eth.safe['New Safe']({ nonce: 0n, threshold: 2, owners: [...], modules: [...] })\n * ```\n */\nexport function constellation<\n const C extends CodegenData = GeneratedCodegen,\n const W extends keyof C['accounts'] & string = keyof C['accounts'] & string,\n const Ch extends ChainId = ChainId,\n>(\n opts: ConstellationOpts<C> & { workspace: W; chain: Ch },\n internal?: ConstellationInternalOpts<C>\n): ConstellationResult<C, W, Ch> {\n const codegen: CodegenData = internal?.codegen ?? loadCodegen()\n\n const ws = codegen.accounts[opts.workspace]\n const safesByLabel: Record<string, Account> = {}\n const rolesByLabel: Record<string, Account> = {}\n if (ws) {\n for (const [label, account] of Object.entries(ws.safes)) {\n safesByLabel[label] = account\n }\n for (const [label, account] of Object.entries(ws.rolesMods)) {\n rolesByLabel[label] = account\n }\n }\n\n const meta: ConstellationMeta = {\n label: opts.label,\n chain: opts.chain,\n workspaceId: (ws?.workspaceId ?? '') as UUID,\n }\n\n function makeNodeRef(\n data: Record<string, any>\n ): Readonly<Record<string, any>> {\n return Object.freeze({\n ...data,\n chain: opts.chain,\n _constellation: meta,\n })\n }\n\n function entityAccessor(\n registry: Record<string, Record<string, any>>,\n type: string\n ) {\n const cache = new Map<string, Record<string, any>>()\n return new Proxy({} as Record<string, any>, {\n get(_target: any, name: string) {\n if (typeof name !== 'string') return undefined\n const cached = cache.get(name)\n if (cached) return cached\n const existing = registry[name]\n // Bracket-access keys in the generated codegen carry a\n // ` (0xChecksummed…)` suffix when multiple workspace accounts share\n // a label. The label sent in the push spec should be the clean\n // original, so prefer `existing.label` when it's available.\n const specLabel: string = existing?.label ?? name\n const fn = (overrides?: Record<string, any>) =>\n makeNodeRef({\n type,\n ...(existing || {}),\n ...overrides,\n label: specLabel,\n })\n Object.assign(fn, {\n type,\n ...(existing || {}),\n label: specLabel,\n chain: opts.chain,\n _constellation: meta,\n })\n cache.set(name, fn)\n return fn\n },\n })\n }\n\n function userAccessor() {\n return new Proxy(\n {},\n {\n get(_target: any, name: string) {\n const user = codegen.users[name]\n if (!user) throw new Error(`Unknown user: ${name}`)\n const personalSafe = user.personalSafes[opts.chain]\n if (!personalSafe) {\n throw new Error(\n `User ${name} has no personal safe on chain ${opts.chain}`\n )\n }\n return personalSafe.address\n },\n }\n )\n }\n\n const safe = entityAccessor(safesByLabel, 'SAFE')\n const roles = entityAccessor(rolesByLabel, 'ROLES')\n\n return {\n safe,\n roles,\n user: userAccessor(),\n } as ConstellationResult<C, W, Ch>\n}\n","import type {\n ApplyConstellationPayload,\n ApplyConstellationResult,\n ChainId,\n} from '@zodiaceco/api-types'\nimport { invariant } from '@epic-web/invariant'\nimport {\n assertRecipientChains,\n isDeFiKitEntry,\n toAnnotation,\n} from './permissionEntries'\nimport { ApiClient } from './api'\nimport type {\n ConstellationMeta,\n ConstellationNode,\n ConstellationNodeInternal,\n RoleDef,\n} from './constellation'\n\ntype PushOpts = {\n /** API client instance. Defaults to a client configured from environment variables. */\n api?: ApiClient\n}\n\n/**\n * Resolves node references and pushes the constellation specification to the API.\n *\n *\n * ```ts\n * const eth = constellation({ workspace: 'GG', label: 'my constellation', chain: 1 })\n * const dao = eth.safe['GG DAO']\n * const roles = eth.roles['New Roles']({ nonce: 0n, target: dao, owner: dao, avatar: dao })\n *\n * await push([dao, roles])\n * ```\n */\nexport async function push(\n nodes: ConstellationNode[] | { [key: string]: ConstellationNode },\n opts?: PushOpts\n): Promise<ApplyConstellationResult[]> {\n const api = opts?.api ?? new ApiClient()\n const refs = deriveRefs(nodes)\n\n // Group nodes by constellation (multiple constellations can be applied with a single call)\n const groups = new Map<\n string,\n { meta: ConstellationMeta; nodes: ConstellationNodeInternal[] }\n >()\n\n for (const node of refs.byIdentity.keys()) {\n const meta = node._constellation\n invariant(\n meta,\n `Node \"${node.label}\" is not associated with a constellation`\n )\n const key = `${meta.workspaceId}:${meta.chain}:${meta.label}`\n let group = groups.get(key)\n if (!group) {\n group = { meta, nodes: [] }\n groups.set(key, group)\n }\n group.nodes.push(node)\n }\n\n const results: ApplyConstellationResult[] = []\n for (const { meta, nodes: groupNodes } of groups.values()) {\n const specification = groupNodes.map((n) => nodeToSpec(n, refs))\n const result = await api.applyConstellation(meta.workspaceId, {\n label: meta.label,\n chain: meta.chain,\n specification,\n })\n results.push(result)\n }\n\n return results\n}\n\ntype RefsIndex = {\n byIdentity: Map<ConstellationNodeInternal, string>\n byLabel: Map<string, string>\n}\n\nfunction labelKey(node: ConstellationNodeInternal): string {\n return `${node._constellation.workspaceId}:${node.type}:${node.label}`\n}\n\nfunction deriveRefs(\n nodes: ConstellationNode[] | { [key: string]: ConstellationNode }\n): RefsIndex {\n const byIdentity = new Map<ConstellationNodeInternal, string>()\n const byLabel = new Map<string, string>()\n\n const register = (node: ConstellationNodeInternal, ref: string) => {\n byIdentity.set(node, ref)\n byLabel.set(labelKey(node), ref)\n }\n\n if (Array.isArray(nodes)) {\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]\n invariant(\n isConstellationNode(node),\n `unexpected node input at index: ${i}`\n )\n register(node, `${i}`)\n }\n } else {\n for (const [key, node] of Object.entries(nodes)) {\n invariant(\n isConstellationNode(node),\n `unexpected node input under key: ${key}`\n )\n register(node, key)\n }\n }\n\n return { byIdentity, byLabel }\n}\n\nfunction nodeToSpec(\n node: ConstellationNodeInternal,\n refs: RefsIndex\n): ApplyConstellationPayload['specification'][number] {\n const { id, _constellation, ...rest } = node as Record<string, any>\n const spec: Record<string, any> = {}\n\n for (const [key, value] of Object.entries(rest)) {\n if (node.type === 'ROLES' && key === 'roles' && value != null) {\n spec.roles = describeRoles(\n value as Record<string, RoleDef | null>,\n node.chain,\n refs\n )\n continue\n }\n spec[key] = resolveRefs(value, refs)\n }\n\n spec.ref = refs.byIdentity.get(node)\n invariant(spec.ref != null, 'ref not found')\n\n return stringifyBigints(\n spec\n ) as ApplyConstellationPayload['specification'][number]\n}\n\n/**\n * Entries travel to the API as they were written — parameters and labels — and\n * are compiled when the constellation is deployed. Only a DeFi Kit entry is\n * rendered here, into the annotation uri that names the chain it was written\n * for; the permissions behind it are fetched from that uri at deploy.\n */\nfunction describeRoles(\n roles: Record<string, RoleDef | null>,\n chain: ChainId,\n refs: RefsIndex\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(roles).map(([key, def]) => {\n if (def == null) {\n return [key, null] as const\n }\n\n return [\n key,\n {\n key,\n members: resolveRefs(def.members, refs),\n permissions: def.permissions.map((entry) => {\n assertRecipientChains(entry, chain)\n\n return resolveRefs(\n isDeFiKitEntry(entry)\n ? { label: entry.label, annotation: toAnnotation(entry, chain) }\n : entry,\n refs\n )\n }),\n },\n ] as const\n })\n )\n}\n\nfunction resolveRefs(value: unknown, refs: RefsIndex): unknown {\n if (isConstellationNode(value)) {\n const ref = refs.byIdentity.get(value) ?? refs.byLabel.get(labelKey(value))\n invariant(\n ref != null,\n `Node \"${value.label}\" is referenced but not included in the push() call`\n )\n return `$${ref}`\n }\n\n if (Array.isArray(value)) {\n return value.map((v) => resolveRefs(v, refs))\n }\n\n if (typeof value === 'object' && value !== null) {\n const resolved: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n resolved[k] = resolveRefs(v, refs)\n }\n return resolved\n }\n\n // API expects lowercase addresses\n if (typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value)) {\n return value.toLowerCase()\n }\n\n return value\n}\n\nfunction stringifyBigints(value: unknown): unknown {\n if (typeof value === 'bigint') {\n return value.toString()\n }\n\n if (Array.isArray(value)) {\n return value.map(stringifyBigints)\n }\n\n if (typeof value === 'object' && value !== null) {\n const result: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n result[k] = stringifyBigints(v)\n }\n return result\n }\n\n return value\n}\n\nfunction isConstellationNode(\n value: unknown\n): value is ConstellationNodeInternal {\n if (typeof value === 'function' || typeof value === 'object') {\n const obj = value as any\n return (\n obj != null &&\n typeof obj.type === 'string' &&\n typeof obj.chain === 'number' &&\n typeof obj._constellation === 'object'\n )\n }\n return false\n}\n"],"mappings":";;;;;;;AA0RA,SAAS,cAA2B;AAElC,QADgB,cAAc,OAAO,KAAK,IAAI,CAC/B,kBAAkB,CAAC;;;;;;;;;;;;;;;AAgBpC,SAAgB,cAKd,MACA,UAC+B;CAC/B,MAAM,UAAuB,UAAU,WAAW,aAAa;CAE/D,MAAM,KAAK,QAAQ,SAAS,KAAK;CACjC,MAAM,eAAwC,EAAE;CAChD,MAAM,eAAwC,EAAE;AAChD,KAAI,IAAI;AACN,OAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,GAAG,MAAM,CACrD,cAAa,SAAS;AAExB,OAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,GAAG,UAAU,CACzD,cAAa,SAAS;;CAI1B,MAAM,OAA0B;EAC9B,OAAO,KAAK;EACZ,OAAO,KAAK;EACZ,aAAc,IAAI,eAAe;EAClC;CAED,SAAS,YACP,MAC+B;AAC/B,SAAO,OAAO,OAAO;GACnB,GAAG;GACH,OAAO,KAAK;GACZ,gBAAgB;GACjB,CAAC;;CAGJ,SAAS,eACP,UACA,MACA;EACA,MAAM,wBAAQ,IAAI,KAAkC;AACpD,SAAO,IAAI,MAAM,EAAE,EAAyB,EAC1C,IAAI,SAAc,MAAc;AAC9B,OAAI,OAAO,SAAS,SAAU,QAAO,KAAA;GACrC,MAAM,SAAS,MAAM,IAAI,KAAK;AAC9B,OAAI,OAAQ,QAAO;GACnB,MAAM,WAAW,SAAS;GAK1B,MAAM,YAAoB,UAAU,SAAS;GAC7C,MAAM,MAAM,cACV,YAAY;IACV;IACA,GAAI,YAAY,EAAE;IAClB,GAAG;IACH,OAAO;IACR,CAAC;AACJ,UAAO,OAAO,IAAI;IAChB;IACA,GAAI,YAAY,EAAE;IAClB,OAAO;IACP,OAAO,KAAK;IACZ,gBAAgB;IACjB,CAAC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UAAU,UAAU;EAC5D,MAAM,MAAM;AACZ,SACE,OAAO,QACP,OAAO,IAAI,SAAS,YACpB,OAAO,IAAI,UAAU,YACrB,OAAO,IAAI,mBAAmB;;AAGlC,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"permissionEntries-D3fSVhwO.mjs","names":[],"sources":["../src/permissionEntries.ts"],"sourcesContent":["import type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { Permission } from 'zodiac-roles-sdk'\n\n/**\n * The shapes a role's `permissions` travel to the API in, and the one piece of\n * rendering `push()` still does. Internal: the helpers that build these live in\n * `./actions`, and nothing here is part of the published interface beyond the\n * `PermissionEntry` type that module re-exports.\n */\n\n/**\n * The base url of the DeFi Kit API. Annotations point back at it so that a role\n * can be read as presets again, and so that a DeFi Kit entry written in code is\n * indistinguishable from one configured in the app.\n */\nconst DEFI_KIT_BASE_URL = 'https://kit.kpk.io/api/v1'\n\n/** The chains DeFi Kit serves, by the prefix it addresses them with. */\nconst DEFI_KIT_CHAIN_PREFIXES: Record<number, string> = {\n 1: 'eth',\n 10: 'oeth',\n 100: 'gno',\n 8453: 'base',\n 42161: 'arb1',\n}\n\n/** Renders a DeFi Kit entry into the annotation it stands for on `chain`. */\nexport const toAnnotation = (\n { defiKit: { protocol, verb, params } }: DeFiKitEntry,\n chain: ChainId\n) => {\n const prefix = DEFI_KIT_CHAIN_PREFIXES[chain]\n\n if (prefix == null) {\n throw new Error(`DeFi Kit does not serve chain \"${chain}\"`)\n }\n\n return {\n uri: `${DEFI_KIT_BASE_URL}/permissions/${prefix}/${protocol}/${verb}?${searchParams(params)}`,\n schema: `${DEFI_KIT_BASE_URL}/openapi.json`,\n }\n}\n\nexport const isDeFiKitEntry = (entry: PermissionEntry): entry is DeFiKitEntry =>\n typeof entry === 'object' && entry !== null && 'defiKit' in entry\n\n/**\n * The chains of the node recipients a `transfer()`'s same-chain `to` named.\n * Symbol-keyed so it never serializes; `push()` checks it against the chain of\n * the roles node the entry ends up on. A transfer to a node on another chain\n * would permit sending funds to an address that may not exist there.\n */\nexport const recipientChains = Symbol('recipientChains')\n\nexport const assertRecipientChains = (\n entry: PermissionEntry,\n chain: ChainId\n): void => {\n const chains = (entry as { [recipientChains]?: readonly ChainId[] })[\n recipientChains\n ]\n\n for (const recipientChain of chains ?? []) {\n if (recipientChain !== chain) {\n const label = 'label' in entry ? `\"${entry.label}\"` : 'a transfer'\n throw new Error(\n `A recipient of ${label} lives on chain \"${recipientChain}\", but the role is on chain \"${chain}\". Use \\`bridge\\` for cross-chain recipients.`\n )\n }\n }\n}\n\n/**\n * Search params are appended one value at a time, the form annotation uris are\n * normalized to before they are matched back against a preset.\n */\nconst searchParams = (params: Record<string, DeFiKitParamValue>) => {\n const searchParams = new URLSearchParams()\n\n for (const [name, value] of Object.entries(params)) {\n if (value == null) {\n continue\n }\n\n for (const entry of Array.isArray(value) ? value : [value]) {\n searchParams.append(name, String(entry))\n }\n }\n\n return searchParams\n}\n\n/**\n * An allowance key. Authored as a plain label, the way a role key is, and\n * encoded to bytes32 when the constellation is deployed. An already-encoded\n * key still works — `encodeKey` passes 32-byte hex through unchanged.\n */\nexport type AllowanceKey = string\n\nexport type SwapEntry = {\n label: string\n action: { type: 'swap'; sell: Address[]; buy: Address[] }\n}\n\nexport type TransferEntry = {\n label: string\n action: {\n type: 'transfer'\n tokens: Address[]\n to: Address[]\n bridge?: { chain: ChainId; to: Address[]; receive: Address[] }[]\n allowance?: AllowanceKey\n }\n}\n\nexport type LabelledPermissions = {\n label: string\n permissions: Permission[]\n}\n\nexport type DeFiKitEntry = {\n label: string\n defiKit: {\n protocol: string\n verb: string\n params: Record<string, DeFiKitParamValue>\n }\n}\n\nexport type DeFiKitParamValue =\n | string\n | number\n | boolean\n | readonly (string | number | boolean)[]\n | null\n | undefined\n\n/**\n * One entry of a role's `permissions`. A bare permission stays valid, but every\n * labelled form names something the app can show as a single card.\n */\nexport type PermissionEntry =\n | Permission\n | LabelledPermissions\n | SwapEntry\n | TransferEntry\n | DeFiKitEntry\n\n/** A role's full permission list — the type `permissions.ts` files satisfy. */\nexport type Permissions = readonly PermissionEntry[]\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,oBAAoB;;AAG1B,MAAM,0BAAkD;CACtD,GAAG;CACH,IAAI;CACJ,KAAK;CACL,MAAM;CACN,OAAO;CACR;;AAGD,MAAa,gBACX,EAAE,SAAS,EAAE,UAAU,MAAM,YAC7B,UACG;CACH,MAAM,SAAS,wBAAwB;AAEvC,KAAI,UAAU,KACZ,OAAM,IAAI,MAAM,kCAAkC,MAAM,GAAG;AAG7D,QAAO;EACL,KAAK,GAAG,kBAAkB,eAAe,OAAO,GAAG,SAAS,GAAG,KAAK,GAAG,aAAa,OAAO;EAC3F,QAAQ,GAAG,kBAAkB;EAC9B;;AAGH,MAAa,kBAAkB,UAC7B,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;;;;;;;AAQ9D,MAAa,kBAAkB,OAAO,kBAAkB;AAExD,MAAa,yBACX,OACA,UACS;CACT,MAAM,SAAU,MACd;AAGF,MAAK,MAAM,kBAAkB,UAAU,EAAE,CACvC,KAAI,mBAAmB,OAAO;EAC5B,MAAM,QAAQ,WAAW,QAAQ,IAAI,MAAM,MAAM,KAAK;AACtD,QAAM,IAAI,MACR,kBAAkB,MAAM,mBAAmB,eAAe,+BAA+B,MAAM,+CAChG;;;;;;;AASP,MAAM,gBAAgB,WAA8C;CAClE,MAAM,eAAe,IAAI,iBAAiB;AAE1C,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,EAAE;AAClD,MAAI,SAAS,KACX;AAGF,OAAK,MAAM,SAAS,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM,CACxD,cAAa,OAAO,MAAM,OAAO,MAAM,CAAC;;AAI5C,QAAO"}
1
+ {"version":3,"file":"permissionEntries-D3fSVhwO.mjs","names":[],"sources":["../src/permissionEntries.ts"],"sourcesContent":["import type { Address, ChainId } from '@zodiaceco/api-types'\nimport type { Permission } from 'zodiac-roles-sdk'\nimport type { NodeRef } from './constellation'\n\n/**\n * The shapes a role's `permissions` travel to the API in, and the one piece of\n * rendering `push()` still does. Internal: the helpers that build these live in\n * `./actions`, and nothing here is part of the published interface beyond the\n * `PermissionEntry` type that module re-exports.\n */\n\n/**\n * The base url of the DeFi Kit API. Annotations point back at it so that a role\n * can be read as presets again, and so that a DeFi Kit entry written in code is\n * indistinguishable from one configured in the app.\n */\nconst DEFI_KIT_BASE_URL = 'https://kit.kpk.io/api/v1'\n\n/** The chains DeFi Kit serves, by the prefix it addresses them with. */\nconst DEFI_KIT_CHAIN_PREFIXES: Record<number, string> = {\n 1: 'eth',\n 10: 'oeth',\n 100: 'gno',\n 8453: 'base',\n 42161: 'arb1',\n}\n\n/** Renders a DeFi Kit entry into the annotation it stands for on `chain`. */\nexport const toAnnotation = (\n { defiKit: { protocol, verb, params } }: DeFiKitEntry,\n chain: ChainId\n) => {\n const prefix = DEFI_KIT_CHAIN_PREFIXES[chain]\n\n if (prefix == null) {\n throw new Error(`DeFi Kit does not serve chain \"${chain}\"`)\n }\n\n return {\n uri: `${DEFI_KIT_BASE_URL}/permissions/${prefix}/${protocol}/${verb}?${searchParams(params)}`,\n schema: `${DEFI_KIT_BASE_URL}/openapi.json`,\n }\n}\n\nexport const isDeFiKitEntry = (entry: PermissionEntry): entry is DeFiKitEntry =>\n typeof entry === 'object' && entry !== null && 'defiKit' in entry\n\n/**\n * The chains of the node recipients a `transfer()`'s same-chain `to` named.\n * Symbol-keyed so it never serializes; `push()` checks it against the chain of\n * the roles node the entry ends up on. A transfer to a node on another chain\n * would permit sending funds to an address that may not exist there.\n */\nexport const recipientChains = Symbol('recipientChains')\n\nexport const assertRecipientChains = (\n entry: PermissionEntry,\n chain: ChainId\n): void => {\n const chains = (entry as { [recipientChains]?: readonly ChainId[] })[\n recipientChains\n ]\n\n for (const recipientChain of chains ?? []) {\n if (recipientChain !== chain) {\n const label = 'label' in entry ? `\"${entry.label}\"` : 'a transfer'\n throw new Error(\n `A recipient of ${label} lives on chain \"${recipientChain}\", but the role is on chain \"${chain}\". Use \\`bridge\\` for cross-chain recipients.`\n )\n }\n }\n}\n\n/**\n * Search params are appended one value at a time, the form annotation uris are\n * normalized to before they are matched back against a preset.\n */\nconst searchParams = (params: Record<string, DeFiKitParamValue>) => {\n const searchParams = new URLSearchParams()\n\n for (const [name, value] of Object.entries(params)) {\n if (value == null) {\n continue\n }\n\n for (const entry of Array.isArray(value) ? value : [value]) {\n searchParams.append(name, String(entry))\n }\n }\n\n return searchParams\n}\n\n/**\n * An allowance key. Authored as a plain label, the way a role key is, and\n * encoded to bytes32 when the constellation is deployed. An already-encoded\n * key still works — `encodeKey` passes 32-byte hex through unchanged.\n */\nexport type AllowanceKey = string\n\nexport type SwapEntry = {\n label: string\n action: { type: 'swap'; sell: Address[]; buy: Address[] }\n}\n\nexport type TransferEntry = {\n label: string\n action: {\n type: 'transfer'\n tokens: Address[]\n to: Address[]\n bridge?: { chain: ChainId; to: Address[]; receive: Address[] }[]\n allowance?: AllowanceKey\n }\n}\n\n/**\n * A permission's target, written either as an address or as another node in the\n * same constellation.\n *\n * A policy is usually pushed alongside the accounts it governs, so the address\n * a permission points at often does not exist yet. Naming the node instead\n * sends a reference, and the address is substituted once it is derived at\n * deploy — the same way a node is named as an owner, a module or an avatar.\n *\n * `NodeRef` for the same reason those fields use it: an uninvoked accessor is\n * a forward reference to a node, and is how two nodes that need each other are\n * written. It carries the label a reference resolves by without being a\n * complete node.\n */\nexport type PermissionTarget = `0x${string}` | NodeRef\n\ntype WithNodeTarget<P> = P extends { targetAddress: `0x${string}` }\n ? Omit<P, 'targetAddress'> & { targetAddress: PermissionTarget }\n : P\n\n/** A `zodiac-roles-sdk` permission that may name a node as its target. */\nexport type ConstellationPermission = WithNodeTarget<Permission>\n\nexport type LabelledPermissions = {\n label: string\n permissions: ConstellationPermission[]\n}\n\nexport type DeFiKitEntry = {\n label: string\n defiKit: {\n protocol: string\n verb: string\n params: Record<string, DeFiKitParamValue>\n }\n}\n\nexport type DeFiKitParamValue =\n | string\n | number\n | boolean\n | readonly (string | number | boolean)[]\n | null\n | undefined\n\n/**\n * One entry of a role's `permissions`. A bare permission stays valid, but every\n * labelled form names something the app can show as a single card.\n */\nexport type PermissionEntry =\n | ConstellationPermission\n | LabelledPermissions\n | SwapEntry\n | TransferEntry\n | DeFiKitEntry\n\n/** A role's full permission list — the type `permissions.ts` files satisfy. */\nexport type Permissions = readonly PermissionEntry[]\n"],"mappings":";;;;;;;;;;;;AAgBA,MAAM,oBAAoB;;AAG1B,MAAM,0BAAkD;CACtD,GAAG;CACH,IAAI;CACJ,KAAK;CACL,MAAM;CACN,OAAO;CACR;;AAGD,MAAa,gBACX,EAAE,SAAS,EAAE,UAAU,MAAM,YAC7B,UACG;CACH,MAAM,SAAS,wBAAwB;AAEvC,KAAI,UAAU,KACZ,OAAM,IAAI,MAAM,kCAAkC,MAAM,GAAG;AAG7D,QAAO;EACL,KAAK,GAAG,kBAAkB,eAAe,OAAO,GAAG,SAAS,GAAG,KAAK,GAAG,aAAa,OAAO;EAC3F,QAAQ,GAAG,kBAAkB;EAC9B;;AAGH,MAAa,kBAAkB,UAC7B,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;;;;;;;AAQ9D,MAAa,kBAAkB,OAAO,kBAAkB;AAExD,MAAa,yBACX,OACA,UACS;CACT,MAAM,SAAU,MACd;AAGF,MAAK,MAAM,kBAAkB,UAAU,EAAE,CACvC,KAAI,mBAAmB,OAAO;EAC5B,MAAM,QAAQ,WAAW,QAAQ,IAAI,MAAM,MAAM,KAAK;AACtD,QAAM,IAAI,MACR,kBAAkB,MAAM,mBAAmB,eAAe,+BAA+B,MAAM,+CAChG;;;;;;;AASP,MAAM,gBAAgB,WAA8C;CAClE,MAAM,eAAe,IAAI,iBAAiB;AAE1C,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,EAAE;AAClD,MAAI,SAAS,KACX;AAGF,OAAK,MAAM,SAAS,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM,CACxD,cAAa,OAAO,MAAM,OAAO,MAAM,CAAC;;AAI5C,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zodiaceco/sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "author": "Zodiac Labs GmbH",
5
5
  "license": "LGPL-3.0-only",
6
6
  "homepage": "https://github.com/gnosisguild/zodiac-sdk",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@epic-web/invariant": "1.0.0",
54
- "@zodiaceco/api-types": "^1.7.0",
54
+ "@zodiaceco/api-types": "^1.9.0",
55
55
  "commander": "^14.0.3",
56
56
  "defi-kit": "^2.26.12",
57
57
  "dotenv": "^17.4.2",
@@ -1,152 +0,0 @@
1
- import { Permission } from "zodiac-roles-sdk";
2
- import { Address, ApplyConstellationPayload, ChainId } from "@zodiaceco/api-types";
3
- import { allow } from "defi-kit/eth";
4
-
5
- //#region src/permissionEntries.d.ts
6
- /**
7
- * An allowance key. Authored as a plain label, the way a role key is, and
8
- * encoded to bytes32 when the constellation is deployed. An already-encoded
9
- * key still works — `encodeKey` passes 32-byte hex through unchanged.
10
- */
11
- type AllowanceKey = string;
12
- type SwapEntry = {
13
- label: string;
14
- action: {
15
- type: 'swap';
16
- sell: Address[];
17
- buy: Address[];
18
- };
19
- };
20
- type TransferEntry = {
21
- label: string;
22
- action: {
23
- type: 'transfer';
24
- tokens: Address[];
25
- to: Address[];
26
- bridge?: {
27
- chain: ChainId;
28
- to: Address[];
29
- receive: Address[];
30
- }[];
31
- allowance?: AllowanceKey;
32
- };
33
- };
34
- type LabelledPermissions = {
35
- label: string;
36
- permissions: Permission[];
37
- };
38
- type DeFiKitEntry = {
39
- label: string;
40
- defiKit: {
41
- protocol: string;
42
- verb: string;
43
- params: Record<string, DeFiKitParamValue>;
44
- };
45
- };
46
- type DeFiKitParamValue = string | number | boolean | readonly (string | number | boolean)[] | null | undefined;
47
- /**
48
- * One entry of a role's `permissions`. A bare permission stays valid, but every
49
- * labelled form names something the app can show as a single card.
50
- */
51
- type PermissionEntry = Permission | LabelledPermissions | SwapEntry | TransferEntry | DeFiKitEntry;
52
- /** A role's full permission list — the type `permissions.ts` files satisfy. */
53
- type Permissions = readonly PermissionEntry[];
54
- //#endregion
55
- //#region src/types.d.ts
56
- type ApiNewRolesSpec = Extract<ApplyConstellationPayload['specification'][number], {
57
- type: 'ROLES';
58
- nonce: string;
59
- }>;
60
- /** A role definition in the API's serialized format (bigints as template literal strings). */
61
- /** An allowance definition in the API's serialized format (bigints as template literal strings). */
62
- type ApiAllowanceSpec = Extract<NonNullable<ApiNewRolesSpec['allowances']>, readonly any[]>[number];
63
- /** Recursively converts `${bigint}` template literal strings to `bigint`. */
64
- type RealBigints<T> = T extends `${bigint}` ? bigint : T extends readonly (infer U)[] ? RealBigints<U>[] : T extends Record<string, any> ? { [K in keyof T]: RealBigints<T[K]> } : T;
65
- /** A role definition with bigint fields as actual bigints. */
66
- /** An allowance definition with bigint fields as actual bigints. */
67
- type AllowanceSpec = RealBigints<ApiAllowanceSpec>;
68
- //#endregion
69
- //#region src/actions.d.ts
70
- /**
71
- * Allows signing CoW orders selling any of `sell` for any of `buy`. The
72
- * parameters are compiled into permissions when the constellation is deployed,
73
- * never here — a stored revision that carried its own copy would go stale as
74
- * soon as the compiler changed.
75
- */
76
- declare const swap: ({
77
- label,
78
- sell,
79
- buy
80
- }: SwapParams) => SwapEntry;
81
- /**
82
- * Allows transferring any of `tokens` to any of `to` on the role's own chain,
83
- * and — through `bridge` — to recipients on other chains over Across. Both are
84
- * optional on their own; a transfer names at least one recipient somewhere.
85
- */
86
- declare const transfer: ({
87
- label,
88
- tokens,
89
- to,
90
- bridge,
91
- allowance
92
- }: TransferParams) => TransferEntry;
93
- /**
94
- * A labelled bag of `allow`-kit permissions — the code-side counterpart of the
95
- * app's Custom action, for everything the other action types don't cover. It
96
- * takes plain permissions, not other actions.
97
- */
98
- declare const custom: ({
99
- label,
100
- permissions
101
- }: CustomParams) => LabelledPermissions;
102
- /**
103
- * The DeFi Kit allow kit — same protocol, verb and parameter surface, plus a
104
- * `label`. A DeFi Kit entry is nothing but its annotation: the permissions are
105
- * fetched from the annotation's uri at deploy, so nothing is fetched here.
106
- *
107
- * Protocols and parameters are typed against the Ethereum kit, the widest of
108
- * the chains DeFi Kit serves. Values that only exist on another chain still
109
- * type-check; the API validates them when the annotation is resolved.
110
- */
111
- declare const defikit: DeFiKit;
112
- type SwapParams = {
113
- /** Names the action in the app. Never reaches the chain. */label: string; /** Tokens the role may sell. */
114
- sell: readonly Address[]; /** Tokens the role may buy. */
115
- buy: readonly Address[];
116
- };
117
- type TransferParams = {
118
- /** Names the action in the app. Never reaches the chain. */label: string; /** Tokens the role may transfer. Use the zero address for the native token. */
119
- tokens: readonly Address[];
120
- /** Addresses the role may transfer to on the role's own chain. A node stands
121
- * for its address, so only nodes that already have one — an account from your
122
- * codegen, or one bound by address — can be named here. */
123
- to?: readonly Recipient[]; /** Destinations on other chains, bridged over Across. */
124
- bridge?: readonly BridgeTarget[];
125
- /** Allowance capping what may be sent. Pass the allowance declared on the
126
- * roles modifier, or its key. */
127
- allowance?: AllowanceSpec | AllowanceKey;
128
- };
129
- type CustomParams = {
130
- /** Names the action in the app. Never reaches the chain. */label: string;
131
- permissions: readonly Permission[];
132
- };
133
- /** An address, or a node that already knows the address it lives at. */
134
- type Recipient = Address | {
135
- readonly address: Address;
136
- readonly chain?: ChainId;
137
- };
138
- type BridgeTarget = {
139
- /** The destination chain. Inferred from the recipients when they are nodes. */chain?: ChainId; /** Addresses the role may bridge to on the destination chain. */
140
- to: readonly Recipient[]; /** Tokens the role may receive on the destination chain. */
141
- receive: readonly Address[];
142
- };
143
- type EthereumKit = typeof allow;
144
- type DeFiKit = { readonly [Protocol in keyof EthereumKit]: { readonly [Verb in keyof EthereumKit[Protocol]]: DeFiKitVerb<EthereumKit[Protocol][Verb]> } };
145
- type DeFiKitVerb<Verb> = Verb extends ((params: infer Params) => unknown) ? (params: Params & {
146
- label: string;
147
- }) => DeFiKitEntry : (params: {
148
- label: string;
149
- }) => DeFiKitEntry;
150
- //#endregion
151
- export { AllowanceSpec as a, transfer as i, defikit as n, PermissionEntry as o, swap as r, Permissions as s, custom as t };
152
- //# sourceMappingURL=actions-DS5XoMiq.d.mts.map