|
| 1 | +/** |
| 2 | + * Pre-Add-New-Key and Pre-Deactivate API Complete Test (using MaciClient and VoterClient) |
| 3 | + * |
| 4 | + * This script demonstrates the complete AMACI Pre-Deactivate workflow: |
| 5 | + * 1. Create Tenant and API Key |
| 6 | + * 2. Create AMACI Round (automatic Pre-Deactivate mode) |
| 7 | + * 3. Query Pre-Deactivate data |
| 8 | + * 4. Test Pre-Add-New-Key |
| 9 | + * 5. Test voting |
| 10 | + */ |
| 11 | + |
| 12 | +import { MaciClient } from '../src/maci'; |
| 13 | +import { VoterClient } from '../src/voter'; |
| 14 | +import { MaciCircuitType } from '../src/types'; |
| 15 | +import * as path from 'path'; |
| 16 | + |
| 17 | +function generateRandomString(length: number) { |
| 18 | + return Math.random() |
| 19 | + .toString(36) |
| 20 | + .substring(2, 2 + length); |
| 21 | +} |
| 22 | + |
| 23 | +async function main() { |
| 24 | + const network = 'testnet'; |
| 25 | + |
| 26 | + console.log('='.repeat(80)); |
| 27 | + console.log('Pre-Add-New-Key and Pre-Deactivate API Complete Test (MaciClient & VoterClient)'); |
| 28 | + console.log('='.repeat(80)); |
| 29 | + |
| 30 | + // API base configuration |
| 31 | + const API_BASE_URL = 'http://localhost:8080'; |
| 32 | + |
| 33 | + // Create temporary MaciClient (for admin operations, no API key required) |
| 34 | + const adminMaciClient = new MaciClient({ |
| 35 | + network: network, |
| 36 | + saasApiEndpoint: API_BASE_URL |
| 37 | + }); |
| 38 | + |
| 39 | + // ==================== 1. Create Tenant and API Key ==================== |
| 40 | + const tenantName = `Test Tenant ${generateRandomString(10)}`; |
| 41 | + console.log(`\n[1/5] Creating Tenant: ${tenantName}`); |
| 42 | + |
| 43 | + // Create Tenant through underlying API client |
| 44 | + const tenantData = await adminMaciClient.getSaasApiClient().createTenant({ |
| 45 | + name: tenantName |
| 46 | + }); |
| 47 | + console.log('✓ Tenant created successfully:', tenantData.id); |
| 48 | + |
| 49 | + const apiKeyData = await adminMaciClient.getSaasApiClient().createApiKey({ |
| 50 | + tenantId: tenantData.id, |
| 51 | + label: 'Test API Key', |
| 52 | + plan: 'pro' |
| 53 | + }); |
| 54 | + const apiKey = apiKeyData.apiKey; |
| 55 | + console.log('✓ API Key created successfully:', apiKey); |
| 56 | + |
| 57 | + // Create MaciClient with API Key |
| 58 | + const maciClient = new MaciClient({ |
| 59 | + network: network, |
| 60 | + saasApiEndpoint: API_BASE_URL, |
| 61 | + saasApiKey: apiKey |
| 62 | + }); |
| 63 | + |
| 64 | + // ==================== 2. Create AMACI Round (Auto Pre-Deactivate Mode) ==================== |
| 65 | + console.log('\n[2/5] Creating AMACI Round (Auto Pre-Deactivate Mode)'); |
| 66 | + console.log('Note: Without allowlistId, API will auto-generate accounts in response'); |
| 67 | + |
| 68 | + const startVoting = new Date(); |
| 69 | + const endVoting = new Date(startVoting.getTime() + 1000 * 60 * 11); // 11 minutes later |
| 70 | + const maxVoter = 10; |
| 71 | + |
| 72 | + const createRoundData = await maciClient.saasCreateAmaciRound({ |
| 73 | + title: 'Pre-Add-New-Key Test Round', |
| 74 | + description: 'Testing pre-add-new-key with auto pre-deactivate', |
| 75 | + link: 'https://test.com', |
| 76 | + startVoting: startVoting.toISOString(), |
| 77 | + endVoting: endVoting.toISOString(), |
| 78 | + operator: 'dora149n5yhzgk5gex0eqmnnpnsxh6ys4exg5xyqjzm', |
| 79 | + maxVoter: maxVoter, |
| 80 | + voteOptionMap: ['Option A', 'Option B', 'Option C', 'Option D', 'Option E'], |
| 81 | + circuitType: MaciCircuitType.IP1V, |
| 82 | + voiceCreditAmount: 10 |
| 83 | + // Without allowlistId, API will auto-generate pre-deactivate data |
| 84 | + }); |
| 85 | + |
| 86 | + const contractAddress = createRoundData.contractAddress; |
| 87 | + if (!contractAddress) { |
| 88 | + throw new Error('Contract address not returned'); |
| 89 | + } |
| 90 | + |
| 91 | + console.log('✓ Round created successfully!'); |
| 92 | + console.log(' Contract Address:', contractAddress); |
| 93 | + console.log(' Status:', createRoundData.status); |
| 94 | + console.log(' TX Hash:', createRoundData.txHash); |
| 95 | + |
| 96 | + // Verify accounts are returned |
| 97 | + if (!createRoundData.accounts) { |
| 98 | + throw new Error('Accounts not returned in response'); |
| 99 | + } |
| 100 | + |
| 101 | + const accountsData = createRoundData.accounts; |
| 102 | + console.log(' Accounts count:', accountsData.length); |
| 103 | + |
| 104 | + // Wait for transaction confirmation |
| 105 | + console.log('\nWaiting 6 seconds to ensure transaction confirmation...'); |
| 106 | + await new Promise((resolve) => setTimeout(resolve, 6000)); |
| 107 | + |
| 108 | + // Display first 3 accounts |
| 109 | + if (accountsData.length > 0) { |
| 110 | + console.log('\nFirst 3 accounts returned:'); |
| 111 | + accountsData.slice(0, 3).forEach((account, index) => { |
| 112 | + console.log(`\n Account ${index + 1}:`); |
| 113 | + console.log(` Pubkey: ${account.pubkey}`); |
| 114 | + console.log(` Secret Key: ${account.secretKey.substring(0, 20)}...`); |
| 115 | + }); |
| 116 | + } |
| 117 | + |
| 118 | + // ==================== 3. Query Pre-Deactivate Data ==================== |
| 119 | + console.log('\n[3/5] Querying Pre-Deactivate data from dedicated API'); |
| 120 | + |
| 121 | + // Use public API (no API key required) - create a temporary VoterClient |
| 122 | + const publicVoterClient = new VoterClient({ |
| 123 | + network: network, |
| 124 | + saasApiEndpoint: API_BASE_URL |
| 125 | + }); |
| 126 | + |
| 127 | + const deactivateData = await publicVoterClient.saasGetPreDeactivate(contractAddress); |
| 128 | + |
| 129 | + console.log('✓ Deactivate data queried successfully!'); |
| 130 | + console.log(' Root:', deactivateData.root); |
| 131 | + console.log(' Coordinator:', deactivateData.coordinator); |
| 132 | + console.log(' Leaves count:', deactivateData.leaves.length); |
| 133 | + console.log(' Deactivates count:', deactivateData.deactivates.length); |
| 134 | + |
| 135 | + // ==================== 4. Test Pre-Add-New-Key ==================== |
| 136 | + console.log('\n[4/5] Testing Pre-Add-New-Key'); |
| 137 | + |
| 138 | + // Use the first auto-generated account for Pre-Add-New-Key |
| 139 | + if (accountsData.length === 0) { |
| 140 | + throw new Error('No available account found for Pre-Add-New-Key test'); |
| 141 | + } |
| 142 | + |
| 143 | + const testAccount = accountsData[0]; |
| 144 | + console.log('Using first account:', testAccount.pubkey); |
| 145 | + |
| 146 | + // Create voter client using account's secretKey |
| 147 | + const voterClient = new VoterClient({ |
| 148 | + network: network, |
| 149 | + secretKey: testAccount.secretKey, |
| 150 | + saasApiEndpoint: API_BASE_URL |
| 151 | + }); |
| 152 | + |
| 153 | + const circuitPower = '2-1-1-5'; |
| 154 | + console.log('Executing Pre-Add-New-Key (with auto payload generation)...'); |
| 155 | + |
| 156 | + // Get coordinator pubkey from deactivateData |
| 157 | + const coordinatorPubkey = BigInt(deactivateData.coordinator); |
| 158 | + |
| 159 | + try { |
| 160 | + // Use saasPreCreateNewAccount: builds payload + submits pre-add-new-key |
| 161 | + // const derivePathParams = { accountIndex: 2 }; |
| 162 | + const { account, result } = await voterClient.saasPreCreateNewAccount({ |
| 163 | + contractAddress: contractAddress, |
| 164 | + stateTreeDepth: 2, |
| 165 | + coordinatorPubkey: coordinatorPubkey, |
| 166 | + deactivates: deactivateData.deactivates as any, |
| 167 | + wasmFile: path.join(process.cwd(), `add-new-key_v3/${circuitPower}/addKey.wasm`), |
| 168 | + zkeyFile: path.join(process.cwd(), `add-new-key_v3/${circuitPower}/addKey.zkey`) |
| 169 | + // derivePathParams |
| 170 | + }); |
| 171 | + |
| 172 | + console.log('✓ Pre-Add-New-Key succeeded!', result); |
| 173 | + console.log('✓ Pre-Add-New-Key account:', account.getPubkey().toPackedData()); |
| 174 | + |
| 175 | + // Wait for transaction confirmation |
| 176 | + console.log('\nWaiting 6 seconds to ensure Pre-Add-New-Key transaction confirmation...'); |
| 177 | + await new Promise((resolve) => setTimeout(resolve, 6000)); |
| 178 | + |
| 179 | + // ==================== 5. Test Voting ==================== |
| 180 | + console.log('\n[5/5] Testing Voting (with auto payload generation)'); |
| 181 | + |
| 182 | + // Use saasVote: builds payload + submits vote |
| 183 | + const voteResult = await account.saasVote({ |
| 184 | + contractAddress, |
| 185 | + operatorPubkey: |
| 186 | + 10721319678265866063861912417916780787229942812531198850410477756757845824096n, |
| 187 | + selectedOptions: [ |
| 188 | + { idx: 0, vc: 1 }, |
| 189 | + { idx: 2, vc: 1 }, |
| 190 | + { idx: 3, vc: 1 } |
| 191 | + ] |
| 192 | + }); |
| 193 | + |
| 194 | + console.log('✓ Voting succeeded!', voteResult); |
| 195 | + } catch (error) { |
| 196 | + console.log('⚠ Failed:', error); |
| 197 | + if (error instanceof Error) { |
| 198 | + console.log(' Error message:', error.message); |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + // ==================== Completed ==================== |
| 203 | + console.log('\n' + '='.repeat(80)); |
| 204 | + console.log('Test completed!'); |
| 205 | + console.log('='.repeat(80)); |
| 206 | + console.log('\nSummary:'); |
| 207 | + console.log('✓ Successfully created Tenant and API Key'); |
| 208 | + console.log('✓ Successfully created AMACI Round (Auto Pre-Deactivate Mode)'); |
| 209 | + console.log('✓ Accounts returned directly in create round response'); |
| 210 | + console.log('✓ Pre-Deactivate data queried from dedicated API'); |
| 211 | + console.log('✓ Completed Pre-Add-New-Key using auto-generated account'); |
| 212 | + console.log('✓ Tested voting functionality'); |
| 213 | + console.log('\nContract Address:', contractAddress); |
| 214 | + console.log('Total Accounts Generated:', accountsData.length); |
| 215 | + console.log('\nClient Features Demonstrated:'); |
| 216 | + console.log(' - MaciClient:'); |
| 217 | + console.log(' • Admin API via getSaasApiClient(): createTenant, createApiKey'); |
| 218 | + console.log(' • Round API via saasCreateAmaciRound()'); |
| 219 | + console.log(' - VoterClient:'); |
| 220 | + console.log(' • Pre-Deactivate API via saasGetPreDeactivate()'); |
| 221 | + console.log(' • Integrated Methods (auto payload + submit):'); |
| 222 | + console.log(' - saasPreCreateNewAccount(): builds payload + submits pre-add-new-key'); |
| 223 | + console.log(' - saasVote(): builds payload + submits vote'); |
| 224 | +} |
| 225 | + |
| 226 | +main().catch((error) => { |
| 227 | + console.error('\n❌ Test failed:', error); |
| 228 | + if (error instanceof Error) { |
| 229 | + console.error('Error message:', error.message); |
| 230 | + console.error('Stack trace:', error.stack); |
| 231 | + } |
| 232 | + process.exit(1); |
| 233 | +}); |
0 commit comments