-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpod-create.ts
309 lines (292 loc) · 10.3 KB
/
pod-create.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { ethers } from 'ethers';
import { getDeployment, getControllerByAddress } from '@orcaprotocol/contracts';
import { labelhash } from '@ensdomains/ensjs';
import { config } from './config';
import { encodeFunctionData, getContract, handleEthersError } from './lib/utils';
import { getSafeInfo, approveSafeTransaction } from './lib/services/transaction-service';
import { createSafeTransaction } from './lib/services/create-safe-transaction';
function createAddressPointer(number) {
const cutLength = String(number).length;
return ethers.constants.AddressZero.slice(0, 42 - cutLength) + number;
}
function getImageUrl(nextPodId: number) {
const baseUrl = `https://orcaprotocol-nft.vercel.app${
config.network === 4 ? '/assets/testnet/' : '/assets/'
}`;
return `${baseUrl}${nextPodId.toString(16).padStart(64, '0')}-image`;
}
/**
* Creates a safe and podifies it.
* If a signer is not provided, instead it returns an unsigned transaction.
* @param args.members - Array of pod member addresses
* @param args.threshold - Voting threshold
* @param args.admin - Optional pod admin
* @param args.name - ENS label for safe, i.e., 'orca-core'. Do not add the pod.eth/pod.xyz suffix
* @param signer - Optional signer
*/
export async function createPod(
args: {
members: Array<string>;
threshold: number;
admin?: string;
name: string;
},
signer?: ethers.Signer,
): Promise<ethers.providers.TransactionResponse | { to: string; data: string }> {
// Checksum all addresses
const members = args.members.map(ethers.utils.getAddress);
const admin = args.admin ? ethers.utils.getAddress(args.admin) : ethers.constants.AddressZero;
try {
const MemberToken = getContract('MemberToken', config.provider);
const expectedPodId = (await MemberToken.getNextAvailablePodId()).toNumber();
const Controller = getContract('ControllerLatest', signer);
if (signer)
return Controller.createPod(
members,
args.threshold,
admin,
labelhash(args.name),
`${args.name}.${config.network === 1 ? 'pod.xyz' : 'pod.eth'}`,
expectedPodId,
getImageUrl(expectedPodId),
);
return (await Controller.populateTransaction.createPod(
members,
args.threshold,
admin,
labelhash(args.name),
`${args.name}.${config.network === 1 ? 'pod.xyz' : 'pod.eth'}`,
expectedPodId,
getImageUrl(expectedPodId),
)) as { to: string; data: string };
} catch (err) {
return handleEthersError(err);
}
}
/**
* Returns the deployment of a controller from a safe's modules, if it exists, otherwise returns null.
* @param safeOrModules - safe address or list of modules
* @returns bool
*/
export async function getControllerFromModules(safeOrModules: string | string[]) {
let modules;
if (typeof safeOrModules === 'string') {
({ modules } = await getSafeInfo(safeOrModules));
} else {
modules = safeOrModules;
}
let controller = null;
modules.forEach(module => {
try {
// This throws if the address does not match a Controller deployment.
controller = getControllerByAddress(module, config.network);
// If the above didn't throw, then we've found an Orca module.
} catch {
// do nothing
}
});
return controller;
}
/**
* Creates a SafeTx on a safe to enable the latest Controller as a module.
*
* @param safe - Safe address
* @param signer
* @throws If a Controller module is already enabled. If you are attempting to upgrade versions, use `Pod.migratePodToLatest`.
*/
export async function enableController(safe: string, signer: ethers.Signer) {
const sender = await signer.getAddress();
// Check to see if signer is safe member
const { owners, modules } = await getSafeInfo(safe);
if (!owners.includes(sender)) throw new Error('Sender was not safe owner');
if (await getControllerFromModules(modules))
throw new Error(
"Pod module was already enabled. If you're trying to upgrade versions, use `Pod.migratePodToLatest` instead",
);
const { address: latestModule } = getDeployment('ControllerLatest', config.network);
let safeTx;
try {
safeTx = await createSafeTransaction({
sender,
safe,
to: safe,
data: encodeFunctionData('GnosisSafe', 'enableModule', [latestModule]),
});
} catch (err) {
if (err.response?.data.message === 'Gas estimation failed') {
throw new Error('Gas estimation failed (this is often a revert error)');
}
throw err;
}
await approveSafeTransaction(safeTx, signer);
}
/**
* Adds a Gnosis Safe to the pod ecosystem.
* If a signer is not provided, it instead returns the unsigned transaction.
* @param args.admin - Optional address of admin
* @param args.name - ENS label for safe, i.e., 'orca-core'. Do not add the pod.eth/pod.xyz suffix
* @param args.safe - Safe address
* @param signer - Signer of a safe owner.
* @throws - If Controller module was not enabled
* @throws - If signer is not a safe owner
* @returns
*/
export async function podifySafe(
args: {
admin?: string;
name: string;
safe: string;
},
signer?: ethers.Signer,
): Promise<ethers.providers.TransactionResponse | { to: string; data: string }> {
const { owners, modules } = await getSafeInfo(args.safe);
if (signer && !owners.includes(await signer.getAddress()))
throw new Error('Sender was not safe owner');
const controllerDeployment = await getControllerFromModules(modules);
if (!controllerDeployment) throw new Error('Pod module was not enabled');
const Controller = new ethers.Contract(
controllerDeployment.address,
controllerDeployment.abi,
signer || config.provider,
);
// Checksum all addresses
const admin = args.admin ? ethers.utils.getAddress(args.admin) : ethers.constants.AddressZero;
try {
const MemberToken = getContract('MemberToken', config.provider);
const expectedPodId = (await MemberToken.getNextAvailablePodId()).toString();
if (signer)
return Controller.createPodWithSafe(
admin,
args.safe,
labelhash(args.name),
`${args.name}.${config.network === 1 ? 'pod.xyz' : 'pod.eth'}`,
expectedPodId,
getImageUrl(expectedPodId),
);
return (await Controller.populateTransaction.createPodWithSafe(
admin,
args.safe,
labelhash(args.name),
`${args.name}.${config.network === 1 ? 'pod.xyz' : 'pod.eth'}`,
expectedPodId,
getImageUrl(expectedPodId),
)) as { to: string; data: string };
} catch (err) {
return handleEthersError(err);
}
}
/**
* Creates multiple pods simultaneously.
*
* Each pod requires an array of members, a threshold and label, with an optional admin.
* Members or admins can be other pods in this create action.
*
* Pods can be added as members of other pods using labels,
* but only with pods earlier up in the array.
* I.e., the second pod in the array can have the first pod in the array as a member or admin,
* but the first pod cannot have the second pod as a member.
*
* The label replacement does not (currently) work with already existing pods.
*
* An example:
* ```
* [
* {
* label: 'orcanauts',
* // This will add the below pods as sub pods to this newly created one.
* members: ['art-nauts', 'gov-nauts'],
* threshold: 1,
* },
* {
* label: 'art-nauts',
* members: ['0x1234...', '0x2345...'],
* threshold: 1,
* },
* {
* label: 'gov-nauts',
* members: ['0x3456...', '0x4567...'],
* threshold: 1,
* // This will add the above 'orcanauts' pod as the admin to this new pod.
* admin: 'orcanauts',
* }
* ]
* ```
* @param pods
*/
// eslint-disable-next-line import/prefer-default-export
export async function multiPodCreate(
pods: Array<{
members: string[];
threshold: number;
admin?: string;
label: string;
}>,
signer: ethers.Signer,
) {
if (!config.network || !config.provider) {
throw new Error('Network/provider was not defined. Did you init the SDK?');
}
const Controller = getDeployment('ControllerLatest', config.network);
const memberTokenDeployment = getDeployment('MemberToken', config.network);
const MemberToken = new ethers.Contract(
memberTokenDeployment.address,
memberTokenDeployment.abi,
config.provider,
);
let nextPodId = (await MemberToken.getNextAvailablePodId()).toNumber();
const members = [];
const thresholds = [];
const admins = [];
const labels = [];
const ensNames = [];
const imageUrls = [];
// The smart contract expects basically the reverse of what our SDK expects.
pods.reverse().forEach(pod => {
// Check if any of the members are labels.
members.push(
pod.members.map(member => {
// If a member is not an eth address it (should) be a label.
if (!ethers.utils.isAddress(member)) {
const childPodIndex = pods.findIndex(findPod => findPod.label === member);
if (childPodIndex < 0) throw new Error(`No pod had the label of ${member}`);
// We start the member array indexing at 1 because address 0 is reserved on the smart contract.
return createAddressPointer(childPodIndex + 1);
}
return member;
}),
);
if (!ethers.utils.isAddress(pod.admin)) {
if (!pod.admin) admins.push(ethers.constants.AddressZero);
else {
const adminPodIndex = pods.findIndex(findPod => findPod.label === pod.admin);
if (adminPodIndex < 0) throw new Error(`No pod had the label of ${pod.admin}`);
// We start the admin array indexing at 1, because address zero is reserved for the no-admin case.
admins.push(createAddressPointer(adminPodIndex + 1));
}
} else {
// It's just an eth address, so we can push.
admins.push(pod.admin);
}
thresholds.push(pod.threshold);
labels.push(labelhash(pod.label));
ensNames.push(`${pod.label}.pod.xyz`);
imageUrls.push(getImageUrl(nextPodId));
nextPodId += 1;
});
const multiCreateDeployment = getDeployment('MultiCreateV1', config.network);
const MultiCreate = new ethers.Contract(
multiCreateDeployment.address,
multiCreateDeployment.abi,
signer,
);
return MultiCreate.createPods(
Controller.address,
members,
thresholds,
admins,
labels,
ensNames,
// We generate these independently of the incoming pods array, so it has to be manually reversed.
imageUrls.reverse(),
);
}