-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-pay.ts
More file actions
295 lines (273 loc) · 9.42 KB
/
Copy pathsetup-pay.ts
File metadata and controls
295 lines (273 loc) · 9.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
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
/**
* Local Dev — Pay Platform Setup (multi-council)
*
* Seeds pay-platform with config for every council created by setup-c.sh via
* the admin API. This runs AFTER setup-c.sh and setup-pp.sh — it reads their
* outputs from .local-dev-state and combines them with the PAY_ADMIN identity
* from .local-dev-keys.
*
* Steps:
* 1. Load PAY_ADMIN keypair from env (passed by setup-pay.sh wrapper)
* 2. Load COUNCIL_COUNT + per-council channel/asset IDs from .local-dev-state
* 3. Fund PAY_ADMIN via Friendbot (needed for wallet auth challenge)
* 4. PAY_ADMIN authenticates to pay-platform → JWT
* 5. Create one council record per COUNCIL_<i>_* via POST /admin/councils
* (includes councilUrl)
*
* PP data is fetched live from council-platform at bundle time, not stored
* locally. The councilUrl stored with each council record tells pay-platform
* where to query.
*
* Why production-like: the admin API endpoints exercised here are the same
* ones an admin console would call. If pay-platform's admin surface breaks,
* this script breaks too — that's the point.
*
* Prereqs:
* - up.sh has run (pay-platform on :3025 with ADMIN_WALLETS set)
* - setup-c.sh has run (.local-dev-state has COUNCIL_COUNT + COUNCIL_<i>_*)
* - setup-pp.sh has run (.local-dev-state has PROVIDER_URL)
*
* Env (set by setup-pay.sh wrapper):
* PAY_ADMIN_PK required
* PAY_ADMIN_SK required
*
* Env overrides:
* PAY_PLATFORM_URL default http://localhost:3025
* FRIENDBOT_URL default http://localhost:8000/friendbot
* STATE_FILE default ./.local-dev-state
*/
import { Keypair } from "npm:@stellar/stellar-sdk@14.2.0";
const PAY_ADMIN_PK = Deno.env.get("PAY_ADMIN_PK");
const PAY_ADMIN_SK = Deno.env.get("PAY_ADMIN_SK");
if (!PAY_ADMIN_PK || !PAY_ADMIN_SK) {
throw new Error(
"PAY_ADMIN_PK and PAY_ADMIN_SK must be set (via setup-pay.sh wrapper)",
);
}
const PAY_PLATFORM_URL = Deno.env.get("PAY_PLATFORM_URL") ??
"http://localhost:3025";
const PAY_API = `${PAY_PLATFORM_URL}/api/v1`;
const FRIENDBOT_URL = Deno.env.get("FRIENDBOT_URL") ??
"http://localhost:8000/friendbot";
const STATE_FILE = Deno.env.get("STATE_FILE") ??
new URL("./.local-dev-state", import.meta.url).pathname;
interface CouncilState {
id: string;
name: string;
channel: string;
jurisdictions: string[];
}
interface State {
ASSET_ID: string;
NETWORK_PASSPHRASE: string;
COUNCIL_URL: string;
PROVIDER_URL: string;
councils: CouncilState[];
}
async function loadState(): Promise<State> {
let content: string;
try {
content = await Deno.readTextFile(STATE_FILE);
} catch {
throw new Error(
`State file not found at ${STATE_FILE}. Run setup-c.sh and setup-pp.sh first.`,
);
}
const env: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIdx = trimmed.indexOf("=");
if (eqIdx === -1) continue;
env[trimmed.slice(0, eqIdx).trim()] = trimmed.slice(eqIdx + 1).trim();
}
const required = [
"ASSET_ID",
"NETWORK_PASSPHRASE",
"COUNCIL_URL",
"PROVIDER_URL",
"COUNCIL_COUNT",
];
for (const key of required) {
if (!env[key]) {
throw new Error(
`State file missing ${key}. Run setup-c.sh and setup-pp.sh first.`,
);
}
}
const count = Number(env.COUNCIL_COUNT);
const councils: CouncilState[] = [];
for (let i = 1; i <= count; i++) {
const id = env[`COUNCIL_${i}_ID`];
const name = env[`COUNCIL_${i}_NAME`];
const channel = env[`COUNCIL_${i}_CHANNEL`];
const jurisdictions = (env[`COUNCIL_${i}_JURISDICTIONS`] ?? "").split(",")
.filter((j) => j);
if (!id || !name || !channel) {
throw new Error(`State file missing COUNCIL_${i}_* fields.`);
}
councils.push({ id, name, channel, jurisdictions });
}
return {
ASSET_ID: env.ASSET_ID,
NETWORK_PASSPHRASE: env.NETWORK_PASSPHRASE,
COUNCIL_URL: env.COUNCIL_URL,
PROVIDER_URL: env.PROVIDER_URL,
councils,
};
}
async function fundAccount(publicKey: string): Promise<void> {
const res = await fetch(`${FRIENDBOT_URL}?addr=${publicKey}`);
if (!res.ok && res.status !== 400) {
throw new Error(
`Friendbot failed for ${publicKey}: ${res.status} ${await res.text()}`,
);
}
}
async function warmupPay(): Promise<void> {
for (let i = 0; i < 30; i++) {
try {
const res = await fetch(`${PAY_API}/health`);
if (res.ok) return;
} catch { /* retry */ }
await new Promise((r) => setTimeout(r, 1000));
}
throw new Error(`pay-platform not reachable at ${PAY_PLATFORM_URL}`);
}
/** Wallet auth: challenge → sign nonce → verify → JWT. */
async function walletAuth(keypair: Keypair): Promise<string> {
const challengeRes = await fetch(`${PAY_API}/auth/challenge`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ publicKey: keypair.publicKey() }),
});
if (!challengeRes.ok) {
throw new Error(
`Auth challenge failed: ${challengeRes.status} ${await challengeRes
.text()}`,
);
}
const { data: { nonce } } = await challengeRes.json();
const nonceBytes = Uint8Array.from(atob(nonce), (c) => c.charCodeAt(0));
const sig = keypair.sign(Buffer.from(nonceBytes));
const signature = btoa(String.fromCharCode(...new Uint8Array(sig)));
const verifyRes = await fetch(`${PAY_API}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ nonce, signature, publicKey: keypair.publicKey() }),
});
if (!verifyRes.ok) {
throw new Error(
`Auth verify failed: ${verifyRes.status} ${await verifyRes.text()}`,
);
}
const { data: { token } } = await verifyRes.json();
return token;
}
async function createCouncil(
jwt: string,
state: State,
council: CouncilState,
): Promise<{ id: string }> {
const councilRes = await fetch(`${PAY_API}/admin/councils`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${jwt}`,
},
body: JSON.stringify({
name: council.name,
channelAuthId: council.id,
councilUrl: state.COUNCIL_URL,
networkPassphrase: state.NETWORK_PASSPHRASE,
channels: [
{
assetCode: "XLM",
assetContractId: state.ASSET_ID,
privacyChannelId: council.channel,
},
],
jurisdictions: council.jurisdictions,
active: true,
}),
});
if (!councilRes.ok) {
throw new Error(
`Create council "${council.name}" failed: ${councilRes.status} ${await councilRes
.text()}`,
);
}
const { data } = await councilRes.json();
return data;
}
async function main() {
const startTime = Date.now();
console.log("\n=== local-dev — Pay Platform Setup ===\n");
console.log("[1/6] Load state from setup-c + setup-pp");
const state = await loadState();
console.log(` Council URL: ${state.COUNCIL_URL}`);
console.log(` XLM SAC: ${state.ASSET_ID}`);
console.log(` Provider URL: ${state.PROVIDER_URL}`);
console.log(` Councils: ${state.councils.length}`);
for (const c of state.councils) {
console.log(
` - ${c.name} (${c.id}) — channel ${c.channel} — [${c.jurisdictions
.join(",")}]`,
);
}
console.log("\n[2/6] Warmup pay-platform");
await warmupPay();
console.log(" pay-platform reachable");
const payAdmin = Keypair.fromSecret(PAY_ADMIN_SK);
console.log(`\n Pay Admin: ${payAdmin.publicKey()}`);
console.log("\n[3/6] Fund PAY_ADMIN via Friendbot");
await fundAccount(payAdmin.publicKey());
console.log(" PAY_ADMIN funded");
console.log("\n[4/6] PAY_ADMIN authenticates to pay-platform");
const jwt = await walletAuth(payAdmin);
console.log(" JWT acquired");
console.log(
`\n[5/6] Create ${state.councils.length} councils via POST /admin/councils`,
);
const created: { id: string }[] = [];
for (const council of state.councils) {
const record = await createCouncil(jwt, state, council);
console.log(` Council created: ${council.name} → ${record.id}`);
created.push(record);
}
// Fund the PAY_SERVICE keypair so it can authenticate with provider-platform
const payServicePk = Deno.env.get("PAY_SERVICE_PK");
if (payServicePk) {
console.log("\n[6/6] Fund PAY_SERVICE via Friendbot");
await fundAccount(payServicePk);
console.log(` PAY_SERVICE funded: ${payServicePk}`);
} else {
console.log("\n[6/6] PAY_SERVICE_PK not set — skipping fund");
}
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
console.log(`\n=== Pay Platform setup complete in ${elapsed}s ===\n`);
console.log(` Councils created: ${created.length}`);
for (let i = 0; i < state.councils.length; i++) {
console.log(
` - ${state.councils[i].name}: DB ID ${created[i].id}, Auth ${
state.councils[i].id
}`,
);
}
console.log(` Council URL: ${state.COUNCIL_URL}`);
console.log(
` Provider URL: ${state.PROVIDER_URL} (PP data from council-platform)`,
);
if (payServicePk) {
console.log(` Service key: ${payServicePk}`);
}
console.log("");
console.log("Pay-platform now has the council config. PP data is fetched");
console.log("live from council-platform at bundle time.");
console.log("");
}
main().catch((err) => {
console.error("\n=== Pay Platform setup FAILED ===");
console.error(err);
Deno.exit(1);
});