forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathissueAsset.js
More file actions
161 lines (144 loc) · 5.42 KB
/
Copy pathissueAsset.js
File metadata and controls
161 lines (144 loc) · 5.42 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
require('dotenv').config();
const {
Keypair,
TransactionBuilder,
Operation,
Networks,
BASE_FEE,
} = require('stellar-sdk');
const { server, NOVA } = require('./stellarService');
const { verifyTrustline } = require('./trustline');
const NETWORK_PASSPHRASE =
process.env.STELLAR_NETWORK === 'mainnet'
? Networks.PUBLIC
: Networks.TESTNET;
const FRIENDBOT_URL = 'https://friendbot.stellar.org';
const INITIAL_SUPPLY = '1000000'; // 1,000,000 NOVA
/**
* Funds a Testnet account using Friendbot.
* Only calls Friendbot if the account does not yet exist on the network.
*
* @param {string} publicKey
*/
async function fundWithFriendbot(publicKey) {
try {
await server.loadAccount(publicKey);
console.log(` ${publicKey} already exists — Friendbot skipped`);
} catch {
// Account not found on network — safe to fund
const res = await fetch(`${FRIENDBOT_URL}?addr=${publicKey}`);
if (res.ok) {
console.log(` Funded ${publicKey} via Friendbot`);
} else {
const body = await res.text();
throw new Error(`Friendbot failed for ${publicKey}: ${body}`);
}
}
}
/**
* Checks whether the Distribution Account already has a NOVA trustline.
*
* @param {string} distributionPublic
* @returns {Promise<boolean>}
*/
async function hasTrustline(distributionPublic) {
try {
const account = await server.loadAccount(distributionPublic);
return account.balances.some(
(b) =>
b.asset_type !== 'native' &&
b.asset_code === NOVA.code &&
b.asset_issuer === NOVA.issuer
);
} catch {
return false;
}
}
/**
* One-time idempotent setup script:
* 1. Funds Issuer and Distribution accounts via Friendbot (Testnet only)
* 2. Establishes a NOVA trustline on the Distribution Account (if not already set)
* 3. Sends the initial NOVA supply from Issuer to Distribution Account
*
* Requirements: 1.1, 1.2, 1.3, 1.5
*/
async function issueAsset() {
const issuerKeypair = Keypair.fromSecret(process.env.ISSUER_SECRET);
const distributionKeypair = Keypair.fromSecret(process.env.DISTRIBUTION_SECRET);
console.log('=== NovaRewards Asset Issuance ===');
console.log(`Issuer: ${issuerKeypair.publicKey()}`);
console.log(`Distribution: ${distributionKeypair.publicKey()}`);
// Step 1: Fund both accounts via Friendbot (idempotent — skips if already funded)
console.log('\n[1] Funding accounts via Friendbot...');
await fundWithFriendbot(issuerKeypair.publicKey());
await fundWithFriendbot(distributionKeypair.publicKey());
// Step 2: Establish trustline on Distribution Account (idempotent check)
console.log('\n[2] Checking Distribution Account trustline...');
const { exists: trustlineExists } = await verifyTrustline(distributionKeypair.publicKey());
if (trustlineExists) {
console.log(' Trustline already exists — skipping.');
} else {
console.log(' Creating NOVA trustline on Distribution Account...');
const distAccount = await server.loadAccount(distributionKeypair.publicKey());
const trustlineTx = new TransactionBuilder(distAccount, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(Operation.changeTrust({ asset: NOVA }))
.setTimeout(180)
.build();
trustlineTx.sign(distributionKeypair);
try {
const trustlineResult = await server.submitTransaction(trustlineTx);
console.log(` Trustline created. Tx hash: ${trustlineResult.hash}`);
} catch (error) {
if (error.response?.data?.extras?.result_codes?.operations?.includes('op_underfunded')) {
throw new Error('Insufficient XLM balance in Distribution Account to cover transaction fees. Please fund the account with more XLM.');
}
throw error;
}
}
// Step 3: Send initial NOVA supply from Issuer to Distribution Account
// Check current balance first to stay idempotent
console.log('\n[3] Checking Distribution Account NOVA balance...');
const distAccountCheck = await server.loadAccount(distributionKeypair.publicKey());
const existingBalance = distAccountCheck.balances.find(
(b) =>
b.asset_type !== 'native' &&
b.asset_code === NOVA.code &&
b.asset_issuer === NOVA.issuer
);
if (existingBalance && parseFloat(existingBalance.balance) > 0) {
console.log(
` Distribution Account already holds ${existingBalance.balance} NOVA — skipping initial supply.`
);
} else {
console.log(` Sending ${INITIAL_SUPPLY} NOVA to Distribution Account...`);
const issuerAccount = await server.loadAccount(issuerKeypair.publicKey());
const paymentTx = new TransactionBuilder(issuerAccount, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
Operation.payment({
destination: distributionKeypair.publicKey(),
asset: NOVA,
amount: INITIAL_SUPPLY,
})
)
.setTimeout(180)
.build();
paymentTx.sign(issuerKeypair);
try {
const paymentResult = await server.submitTransaction(paymentTx);
console.log(` Initial supply sent. Tx hash: ${paymentResult.hash}`);
} catch (error) {
if (error.response?.data?.extras?.result_codes?.operations?.includes('op_underfunded')) {
throw new Error('Insufficient XLM balance in Issuer Account to cover transaction fees. Please fund the account with more XLM.');
}
throw error;
}
}
console.log('\n=== Asset issuance complete ===');
}
module.exports = { issueAsset };