@wasit-dev/core 0.8.0-beta.1 → 0.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.js +3 -1
  3. package/dist/check.d.ts +1 -1
  4. package/dist/ci-report.js +15 -7
  5. package/dist/config-writer.d.ts +96 -0
  6. package/dist/config-writer.js +281 -0
  7. package/dist/guard/budget.d.ts +6 -3
  8. package/dist/guard/budget.js +10 -3
  9. package/dist/guard/ci-event.d.ts +6 -0
  10. package/dist/guard/ci-event.js +7 -3
  11. package/dist/guard/ci-mainnet.d.ts +59 -0
  12. package/dist/guard/ci-mainnet.js +149 -0
  13. package/dist/guard/horizon.d.ts +30 -0
  14. package/dist/guard/horizon.js +107 -0
  15. package/dist/guard/mainnet-payer.d.ts +66 -0
  16. package/dist/guard/mainnet-payer.js +92 -0
  17. package/dist/guard/mainnet-plan.d.ts +133 -0
  18. package/dist/guard/mainnet-plan.js +208 -0
  19. package/dist/guard/mainnet-run.d.ts +87 -0
  20. package/dist/guard/mainnet-run.js +225 -0
  21. package/dist/guard/networks.d.ts +9 -8
  22. package/dist/guard/networks.js +21 -10
  23. package/dist/guard/optin.d.ts +106 -0
  24. package/dist/guard/optin.js +202 -0
  25. package/dist/guard/run-ledger.d.ts +212 -0
  26. package/dist/guard/run-ledger.js +426 -0
  27. package/dist/guard/run-lock.d.ts +62 -0
  28. package/dist/guard/run-lock.js +172 -0
  29. package/dist/guard/signed-terms.d.ts +96 -0
  30. package/dist/guard/signed-terms.js +207 -0
  31. package/dist/index.d.ts +18 -7
  32. package/dist/index.js +19 -5
  33. package/dist/mpp/channel-credential.d.ts +13 -1
  34. package/dist/mpp/channel-credential.js +18 -2
  35. package/dist/mpp/channel.d.ts +6 -0
  36. package/dist/mpp/channel.js +7 -3
  37. package/dist/mpp/charge.d.ts +31 -1
  38. package/dist/mpp/charge.js +74 -20
  39. package/dist/mpp/plan.d.ts +77 -0
  40. package/dist/mpp/plan.js +188 -0
  41. package/dist/mpp/suite.d.ts +6 -0
  42. package/dist/mpp/suite.js +2 -1
  43. package/dist/route-reader.d.ts +124 -0
  44. package/dist/route-reader.js +349 -0
  45. package/dist/wallet.d.ts +58 -1
  46. package/dist/wallet.js +128 -0
  47. package/dist/x402/chains/stellar.js +134 -3
  48. package/dist/x402/chains/types.d.ts +36 -2
  49. package/dist/x402/plan.d.ts +102 -0
  50. package/dist/x402/plan.js +380 -6
  51. package/dist/x402/rejected-request.d.ts +10 -0
  52. package/dist/x402/rejected-request.js +18 -0
  53. package/dist/x402/simulator.d.ts +34 -0
  54. package/dist/x402/simulator.js +452 -46
  55. package/package.json +1 -1
  56. package/dist/guard/mainnet-optin.d.ts +0 -58
  57. package/dist/guard/mainnet-optin.js +0 -95
