-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase-test.ts
More file actions
380 lines (332 loc) · 13.9 KB
/
Copy pathbase-test.ts
File metadata and controls
380 lines (332 loc) · 13.9 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
/**
* Base Test Class for SecureOwnable SDK Tests
* Provides SecureOwnable-specific functionality
*/
import { Address, Hex } from 'viem';
import { SecureOwnable } from '../../../sdk/typescript/contracts/core/SecureOwnable.tsx';
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 { FUNCTION_SELECTORS } from '../../../sdk/typescript/types/core.access.index.tsx';
import { extractErrorInfo } from '../../../sdk/typescript/utils/contract-errors.ts';
/** 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 SecureOwnableRoles {
owner: Address;
broadcaster: Address;
recovery: Address;
}
export abstract class BaseSecureOwnableTest extends BaseSDKTest {
protected secureOwnable: SecureOwnable | null = null;
/** Deployed SecureOwnableDefinitions library address (for execution params) */
protected secureOwnableDefinitionsAddress: Address | null = null;
protected roles: SecureOwnableRoles = {
owner: '0x' as Address,
broadcaster: '0x' as Address,
recovery: '0x' as Address,
};
protected roleWallets: Record<string, TestWallet> = {};
protected metaTxSigner: MetaTransactionSigner | null = null;
constructor(testName: string) {
super(testName);
}
/**
* Get contract address from artifacts (AccountBlox is the single account contract)
*/
protected async getContractAddress(): Promise<Address | null> {
return getContractAddressFromArtifacts('AccountBlox');
}
/**
* Get contract address from environment
*/
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 SecureOwnable SDK instance
*/
protected async initializeSDK(): Promise<void> {
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
this.secureOwnableDefinitionsAddress = await getDefinitionAddress('SecureOwnableDefinitions');
// Create a wallet client for the owner (default)
const walletClient = this.createWalletClient('wallet1');
this.secureOwnable = new SecureOwnable(
this.publicClient,
walletClient,
this.contractAddress,
this.chain
);
console.log('✅ SecureOwnable SDK initialized');
}
/**
* Discover role assignments from contract
*/
protected async discoverRoleAssignments(): Promise<void> {
if (!this.secureOwnable) {
throw new Error('SecureOwnable SDK not initialized');
}
try {
this.roles.owner = await this.secureOwnable.owner();
const broadcasters = await this.secureOwnable.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.secureOwnable.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 SecureOwnable instance with specific wallet
*/
protected createSecureOwnableWithWallet(walletName: string): SecureOwnable {
if (!this.contractAddress) {
throw new Error('Contract address not set');
}
const walletClient = this.createWalletClient(walletName);
return new SecureOwnable(
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
* The contract's createMetaTxParams method handles nonce and chainId automatically
*/
protected async createMetaTxParams(
handlerSelector: Hex,
action: TxAction,
signerAddress: Address,
deadlineSeconds: number = 3600
): Promise<MetaTxParams> {
if (!this.secureOwnable) {
throw new Error('SecureOwnable SDK not initialized');
}
// Contract expects deadline as seconds to add to current timestamp, not absolute timestamp
const deadline = BigInt(deadlineSeconds);
const maxGasPrice = BigInt(0);
// The contract's createMetaTxParams method automatically handles nonce, chainId, and deadline calculation
return await this.secureOwnable.createMetaTxParams(
this.contractAddress!,
handlerSelector,
action,
deadline,
maxGasPrice,
signerAddress
);
}
/**
* Create and sign a meta-transaction for an existing transaction
*/
protected async createSignedMetaTxForExisting(
txId: bigint,
handlerSelector: Hex,
action: TxAction,
signerWalletName: string
): Promise<MetaTransaction> {
if (!this.metaTxSigner) {
throw new Error('MetaTransactionSigner not initialized');
}
const signerWallet = this.wallets[signerWalletName];
if (!signerWallet) {
throw new Error(`Wallet not found: ${signerWalletName}`);
}
// Verify transaction exists and is pending before generating meta-transaction
console.log(` 🔍 Verifying transaction ${txId} is still pending before generating meta-transaction...`);
try {
const txBeforeMeta = await this.secureOwnable!.getTransaction(txId);
console.log(` 📋 Transaction ${txId} status: ${txBeforeMeta.status} (${Number(txBeforeMeta.status) === 1 ? 'PENDING' : 'NOT PENDING'})`);
if (Number(txBeforeMeta.status) !== 1) {
throw new Error(`Transaction ${txId} is no longer pending (status: ${txBeforeMeta.status}). Cannot generate meta-transaction.`);
}
console.log(` ✅ Transaction ${txId} confirmed as pending`);
} catch (verifyError: any) {
console.log(` ❌ Transaction verification failed: ${verifyError.message}`);
throw new Error(`Cannot generate meta-transaction: Transaction ${txId} verification failed: ${verifyError.message}`);
}
// Create meta-tx params
console.log(` 📋 Creating meta-transaction parameters...`);
console.log(` Handler Selector: ${handlerSelector}`);
console.log(` Action: ${action}`);
console.log(` Signer: ${signerWallet.address}`);
const metaTxParams = await this.createMetaTxParams(
handlerSelector,
action,
signerWallet.address
);
console.log(` ✅ Meta-transaction parameters created:`);
console.log(` Nonce: ${metaTxParams.nonce}`);
console.log(` Chain ID: ${metaTxParams.chainId}`);
console.log(` Deadline: ${metaTxParams.deadline}`);
// Generate unsigned meta-transaction
console.log(` 📋 Generating unsigned meta-transaction for transaction ${txId}...`);
const unsignedMetaTx = await this.metaTxSigner.createUnsignedMetaTransactionForExisting(
txId,
metaTxParams
);
console.log(` ✅ Unsigned meta-transaction generated`);
// Sign the meta-transaction using private key (for remote Ganache compatibility)
const signedMetaTx = await this.metaTxSigner.signMetaTransaction(
unsignedMetaTx,
signerWallet.address,
signerWallet.privateKey
);
// Create fullMetaTx object matching sanity test structure
const fullMetaTx = {
txRecord: signedMetaTx.txRecord,
params: signedMetaTx.params,
message: signedMetaTx.message,
signature: signedMetaTx.signature,
data: signedMetaTx.data
};
return fullMetaTx;
}
/**
* Wait for timelock with transaction ID
*/
protected async waitForTimelockWithTxId(txId: bigint): Promise<boolean> {
console.log(`⏳ WAITING FOR TIMELOCK: Transaction ${txId}`);
console.log('-'.repeat(40));
try {
if (!this.secureOwnable) {
throw new Error('SecureOwnable SDK not initialized');
}
// Get transaction details
const tx = await this.secureOwnable.getTransaction(txId);
const releaseTime = Number(tx.releaseTime);
const currentBlock = await this.publicClient.getBlock({ blockTag: 'latest' });
const currentBlockchainTime = Number(currentBlock.timestamp);
console.log(` 📋 Transaction ID: ${txId}`);
console.log(` 🕐 Release time: ${new Date(releaseTime * 1000).toLocaleString()}`);
console.log(` 🕐 Current blockchain time: ${new Date(currentBlockchainTime * 1000).toLocaleString()}`);
const waitTime = releaseTime - currentBlockchainTime;
if (waitTime <= 0) {
console.log(` ✅ Timelock already expired!`);
return true;
}
console.log(` ⏰ Need to wait ${waitTime} seconds for timelock to expire`);
const success = await this.advanceBlockchainTime(waitTime + 2); // Add 2 seconds buffer
if (success) {
// Verify timelock has expired
const newBlock = await this.publicClient.getBlock({ blockTag: 'latest' });
const newBlockchainTime = Number(newBlock.timestamp);
console.log(` 🕐 New blockchain time: ${new Date(newBlockchainTime * 1000).toLocaleString()}`);
if (newBlockchainTime >= releaseTime) {
console.log(` ✅ Timelock has expired!`);
return true;
}
}
return false;
} catch (error: any) {
console.log(` ❌ Error waiting for timelock: ${error.message}`);
return false;
}
}
/**
* Map high-level SecureOwnable operation names to their EngineBlox operationType hashes.
* Mirrors the CJS SecureOwnable base test helper so shared tests can use a single helper.
*/
protected getOperationType(
operationName: 'OWNERSHIP_TRANSFER' | 'BROADCASTER_UPDATE' | 'RECOVERY_UPDATE' | 'TIMELOCK_UPDATE'
): Hex {
const map: Record<string, Hex> = {
OWNERSHIP_TRANSFER: '0xb23d8fa2f62c8a954db45521d1249908693b29ffd3d2dab6348898c4198996b2' as Hex,
BROADCASTER_UPDATE: '0xae23396f8eb008d2f5f9673f91ccf20bf248201a6e0dbeaf46c421777ad8dc5b' as Hex,
RECOVERY_UPDATE: '0x032398090b003ba6aff30213cf16b7307ece6fbd6d969286006538a576526983' as Hex,
TIMELOCK_UPDATE: '0x06e0fdee0e8a4d2e629ae3d26c7bc6342072096facbcbe06d204d6051d97c50f' as Hex
};
const value = map[operationName];
if (!value) {
throw new Error(`Unknown operation type: ${operationName}`);
}
return value;
}
}