forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalletController.js
More file actions
248 lines (221 loc) · 6.42 KB
/
Copy pathwalletController.js
File metadata and controls
248 lines (221 loc) · 6.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
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
// controllers/stellar/walletController.js
import User from "../../models/User.js";
import {
isValidPublicKey,
getAccountBalance,
NETWORK,
} from "../../services/stellar/stellarService.js";
import logger from "../../config/logger.js";
import { recordAudit } from "../../services/audit/auditService.js";
import { AUDIT_ACTIONS } from "../../models/AuditLog.js";
/**
* Connect Stellar wallet to user profile
* POST /api/stellar/wallet/connect
*/
export const connectWallet = async (req, res) => {
try {
const userId = req.user._id;
const { publicKey } = req.body;
if (!publicKey || !isValidPublicKey(publicKey)) {
recordAudit({
action: AUDIT_ACTIONS.WALLET_CONNECT_FAILURE,
actor: userId,
req,
targetType: "Wallet",
targetId: publicKey ?? null,
status: "failure",
metadata: { reason: "invalid_public_key" },
});
return res.status(400).json({
success: false,
message: "Invalid Stellar public key",
});
}
const existingUser = await User.findOne({
"stellarWallet.publicKey": publicKey,
_id: { $ne: userId },
});
if (existingUser) {
recordAudit({
action: AUDIT_ACTIONS.WALLET_REASSIGN_ATTEMPT,
actor: userId,
req,
targetType: "Wallet",
targetId: publicKey,
status: "failure",
metadata: { publicKey, reason: "wallet_already_claimed", conflictUserId: existingUser._id.toString() },
});
return res.status(400).json({
success: false,
message: "This wallet is already connected to another account",
});
}
// Verify account exists on Stellar network and get balance/trustline info
// (accountInfo now includes per-asset balances/trustlines from the
// registry, e.g. { balances: { USDC, EURC }, trustlines: { USDC, EURC } })
const accountInfo = await getAccountBalance(publicKey);
const user = await User.findByIdAndUpdate(
userId,
{
stellarWallet: {
publicKey,
connectedAt: new Date(),
network: NETWORK,
},
},
{ new: true }
).select("-password");
logger.info(`Wallet connected for user ${userId}: ${publicKey}`);
recordAudit({
action: AUDIT_ACTIONS.WALLET_CONNECT_SUCCESS,
actor: userId,
req,
targetType: "Wallet",
targetId: publicKey,
status: "success",
metadata: { publicKey, network: NETWORK },
});
res.status(200).json({
success: true,
message: "Wallet connected successfully",
wallet: {
publicKey,
network: NETWORK,
...accountInfo,
},
});
} catch (error) {
logger.error("Connect wallet error:", error);
res.status(500).json({
success: false,
message: "Failed to connect wallet",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
}
};
/**
* Disconnect wallet from user profile
* DELETE /api/stellar/wallet/disconnect
*/
export const disconnectWallet = async (req, res) => {
try {
const userId = req.user._id;
// Capture the wallet key before unsetting it (for the audit row)
const currentUser = await User.findById(userId).select("stellarWallet");
const previousPublicKey = currentUser?.stellarWallet?.publicKey ?? null;
await User.findByIdAndUpdate(userId, {
$unset: { stellarWallet: 1 },
});
logger.info(`Wallet disconnected for user ${userId}`);
recordAudit({
action: AUDIT_ACTIONS.WALLET_DISCONNECT,
actor: userId,
req,
targetType: "Wallet",
targetId: previousPublicKey,
status: "success",
metadata: { previousPublicKey },
});
res.status(200).json({
success: true,
message: "Wallet disconnected successfully",
});
} catch (error) {
logger.error("Disconnect wallet error:", error);
res.status(500).json({
success: false,
message: "Failed to disconnect wallet",
});
}
};
/**
* Get wallet balance for any public key
* GET /api/stellar/wallet/balance/:publicKey
* Response now includes balances/trustlines per registry asset (USDC,
* EURC, XLM, ...) alongside the back-compat usdcBalance/hasTrustline
* fields, so the UI can prompt e.g. "add a EURC trustline" when needed.
*/
export const getWalletBalance = async (req, res) => {
try {
const { publicKey } = req.params;
if (!isValidPublicKey(publicKey)) {
return res.status(400).json({
success: false,
message: "Invalid public key",
});
}
const balance = await getAccountBalance(publicKey);
res.status(200).json({
success: true,
publicKey,
...balance,
});
} catch (error) {
logger.error("Get wallet balance error:", error);
res.status(500).json({
success: false,
message: "Failed to fetch balance",
});
}
};
/**
* Get current user's wallet info
* GET /api/stellar/wallet/me
*/
export const getMyWallet = async (req, res) => {
try {
const user = await User.findById(req.user._id).select("stellarWallet");
if (!user?.stellarWallet?.publicKey) {
return res.status(200).json({
success: true,
connected: false,
});
}
// Get live balance/trustlines from Stellar network (per-asset)
const balance = await getAccountBalance(user.stellarWallet.publicKey);
res.status(200).json({
success: true,
connected: true,
wallet: {
...user.stellarWallet.toObject(),
...balance,
},
});
} catch (error) {
logger.error("Get my wallet error:", error);
res.status(500).json({
success: false,
message: "Failed to fetch wallet info",
});
}
};
/**
* Check if a user has a connected wallet
* GET /api/stellar/wallet/check/:userId
*/
export const checkUserWallet = async (req, res) => {
try {
const { userId } = req.params;
const user = await User.findById(userId).select(
"stellarWallet.publicKey name"
);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found",
});
}
res.status(200).json({
success: true,
hasWallet: !!user.stellarWallet?.publicKey,
userName: user.name,
});
} catch (error) {
logger.error("Check user wallet error:", error);
res.status(500).json({
success: false,
message: "Failed to check wallet status",
});
}
};