@@ -0,0 +1,349 @@
1
+ /**
2
+ * What `wasit init` reads from a route (spec C2, C7 row 4; W3-2 slice 3).
3
+ *
4
+ * One unpaid request with the method and body the route takes: no payment,
5
+ * no signature, no key. A redirect is followed once inside the origin, and
6
+ * only when it keeps the request, the rule of the unpaid request a payment
7
+ * check reads (`fetchPaymentChallenge`, spec A8 row 5); any other redirect is
8
+ * reported and nothing is sent to its Location. The answer is data: read,
9
+ * never followed or run (rule 3). What a message takes from it passes through
10
+ * the sanitiser (A8 row 6), on one line and bounded; what the config takes
11
+ * from it is held to the config's own rules before it is written.
12
+ *
13
+ * Reading. A `PAYMENT-REQUIRED` header (or `X-Payment`, which the read checks
14
+ * also accept) is x402, one offer per payment option. A `WWW-Authenticate`
15
+ * header with `Payment` challenges is MPP: the intent tells charge from
16
+ * channel, and a channel challenge names its channel. MPP's network is read
17
+ * the way the Stellar MPP client reads it, so a challenge that names none is
18
+ * stellar:testnet (`@stellar/mpp` 0.7.1 `resolveNetworkId`,
19
+ * dist/shared/validation.js; the charge and the channel client both call it).
20
+ * An x402 v1 challenge in the body is reported as v1.
21
+ *
22
+ * Choosing. init writes one protocol on one network per route, and only what
23
+ * is certain (Najmi, 2026-11-15): with several ways to pay on test networks
24
+ * and no flag to choose, it does not choose; a network that is mainnet or
25
+ * that Wasit does not know is not written in this version.
26
+ */
27
+ import { StrKey } from "@stellar/stellar-sdk";
28
+ import { Challenge } from "mppx";
29
+ import { RedirectRefusedError, TargetUnreachableError, fetchPaymentChallenge } from "./errors.js";
30
+ import { RunBudget, formatUsd, shown, usdAsset } from "./guard/budget.js";
31
+ import { NETWORK_CLASSES, networkClass } from "./guard/networks.js";
32
+ import { isMppNetwork } from "./mpp/network.js";
33
+ import { sanitizeText } from "./sanitize.js";
34
+ import { acceptsOf } from "./x402/requirements.js";
35
+ import { buildInit, readV1BodyChallenge } from "./x402/simulator.js";
36
+ /** How long init waits for the route's answer. */
37
+ export const ROUTE_READ_TIMEOUT_MS = 15_000;
38
+ /** The most of a body init reads: enough for an x402 v1 challenge. */
39
+ const BODY_LIMIT_BYTES = 64 * 1024;
40
+ /** The most notes a reading keeps: a hostile header cannot flood the terminal. */
41
+ const MAX_NOTES = 10;
42
+ /** The loader's rule for a pinned address (config.ts, ADDRESS). */
43
+ const PIN_ADDRESS = /^[A-Za-z0-9]{20,128}$/;
44
+ /** The loader refuses a file with a value of this shape anywhere (config.ts, STELLAR_SECRET). */
45
+ const STELLAR_SECRET_SHAPE = /S[A-Z2-7]{55}/;
46
+ function asRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
48
+ }
49
+ function text(value) {
50
+ return typeof value === "string" && value !== "" ? value : undefined;
51
+ }
52
+ /** A value of the service's for a line of output: sanitised, one line, bounded, unquoted. */
53
+ function brief(value) {
54
+ const line = sanitizeText(String(value)).replace(/\s+/g, " ").trim();
55
+ return line.length > 80 ? `${line.slice(0, 77)}...` : line;
56
+ }
57
+ /** A message for a line of output: sanitised and on one line, not cut. */
58
+ function oneLine(message) {
59
+ return sanitizeText(message).replace(/\s+/g, " ").trim();
60
+ }
61
+ function capped(notes) {
62
+ return notes.length <= MAX_NOTES ? notes : [...notes.slice(0, MAX_NOTES), `... and ${notes.length - MAX_NOTES} more.`];
63
+ }
64
+ function offerFields(fields) {
65
+ const out = {};
66
+ for (const key of ["amount", "asset", "payTo", "channel"]) {
67
+ const value = text(fields[key]);
68
+ if (value !== undefined)
69
+ out[key] = value;
70
+ }
71
+ return out;
72
+ }
73
+ function x402Offers(header, notes) {
74
+ let payload;
75
+ try {
76
+ payload = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
77
+ }
78
+ catch {
79
+ notes.push("The PAYMENT-REQUIRED header does not decode to JSON: x402 v2 sends the base64 of a JSON object.");
80
+ return [];
81
+ }
82
+ const accepts = acceptsOf(payload);
83
+ if (accepts === undefined || accepts.length === 0) {
84
+ notes.push("The PAYMENT-REQUIRED header lists no payment options (accepts).");
85
+ return [];
86
+ }
87
+ const offers = [];
88
+ accepts.forEach((option, index) => {
89
+ const network = text(option?.["network"]);
90
+ if (network === undefined) {
91
+ notes.push(`Payment option ${index + 1} of the PAYMENT-REQUIRED header names no network.`);
92
+ return;
93
+ }
94
+ offers.push({
95
+ protocol: "x402",
96
+ network,
97
+ networkNamed: true,
98
+ ...offerFields({ amount: option?.["amount"], asset: option?.["asset"], payTo: option?.["payTo"], channel: undefined }),
99
+ });
100
+ });
101
+ return offers;
102
+ }
103
+ function mppOffers(header, notes) {
104
+ let challenges;
105
+ try {
106
+ challenges = Challenge.deserializeList(header);
107
+ }
108
+ catch (error) {
109
+ notes.push(`The WWW-Authenticate header is not an MPP payment challenge Wasit can read (${brief(error.message)}).`);
110
+ return [];
111
+ }
112
+ const offers = [];
113
+ for (const challenge of challenges) {
114
+ if (challenge.method !== "stellar") {
115
+ notes.push(`An MPP challenge for the payment method ${shown(challenge.method)}: Wasit tests MPP on Stellar only.`);
116
+ continue;
117
+ }
118
+ const request = asRecord(challenge.request) ?? {};
119
+ const named = asRecord(request["methodDetails"])?.["network"];
120
+ let network;
121
+ if (named === undefined || named === null)
122
+ network = "stellar:testnet";
123
+ else if (typeof named === "string" && isMppNetwork(named))
124
+ network = named;
125
+ else {
126
+ notes.push(`An MPP ${brief(challenge.intent)} challenge names the network ${shown(named)}: a Stellar network is ` +
127
+ "stellar:testnet or stellar:pubnet.");
128
+ continue;
129
+ }
130
+ const networkNamed = named !== undefined && named !== null;
131
+ if (challenge.intent === "charge") {
132
+ offers.push({
133
+ protocol: "mpp-charge",
134
+ network,
135
+ networkNamed,
136
+ ...offerFields({ amount: request["amount"], asset: request["currency"], payTo: request["recipient"], channel: undefined }),
137
+ });
138
+ }
139
+ else if (challenge.intent === "channel") {
140
+ const fields = offerFields({ amount: request["amount"], asset: undefined, payTo: undefined, channel: request["channel"] });
141
+ if (fields.channel === undefined) {
142
+ notes.push("An MPP channel challenge names no channel.");
143
+ continue;
144
+ }
145
+ offers.push({ protocol: "mpp-channel", network, networkNamed, ...fields });
146
+ }
147
+ else {
148
+ notes.push(`An MPP challenge with the intent ${shown(challenge.intent)}: Wasit tests the intents charge and channel.`);
149
+ }
150
+ }
151
+ return offers;
152
+ }
153
+ /**
154
+ * What an answer says, without a network: the recorded answers of the tests
155
+ * go through the same reading as a live one.
156
+ */
157
+ export function interpretRouteAnswer(answer) {
158
+ const { status, headers, body, url } = answer;
159
+ if (status !== 402)
160
+ return { kind: "status", url, status };
161
+ const notes = [];
162
+ const offers = [];
163
+ const x402 = headers.get("PAYMENT-REQUIRED") ?? headers.get("X-Payment");
164
+ const mpp = headers.get("WWW-Authenticate");
165
+ if (x402 !== null)
166
+ offers.push(...x402Offers(x402, notes));
167
+ if (mpp !== null)
168
+ offers.push(...mppOffers(mpp, notes));
169
+ if (offers.length > 0)
170
+ return { kind: "challenge", url, offers, notes: capped(notes) };
171
+ if (x402 === null && mpp === null) {
172
+ if (readV1BodyChallenge(body) !== undefined)
173
+ return { kind: "x402-v1", url };
174
+ notes.push("The 402 carries no PAYMENT-REQUIRED header (x402 v2), no WWW-Authenticate header (MPP) and no x402 v1 challenge in its body.");
175
+ }
176
+ return { kind: "unreadable", url, notes: capped(notes) };
177
+ }
178
+ /** Reads at most `limit` bytes of a body, then lets the rest go. */
179
+ async function readBounded(response, limit) {
180
+ const reader = response.body?.getReader();
181
+ if (reader === undefined)
182
+ return "";
183
+ const chunks = [];
184
+ let size = 0;
185
+ try {
186
+ while (size < limit) {
187
+ const { done, value } = await reader.read();
188
+ if (done)
189
+ break;
190
+ chunks.push(value);
191
+ size += value.byteLength;
192
+ }
193
+ }
194
+ catch {
195
+ // What was read is the body.
196
+ }
197
+ finally {
198
+ await reader.cancel().catch(() => undefined);
199
+ }
200
+ return Buffer.concat(chunks).subarray(0, limit).toString("utf-8");
201
+ }
202
+ /**
203
+ * Sends the route one unpaid request and reads its answer.
204
+ *
205
+ * @throws {ConfigurationError} For a URL or a request shape that cannot be sent (checked before anything is sent).
206
+ */
207
+ export async function readRoute(url, shape, options = {}) {
208
+ const timeoutMs = options.timeoutMs ?? ROUTE_READ_TIMEOUT_MS;
209
+ const signal = AbortSignal.timeout(timeoutMs);
210
+ const init = { ...buildInit(shape), signal };
211
+ let answer;
212
+ try {
213
+ answer = await fetchPaymentChallenge(url, init);
214
+ }
215
+ catch (error) {
216
+ // Wasit's own messages, which name the origins already sanitised: one line, not cut.
217
+ if (error instanceof RedirectRefusedError)
218
+ return { kind: "redirect", message: oneLine(error.message) };
219
+ if (error instanceof TargetUnreachableError) {
220
+ return {
221
+ kind: "unreachable",
222
+ message: signal.aborted ? `It did not answer within ${timeoutMs / 1000} s.` : oneLine(error.message),
223
+ };
224
+ }
225
+ throw error;
226
+ }
227
+ const { response } = answer;
228
+ const plain = response.status === 402 &&
229
+ !response.headers.has("PAYMENT-REQUIRED") &&
230
+ !response.headers.has("X-Payment") &&
231
+ !response.headers.has("WWW-Authenticate");
232
+ let body = "";
233
+ if (plain)
234
+ body = await readBounded(response, BODY_LIMIT_BYTES);
235
+ else
236
+ await response.body?.cancel().catch(() => undefined);
237
+ return interpretRouteAnswer({ status: response.status, headers: response.headers, body, url: answer.url });
238
+ }
239
+ function testNetworks() {
240
+ return [...NETWORK_CLASSES]
241
+ .filter(([, kind]) => kind === "test")
242
+ .map(([network]) => network)
243
+ .join(", ");
244
+ }
245
+ const PROTOCOL_LABEL = {
246
+ x402: "x402",
247
+ "mpp-charge": "MPP charge",
248
+ "mpp-channel": "MPP channel",
249
+ };
250
+ /** One offer for a line of output. Sanitised. */
251
+ export function describeOffer(offer) {
252
+ const parts = [];
253
+ if (offer.amount !== undefined) {
254
+ const valued = /^\d{1,78}$/.test(offer.amount) && offer.asset !== undefined
255
+ ? RunBudget.valueOf(offer.network, offer.asset, BigInt(offer.amount))
256
+ : undefined;
257
+ const symbol = offer.asset === undefined ? undefined : usdAsset(offer.network, offer.asset)?.symbol;
258
+ parts.push(`price ${brief(offer.amount)} base units${offer.protocol === "mpp-channel" ? " a request" : ""}` +
259
+ (valued !== undefined && symbol !== undefined ? ` (${formatUsd(valued)} in ${symbol})` : ""));
260
+ }
261
+ if (offer.asset !== undefined)
262
+ parts.push(`${offer.protocol === "x402" ? "asset" : "currency"} ${brief(offer.asset)}`);
263
+ if (offer.payTo !== undefined)
264
+ parts.push(`${offer.protocol === "x402" ? "payTo" : "recipient"} ${brief(offer.payTo)}`);
265
+ if (offer.channel !== undefined)
266
+ parts.push(`channel ${brief(offer.channel)}`);
267
+ const where = `${PROTOCOL_LABEL[offer.protocol]} on ${brief(offer.network)}${offer.networkNamed ? "" : " (the challenge names no network; the Stellar MPP client reads that as stellar:testnet)"}`;
268
+ return parts.length === 0 ? where : `${where}: ${parts.join(", ")}`;
269
+ }
270
+ function way(offer) {
271
+ return `${PROTOCOL_LABEL[offer.protocol]} on ${brief(offer.network)}`;
272
+ }
273
+ function ways(offers) {
274
+ return [...new Set(offers.map(way))];
275
+ }
276
+ function wantedText(wanted) {
277
+ return [
278
+ ...(wanted.protocol === undefined ? [] : [PROTOCOL_LABEL[wanted.protocol]]),
279
+ ...(wanted.network === undefined ? [] : [`on ${brief(wanted.network)}`]),
280
+ ].join(" ");
281
+ }
282
+ /**
283
+ * The one way to pay init writes for this route, or why it writes none.
284
+ * Pure: the same offers and flags always give the same answer.
285
+ */
286
+ export function chooseOffer(offers, wanted = {}) {
287
+ const matching = offers.filter((offer) => (wanted.protocol === undefined || offer.protocol === wanted.protocol) &&
288
+ (wanted.network === undefined || offer.network === wanted.network));
289
+ if (matching.length === 0) {
290
+ return {
291
+ ok: false,
292
+ reason: `The route offers ${ways(offers).join("; ")}, and nothing as ${wantedText(wanted)}. Name one of those, or leave the flag out.`,
293
+ };
294
+ }
295
+ const onTest = matching.filter((offer) => networkClass(offer.network) === "test");
296
+ const testWays = ways(onTest);
297
+ if (testWays.length > 1) {
298
+ return {
299
+ ok: false,
300
+ reason: `The route offers more than one way to pay on a test network: ${testWays.join("; ")}. init writes one per ` +
301
+ "route and does not choose: name it with --protocol, --network or both.",
302
+ };
303
+ }
304
+ if (testWays.length === 0) {
305
+ const mainnet = matching.every((offer) => networkClass(offer.network) === "mainnet-optin");
306
+ return {
307
+ ok: false,
308
+ reason: mainnet
309
+ ? `The route asks to be paid on stellar:pubnet (mainnet): ${ways(matching).join("; ")}. init writes test networks only in this version.`
310
+ : `The route asks to be paid on ${ways(matching).join("; ")}, and none is a test network Wasit knows (${testNetworks()}).`,
311
+ };
312
+ }
313
+ const first = onTest[0];
314
+ const chosen = onTest.filter((offer) => offer.protocol === first.protocol && offer.network === first.network);
315
+ const left = offers.filter((offer) => !chosen.includes(offer));
316
+ const base = { ok: true, protocol: first.protocol, network: first.network, offers: chosen, left };
317
+ if (first.protocol === "mpp-channel") {
318
+ const channels = [...new Set(chosen.map((offer) => offer.channel ?? ""))];
319
+ if (channels.length > 1) {
320
+ return {
321
+ ok: false,
322
+ reason: `The route's channel challenges name ${channels.length} channels (${channels.map(brief).join(", ")}): init cannot tell which one it bills through.`,
323
+ };
324
+ }
325
+ const channel = channels[0];
326
+ if (!StrKey.isValidContract(channel)) {
327
+ return { ok: false, reason: `The channel challenge names the channel ${shown(channel)}, which is not a Soroban contract address (C...).` };
328
+ }
329
+ return { ...base, channel };
330
+ }
331
+ const payTos = [...new Set(chosen.map((offer) => offer.payTo))];
332
+ const assets = [...new Set(chosen.map((offer) => offer.asset))];
333
+ const payTo = payTos[0];
334
+ const asset = assets[0];
335
+ if (payTos.length > 1 || assets.length > 1) {
336
+ return { ...base, noPin: `the route offers more than one receiving address or asset on ${brief(first.network)}` };
337
+ }
338
+ if (payTo === undefined || asset === undefined || !PIN_ADDRESS.test(payTo) || !PIN_ADDRESS.test(asset)) {
339
+ return { ...base, noPin: "the challenge's receiving address or asset is missing or is not an address" };
340
+ }
341
+ if (STELLAR_SECRET_SHAPE.test(payTo) || STELLAR_SECRET_SHAPE.test(asset)) {
342
+ return {
343
+ ...base,
344
+ noPin: "the challenge's receiving address or asset is shaped like a Stellar secret key, so init does not write it " +
345
+ "(if it is a real key, the service is giving it away: rotate it)",
346
+ };
347
+ }
348
+ return { ...base, pin: { payTo, asset } };
349
+ }
package/dist/wallet.d.ts CHANGED
@@ -12,6 +12,9 @@
12
12
  * (faucet.circle.com) is a captcha-gated web form with no public API for
