forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.js
More file actions
398 lines (351 loc) · 16.5 KB
/
Copy pathdeploy.js
File metadata and controls
398 lines (351 loc) · 16.5 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
#!/usr/bin/env node
/**
* Nova Rewards — Main Deployment Script
*
* Orchestrates the full deployment of the Nova Rewards token infrastructure
* on either Stellar Testnet or Mainnet. Steps:
*
* 1. Validate environment
* 2. Fund accounts (Testnet: Friendbot | Mainnet: manual pre-fund required)
* 3. Establish NOVA trustline on Distribution Account
* 4. Issue initial NOVA supply from Issuer to Distribution Account
* 5. Initialize contract state
* 6. Verify deployment health
*
* Each step is logged to deploy/logs/<id>.json. On failure the script exits
* with code 1 and the log captures the failure for rollback use.
*
* Usage:
* node deploy/deploy.js # deploys to testnet
* node deploy/deploy.js --network testnet
* node deploy/deploy.js --network mainnet
* node deploy/deploy.js --dry-run # validate env only, no tx submitted
*
* Requirements: 1.1, 1.2, 1.3, 1.5
*/
'use strict';
require('dotenv').config({ path: require('path').join(__dirname, '../.env') });
const {
Keypair,
TransactionBuilder,
Operation,
Memo,
BASE_FEE,
StrKey,
Horizon,
Asset,
} = require('stellar-sdk');
const readline = require('readline');
const { getNetworkConfig, resolveNetwork } = require('./config/networks');
const { Logger, Status } = require('./lib/logger');
const { initContract, validateEnv } = require('./init-contract');
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
/**
* Prompt the user for a yes/no confirmation.
* @param {string} question
* @returns {Promise<boolean>}
*/
function confirm(question) {
return new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question(`${question} [y/N] `, (answer) => {
rl.close();
resolve(/^y(es)?$/i.test(answer.trim()));
});
});
}
/**
* Funds a Testnet account via Friendbot.
* Skips silently if the account already exists.
*
* @param {string} friendbotUrl
* @param {Horizon.Server} server
* @param {string} publicKey
*/
async function friendbotFund(friendbotUrl, server, publicKey) {
try {
await server.loadAccount(publicKey);
return { funded: false, reason: 'already_exists' };
} catch {
// Account does not exist — fund it
}
const res = await fetch(`${friendbotUrl}?addr=${encodeURIComponent(publicKey)}`);
if (!res.ok) {
const body = await res.text();
throw new Error(`Friendbot failed for ${publicKey}: ${body}`);
}
return { funded: true };
}
/**
* Checks whether an account has a NOVA trustline.
*
* @param {Horizon.Server} server
* @param {string} publicKey
* @param {Asset} asset
* @returns {Promise<boolean>}
*/
async function hasTrustline(server, publicKey, asset) {
try {
const account = await server.loadAccount(publicKey);
return account.balances.some(
(b) =>
b.asset_type !== 'native' &&
b.asset_code === asset.code &&
b.asset_issuer === asset.issuer
);
} catch {
return false;
}
}
/**
* Checks whether the Distribution Account already holds NOVA tokens.
*
* @param {Horizon.Server} server
* @param {string} publicKey
* @param {Asset} asset
* @returns {Promise<{balance: string, hasTokens: boolean}>}
*/
async function getNovaBalance(server, publicKey, asset) {
const account = await server.loadAccount(publicKey);
const b = account.balances.find(
(bal) =>
bal.asset_type !== 'native' &&
bal.asset_code === asset.code &&
bal.asset_issuer === asset.issuer
);
const balance = b ? b.balance : '0';
return { balance, hasTokens: parseFloat(balance) > 0 };
}
// ─────────────────────────────────────────────────────────────────────────────
// Core deploy logic
// ─────────────────────────────────────────────────────────────────────────────
async function deploy({ network, dryRun = false }) {
const cfg = getNetworkConfig(network);
const server = new Horizon.Server(cfg.horizonUrl);
const issuerKeypair = Keypair.fromSecret(process.env.ISSUER_SECRET);
const distributionKeypair = Keypair.fromSecret(process.env.DISTRIBUTION_SECRET);
const issuerPublic = issuerKeypair.publicKey();
const distributionPublic = distributionKeypair.publicKey();
const novaAsset = new Asset(cfg.assetCode, issuerPublic);
// ── Banner ─────────────────────────────────────────────────────────────────
console.log('\n╔══════════════════════════════════════════════════════╗');
console.log(`║ Nova Rewards Deployment — ${cfg.name.padEnd(24)}║`);
console.log('╚══════════════════════════════════════════════════════╝\n');
console.log(` Network: ${cfg.name}`);
console.log(` Horizon: ${cfg.horizonUrl}`);
console.log(` Issuer: ${issuerPublic}`);
console.log(` Distribution: ${distributionPublic}`);
console.log(` Asset: ${cfg.assetCode}`);
console.log(` Supply: ${cfg.initialSupply} ${cfg.assetCode}`);
if (dryRun) console.log('\n ⚠️ DRY-RUN MODE — no transactions will be submitted\n');
// ── Mainnet confirmation guard ─────────────────────────────────────────────
if (cfg.requireConfirm && !dryRun) {
console.log('\n⚠️ You are about to deploy to MAINNET. This is irreversible.\n');
const ok = await confirm('Continue with mainnet deployment?');
if (!ok) {
console.log('\nDeployment cancelled.\n');
process.exit(0);
}
}
// ── Start deployment log ───────────────────────────────────────────────────
const log = Logger.begin({
network,
issuer: issuerPublic,
distribution: distributionPublic,
});
console.log(`\n📄 Deployment log: deploy/logs/${log.deploymentId}.json\n`);
try {
// ── Step 1: Environment validation ──────────────────────────────────────
console.log('[1/6] Validating environment...');
validateEnv(network);
log.step({ name: 'Validate environment', status: Status.SUCCESS });
if (dryRun) {
log.finish('success', { dryRun: true });
console.log('\n✅ Dry-run complete — environment is valid.\n');
return { deploymentId: log.deploymentId, dryRun: true };
}
// ── Step 2: Fund accounts ───────────────────────────────────────────────
console.log('[2/6] Funding accounts...');
if (cfg.friendbotUrl) {
// Testnet: use Friendbot
const issuerResult = await friendbotFund(cfg.friendbotUrl, server, issuerPublic);
log.step({
name: 'Fund issuer account (Friendbot)',
status: Status.SUCCESS,
data: issuerResult,
});
console.log(` Issuer: ${issuerResult.funded ? 'funded via Friendbot' : 'already funded'}`);
const distResult = await friendbotFund(cfg.friendbotUrl, server, distributionPublic);
log.step({
name: 'Fund distribution account (Friendbot)',
status: Status.SUCCESS,
data: distResult,
});
console.log(` Distribution: ${distResult.funded ? 'funded via Friendbot' : 'already funded'}`);
} else {
// Mainnet: verify accounts were pre-funded
try {
await server.loadAccount(issuerPublic);
log.step({ name: 'Verify issuer account funded', status: Status.SUCCESS });
console.log(' Issuer: found on mainnet ✓');
} catch {
const err = new Error(
`Issuer account not found on mainnet: ${issuerPublic}\n` +
'You must manually fund this account before deploying to mainnet.'
);
log.step({ name: 'Verify issuer account funded', status: Status.FAILED, error: err.message });
throw err;
}
try {
await server.loadAccount(distributionPublic);
log.step({ name: 'Verify distribution account funded', status: Status.SUCCESS });
console.log(' Distribution: found on mainnet ✓');
} catch {
const err = new Error(
`Distribution account not found on mainnet: ${distributionPublic}\n` +
'You must manually fund this account before deploying to mainnet.'
);
log.step({ name: 'Verify distribution account funded', status: Status.FAILED, error: err.message });
throw err;
}
}
// ── Step 3: Establish NOVA trustline ────────────────────────────────────
console.log('[3/6] Establishing NOVA trustline on Distribution Account...');
const trustlineExists = await hasTrustline(server, distributionPublic, novaAsset);
if (trustlineExists) {
log.step({ name: 'Establish NOVA trustline', status: Status.SKIPPED, data: { reason: 'already_exists' } });
console.log(' Trustline already exists — skipped.');
} else {
const distAccount = await server.loadAccount(distributionPublic);
const trustlineTx = new TransactionBuilder(distAccount, {
fee: String(cfg.baseFee),
networkPassphrase: cfg.networkPassphrase,
})
.addOperation(Operation.changeTrust({ asset: novaAsset }))
.setTimeout(cfg.txTimeout)
.build();
trustlineTx.sign(distributionKeypair);
const trustlineResult = await server.submitTransaction(trustlineTx);
log.step({
name: 'Establish NOVA trustline',
status: Status.SUCCESS,
data: {
txHash: trustlineResult.hash,
explorer: `${cfg.explorerBase}/${trustlineResult.hash}`,
},
});
log.update({ trustlineTxHash: trustlineResult.hash });
console.log(` Trustline created. Tx: ${trustlineResult.hash}`);
console.log(` Explorer: ${cfg.explorerBase}/${trustlineResult.hash}`);
}
// ── Step 4: Issue initial NOVA supply ───────────────────────────────────
console.log('[4/6] Issuing initial NOVA supply...');
const { balance: currentBalance, hasTokens } = await getNovaBalance(
server, distributionPublic, novaAsset
);
if (hasTokens) {
log.step({
name: 'Issue initial NOVA supply',
status: Status.SKIPPED,
data: { reason: 'already_funded', currentBalance },
});
console.log(` Distribution already holds ${currentBalance} NOVA — skipped.`);
} else {
const issuerAccount = await server.loadAccount(issuerPublic);
const paymentTx = new TransactionBuilder(issuerAccount, {
fee: String(cfg.baseFee),
networkPassphrase: cfg.networkPassphrase,
})
.addOperation(
Operation.payment({
destination: distributionPublic,
asset: novaAsset,
amount: cfg.initialSupply,
})
)
.addMemo(Memo.text('NovaRewards initial supply'))
.setTimeout(cfg.txTimeout)
.build();
paymentTx.sign(issuerKeypair);
const paymentResult = await server.submitTransaction(paymentTx);
log.step({
name: 'Issue initial NOVA supply',
status: Status.SUCCESS,
data: {
amount: cfg.initialSupply,
txHash: paymentResult.hash,
explorer: `${cfg.explorerBase}/${paymentResult.hash}`,
},
});
log.update({ supplyTxHash: paymentResult.hash });
console.log(` ${cfg.initialSupply} NOVA issued. Tx: ${paymentResult.hash}`);
console.log(` Explorer: ${cfg.explorerBase}/${paymentResult.hash}`);
}
// ── Step 5: Initialize contract state ───────────────────────────────────
console.log('[5/6] Initializing contract state...');
await initContract({ network, logger: log, deploymentId: log.deploymentId });
// ── Step 6: Run inline verification ─────────────────────────────────────
console.log('[6/6] Verifying deployment...');
const { runVerification } = require('./verify');
const verifyResult = await runVerification({ network, silent: false });
if (verifyResult.allPassed) {
log.step({ name: 'Post-deploy verification', status: Status.SUCCESS });
} else {
log.step({
name: 'Post-deploy verification',
status: Status.FAILED,
error: `${verifyResult.failed} check(s) failed`,
data: { checks: verifyResult.checks },
});
throw new Error(`Deployment verification failed: ${verifyResult.failed} check(s) did not pass.`);
}
// ── Done ─────────────────────────────────────────────────────────────────
log.finish('success');
console.log('\n╔══════════════════════════════════════════════════════╗');
console.log('║ ✅ Nova Rewards deployed successfully! ║');
console.log('╚══════════════════════════════════════════════════════╝\n');
console.log(` Deployment ID: ${log.deploymentId}`);
console.log(` Network: ${cfg.name}`);
console.log(` Log: deploy/logs/${log.deploymentId}.json`);
console.log(` Contract: deploy/contract-state.json\n`);
console.log(' Next steps:');
console.log(' 1. Start the backend: cd backend && npm start');
console.log(' 2. Start the frontend: cd frontend && npm run dev');
console.log(' 3. Run migrations: npm run migrate\n');
return { deploymentId: log.deploymentId, success: true };
} catch (err) {
log.finish('failed', { errorMessage: err.message });
console.error(`\n❌ Deployment failed: ${err.message}`);
if (err.response?.data) {
console.error('Stellar error:', JSON.stringify(err.response.data.extras?.result_codes ?? err.response.data, null, 2));
}
console.error(`\n Log saved to: deploy/logs/${log.deploymentId}.json`);
console.error(` To rollback: node deploy/rollback.js --deployment-id ${log.deploymentId}\n`);
process.exitCode = 1;
return { deploymentId: log.deploymentId, success: false, error: err.message };
}
}
// ─────────────────────────────────────────────────────────────────────────────
// CLI entry point
// ─────────────────────────────────────────────────────────────────────────────
if (require.main === module) {
const network = resolveNetwork();
const dryRun = process.argv.includes('--dry-run');
try {
validateEnv(network);
} catch (err) {
console.error(`\n❌ Environment error: ${err.message}\n`);
process.exit(1);
}
deploy({ network, dryRun })
.then((result) => {
if (!result.success && !result.dryRun) process.exit(1);
})
.catch((err) => {
console.error('Unexpected error:', err);
process.exit(1);
});
}
module.exports = { deploy };