-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase-test.ts
More file actions
1123 lines (1033 loc) · 45.1 KB
/
Copy pathbase-test.ts
File metadata and controls
1123 lines (1033 loc) · 45.1 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Base Test Class for GuardController SDK Tests
* Provides GuardController-specific functionality
*/
import { Address, Hex } from 'viem';
import { GuardController } from '../../../sdk/typescript/contracts/core/GuardController.tsx';
import { RuntimeRBAC } from '../../../sdk/typescript/contracts/core/RuntimeRBAC.tsx';
import AccountBloxABIJson from '../../../sdk/typescript/abi/AccountBlox.abi.json';
import { BaseSDKTest, TestWallet } from '../base/BaseSDKTest.ts';
import { getContractAddressFromArtifacts, getDefinitionAddress } from '../base/test-helpers.ts';
import { getTestConfig } from '../base/test-config.ts';
import { MetaTransactionSigner } from '../../../sdk/typescript/utils/metaTx/metaTransaction.tsx';
import { MetaTransaction, MetaTxParams } from '../../../sdk/typescript/interfaces/lib.index.tsx';
import { TxAction } from '../../../sdk/typescript/types/lib.index.tsx';
import { GuardConfigActionType, GuardConfigAction } from '../../../sdk/typescript/types/core.execution.index.tsx';
import {
guardConfigBatchExecutionParams,
encodeAddTargetToWhitelist,
encodeRemoveTargetFromWhitelist,
encodeRegisterFunction,
encodeUnregisterFunction,
} from '../../../sdk/typescript/lib/definitions/GuardControllerDefinitions';
import {
roleConfigBatchExecutionParams,
encodeCreateRole,
encodeAddWallet,
encodeAddFunctionToRole,
} from '../../../sdk/typescript/lib/definitions/RuntimeRBACDefinitions';
import { extractErrorInfo } from '../../../sdk/typescript/utils/contract-errors.ts';
import { RoleConfigActionType, RoleConfigAction, FunctionPermission } from '../runtime-rbac/base-test.ts';
import { keccak256, toBytes } from 'viem';
/** Extract raw revert data from a viem/contract error for decoding. */
function getRevertDataFromError(error: any): string | null {
const data = error?.data ?? error?.cause?.data ?? error?.cause?.cause?.data;
if (typeof data === 'string' && data.startsWith('0x')) return data;
if (data?.data && typeof data.data === 'string' && data.data.startsWith('0x')) return data.data;
const msg = (error?.message ?? error?.cause?.message ?? '').toString();
const hexMatch = msg.match(/0x[a-fA-F0-9]{8,}/);
return hexMatch ? hexMatch[0] : null;
}
export interface GuardControllerRoles {
owner: Address;
broadcaster: Address;
recovery: Address;
}
export abstract class BaseGuardControllerTest extends BaseSDKTest {
protected guardController: GuardController | null = null;
/** RuntimeRBAC SDK (AccountBlox ABI) for role config batch (mint roles). */
protected runtimeRBAC: RuntimeRBAC | null = null;
/** Deployed GuardControllerDefinitions library address (for execution params) */
protected guardControllerDefinitionsAddress: Address | null = null;
/** Deployed RuntimeRBACDefinitions library address (for role config batch params) */
protected runtimeRBACDefinitionsAddress: Address | null = null;
protected roles: GuardControllerRoles = {
owner: '0x' as Address,
broadcaster: '0x' as Address,
recovery: '0x' as Address,
};
protected roleWallets: Record<string, TestWallet> = {};
protected metaTxSigner: MetaTransactionSigner | null = null;
// GuardController constants
protected readonly CONTROLLER_CONFIG_OPERATION_TYPE: Hex = keccak256(
new TextEncoder().encode('CONTROLLER_CONFIG_OPERATION')
) as Hex;
protected readonly GUARD_CONFIG_BATCH_META_SELECTOR: Hex = keccak256(
new TextEncoder().encode('guardConfigBatchRequestAndApprove(((uint256,uint256,uint8,(address,address,uint256,uint256,bytes32,bytes4,bytes),bytes32,bytes,(address,uint256,address,uint256)),(uint256,uint256,address,bytes4,uint8,uint256,uint256,address),bytes32,bytes,bytes))')
).slice(0, 10) as Hex;
protected readonly GUARD_CONFIG_BATCH_EXECUTE_SELECTOR: Hex = keccak256(
new TextEncoder().encode('executeGuardConfigBatch((uint8,bytes)[])')
).slice(0, 10) as Hex;
protected readonly NATIVE_TRANSFER_SELECTOR: Hex = '0xd8cb519d' as Hex; // bytes4(keccak256("__bloxchain_native_transfer__()")) - matches EngineBlox.NATIVE_TRANSFER_SELECTOR
// Role config batch (for mint flow: create MINT_REQUESTOR, MINT_APPROVER, add function to roles)
protected readonly ROLE_CONFIG_BATCH_META_SELECTOR: Hex = keccak256(
toBytes('roleConfigBatchRequestAndApprove(((uint256,uint256,uint8,(address,address,uint256,uint256,bytes32,bytes4,bytes),bytes32,bytes,(address,uint256,address,uint256)),(uint256,uint256,address,bytes4,uint8,uint256,uint256,address),bytes32,bytes,bytes))')
).slice(0, 10) as Hex;
protected readonly ROLE_CONFIG_BATCH_EXECUTE_SELECTOR: Hex = keccak256(
toBytes('executeRoleConfigBatch((uint8,bytes)[])')
).slice(0, 10) as Hex;
protected readonly ROLE_CONFIG_BATCH_OPERATION_TYPE: Hex = keccak256(toBytes('ROLE_CONFIG_BATCH')) as Hex;
/** requestAndApproveExecution selector (handler for mint meta-approve). */
protected readonly REQUEST_AND_APPROVE_EXECUTION_SELECTOR: Hex = keccak256(
toBytes('requestAndApproveExecution(((uint256,uint256,uint8,(address,address,uint256,uint256,bytes32,bytes4,bytes),bytes32,bytes,(address,uint256,address,uint256)),(uint256,uint256,address,bytes4,uint8,uint256,uint256,address),bytes32,bytes,bytes))')
).slice(0, 10) as Hex;
/** executeWithTimeLock selector (controller; MINT_REQUESTOR needs EXECUTE_TIME_DELAY_REQUEST for mint). */
protected readonly EXECUTE_WITH_TIMELOCK_SELECTOR: Hex = keccak256(
toBytes('executeWithTimeLock(address,uint256,bytes4,bytes,uint256,bytes32)')
).slice(0, 10) as Hex;
/** approveTimeLockExecutionWithMetaTx selector (controller; MINT_APPROVER needs SIGN_META_APPROVE for mint). */
protected readonly APPROVE_TIMELOCK_EXECUTION_META_SELECTOR: Hex = keccak256(
toBytes('approveTimeLockExecutionWithMetaTx(((uint256,uint256,uint8,(address,address,uint256,uint256,bytes32,bytes4,bytes),bytes32,bytes,(address,uint256,address,uint256)),(uint256,uint256,address,bytes4,uint8,uint256,uint256,address),bytes32,bytes,bytes))')
).slice(0, 10) as Hex;
/** cancelTimeLockExecutionWithMetaTx selector (controller; MINT_APPROVER needs SIGN_META_CANCEL for mint). */
protected readonly CANCEL_TIMELOCK_EXECUTION_META_SELECTOR: Hex = keccak256(
toBytes('cancelTimeLockExecutionWithMetaTx(((uint256,uint256,uint8,(address,address,uint256,uint256,bytes32,bytes4,bytes),bytes32,bytes,(address,uint256,address,uint256)),(uint256,uint256,address,bytes4,uint8,uint256,uint256,address),bytes32,bytes,bytes))')
).slice(0, 10) as Hex;
constructor(testName: string) {
super(testName);
}
/**
* Get contract address from artifacts
*/
protected async getContractAddress(): Promise<Address | null> {
return getContractAddressFromArtifacts('AccountBlox');
}
/**
* Get contract address from environment (single account contract)
*/
protected getContractAddressFromEnv(): Address | null {
const address = getTestConfig().contractAddresses.accountBlox;
if (!address) {
throw new Error('ACCOUNTBLOX_ADDRESS not set in environment variables');
}
return address as Address;
}
/**
* Initialize GuardController SDK instance
*/
protected async initializeSDK(): Promise<void> {
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
this.guardControllerDefinitionsAddress = await getDefinitionAddress('GuardControllerDefinitions');
this.runtimeRBACDefinitionsAddress = await getDefinitionAddress('RuntimeRBACDefinitions');
// Create a wallet client for the owner (default)
const walletClient = this.createWalletClient('wallet1');
this.guardController = new GuardController(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
(this.guardController as any).abi = AccountBloxABIJson;
this.runtimeRBAC = new RuntimeRBAC(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
(this.runtimeRBAC as any).abi = AccountBloxABIJson;
console.log('✅ GuardController SDK initialized');
}
/**
* Discover role assignments from contract
*/
protected async discoverRoleAssignments(): Promise<void> {
if (!this.guardController) {
throw new Error('GuardController SDK not initialized');
}
try {
this.roles.owner = await this.guardController.owner();
const broadcasters = await this.guardController.getBroadcasters();
if (!broadcasters || broadcasters.length === 0) {
throw new Error('No broadcasters configured on contract');
}
this.roles.broadcaster = broadcasters[0]; // Use primary broadcaster
this.roles.recovery = await this.guardController.getRecovery();
console.log('📋 DISCOVERED ROLE ASSIGNMENTS:');
console.log(` 👑 Owner: ${this.roles.owner}`);
console.log(` 📡 Broadcaster: ${this.roles.broadcaster}`);
console.log(` 🛡️ Recovery: ${this.roles.recovery}`);
// Map roles to available wallets
for (const [walletName, wallet] of Object.entries(this.wallets)) {
if (wallet.address.toLowerCase() === this.roles.owner.toLowerCase()) {
this.roleWallets.owner = wallet;
console.log(` 🔑 Owner role served by: ${walletName} (${wallet.address})`);
}
if (wallet.address.toLowerCase() === this.roles.broadcaster.toLowerCase()) {
this.roleWallets.broadcaster = wallet;
console.log(` 🔑 Broadcaster role served by: ${walletName} (${wallet.address})`);
}
if (wallet.address.toLowerCase() === this.roles.recovery.toLowerCase()) {
this.roleWallets.recovery = wallet;
console.log(` 🔑 Recovery role served by: ${walletName} (${wallet.address})`);
}
}
} catch (error: any) {
const addr = this.contractAddress ?? 'unknown';
let hint = `Contract at ${addr} reverted when calling owner() or getBroadcasters/getRecovery. Ensure AccountBlox is deployed and initialized for this network (see deployed-addresses.json).`;
const revertData = getRevertDataFromError(error);
if (revertData) {
const { userMessage, error: decoded } = extractErrorInfo(revertData);
if (decoded?.name) {
console.error(` 📋 Revert decoded: ${decoded.name}${decoded.params ? ` ${JSON.stringify(decoded.params)}` : ''}`);
hint = `${userMessage}. ${hint}`;
}
}
console.error('❌ Failed to discover role assignments:', error?.message ?? error);
throw new Error(`Role discovery failed: ${hint}`);
}
}
/**
* Get wallet for a specific role
*/
protected getRoleWallet(roleName: 'owner' | 'broadcaster' | 'recovery'): TestWallet {
const wallet = this.roleWallets[roleName.toLowerCase()];
if (!wallet) {
throw new Error(`No wallet found for role: ${roleName}`);
}
return wallet;
}
/**
* Create GuardController instance with specific wallet
*/
protected createGuardControllerWithWallet(walletName: string): GuardController {
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
const walletClient = this.createWalletClient(walletName);
return new GuardController(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
}
/**
* Override initialize to include SDK initialization
*/
async initialize(): Promise<void> {
await super.initialize();
await this.initializeSDK();
await this.discoverRoleAssignments();
await this.initializeMetaTxSigner();
}
/**
* Initialize MetaTransactionSigner for EIP-712 signing
*/
protected async initializeMetaTxSigner(): Promise<void> {
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
// Use a wallet client for signing (owner wallet by default)
const ownerWallet = this.getRoleWallet('owner');
const ownerWalletName = Object.keys(this.wallets).find(
(k) => this.wallets[k].address.toLowerCase() === ownerWallet.address.toLowerCase()
) || 'wallet1';
const walletClient = this.createWalletClient(ownerWalletName);
this.metaTxSigner = new MetaTransactionSigner(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
}
/**
* Create meta-transaction parameters for a function
*/
protected async createMetaTxParams(
handlerSelector: Hex,
action: TxAction,
signerAddress: Address,
deadlineSeconds: number = 3600
): Promise<MetaTxParams> {
if (!this.guardController) {
throw new Error('GuardController SDK not initialized');
}
const deadline = BigInt(deadlineSeconds);
const maxGasPrice = BigInt(0);
return await this.guardController.createMetaTxParams(
this.contractAddress!,
handlerSelector,
action,
deadline,
maxGasPrice,
signerAddress
);
}
/** Encode guard config action data using the deployed GuardControllerDefinitions contract. */
protected async encodeGuardConfigAction(
actionType: GuardConfigActionType,
data: {
functionSelector?: Hex;
target?: Address;
isAdd?: boolean;
functionSignature?: string;
operationName?: string;
supportedActions?: number[];
safeRemoval?: boolean;
}
): Promise<Hex> {
if (!this.publicClient || !this.guardControllerDefinitionsAddress) {
throw new Error('publicClient and guardControllerDefinitionsAddress required for definition encoding');
}
const client = this.publicClient;
const def = this.guardControllerDefinitionsAddress;
switch (actionType) {
case GuardConfigActionType.ADD_TARGET_TO_WHITELIST:
if (!data.functionSelector || !data.target) throw new Error('Missing required data for whitelist action');
return encodeAddTargetToWhitelist(client, def, data.functionSelector, data.target);
case GuardConfigActionType.REMOVE_TARGET_FROM_WHITELIST:
if (!data.functionSelector || !data.target) throw new Error('Missing required data for whitelist action');
return encodeRemoveTargetFromWhitelist(client, def, data.functionSelector, data.target);
case GuardConfigActionType.REGISTER_FUNCTION:
if (!data.functionSignature || !data.operationName || !data.supportedActions) {
throw new Error('Missing required data for register function action');
}
return encodeRegisterFunction(
client,
def,
data.functionSignature,
data.operationName,
data.supportedActions as TxAction[]
);
case GuardConfigActionType.UNREGISTER_FUNCTION:
if (!data.functionSelector || data.safeRemoval === undefined) {
throw new Error('Missing required data for unregister function action');
}
return encodeUnregisterFunction(client, def, data.functionSelector, data.safeRemoval);
default:
throw new Error(`Unknown action type: ${actionType}`);
}
}
/**
* Create and sign a meta-transaction for guard config batch (whitelist update)
*/
protected async createSignedMetaTxForWhitelistUpdate(
functionSelector: Hex,
target: Address,
isAdd: boolean,
signerWalletName: string
): Promise<MetaTransaction> {
if (!this.metaTxSigner || !this.guardController) {
throw new Error('MetaTransactionSigner or GuardController not initialized');
}
const signerWallet = this.wallets[signerWalletName];
if (!signerWallet) {
throw new Error(`Wallet not found: ${signerWalletName}`);
}
// Create guard config action
const actionType = isAdd
? GuardConfigActionType.ADD_TARGET_TO_WHITELIST
: GuardConfigActionType.REMOVE_TARGET_FROM_WHITELIST;
const actionData = await this.encodeGuardConfigAction(actionType, {
functionSelector,
target,
isAdd,
});
const actions: GuardConfigAction[] = [
{
actionType,
data: actionData,
},
];
// Get execution params using the new batch method (via definition contract)
if (!this.guardControllerDefinitionsAddress) {
throw new Error('GuardControllerDefinitions address not set');
}
console.log(` 📋 Getting execution params for guard config batch...`);
const executionParams = await guardConfigBatchExecutionParams(this.publicClient, this.guardControllerDefinitionsAddress!, actions);
console.log(` ✅ Execution params obtained`);
// Create meta-tx params
console.log(` 📋 Creating meta-transaction parameters...`);
console.log(` Handler Selector: ${this.GUARD_CONFIG_BATCH_META_SELECTOR}`);
console.log(` Action: ${TxAction.SIGN_META_REQUEST_AND_APPROVE}`);
console.log(` Signer: ${signerWallet.address}`);
const metaTxParams = await this.createMetaTxParams(
this.GUARD_CONFIG_BATCH_META_SELECTOR,
TxAction.SIGN_META_REQUEST_AND_APPROVE,
signerWallet.address
);
console.log(` ✅ Meta-transaction parameters created:`);
console.log(` Nonce: ${metaTxParams.nonce}`);
console.log(` Chain ID: ${metaTxParams.chainId}`);
console.log(` Deadline: ${metaTxParams.deadline}`);
// Create TxParams for the new transaction (gasLimit matches CJS createGuardConfigBatchMetaTx: 1000000)
const txParams = {
requester: signerWallet.address,
target: this.contractAddress!,
value: BigInt(0),
gasLimit: BigInt(1000000),
operationType: this.CONTROLLER_CONFIG_OPERATION_TYPE,
executionSelector: this.GUARD_CONFIG_BATCH_EXECUTE_SELECTOR,
executionParams: executionParams
};
// Generate unsigned meta-transaction
console.log(` 📋 Generating unsigned meta-transaction for guard config batch...`);
const unsignedMetaTx = await this.metaTxSigner.createUnsignedMetaTransactionForNew(
txParams,
metaTxParams
);
console.log(` ✅ Unsigned meta-transaction generated`);
// Sign the meta-transaction
const signedMetaTx = await this.metaTxSigner.signMetaTransaction(
unsignedMetaTx,
signerWallet.address,
signerWallet.privateKey
);
return signedMetaTx;
}
/**
* Create and sign a meta-transaction for guard config batch (function registration)
*/
protected async createSignedMetaTxForFunctionRegistration(
functionSignature: string,
operationName: string,
supportedActions: number[],
signerWalletName: string
): Promise<MetaTransaction> {
if (!this.metaTxSigner || !this.guardController) {
throw new Error('MetaTransactionSigner or GuardController not initialized');
}
const signerWallet = this.wallets[signerWalletName];
if (!signerWallet) {
throw new Error(`Wallet not found: ${signerWalletName}`);
}
// Create guard config action for function registration
const actionData = await this.encodeGuardConfigAction(GuardConfigActionType.REGISTER_FUNCTION, {
functionSignature,
operationName,
supportedActions,
});
const actions: GuardConfigAction[] = [
{
actionType: GuardConfigActionType.REGISTER_FUNCTION,
data: actionData,
},
];
// Get execution params using the new batch method (via definition contract)
if (!this.guardControllerDefinitionsAddress) {
throw new Error('GuardControllerDefinitions address not set');
}
console.log(` 📋 Getting execution params for guard config batch (function registration)...`);
const executionParams = await guardConfigBatchExecutionParams(this.publicClient, this.guardControllerDefinitionsAddress!, actions);
console.log(` ✅ Execution params obtained`);
// Create meta-tx params
console.log(` 📋 Creating meta-transaction parameters...`);
console.log(` Handler Selector: ${this.GUARD_CONFIG_BATCH_META_SELECTOR}`);
console.log(` Action: ${TxAction.SIGN_META_REQUEST_AND_APPROVE}`);
console.log(` Signer: ${signerWallet.address}`);
const metaTxParams = await this.createMetaTxParams(
this.GUARD_CONFIG_BATCH_META_SELECTOR,
TxAction.SIGN_META_REQUEST_AND_APPROVE,
signerWallet.address
);
console.log(` ✅ Meta-transaction parameters created:`);
console.log(` Nonce: ${metaTxParams.nonce}`);
console.log(` Chain ID: ${metaTxParams.chainId}`);
console.log(` Deadline: ${metaTxParams.deadline}`);
// Create TxParams for the new transaction (gasLimit matches CJS createGuardConfigBatchMetaTx: 1000000)
const txParams = {
requester: signerWallet.address,
target: this.contractAddress!,
value: BigInt(0),
gasLimit: BigInt(1000000),
operationType: this.CONTROLLER_CONFIG_OPERATION_TYPE,
executionSelector: this.GUARD_CONFIG_BATCH_EXECUTE_SELECTOR,
executionParams: executionParams
};
// Generate unsigned meta-transaction
console.log(` 📋 Generating unsigned meta-transaction for guard config batch...`);
const unsignedMetaTx = await this.metaTxSigner.createUnsignedMetaTransactionForNew(
txParams,
metaTxParams
);
console.log(` ✅ Unsigned meta-transaction generated`);
// Sign the meta-transaction
const signedMetaTx = await this.metaTxSigner.signMetaTransaction(
unsignedMetaTx,
signerWallet.address,
signerWallet.privateKey
);
return signedMetaTx;
}
/**
* Execute one or more guard config actions via guardConfigBatchRequestAndApprove.
* Uses a meta-transaction signed by signerWalletName and broadcast by broadcasterWalletName.
*/
protected async executeGuardConfigActions(
actions: GuardConfigAction[],
signerWalletName: string,
broadcasterWalletName: string,
operationName: string
): Promise<void> {
if (!this.metaTxSigner || !this.guardController) {
throw new Error('MetaTransactionSigner or GuardController not initialized');
}
if (!this.publicClient || !this.guardControllerDefinitionsAddress) {
throw new Error('publicClient and guardControllerDefinitionsAddress required for guard config batch');
}
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
const signerWallet = this.wallets[signerWalletName];
if (!signerWallet) {
throw new Error(`Wallet not found: ${signerWalletName}`);
}
const broadcasterWallet = this.wallets[broadcasterWalletName];
if (!broadcasterWallet) {
throw new Error(`Broadcaster wallet not found: ${broadcasterWalletName}`);
}
// Build execution params for the guard config batch
const executionParams = await guardConfigBatchExecutionParams(
this.publicClient,
this.guardControllerDefinitionsAddress,
actions
);
// Create meta-tx params for the guard config batch handler
const metaTxParams = await this.createMetaTxParams(
this.GUARD_CONFIG_BATCH_META_SELECTOR,
TxAction.SIGN_META_REQUEST_AND_APPROVE,
signerWallet.address
);
// TxParams for controller config operation (mirrors createSignedMetaTxForFunctionRegistration)
const txParams = {
requester: signerWallet.address,
target: this.contractAddress,
value: BigInt(0),
gasLimit: BigInt(1_000_000),
operationType: this.CONTROLLER_CONFIG_OPERATION_TYPE,
executionSelector: this.GUARD_CONFIG_BATCH_EXECUTE_SELECTOR,
executionParams,
};
const unsignedMetaTx = await this.metaTxSigner.createUnsignedMetaTransactionForNew(
txParams,
metaTxParams
);
const signedMetaTx = await this.metaTxSigner.signMetaTransaction(
unsignedMetaTx,
signerWallet.address,
signerWallet.privateKey
);
const broadcasterGuardController = this.createGuardControllerWithWallet(broadcasterWalletName);
const result = await broadcasterGuardController.guardConfigBatchRequestAndApprove(
signedMetaTx,
// Explicit gas so viem does not call eth_estimateGas for this large payload.
this.getTxOptions(broadcasterWallet.address, { gas: 1_500_000n })
);
const receipt = await result.wait();
await this.assertGuardConfigBatchSucceeded(receipt, operationName);
}
/**
* Get role hash from role name (must match contract keccak256(roleName))
*/
protected getRoleHash(roleName: string): Hex {
return keccak256(toBytes(roleName)) as Hex;
}
/**
* Check if role exists (for mint flow setup).
*/
protected async roleExists(roleHash: Hex): Promise<boolean> {
if (!this.contractAddress) return false;
try {
// Use an owner-scoped RuntimeRBAC client for reads that require _validateAnyRole.
const ownerWallet = this.getRoleWallet('owner');
const ownerWalletName =
Object.keys(this.wallets).find(
(k) => this.wallets[k].address.toLowerCase() === ownerWallet.address.toLowerCase()
) || 'wallet1';
const rbac = this.createRuntimeRBACWithWallet(ownerWalletName);
(rbac as any).abi = AccountBloxABIJson;
const role = await (rbac as any).getRole(roleHash);
const h = (role as any).roleHashReturn ?? (role as any).roleHash;
return !!h && String(h).toLowerCase() !== '0x0000000000000000000000000000000000000000000000000000000000000000';
} catch {
return false;
}
}
protected createBitmapFromActions(actions: TxAction[]): number {
let bitmap = 0;
for (const action of actions) bitmap |= 1 << action;
return bitmap;
}
protected createFunctionPermission(
functionSelector: Hex,
actions: TxAction[],
handlerForSelectors: Hex[] | null = null
): FunctionPermission {
return {
functionSelector,
grantedActionsBitmap: this.createBitmapFromActions(actions),
handlerForSelectors: handlerForSelectors ?? [functionSelector],
};
}
/** Encode role config action data using the deployed RuntimeRBACDefinitions contract. */
protected async encodeRoleConfigAction(actionType: RoleConfigActionType, data: any): Promise<RoleConfigAction> {
if (!this.publicClient || !this.runtimeRBACDefinitionsAddress) {
throw new Error('publicClient and runtimeRBACDefinitionsAddress required for definition encoding');
}
const client = this.publicClient;
const def = this.runtimeRBACDefinitionsAddress;
let encodedData: Hex;
switch (actionType) {
case RoleConfigActionType.CREATE_ROLE:
encodedData = await encodeCreateRole(client, def, data.roleName, BigInt(data.maxWallets));
break;
case RoleConfigActionType.ADD_WALLET:
encodedData = await encodeAddWallet(client, def, data.roleHash, data.wallet);
break;
case RoleConfigActionType.ADD_FUNCTION_TO_ROLE:
encodedData = await encodeAddFunctionToRole(client, def, data.roleHash, {
functionSelector: data.functionPermission.functionSelector,
grantedActionsBitmap: data.functionPermission.grantedActionsBitmap,
handlerForSelectors: data.functionPermission.handlerForSelectors ?? [data.functionPermission.functionSelector],
});
break;
default:
throw new Error(`Unsupported role config action type: ${actionType}`);
}
return { actionType, data: encodedData };
}
protected async createRoleConfigBatchMetaTx(
actions: RoleConfigAction[],
signerWalletName: string
): Promise<MetaTransaction> {
if (!this.metaTxSigner || !this.runtimeRBAC || !this.runtimeRBACDefinitionsAddress) {
throw new Error('MetaTransactionSigner or RuntimeRBAC not initialized');
}
const signerWallet = this.wallets[signerWalletName];
if (!signerWallet) throw new Error(`Wallet not found: ${signerWalletName}`);
const executionParams = await roleConfigBatchExecutionParams(
this.publicClient,
this.runtimeRBACDefinitionsAddress,
actions
);
const metaTxParams = await this.guardController!.createMetaTxParams(
this.contractAddress!,
this.ROLE_CONFIG_BATCH_META_SELECTOR,
TxAction.SIGN_META_REQUEST_AND_APPROVE,
BigInt(3600),
BigInt(0),
signerWallet.address
);
const txParams = {
requester: signerWallet.address,
target: this.contractAddress!,
value: BigInt(0),
gasLimit: BigInt(0),
operationType: this.ROLE_CONFIG_BATCH_OPERATION_TYPE,
executionSelector: this.ROLE_CONFIG_BATCH_EXECUTE_SELECTOR,
executionParams,
};
const unsignedMetaTx = await this.metaTxSigner.createUnsignedMetaTransactionForNew(txParams, metaTxParams);
const signedMetaTx = await this.metaTxSigner.signMetaTransaction(
unsignedMetaTx,
signerWallet.address,
signerWallet.privateKey
);
return {
txRecord: signedMetaTx.txRecord,
params: signedMetaTx.params,
message: signedMetaTx.message,
signature: signedMetaTx.signature,
data: signedMetaTx.data ?? ('0x' as Hex),
};
}
protected async executeRoleConfigBatch(
actions: RoleConfigAction[],
signerWalletName: string,
broadcasterWalletName: string
): Promise<any> {
if (!this.runtimeRBAC) throw new Error('RuntimeRBAC SDK not initialized');
const signedMetaTx = await this.createRoleConfigBatchMetaTx(actions, signerWalletName);
const broadcasterWallet = this.wallets[broadcasterWalletName];
if (!broadcasterWallet) throw new Error(`Broadcaster wallet not found: ${broadcasterWalletName}`);
const broadcasterRuntimeRBAC = this.createRuntimeRBACWithWallet(broadcasterWalletName);
// Provide an explicit gas limit so viem does not call eth_estimateGas for this
// large roleConfigBatchRequestAndApprove payload (which can hang or time out
// on constrained remote RPCs).
const result = await broadcasterRuntimeRBAC.roleConfigBatchRequestAndApprove(
signedMetaTx,
this.getTxOptions(broadcasterWallet.address, { gas: 10_000_000n })
);
// Mirror guard config batch assertions: ensure TxStatus is COMPLETED (5), not FAILED (6).
try {
const receipt = await result.wait();
await this.assertRoleConfigBatchSucceeded(receipt, 'Mint role config batch');
} catch (e: any) {
console.error(`❌ Role config batch failed for mint roles: ${e?.message ?? e}`);
throw e;
}
return result;
}
/**
* Assert role config batch succeeded by checking tx record status (5 = COMPLETED, 6 = FAILED).
* Uses the same transaction history as GuardController / AccountBlox (shared EngineBlox state).
*/
protected async assertRoleConfigBatchSucceeded(receipt: any, operationName: string): Promise<void> {
const txId = await this.resolveTxIdForControllerOperation(receipt);
if (txId == null) {
console.log(` ⚠️ No txId in receipt for ${operationName}; skipping tx-record status check`);
return;
}
const txRecord = await this.getGuardTransactionRecord(txId);
if (!txRecord) {
throw new Error(`${operationName}: could not get transaction record for txId ${txId}`);
}
const status =
typeof txRecord.status === 'bigint'
? Number(txRecord.status)
: typeof txRecord.status === 'string'
? parseInt(txRecord.status, 10)
: txRecord.status;
console.log(` 📋 Role config tx record status: ${status} (5=COMPLETED, 6=FAILED)`);
if (status === 6) {
const result = txRecord.result ?? '0x';
const resultHex =
typeof result === 'string'
? result
: result && typeof result === 'object' && 'length' in result
? '0x' +
Array.from(new Uint8Array(result as ArrayBuffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
: String(result);
const errorSelector = this.decodeErrorSelector(result);
const errorName = errorSelector ? this.getErrorName(errorSelector) : 'Unknown';
console.log(` 🔍 Role config revert selector: ${errorSelector ?? 'none'} (${errorName})`);
// Treat idempotent role-config replays as soft success so that re-running tests on
// an environment where roles already exist does not fail the suite. Rely on the
// subsequent roleExists/hasRole/permission checks in the caller to enforce correctness.
if (errorName === 'ResourceAlreadyExists' || errorName === 'ItemAlreadyExists') {
console.log(
` ⏭️ Role config batch reported ${errorName} (TxStatus 6); treating as already-applied and continuing`
);
return;
}
if (!errorSelector || errorName.startsWith('Unknown')) {
console.log(` 🔍 Raw revert data (first 66 chars): ${resultHex.slice(0, 66)}`);
}
throw new Error(
`Role config batch failed (TxStatus 6) for ${operationName}. Revert: ${errorName}`
);
}
if (status !== 5) {
throw new Error(
`Role config batch did not complete for ${operationName}. Status: ${status} (expected 5)`
);
}
console.log(` ✅ Role config batch completed (status 5) for ${operationName}`);
}
protected createRuntimeRBACWithWallet(walletName: string): RuntimeRBAC {
if (!this.contractAddress) throw new Error('Contract address not set');
const walletClient = this.createWalletClient(walletName);
const rbac = new RuntimeRBAC(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
(rbac as any).abi = AccountBloxABIJson;
return rbac;
}
/**
* Check if a role has a specific TxAction permission for a function selector.
* Mirrors the CJS helper roleHasPermissionForSelector using RuntimeRBAC.getActiveRolePermissions.
*/
protected async roleHasPermissionForSelector(
roleHash: Hex,
functionSelector: Hex,
action: TxAction
): Promise<boolean> {
if (!this.runtimeRBAC) {
throw new Error('RuntimeRBAC SDK not initialized');
}
const permissions = await this.runtimeRBAC.getActiveRolePermissions(roleHash);
const list: any[] =
Array.isArray(permissions)
? permissions
: (permissions as any)?.functionPermissions ??
(permissions as any)?.functionPermissionsReturn ??
[];
const norm = (v: string | Hex | undefined) =>
(v ? String(v) : '').toLowerCase();
const selectorNorm = norm(functionSelector);
for (const p of list) {
const sel =
(p as any).functionSelector ??
(p as any).functionSelectorReturn ??
(p as any)[0];
if (sel && norm(sel) === selectorNorm) {
const rawBitmap =
(p as any).grantedActionsBitmap ??
(p as any).grantedActionsBitmapReturn ??
(p as any)[1];
const bitmap =
typeof rawBitmap === 'bigint'
? Number(rawBitmap)
: typeof rawBitmap === 'number'
? rawBitmap
: rawBitmap != null
? Number(rawBitmap)
: 0;
return (bitmap & (1 << action)) !== 0;
}
}
return false;
}
/**
* Detect if a thrown error is a contract revert with ResourceAlreadyExists / ItemAlreadyExists.
* Used for idempotent permission setup (e.g. ADD_FUNCTION_TO_ROLE when already present).
*/
protected isResourceAlreadyExistsRevert(error: any): boolean {
if (!error) return false;
const msg = (error.shortMessage ?? error.message ?? error.cause?.shortMessage ?? error.cause?.message ?? '').toString();
if (/ResourceAlreadyExists|ItemAlreadyExists|Item already exists/i.test(msg)) return true;
const data = error.data ?? error.cause?.data;
if (data?.errorName === 'ResourceAlreadyExists' || data?.errorName === 'ItemAlreadyExists') return true;
const selector = this.decodeErrorSelector(data?.data ?? data);
if (selector) {
const name = this.getErrorName(selector);
if (name === 'ResourceAlreadyExists' || name === 'ItemAlreadyExists') return true;
}
return false;
}
/**
* Detect if a thrown error is a contract revert with NotSupported.
* Used where role-config batches may legitimately hit a schema/permission ceiling but we still
* want the final on-chain permission assertions to be the source of truth.
*/
protected isNotSupportedRevert(error: any): boolean {
if (!error) return false;
const msg = (error.shortMessage ?? error.message ?? error.cause?.shortMessage ?? error.cause?.message ?? '').toString();
if (/NotSupported/i.test(msg)) return true;
const data = error.data ?? error.cause?.data;
if (data?.errorName === 'NotSupported') return true;
const selector = this.decodeErrorSelector(data?.data ?? data);
if (selector) {
const name = this.getErrorName(selector);
if (name === 'NotSupported') return true;
}
return false;
}
/**
* Decode error selector from transaction result (revert data)
*/
protected decodeErrorSelector(result: any): string | null {
if (!result) return null;
let resultStr = '';
if (typeof result === 'string') {
resultStr = result.startsWith('0x') ? result : `0x${result}`;
} else if (result instanceof Uint8Array) {
resultStr = '0x' + Array.from(result).map((b) => b.toString(16).padStart(2, '0')).join('');
} else {
return null;
}
if (resultStr.length < 10) return null;
return resultStr.slice(0, 10);
}
/**
* Get error name from error selector
*/
protected getErrorName(errorSelector: string): string {
const errorMap: Record<string, string> = {
'0x430fab94': 'ResourceAlreadyExists',
'0x474d3baf': 'ResourceNotFound',
'0x3b94fe24': 'SignerNotAuthorized',
'0xf37a3442': 'NoPermission',
'0xc26028e0': 'InvalidOperation',
'0x6e8eb7bc': 'ResourceNotFound',
'0x7a6318f1': 'ItemNotFound',
'0x0da9443d': 'ItemAlreadyExists',
'0xf438c55f': 'InvalidOperation',
'0xa0387940': 'NotSupported',
'0x405c16b9': 'ConflictingMetaTxPermissions',
'0xee809d50': 'CannotModifyProtected',
};
return errorMap[errorSelector.toLowerCase()] || `Unknown(${errorSelector})`;
}
/**
* Extract transaction ID from receipt by decoding TransactionEvent (same state machine as runtime-rbac).
* This is a low-level helper used by higher-level methods that can fall back to getTransactionHistory when needed.
*/
protected extractTxIdFromReceipt(receipt: any): bigint | null {
if (!receipt?.logs?.length) return null;
const eventSignature = keccak256(
toBytes('TransactionEvent(uint256,bytes4,uint8,address,address,bytes32)')
) as Hex;
for (const log of receipt.logs) {
if (log.topics?.[0] === eventSignature && log.topics.length >= 2) {
const txId = BigInt(log.topics[1]);
console.log(` 📋 Extracted txId from TransactionEvent: ${txId}`);
return txId;
}
}
return null;
}
/**
* Extract transaction ID for a controller operation strictly from TransactionEvent logs.
* If no TransactionEvent is present in the receipt, we do NOT fall back to history inference;
* callers must rely on higher-level state checks instead of an ambiguous txId.
*/
protected async resolveTxIdForControllerOperation(receipt: any): Promise<bigint | null> {
const fromEvent = this.extractTxIdFromReceipt(receipt);
if (fromEvent == null) {
console.log(' ⚠️ No TransactionEvent found in receipt; txId cannot be resolved unambiguously');
}
return fromEvent;
}
/**
* CJS-style pre-check: skip registration if selector already has a schema or is in supportedFunctionsSet.
* Mirrors scripts/sanity/guard-controller (getFunctionSchema + getSupportedFunctions).
* @returns true if we should skip registration (schema exists with matching selector, or selector in getSupportedFunctions).
*/
protected async schemaOrSupportedSetPreCheck(selector: Hex): Promise<boolean> {
if (!this.guardController) return false;
const norm = (s: string | Hex) => String(s).toLowerCase();
// Prefer an owner-scoped client for reads in case the contract now
// enforces _validateAnyRole() or similar on view functions.
let client: GuardController;
try {
const ownerWallet = this.getRoleWallet('owner');
const ownerWalletName =
Object.keys(this.wallets).find(
(k) => this.wallets[k].address.toLowerCase() === ownerWallet.address.toLowerCase()
) ?? 'wallet1';
client = this.createGuardControllerWithWallet(ownerWalletName);
} catch {
// Fallback to the default client if role discovery or mapping fails.
client = this.guardController;
}
try {
const schema = await client.getFunctionSchema(selector);
const returnedSelector =