13
13
  * Stellar. `sendUsdcFromDistributor` covers the case where the operator has
14
14
  * already completed that manual step once, on an account of their own.
15
+ * `addTestnetUsdc` (used by `wasit init`) needs neither: it swaps a little of
16
+ * the account's own test XLM for test USDC on the public test exchange, the
17
+ * starter kit's way, and falls back to the trustline alone.
15
18
  *
16
19
  * **Error contract.** Every exported function that can fail throws one of
17
20
  * `errors.ts`'s types and never a raw Stellar SDK error: a bad key or a
@@ -23,7 +26,7 @@
23
26
  * Horizon's result codes into those messages; it stays exported only because
24
27
  * the CLI's own `--json` surface reuses it for non-wallet errors.
25
28
  */
26
- import { Asset } from "@stellar/stellar-sdk";
29
+ import { Asset, Keypair, type Transaction, type TransactionSource } from "@stellar/stellar-sdk";
27
30
  export declare const TESTNET_HORIZON_URL = "https://horizon-testnet.stellar.org";
28
31
  /** Circle's official USDC issuer on Stellar testnet — not a pubnet address. */
29
32
  export declare const TESTNET_USDC_ISSUER = "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5";
@@ -115,6 +118,60 @@ export declare function fundWithFriendbot(publicKey: string, attempts?: number):
115
118
  * reserve a trustline adds); callers should ensure that before calling this.
