/
roles.ts
488 lines (471 loc) · 13.6 KB
/
roles.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import {
requiredParamInvariant,
RequiredParam,
} from "../../../core/query-utils/required-param";
import { useSDKChainId } from "../useSDK";
import { WalletAddress } from "../../types";
import {
cacheKeys,
invalidateContractAndBalances,
} from "../../utils/cache-keys";
import { useQueryWithNetwork } from "../query-utils/useQueryWithNetwork";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Role, ValidContractInstance } from "@thirdweb-dev/sdk";
import type { Vote } from "@thirdweb-dev/sdk";
import type { SmartContract } from "@thirdweb-dev/sdk";
import { constants } from "ethers";
import invariant from "tiny-invariant";
/** **********************/
/** UTILS **/
/** **********************/
/**
* @internal
*/
export type ContractWithRoles = Exclude<ValidContractInstance, Vote>;
/**
* @permissionControl
*/
export type RolesForContract<TContract extends ContractWithRoles> =
TContract extends SmartContract
? // eslint-disable-next-line @typescript-eslint/ban-types
Role | (string & {})
: NonNullable<Exclude<TContract, SmartContract>["roles"]>["roles"][number];
/**
* @internal
*/
type GetAllReturnType<TContract extends ContractWithRoles> = Promise<
Record<RolesForContract<TContract>, string[]>
>;
/** **********************/
/** READ HOOKS **/
/** **********************/
/**
* Hook for getting all wallet addresses that have a role in a smart contract.
*
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions).
*
* @example
*
* ```jsx
* import { useAllRoleMembers, useContract } from "@thirdweb-dev/react";
*
* function App() {
* const { contract } = useContract(contractAddress);
* const { data, isLoading, error } = useAllRoleMembers(contract);
* }
* ```
*
* @param contract - Instance of a `SmartContract`
*
* @returns
* The hook's `data` property, once loaded, is an object, where the keys are the role names and the values are arrays of wallet addresses that have that role.
*
* For example, if the contract has two roles, `admin` and `transfer`, and the `admin` role has two members, the `data` property will look like this:
*
* ```ts
* {
* admin: ["0x1234", "0x5678"],
* transfer: [],
* }
* ```
*
* #### Type
*
* ```ts
* Record<
* | "admin"
* | "transfer"
* | "minter"
* | "pauser"
* | "lister"
* | "asset"
* | "unwrap"
* | "factory"
* | (string & {}),
* string[]
* > | undefined;
* ```
*
* @twfeature PermissionsEnumerable
* @permissionControl
*/
export function useAllRoleMembers<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
) {
const contractAddress = contract?.getAddress();
return useQueryWithNetwork<Awaited<GetAllReturnType<TContract>>>(
cacheKeys.extensions.roles.getAll(contractAddress),
() => {
requiredParamInvariant(contract, "No contract provided");
invariant(contract.roles, "Contract does not support roles");
// have to cast to any because of role bs, type is defined in the useQueryWithNetwork definition above
return contract.roles.getAll() as any;
},
{
enabled: !!contract && !!contractAddress,
},
);
}
/**
* Hook for getting all wallet addresses that have a specific role in a smart contract.
*
* Available to use on contracts that implement the [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface.
*
* @example
* ```jsx
* import { useContract, useRoleMembers } from "@thirdweb-dev/react";
*
* // Your smart contract address (must implement permission controls)
* const contractAddress = "{{contract_address}}";
*
* const roleName = "admin";
*
* function App() {
* const { contract } = useContract(contractAddress);
* const { data, isLoading, error } = useRoleMembers(contract, roleName);
* }
* ```
*
* @param contract - Instance of a `SmartContract`
* @param role -
* The name of the role to get the members of
*
* Can be any custom role, or a built-in role, such as:
* - `"admin"`
* - `"transfer"`
* - `"minter"`
* - `"pauser"`
* - `"lister"`
* - `"asset"`
* - `"unwrap"`
* - `"factory"`
*
* @returns The hook's `data` property, once loaded, is an array of wallet addresses that have the specified role
*
* @twfeature Permissions
* @permissionControl
*/
export function useRoleMembers<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
role: RolesForContract<TContract>,
) {
const contractAddress = contract?.getAddress();
return useQueryWithNetwork(
cacheKeys.extensions.roles.get(contractAddress, role),
() => {
requiredParamInvariant(contract, "No contract provided");
invariant(contract.roles, "Contract does not support roles");
return contract.roles.get(role);
},
{
enabled: !!contract && !!contractAddress && !!role,
},
);
}
/**
* Hook to check if an address is a member of a role on a smart contract.
*
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface
*
* Provide the following arguments to the hook:
*
* 1. `contract` - The contract instance to check the role on.
* 2. `roleName` - The name of the role to check.
* 3. `address` - The wallet address to see if it is a member of the role.
*
* @example
*
* ```jsx
* import { useIsAddressRole, useContract } from "@thirdweb-dev/react";
*
* function App() {
* const { contract } = useContract(contractAddress);
* const isMember = useIsAddressRole(contract, roleName, walletAddress);
* }
* ```
*
* @param contract - Instance of a `SmartContract`
*
* @param role - The name of the role to check. Can be any custom role, or a built-in role, such as:
* - `"admin"`
* - `"transfer"`
* - `"minter"`
* - `"pauser"`
* - `"lister"`
* - `"asset"`
* - `"unwrap"`
* - `"factory"`
*
* @param walletAddress -
* The wallet address to check if it is a member of the role.
* Use the `useAddress` hook to get the current wallet address.
*
* @returns `true` if the address is a member of the role, or `false` if not
*
* @twfeature PermissionsEnumerable
* @permissionControl
*/
export function useIsAddressRole<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
role: RolesForContract<TContract>,
walletAddress: RequiredParam<WalletAddress>,
): boolean {
// TODO this might be possible to do with `verify` fn instead?
const contractHasRoles = !!(contract && contract.roles);
const { data } = useRoleMembers(
contractHasRoles ? contract : undefined,
role,
);
// if the contract does not have roles then everything is allowed === true
if (contractHasRoles === false) {
return true;
}
// switch logic (if address 0 is in the role list then anyone has permissions to it)
if (data?.includes(constants.AddressZero)) {
return true;
}
// actual role check logic
return !!(walletAddress && data?.includes(walletAddress));
}
/** **********************/
/** WRITE HOOKS **/
/** **********************/
/**
* Overwrite the list of members for specific roles
*
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const {
* mutate: overwriteRoles,
* isLoading,
* error,
* } = useSetAllRoleMembers(contract);
*
* if (error) {
* console.error("failed to overwrite roles", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => overwriteRoles({ rolesWithAddresses: { minter: ["{{wallet_address}"] } })}
* >
* Overwrite Roles
* </button>
* );
* };
* ```
*
* @param contract - Instance of a `SmartContract`
* @returns A mutation object to overwrite all roles on the contract
* @twfeature Permissions
* @permissionControl
*/
export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
return useMutation(
async (rolesWithAddresses: {
[role in RolesForContract<TContract>]: string[];
}) => {
requiredParamInvariant(contract, "No contract provided");
invariant(contract.roles, "Contract does not support roles");
await contract.roles.setAll(rolesWithAddresses);
},
{
onSettled: () =>
invalidateContractAndBalances(
queryClient,
contractAddress,
activeChainId,
),
},
);
}
/**
* Hook for granting a role on a smart contract.
*
* Available to use on smart contracts that implement the [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface.
*
* @example
* ```jsx
* import { useGrantRole, useContract, Web3Button } from "@thirdweb-dev/react";
*
* const contractAddress = "{{contract_address}}";
* const roleToGrant = "{{role}}";
* const walletAddressToGrant = "{{wallet_address}}";
*
* function App() {
* const { contract } = useContract(contractAddress);
* const { mutateAsync: grantRole, isLoading, error } = useGrantRole(contract);
*
* return (
* <Web3Button
* contractAddress={contractAddress}
* action={() =>
* grantRole({
* role: roleToGrant, // name of your role.
* address: walletAddressToGrant, // address to grant the role to.
* })
* }
* >
* Grant Role
* </Web3Button>
* );
* }
* ```
*
* @param contract - Instance of a `SmartContract`
*
* @returns A mutation object to grant a member of a role on the contract
*
* ```ts
* const { mutateAsync, isLoading, error } = useGrantRole(contract);
* ```
*
* ### options
* The mutation function accepts an object with the following properties:
*
* #### role
* The name of the role to grant the address.
*
* Accepts any `string` value to include custom-defined roles.
*
* Also accepts the default roles available on the [prebuilt contracts](https://portal.thirdweb.com/pre-built-contracts):
*
* ```ts
* string |
* "admin" |
* "minter" |
* "transfer" |
* "lister" |
* "asset" |
* "unwrap" |
* "pauser" |
* "factory";
* ```
*
* #### address
* The address to grant the role to.
*
* To use the address of the connected wallet, use the `useAddress` hook.
*
* @twfeature Permissions | PermissionsEnumerable
* @permissionControl
*/
export function useGrantRole<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
return useMutation(
async (params: {
role: RolesForContract<TContract>;
address: WalletAddress;
}) => {
requiredParamInvariant(contract, "No contract provided");
invariant(contract.roles, "Contract does not support roles");
await contract.roles.grant(params.role as any, params.address);
},
{
onSettled: () =>
invalidateContractAndBalances(
queryClient,
contractAddress,
activeChainId,
),
},
);
}
/**
* Hook for revoking a wallet address from a role on a smart contract.
*
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface
*
* The wallet address that initiates this transaction must have the relevant permissions on the contract to remove the role from the wallet address (typically `"admin"` level required).
*
* ```jsx
* import { useContract, useRevokeRole, Web3Button } from "@thirdweb-dev/react";
*
* // Your smart contract address (must implement permission controls)
* const contractAddress = "{{contract_address}}";
* const walletAddress = "{{wallet_address}}";
*
* function App() {
* // Contract must be a contract that implements the Permission Controls interface
* const { contract } = useContract(contractAddress);
* const { mutateAsync: revokeRole, isLoading, error } = useRevokeRole(contract);
*
* return (
* <Web3Button
* contractAddress={contractAddress}
* action={() =>
* revokeRole({
* role: "admin",
* address: walletAddress,
* })
* }
* >
* Revoke Role
* </Web3Button>
* );
* }
* ```
*
* @param contract - Instance of a `SmartContract`
*
* @returns A mutation object to revoke a role from a member on the contract
* #### role (required)
*
* The role to revoke from the wallet address.
*
* Can be any custom role, or a built-in role, such as:
* - `"admin"`
* - `"transfer"`
* - `"minter"`
* - `"pauser"`
* - `"lister"`
* - `"asset"`
* - `"unwrap"`
* - `"factory"`
*
* #### address
*
* The wallet address to revoke the role from.
*
* To use the connected wallet address, use the `useAddress` hook.
*
* @twfeature Permissions | PermissionsEnumerable
* @permissionControl
*/
export function useRevokeRole<TContract extends ContractWithRoles>(
contract: RequiredParam<TContract>,
) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
return useMutation(
async (params: {
role: RolesForContract<TContract>;
address: WalletAddress;
}) => {
requiredParamInvariant(contract, "No contract provided");
invariant(contract.roles, "Contract does not support roles");
await contract.roles.revoke(params.role as any, params.address);
},
{
onSettled: () =>
invalidateContractAndBalances(
queryClient,
contractAddress,
activeChainId,
),
},
);
}