116
119
  */
117
120
  export declare function createUsdcTrustline(secretKey: string, source?: string): Promise<void>;
121
+ /**
122
+ * How much test XLM a new payer swaps for test USDC on the public test
123
+ * exchange, so it needs no faucet: the starter kit's amount
124
+ * (x402-starter-kit `lib/full.mjs`, `SWAP_XLM`), out of the 10,000 XLM
125
+ * Friendbot gives.
126
+ */
127
+ export declare const TESTNET_SWAP_XLM = "10";
128
+ /** One path Horizon's strict-send search answers with: only the fields the swap reads. */
129
+ export interface SwapPathRecord {
130
+ readonly destination_amount?: unknown;
131
+ readonly destination_asset_type?: unknown;
132
+ readonly destination_asset_code?: unknown;
133
+ readonly destination_asset_issuer?: unknown;
134
+ readonly path?: unknown;
135
+ }
136
+ /** The terms of the swap: the least USDC it accepts, and the assets in between. */
137
+ export interface UsdcSwapQuote {
138
+ /** A Stellar amount with 7 decimals. */
139
+ readonly destMin: string;
140
+ readonly path: readonly Asset[];
141
+ }
142
+ /**
143
+ * The swap's terms from Horizon's answer, or undefined when it gives no usable
144
+ * price. Every record is the exchange's, not trusted: only a path to Circle's
145
+ * testnet USDC counts, with an amount Stellar can carry and assets that parse;
146
+ * of those, the one that gives the most. It must give at least one USDC, and
147
+ * the swap then accepts no less than 80% of it, so it never runs at a much
148
+ * worse price than the one quoted. Sends nothing.
149
+ */
150
+ export declare function swapQuoteFrom(records: readonly SwapPathRecord[]): UsdcSwapQuote | undefined;
151
+ /**
152
+ * The one transaction that gives the account of `keypair` the testnet USDC
153
+ * trustline and, with a quote, swaps {@link TESTNET_SWAP_XLM} of its test XLM
154
+ * for test USDC paid to itself: both happen or neither does. Built for Stellar
155
+ * testnet only and signed; sends nothing.
156
+ */
157
+ export declare function usdcSetupTransaction(account: TransactionSource, keypair: Keypair, quote: UsdcSwapQuote | undefined): Transaction;
158
+ /** What {@link addTestnetUsdc} did: the trustline is there in both cases. */
159
+ export type UsdcSetupOutcome = {
160
+ readonly swapped: true;
161
+ } | {
162
+ readonly swapped: false;
163
+ readonly why: string;
164
+ };
165
+ /**
166
+ * Gives the account of `secretKey` the testnet USDC trustline and test USDC,
167
+ * with no faucet: it swaps {@link TESTNET_SWAP_XLM} test XLM on the public test
168
+ * exchange, in the same transaction as the trustline (the starter kit's way,
169
+ * spec C7 row 3). Without a usable price, or when that transaction fails (a
170
+ * price that moved, an empty book), it adds the trustline alone and says why.
171
+ * Throws only when the trustline itself could not be added. The account needs
172
+ * its test XLM first.
173
+ */
174
+ export declare function addTestnetUsdc(secretKey: string, source?: string): Promise<UsdcSetupOutcome>;
118
175
  /**
119
176
  * Sends testnet USDC from an already-funded distributor account to
120
177
  * `destinationPublicKey`. There is no way to acquire the first unit of
package/dist/wallet.js CHANGED
@@ -12,6 +12,9 @@
12
12
  * (faucet.circle.com) is a captcha-gated web form with no public API for
13
13
  * Stellar. `sendUsdcFromDistributor` covers the case where the operator has
14
14
  * already completed that manual step once, on an account of their own.
15
+ * `addTestnetUsdc` (used by `wasit init`) needs neither: it swaps a little of
16
+ * the account's own test XLM for test USDC on the public test exchange, the
17
+ * starter kit's way, and falls back to the trustline alone.
15
18
  *
16
19
  * **Error contract.** Every exported function that can fail throws one of
17
20
  * `errors.ts`'s types and never a raw Stellar SDK error: a bad key or a
@@ -221,6 +224,131 @@ export async function createUsdcTrustline(secretKey, source) {
221
224
  throw asWalletError(error, "create the USDC trustline");
222
225
  }
223
226
  }
227
+ /**
228
+ * How much test XLM a new payer swaps for test USDC on the public test
229
+ * exchange, so it needs no faucet: the starter kit's amount
230
+ * (x402-starter-kit `lib/full.mjs`, `SWAP_XLM`), out of the 10,000 XLM
231
+ * Friendbot gives.
232
+ */
233
+ export const TESTNET_SWAP_XLM = "10";
234
+ /** The swap accepts no less than this share of the quoted USDC, in percent (the kit's `SWAP_MIN_SHARE`, 0.8). */
235
+ const SWAP_MIN_PERCENT = 80n;
236
+ /** A quote under one USDC, in stroops, is no usable price (the kit's `out >= 1`). */
237
+ const SWAP_MIN_QUOTE_STROOPS = 10000000n;
238
+ const STROOPS_PER_UNIT = 10000000n;
239
+ /** A Stellar amount (at most 7 decimals) in stroops, or undefined when it is not one. */
240
+ function toStroops(amount) {
241
+ if (typeof amount !== "string")
242
+ return undefined;
243
+ const match = /^(\d{1,15})(?:\.(\d{1,7}))?$/.exec(amount);
244
+ if (match === null)
245
+ return undefined;
246
+ return BigInt(match[1]) * STROOPS_PER_UNIT + BigInt((match[2] ?? "").padEnd(7, "0"));
247
+ }
248
+ function fromStroops(stroops) {
249
+ return `${stroops / STROOPS_PER_UNIT}.${(stroops % STROOPS_PER_UNIT).toString().padStart(7, "0")}`;
250
+ }
251
+ function pathAssets(path) {
252
+ if (!Array.isArray(path))
253
+ return undefined;
254
+ try {
255
+ return path.map((entry) => entry.asset_type === "native" ? Asset.native() : new Asset(String(entry.asset_code), String(entry.asset_issuer)));
256
+ }
257
+ catch {
258
+ return undefined;
259
+ }
260
+ }
261
+ /**
262
+ * The swap's terms from Horizon's answer, or undefined when it gives no usable
263
+ * price. Every record is the exchange's, not trusted: only a path to Circle's
264
+ * testnet USDC counts, with an amount Stellar can carry and assets that parse;
265
+ * of those, the one that gives the most. It must give at least one USDC, and
266
+ * the swap then accepts no less than 80% of it, so it never runs at a much
267
+ * worse price than the one quoted. Sends nothing.
268
+ */
269
+ export function swapQuoteFrom(records) {
270
+ let best;
271
+ for (const record of records) {
272
+ if (record.destination_asset_type === "native" ||
273
+ record.destination_asset_code !== "USDC" ||
274
+ record.destination_asset_issuer !== TESTNET_USDC_ISSUER) {
275
+ continue;
276
+ }
277
+ const stroops = toStroops(record.destination_amount);
278
+ const path = pathAssets(record.path);
279
+ if (stroops === undefined || path === undefined)
280
+ continue;
281
+ if (best === undefined || stroops > best.stroops)
282
+ best = { stroops, path };
283
+ }
284
+ if (best === undefined || best.stroops < SWAP_MIN_QUOTE_STROOPS)
285
+ return undefined;
286
+ return { destMin: fromStroops((best.stroops * SWAP_MIN_PERCENT) / 100n), path: best.path };
287
+ }
288
+ /**
289
+ * The one transaction that gives the account of `keypair` the testnet USDC
290
+ * trustline and, with a quote, swaps {@link TESTNET_SWAP_XLM} of its test XLM
291
+ * for test USDC paid to itself: both happen or neither does. Built for Stellar
292
+ * testnet only and signed; sends nothing.
293
+ */
294
+ export function usdcSetupTransaction(account, keypair, quote) {
295
+ const usdc = testnetUsdcAsset();
296
+ const builder = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: Networks.TESTNET }).addOperation(Operation.changeTrust({ asset: usdc }));
297
+ if (quote !== undefined) {
298
+ builder.addOperation(Operation.pathPaymentStrictSend({
299
+ sendAsset: Asset.native(),
300
+ sendAmount: TESTNET_SWAP_XLM,
301
+ destination: keypair.publicKey(),
302
+ destAsset: usdc,
303
+ destMin: quote.destMin,
304
+ path: [...quote.path],
305
+ }));
306
+ }
307
+ const transaction = builder.setTimeout(60).build();
308
+ transaction.sign(keypair);
309
+ return transaction;
310
+ }
311
+ /**
312
+ * Gives the account of `secretKey` the testnet USDC trustline and test USDC,
313
+ * with no faucet: it swaps {@link TESTNET_SWAP_XLM} test XLM on the public test
314
+ * exchange, in the same transaction as the trustline (the starter kit's way,
315
+ * spec C7 row 3). Without a usable price, or when that transaction fails (a
316
+ * price that moved, an empty book), it adds the trustline alone and says why.
317
+ * Throws only when the trustline itself could not be added. The account needs
318
+ * its test XLM first.
319
+ */
320
+ export async function addTestnetUsdc(secretKey, source) {
321
+ publicKeyFromSecret(secretKey, source);
322
+ const keypair = Keypair.fromSecret(secretKey);
323
+ const server = horizonServer();
324
+ let quote;
325
+ let why = "the public test exchange gave no usable price";
326
+ try {
327
+ const found = await server.strictSendPaths(Asset.native(), TESTNET_SWAP_XLM, [testnetUsdcAsset()]).call();
328
+ quote = swapQuoteFrom(found.records);
329
+ }
330
+ catch {
331
+ why = "the public test exchange could not be asked for a price";
332
+ }
333
+ if (quote !== undefined) {
334
+ try {
335
+ const account = await server.loadAccount(keypair.publicKey());
336
+ await server.submitTransaction(usdcSetupTransaction(account, keypair, quote));
337
+ return { swapped: true };
338
+ }
339
+ catch (error) {
340
+ why = `the swap was not confirmed (${describeTransactionError(error)})`;
341
+ }
342
+ }
343
+ try {
344
+ const account = await server.loadAccount(keypair.publicKey());
345
+ await server.submitTransaction(usdcSetupTransaction(account, keypair, undefined));
346
+ }
347
+ catch (error) {
348
+ throw asWalletError(error, "create the USDC trustline");
349
+ }
350
+ return { swapped: false, why };
351
+ }
224
352
  /**
225
353
  * Sends testnet USDC from an already-funded distributor account to
226
354
  * `destinationPublicKey`. There is no way to acquire the first unit of