@subly_fi/pay 0.1.0

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.
package/dist/pay.js ADDED
@@ -0,0 +1,1769 @@
1
+ // ../../demo/pay.ts
2
+ import { readFileSync as readFileSync2, writeFileSync } from "node:fs";
3
+
4
+ // ../../src/client/agent-wallet-signer.ts
5
+ import { signBytes } from "@solana/kit";
6
+ import bs584 from "bs58";
7
+
8
+ // ../../src/solana/tx.ts
9
+ import bs58 from "bs58";
10
+ import {
11
+ appendTransactionMessageInstructions,
12
+ compileTransaction,
13
+ compressTransactionMessageUsingAddressLookupTables,
14
+ createTransactionMessage,
15
+ getBase64EncodedWireTransaction,
16
+ getTransactionDecoder,
17
+ partiallySignTransaction,
18
+ pipe,
19
+ setTransactionMessageFeePayer,
20
+ setTransactionMessageLifetimeUsingBlockhash
21
+ } from "@solana/kit";
22
+
23
+ // ../../src/lib/hash.ts
24
+ import { createHash } from "node:crypto";
25
+ var EMPTY_BODY_HASH = "sha256-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
26
+ function sha256TaggedHex(data) {
27
+ return `sha256-${createHash("sha256").update(data).digest("hex")}`;
28
+ }
29
+ function stableStringify(value) {
30
+ if (value === null) {
31
+ return "null";
32
+ }
33
+ if (typeof value === "bigint") {
34
+ return JSON.stringify(value.toString());
35
+ }
36
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
37
+ return JSON.stringify(value);
38
+ }
39
+ if (Array.isArray(value)) {
40
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
41
+ }
42
+ const keys = Object.keys(value).filter((key) => value[key] !== void 0).sort();
43
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
44
+ }
45
+ function hashStableJson(value) {
46
+ return sha256TaggedHex(stableStringify(value));
47
+ }
48
+
49
+ // ../../src/solana/tx.ts
50
+ function decodeSerializedTransaction(serializedBase64) {
51
+ return getTransactionDecoder().decode(Buffer.from(serializedBase64, "base64"));
52
+ }
53
+ async function addSignaturesToSerializedTransaction(params) {
54
+ const decoded = decodeSerializedTransaction(params.serializedBase64);
55
+ const signed = await partiallySignTransaction(params.signers, decoded);
56
+ return {
57
+ serializedBase64: getBase64EncodedWireTransaction(signed),
58
+ transaction: signed
59
+ };
60
+ }
61
+ function signatureBase58ForSigner(transaction, signer2) {
62
+ const signature = transaction.signatures[signer2];
63
+ if (signature === null || signature === void 0) {
64
+ return null;
65
+ }
66
+ return bs58.encode(signature);
67
+ }
68
+
69
+ // ../../src/client/transaction-intent-validator.ts
70
+ import bs583 from "bs58";
71
+ import { getCompiledTransactionMessageDecoder } from "@solana/kit";
72
+
73
+ // ../../src/config/constants.ts
74
+ var PAYMENT_SCHEME = "subly-yield-exact";
75
+ var SOLANA_MAINNET_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
76
+ var SPL_TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
77
+ var ASSOCIATED_TOKEN_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
78
+ var SUBLY_VAULT = {
79
+ name: "Subly USDC Payment Vault Alpha",
80
+ address: "5kfkpQZ6AkQgizHVThqkxD4J3db2i7pE3mHdPNRbx7jr",
81
+ programId: "KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd",
82
+ usdcMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
83
+ shareMint: "7hGX49So539MU9Rrah8nBNVYXswWVwEJvgWNYeBDYq3a",
84
+ lookupTable: "7UbXhDnpK7WVnwsfivzQRENoqKqAULQ5s19gS1xJrQEo",
85
+ farm: "E2Ct77LowkDAH1T9ubwPpb84pU2GSGrUdgH3KeTTpLX"
86
+ };
87
+ var USDC_DECIMALS = 6;
88
+
89
+ // ../../src/domain/request-binding.ts
90
+ function computeRequestBindingHash(fields) {
91
+ return hashStableJson({
92
+ sellerRequestId: fields.sellerRequestId,
93
+ httpMethod: fields.httpMethod.toUpperCase(),
94
+ canonicalResourceUrl: fields.canonicalResourceUrl,
95
+ requestBodyHash: fields.requestBodyHash,
96
+ seller: fields.seller,
97
+ asset: fields.asset,
98
+ amountRawUsdc: fields.amountRawUsdc,
99
+ payTo: fields.payTo,
100
+ sellerUsdcAta: fields.sellerUsdcAta
101
+ });
102
+ }
103
+
104
+ // ../../src/lib/associated-token-account.ts
105
+ import { createHash as createHash2 } from "node:crypto";
106
+ import bs582 from "bs58";
107
+ var PDA_MARKER = Buffer.from("ProgramDerivedAddress", "utf8");
108
+ var ED25519_P = (1n << 255n) - 19n;
109
+ var ED25519_D = mod(-121665n * modPow(121666n, ED25519_P - 2n, ED25519_P), ED25519_P);
110
+ function deriveAssociatedTokenAddress(params) {
111
+ const owner = decodePublicKey(params.owner, "owner");
112
+ const mint = decodePublicKey(params.mint ?? SUBLY_VAULT.usdcMint, "mint");
113
+ const tokenProgramId = decodePublicKey(
114
+ params.tokenProgramId ?? SPL_TOKEN_PROGRAM_ID,
115
+ "tokenProgramId"
116
+ );
117
+ const associatedTokenProgramId = decodePublicKey(
118
+ ASSOCIATED_TOKEN_PROGRAM_ID,
119
+ "associatedTokenProgramId"
120
+ );
121
+ for (let bump = 255; bump >= 0; bump -= 1) {
122
+ const address2 = createProgramAddress(
123
+ [owner, tokenProgramId, mint, Uint8Array.of(bump)],
124
+ associatedTokenProgramId
125
+ );
126
+ if (address2 !== null) {
127
+ return bs582.encode(address2);
128
+ }
129
+ }
130
+ throw new Error("Unable to derive associated token account address");
131
+ }
132
+ function createProgramAddress(seeds, programId) {
133
+ const hash = createHash2("sha256");
134
+ for (const seed of seeds) {
135
+ hash.update(seed);
136
+ }
137
+ hash.update(programId);
138
+ hash.update(PDA_MARKER);
139
+ const digest = hash.digest();
140
+ return isEd25519Point(digest) ? null : new Uint8Array(digest);
141
+ }
142
+ function decodePublicKey(value, fieldName) {
143
+ const decoded = bs582.decode(value);
144
+ if (decoded.length !== 32) {
145
+ throw new Error(`${fieldName} must be a 32-byte public key`);
146
+ }
147
+ return decoded;
148
+ }
149
+ function isEd25519Point(bytes) {
150
+ if (bytes.length !== 32) {
151
+ return false;
152
+ }
153
+ const yBytes = Uint8Array.from(bytes);
154
+ yBytes[31] = yBytes[31] & 127;
155
+ const y = littleEndianToBigInt(yBytes);
156
+ if (y >= ED25519_P) {
157
+ return false;
158
+ }
159
+ const ySquared = mod(y * y, ED25519_P);
160
+ const numerator = mod(ySquared - 1n, ED25519_P);
161
+ const denominator = mod(ED25519_D * ySquared + 1n, ED25519_P);
162
+ if (denominator === 0n) {
163
+ return false;
164
+ }
165
+ const xSquared = mod(
166
+ numerator * modPow(denominator, ED25519_P - 2n, ED25519_P),
167
+ ED25519_P
168
+ );
169
+ return xSquared === 0n || modPow(xSquared, (ED25519_P - 1n) / 2n, ED25519_P) === 1n;
170
+ }
171
+ function littleEndianToBigInt(bytes) {
172
+ let value = 0n;
173
+ for (let index = bytes.length - 1; index >= 0; index -= 1) {
174
+ value = (value << 8n) + BigInt(bytes[index]);
175
+ }
176
+ return value;
177
+ }
178
+ function mod(value, modulus) {
179
+ const result = value % modulus;
180
+ return result >= 0n ? result : result + modulus;
181
+ }
182
+ function modPow(base, exponent, modulus) {
183
+ let result = 1n;
184
+ let nextBase = mod(base, modulus);
185
+ let nextExponent = exponent;
186
+ while (nextExponent > 0n) {
187
+ if ((nextExponent & 1n) === 1n) {
188
+ result = mod(result * nextBase, modulus);
189
+ }
190
+ nextBase = mod(nextBase * nextBase, modulus);
191
+ nextExponent >>= 1n;
192
+ }
193
+ return result;
194
+ }
195
+
196
+ // ../../src/client/transaction-intent-validator.ts
197
+ var COMPUTE_BUDGET_PROGRAM_ID = "ComputeBudget111111111111111111111111111111";
198
+ var SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
199
+ var ASSOCIATED_TOKEN_PROGRAM_ID2 = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
200
+ var MEMO_PROGRAM_ID = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
201
+ var KVAULT_PROGRAM_ID = "KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd";
202
+ var KAMINO_FARMS_PROGRAM_ID = "FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr";
203
+ var KVAULT_WITHDRAW_DISCRIMINATOR = Uint8Array.from([
204
+ 183,
205
+ 18,
206
+ 70,
207
+ 156,
208
+ 148,
209
+ 109,
210
+ 161,
211
+ 34
212
+ ]);
213
+ var KVAULT_WITHDRAW_FROM_AVAILABLE_DISCRIMINATOR = Uint8Array.from([
214
+ 19,
215
+ 131,
216
+ 112,
217
+ 155,
218
+ 170,
219
+ 220,
220
+ 34,
221
+ 57
222
+ ]);
223
+ var KVAULT_DEPOSIT_DISCRIMINATOR = Uint8Array.from([
224
+ 242,
225
+ 35,
226
+ 198,
227
+ 137,
228
+ 82,
229
+ 225,
230
+ 242,
231
+ 182
232
+ ]);
233
+ var U64_MAX = 18446744073709551615n;
234
+ var MAX_TEMP_ACCOUNT_LAMPORTS = 10000000n;
235
+ var DEFAULT_MAX_COMPUTE_UNIT_LIMIT = 14e5;
236
+ var DEFAULT_MAX_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS = 100000n;
237
+ var IntentValidationError = class extends Error {
238
+ reason;
239
+ constructor(reason, message) {
240
+ super(message);
241
+ this.name = "IntentValidationError";
242
+ this.reason = reason;
243
+ }
244
+ };
245
+ function reject(reason, message) {
246
+ throw new IntentValidationError(reason, message);
247
+ }
248
+ function decodeIntentTransaction(params) {
249
+ const wire = Buffer.from(params.serializedTransaction, "base64");
250
+ const signatureCount = readShortVec(wire, 0);
251
+ if (signatureCount === null) {
252
+ reject("invalid_transaction_encoding", "Cannot parse signature count");
253
+ }
254
+ const messageOffset = signatureCount.nextOffset + signatureCount.value * 64;
255
+ if (messageOffset >= wire.length) {
256
+ reject("invalid_transaction_encoding", "Transaction has no message bytes");
257
+ }
258
+ const messageBytes = wire.subarray(messageOffset);
259
+ const compiled = getCompiledTransactionMessageDecoder().decode(messageBytes);
260
+ if (compiled.version !== 0) {
261
+ reject("unsupported_transaction_version", "Only v0 transactions are supported");
262
+ }
263
+ const staticAccounts = compiled.staticAccounts.map(String);
264
+ const loadedWritable = [];
265
+ const loadedReadonly = [];
266
+ const lookups = compiled.addressTableLookups ?? [];
267
+ for (const rawLookup of lookups) {
268
+ const lookup = rawLookup;
269
+ const table = params.lookupTables?.[String(lookup.lookupTableAddress)];
270
+ if (table === void 0) {
271
+ reject(
272
+ "lookup_table_unresolved",
273
+ `Transaction references unknown lookup table ${lookup.lookupTableAddress}`
274
+ );
275
+ }
276
+ const writableIndexes = lookup.writableIndexes ?? lookup.writableIndices ?? [];
277
+ const readonlyIndexes = lookup.readonlyIndexes ?? lookup.readableIndices ?? [];
278
+ for (const index of writableIndexes) {
279
+ const resolved = table[index];
280
+ if (resolved === void 0) {
281
+ reject("lookup_table_unresolved", "Lookup table index out of range");
282
+ }
283
+ loadedWritable.push(String(resolved));
284
+ }
285
+ for (const index of readonlyIndexes) {
286
+ const resolved = table[index];
287
+ if (resolved === void 0) {
288
+ reject("lookup_table_unresolved", "Lookup table index out of range");
289
+ }
290
+ loadedReadonly.push(String(resolved));
291
+ }
292
+ }
293
+ const orderedAccounts = [...staticAccounts, ...loadedWritable, ...loadedReadonly];
294
+ const instructions = compiled.instructions.map(
295
+ (instruction) => {
296
+ const programAddress = orderedAccounts[instruction.programAddressIndex];
297
+ if (programAddress === void 0) {
298
+ reject("invalid_transaction_encoding", "Program index out of range");
299
+ }
300
+ const accounts = (instruction.accountIndices ?? []).map((index) => {
301
+ const account = orderedAccounts[index];
302
+ if (account === void 0) {
303
+ reject("invalid_transaction_encoding", "Account index out of range");
304
+ }
305
+ return account;
306
+ });
307
+ return {
308
+ programAddress,
309
+ accounts,
310
+ data: instruction.data === void 0 ? new Uint8Array() : Uint8Array.from(instruction.data)
311
+ };
312
+ }
313
+ );
314
+ const feePayer = staticAccounts[0];
315
+ if (feePayer === void 0) {
316
+ reject("invalid_transaction_encoding", "Transaction has no fee payer");
317
+ }
318
+ return {
319
+ feePayer,
320
+ requiredSigners: staticAccounts.slice(0, compiled.header.numSignerAccounts),
321
+ instructions,
322
+ messageHash: sha256TaggedHex(Buffer.from(messageBytes))
323
+ };
324
+ }
325
+ function validatePaymentIntentTransaction(params) {
326
+ const { intent } = params;
327
+ const now = params.nowMs ?? Date.now();
328
+ const policy = resolveIntentValidationPolicy(params.policy);
329
+ if (new Date(intent.expiresAt).getTime() <= now) {
330
+ reject("expired", "Payment intent has expired");
331
+ }
332
+ if (intent.scheme !== PAYMENT_SCHEME) {
333
+ reject("scheme_mismatch", `scheme must be ${PAYMENT_SCHEME}`);
334
+ }
335
+ if (intent.network !== SOLANA_MAINNET_NETWORK) {
336
+ reject("network_mismatch", "Unsupported network");
337
+ }
338
+ if (intent.vault !== SUBLY_VAULT.address) {
339
+ reject("vault_mismatch", "Unsupported vault");
340
+ }
341
+ if (intent.shareMint !== SUBLY_VAULT.shareMint) {
342
+ reject("share_mint_mismatch", "Unsupported share mint");
343
+ }
344
+ if (intent.asset !== SUBLY_VAULT.usdcMint) {
345
+ reject("asset_mismatch", "Only USDC payments are supported");
346
+ }
347
+ if (intent.memo !== intent.paymentId) {
348
+ reject("memo_mismatch", "Memo must equal the paymentId");
349
+ }
350
+ const expectedBinding = computeRequestBindingHash({
351
+ sellerRequestId: intent.sellerRequestId,
352
+ httpMethod: intent.httpMethod,
353
+ canonicalResourceUrl: intent.canonicalResourceUrl,
354
+ requestBodyHash: intent.requestBodyHash,
355
+ seller: intent.seller,
356
+ asset: intent.asset,
357
+ amountRawUsdc: intent.amountRawUsdc,
358
+ payTo: intent.payTo,
359
+ sellerUsdcAta: intent.sellerUsdcAta
360
+ });
361
+ if (expectedBinding !== intent.requestBindingHash) {
362
+ reject(
363
+ "request_binding_mismatch",
364
+ "requestBindingHash does not match the request fields"
365
+ );
366
+ }
367
+ const expectedSellerAta = deriveAssociatedTokenAddress({
368
+ owner: intent.payTo,
369
+ mint: intent.asset
370
+ });
371
+ if (expectedSellerAta !== intent.sellerUsdcAta) {
372
+ reject(
373
+ "seller_ata_mismatch",
374
+ "sellerUsdcAta must be the associated USDC account for payTo"
375
+ );
376
+ }
377
+ const expectedDustAta = deriveAssociatedTokenAddress({
378
+ owner: intent.wallet,
379
+ mint: intent.asset
380
+ });
381
+ if (expectedDustAta !== intent.dustRecipientUsdcAta) {
382
+ reject(
383
+ "dust_recipient_mismatch",
384
+ "dustRecipientUsdcAta must be the agent wallet's USDC ATA"
385
+ );
386
+ }
387
+ const decoded = decodeIntentTransaction({
388
+ serializedTransaction: params.serializedTransaction,
389
+ ...params.lookupTables === void 0 ? {} : { lookupTables: params.lookupTables }
390
+ });
391
+ if (decoded.messageHash !== intent.preparedMessageHash) {
392
+ reject("message_hash_mismatch", "Prepared message hash mismatch");
393
+ }
394
+ if (decoded.feePayer !== intent.feePayer) {
395
+ reject("fee_payer_mismatch", "Transaction fee payer is not the Subly sponsor");
396
+ }
397
+ const expectedSigners = /* @__PURE__ */ new Set([
398
+ intent.feePayer,
399
+ intent.wallet,
400
+ intent.temporarySettlementTokenAccount
401
+ ]);
402
+ if (decoded.requiredSigners.length !== expectedSigners.size || !decoded.requiredSigners.every((signer2) => expectedSigners.has(signer2))) {
403
+ reject(
404
+ "unexpected_signers",
405
+ "Transaction signers must be exactly the sponsor, the agent wallet, and the temporary settlement account"
406
+ );
407
+ }
408
+ const ixs = [...decoded.instructions];
409
+ expectComputeBudgetPair(ixs, policy);
410
+ expectCreateTemporaryAccount(ixs, intent, policy);
411
+ expectInitializeTemporaryAccount(ixs, intent);
412
+ consumeFarmInstructions(ixs, intent.wallet);
413
+ expectKvaultWithdraw(ixs, {
414
+ wallet: intent.wallet,
415
+ vault: intent.vault,
416
+ shareMint: intent.shareMint,
417
+ asset: intent.asset,
418
+ userTokenAccount: intent.temporarySettlementTokenAccount,
419
+ maxSharesToRedeemRaw: BigInt(intent.maxSharesToRedeemRaw),
420
+ allowFullExit: false
421
+ });
422
+ expectTransferChecked(ixs, {
423
+ source: intent.temporarySettlementTokenAccount,
424
+ mint: intent.asset,
425
+ destination: intent.sellerUsdcAta,
426
+ authority: intent.wallet,
427
+ amount: BigInt(intent.amountRawUsdc),
428
+ label: "seller transfer"
429
+ });
430
+ if (ixs[0] !== void 0 && ixs[0].programAddress === SPL_TOKEN_PROGRAM_ID && ixs[0].data[0] === 12) {
431
+ expectTransferChecked(ixs, {
432
+ source: intent.temporarySettlementTokenAccount,
433
+ mint: intent.asset,
434
+ destination: intent.dustRecipientUsdcAta,
435
+ authority: intent.wallet,
436
+ amount: null,
437
+ label: "dust sweep"
438
+ });
439
+ }
440
+ expectCloseAccount(ixs, {
441
+ account: intent.temporarySettlementTokenAccount,
442
+ destination: intent.feePayer,
443
+ owner: intent.wallet
444
+ });
445
+ expectMemo(ixs, intent.memo);
446
+ if (ixs.length > 0) {
447
+ reject(
448
+ "unexpected_instruction",
449
+ `Transaction contains ${ixs.length} unexpected trailing instruction(s)`
450
+ );
451
+ }
452
+ }
453
+ function validateDepositIntentTransaction(params) {
454
+ const { intent } = params;
455
+ const now = params.nowMs ?? Date.now();
456
+ const policy = resolveIntentValidationPolicy(params.policy);
457
+ if (new Date(intent.expiresAt).getTime() <= now) {
458
+ reject("expired", "Deposit intent has expired");
459
+ }
460
+ assertVaultIntentTargets(intent);
461
+ const decoded = decodeIntentTransaction({
462
+ serializedTransaction: params.serializedTransaction,
463
+ ...params.lookupTables === void 0 ? {} : { lookupTables: params.lookupTables }
464
+ });
465
+ if (decoded.messageHash !== intent.preparedMessageHash) {
466
+ reject("message_hash_mismatch", "Prepared message hash mismatch");
467
+ }
468
+ if (decoded.feePayer !== intent.feePayer) {
469
+ reject("fee_payer_mismatch", "Transaction fee payer is not the Subly sponsor");
470
+ }
471
+ let sawDeposit = false;
472
+ for (const ix of decoded.instructions) {
473
+ switch (ix.programAddress) {
474
+ case COMPUTE_BUDGET_PROGRAM_ID:
475
+ validateComputeBudgetInstruction(ix, policy);
476
+ break;
477
+ case ASSOCIATED_TOKEN_PROGRAM_ID2:
478
+ expectAtaCreateForOwner(ix, intent.wallet);
479
+ break;
480
+ case MEMO_PROGRAM_ID:
481
+ break;
482
+ case KVAULT_PROGRAM_ID: {
483
+ if (!bytesStartWith(ix.data, KVAULT_DEPOSIT_DISCRIMINATOR)) {
484
+ reject("unexpected_instruction", "Unexpected KVault instruction in deposit");
485
+ }
486
+ const maxAmount = readU64LE(ix.data, 8);
487
+ if (maxAmount !== BigInt(intent.amountRawUsdc)) {
488
+ reject("amount_mismatch", "Deposit amount does not match the intent");
489
+ }
490
+ if (ix.accounts[0] !== intent.wallet) {
491
+ reject("wallet_mismatch", "Deposit user is not the agent wallet");
492
+ }
493
+ if (ix.accounts[1] !== intent.vault) {
494
+ reject("vault_mismatch", "Deposit vault mismatch");
495
+ }
496
+ if (ix.accounts[3] !== intent.asset) {
497
+ reject("asset_mismatch", "Deposit token mint mismatch");
498
+ }
499
+ if (ix.accounts[5] !== intent.shareMint) {
500
+ reject("share_mint_mismatch", "Deposit share mint mismatch");
501
+ }
502
+ const expectedSourceAta = deriveAssociatedTokenAddress({
503
+ owner: intent.wallet,
504
+ mint: intent.asset
505
+ });
506
+ if (ix.accounts[6] !== expectedSourceAta) {
507
+ reject(
508
+ "source_ata_mismatch",
509
+ "Deposit source must be the agent wallet's USDC ATA"
510
+ );
511
+ }
512
+ sawDeposit = true;
513
+ break;
514
+ }
515
+ default:
516
+ reject(
517
+ "unexpected_instruction",
518
+ `Unexpected program ${ix.programAddress} in deposit transaction`
519
+ );
520
+ }
521
+ }
522
+ if (!sawDeposit) {
523
+ reject("missing_instruction", "Deposit transaction has no KVault deposit");
524
+ }
525
+ }
526
+ function validateWithdrawalIntentTransaction(params) {
527
+ const { intent } = params;
528
+ const now = params.nowMs ?? Date.now();
529
+ const policy = resolveIntentValidationPolicy(params.policy);
530
+ if (new Date(intent.expiresAt).getTime() <= now) {
531
+ reject("expired", "Withdrawal intent has expired");
532
+ }
533
+ assertVaultIntentTargets(intent);
534
+ const expectedDestination = deriveAssociatedTokenAddress({
535
+ owner: intent.wallet,
536
+ mint: intent.asset
537
+ });
538
+ if (expectedDestination !== intent.destinationUsdcAta) {
539
+ reject(
540
+ "destination_mismatch",
541
+ "Withdrawal destination must be the agent wallet's USDC ATA"
542
+ );
543
+ }
544
+ const decoded = decodeIntentTransaction({
545
+ serializedTransaction: params.serializedTransaction,
546
+ ...params.lookupTables === void 0 ? {} : { lookupTables: params.lookupTables }
547
+ });
548
+ if (decoded.messageHash !== intent.preparedMessageHash) {
549
+ reject("message_hash_mismatch", "Prepared message hash mismatch");
550
+ }
551
+ if (decoded.feePayer !== intent.feePayer) {
552
+ reject("fee_payer_mismatch", "Transaction fee payer is not the Subly sponsor");
553
+ }
554
+ let sawWithdraw = false;
555
+ for (const ix of decoded.instructions) {
556
+ switch (ix.programAddress) {
557
+ case COMPUTE_BUDGET_PROGRAM_ID:
558
+ validateComputeBudgetInstruction(ix, policy);
559
+ break;
560
+ case MEMO_PROGRAM_ID:
561
+ case KAMINO_FARMS_PROGRAM_ID:
562
+ break;
563
+ case ASSOCIATED_TOKEN_PROGRAM_ID2:
564
+ expectAtaCreateForOwner(ix, intent.wallet);
565
+ break;
566
+ case SPL_TOKEN_PROGRAM_ID: {
567
+ if (ix.data[0] !== 9) {
568
+ reject(
569
+ "unexpected_instruction",
570
+ "Only CloseAccount token instructions are allowed in withdrawals"
571
+ );
572
+ }
573
+ if (ix.accounts[1] !== intent.wallet || ix.accounts[2] !== intent.wallet) {
574
+ reject(
575
+ "unexpected_instruction",
576
+ "Withdrawal CloseAccount must pay out to the agent wallet"
577
+ );
578
+ }
579
+ break;
580
+ }
581
+ case KVAULT_PROGRAM_ID: {
582
+ validateKvaultWithdrawInstruction(ix, {
583
+ wallet: intent.wallet,
584
+ vault: intent.vault,
585
+ shareMint: intent.shareMint,
586
+ asset: intent.asset,
587
+ userTokenAccount: intent.destinationUsdcAta,
588
+ maxSharesToRedeemRaw: BigInt(intent.maxSharesToRedeemRaw),
589
+ allowFullExit: intent.allowFullExit
590
+ });
591
+ sawWithdraw = true;
592
+ break;
593
+ }
594
+ default:
595
+ reject(
596
+ "unexpected_instruction",
597
+ `Unexpected program ${ix.programAddress} in withdrawal transaction`
598
+ );
599
+ }
600
+ }
601
+ if (!sawWithdraw) {
602
+ reject("missing_instruction", "Withdrawal transaction has no KVault withdraw");
603
+ }
604
+ }
605
+ function assertVaultIntentTargets(intent) {
606
+ if (intent.vault !== SUBLY_VAULT.address) {
607
+ reject("vault_mismatch", "Unsupported vault");
608
+ }
609
+ if (intent.shareMint !== SUBLY_VAULT.shareMint) {
610
+ reject("share_mint_mismatch", "Unsupported share mint");
611
+ }
612
+ if (intent.asset !== SUBLY_VAULT.usdcMint) {
613
+ reject("asset_mismatch", "Only USDC is supported");
614
+ }
615
+ }
616
+ function resolveIntentValidationPolicy(policy) {
617
+ const resolved = {
618
+ maxComputeUnitLimit: policy?.maxComputeUnitLimit ?? DEFAULT_MAX_COMPUTE_UNIT_LIMIT,
619
+ maxComputeUnitPriceMicroLamports: policy?.maxComputeUnitPriceMicroLamports ?? DEFAULT_MAX_COMPUTE_UNIT_PRICE_MICRO_LAMPORTS,
620
+ maxTemporaryAccountLamports: policy?.maxTemporaryAccountLamports ?? MAX_TEMP_ACCOUNT_LAMPORTS
621
+ };
622
+ if (!Number.isSafeInteger(resolved.maxComputeUnitLimit) || resolved.maxComputeUnitLimit <= 0) {
623
+ reject("invalid_policy", "maxComputeUnitLimit must be a positive safe integer");
624
+ }
625
+ if (resolved.maxComputeUnitPriceMicroLamports < 0n) {
626
+ reject(
627
+ "invalid_policy",
628
+ "maxComputeUnitPriceMicroLamports must be non-negative"
629
+ );
630
+ }
631
+ if (resolved.maxTemporaryAccountLamports <= 0n) {
632
+ reject("invalid_policy", "maxTemporaryAccountLamports must be positive");
633
+ }
634
+ return resolved;
635
+ }
636
+ function expectComputeBudgetPair(ixs, policy) {
637
+ for (const discriminator of [2, 3]) {
638
+ const ix = ixs.shift();
639
+ if (ix === void 0 || ix.programAddress !== COMPUTE_BUDGET_PROGRAM_ID || ix.data[0] !== discriminator) {
640
+ reject(
641
+ "compute_budget_mismatch",
642
+ "Transaction must start with ComputeBudget limit and price instructions"
643
+ );
644
+ }
645
+ validateComputeBudgetInstruction(ix, policy);
646
+ }
647
+ }
648
+ function validateComputeBudgetInstruction(ix, policy) {
649
+ switch (ix.data[0]) {
650
+ case 2: {
651
+ const units = readU32LE(ix.data, 1);
652
+ if (units <= 0 || units > policy.maxComputeUnitLimit) {
653
+ reject(
654
+ "compute_budget_mismatch",
655
+ `Compute unit limit ${units} exceeds policy maximum ${policy.maxComputeUnitLimit}`
656
+ );
657
+ }
658
+ break;
659
+ }
660
+ case 3: {
661
+ const microLamports = readU64LE(ix.data, 1);
662
+ if (microLamports > policy.maxComputeUnitPriceMicroLamports) {
663
+ reject(
664
+ "compute_budget_mismatch",
665
+ `Compute unit price ${microLamports} exceeds policy maximum ${policy.maxComputeUnitPriceMicroLamports}`
666
+ );
667
+ }
668
+ break;
669
+ }
670
+ default:
671
+ reject("compute_budget_mismatch", "Unexpected ComputeBudget instruction");
672
+ }
673
+ }
674
+ function expectCreateTemporaryAccount(ixs, intent, policy) {
675
+ const ix = ixs.shift();
676
+ if (ix === void 0 || ix.programAddress !== SYSTEM_PROGRAM_ID) {
677
+ reject("temp_account_mismatch", "Expected System createAccount instruction");
678
+ }
679
+ if (ix.data.length < 52 || readU32LE(ix.data, 0) !== 0) {
680
+ reject("temp_account_mismatch", "Expected createAccount discriminator");
681
+ }
682
+ const lamports = readU64LE(ix.data, 4);
683
+ const space = readU64LE(ix.data, 12);
684
+ const owner = bs583.encode(ix.data.subarray(20, 52));
685
+ if (space !== 165n) {
686
+ reject("temp_account_mismatch", "Temporary account space must be 165 bytes");
687
+ }
688
+ if (owner !== SPL_TOKEN_PROGRAM_ID) {
689
+ reject("temp_account_mismatch", "Temporary account owner must be the token program");
690
+ }
691
+ if (lamports > policy.maxTemporaryAccountLamports) {
692
+ reject("temp_account_mismatch", "Temporary account rent exceeds the cap");
693
+ }
694
+ if (ix.accounts[0] !== intent.feePayer) {
695
+ reject("temp_account_mismatch", "Temporary account must be funded by the sponsor");
696
+ }
697
+ if (ix.accounts[1] !== intent.temporarySettlementTokenAccount) {
698
+ reject("temp_account_mismatch", "createAccount target is not the temporary account");
699
+ }
700
+ }
701
+ function expectInitializeTemporaryAccount(ixs, intent) {
702
+ const ix = ixs.shift();
703
+ if (ix === void 0 || ix.programAddress !== SPL_TOKEN_PROGRAM_ID || ix.data[0] !== 18) {
704
+ reject("temp_account_mismatch", "Expected InitializeAccount3 instruction");
705
+ }
706
+ const owner = bs583.encode(ix.data.subarray(1, 33));
707
+ if (owner !== intent.wallet) {
708
+ reject(
709
+ "temp_account_mismatch",
710
+ "Temporary account token authority must be the agent wallet"
711
+ );
712
+ }
713
+ if (ix.accounts[0] !== intent.temporarySettlementTokenAccount) {
714
+ reject("temp_account_mismatch", "InitializeAccount3 target mismatch");
715
+ }
716
+ if (ix.accounts[1] !== intent.asset) {
717
+ reject("temp_account_mismatch", "Temporary account mint must be USDC");
718
+ }
719
+ }
720
+ function consumeFarmInstructions(ixs, wallet) {
721
+ while (ixs[0] !== void 0 && ixs[0].programAddress === KAMINO_FARMS_PROGRAM_ID) {
722
+ const ix = ixs.shift();
723
+ if (!ix.accounts.includes(wallet)) {
724
+ reject(
725
+ "farm_instruction_mismatch",
726
+ "Farm unstake instruction does not reference the agent wallet"
727
+ );
728
+ }
729
+ }
730
+ }
731
+ function expectKvaultWithdraw(ixs, expectation) {
732
+ const ix = ixs.shift();
733
+ if (ix === void 0 || ix.programAddress !== KVAULT_PROGRAM_ID) {
734
+ reject("withdraw_mismatch", "Expected KVault withdraw instruction");
735
+ }
736
+ validateKvaultWithdrawInstruction(ix, expectation);
737
+ }
738
+ function validateKvaultWithdrawInstruction(ix, expectation) {
739
+ const isWithdraw = bytesStartWith(ix.data, KVAULT_WITHDRAW_DISCRIMINATOR);
740
+ const isWithdrawFromAvailable = bytesStartWith(
741
+ ix.data,
742
+ KVAULT_WITHDRAW_FROM_AVAILABLE_DISCRIMINATOR
743
+ );
744
+ if (!isWithdraw && !isWithdrawFromAvailable) {
745
+ reject("withdraw_mismatch", "Unexpected KVault instruction");
746
+ }
747
+ const sharesAmount = readU64LE(ix.data, 8);
748
+ const fullExit = sharesAmount === U64_MAX;
749
+ if (fullExit && !expectation.allowFullExit) {
750
+ reject("withdraw_mismatch", "Full-exit share burn is not allowed for this intent");
751
+ }
752
+ if (!fullExit && sharesAmount > expectation.maxSharesToRedeemRaw) {
753
+ reject(
754
+ "shares_exceed_max",
755
+ `Withdraw burns ${sharesAmount} shares which exceeds the approved maximum ${expectation.maxSharesToRedeemRaw}`
756
+ );
757
+ }
758
+ if (ix.accounts[0] !== expectation.wallet) {
759
+ reject("withdraw_mismatch", "Withdraw user is not the agent wallet");
760
+ }
761
+ if (ix.accounts[1] !== expectation.vault) {
762
+ reject("withdraw_mismatch", "Withdraw vault mismatch");
763
+ }
764
+ if (ix.accounts[5] !== expectation.userTokenAccount) {
765
+ reject(
766
+ "withdraw_mismatch",
767
+ "Withdraw token destination is not the approved account"
768
+ );
769
+ }
770
+ if (ix.accounts[6] !== expectation.asset) {
771
+ reject("withdraw_mismatch", "Withdraw token mint mismatch");
772
+ }
773
+ const expectedSharesAta = deriveAssociatedTokenAddress({
774
+ owner: expectation.wallet,
775
+ mint: expectation.shareMint
776
+ });
777
+ if (ix.accounts[7] !== expectedSharesAta) {
778
+ reject("withdraw_mismatch", "Withdraw share source must be the agent share ATA");
779
+ }
780
+ if (ix.accounts[8] !== expectation.shareMint) {
781
+ reject("withdraw_mismatch", "Withdraw share mint mismatch");
782
+ }
783
+ }
784
+ function expectTransferChecked(ixs, expectation) {
785
+ const ix = ixs.shift();
786
+ if (ix === void 0 || ix.programAddress !== SPL_TOKEN_PROGRAM_ID || ix.data[0] !== 12) {
787
+ reject("transfer_mismatch", `Expected TransferChecked for ${expectation.label}`);
788
+ }
789
+ const amount = readU64LE(ix.data, 1);
790
+ const decimals = ix.data[9];
791
+ if (expectation.amount !== null && amount !== expectation.amount) {
792
+ reject(
793
+ "amount_mismatch",
794
+ `${expectation.label} amount ${amount} does not match ${expectation.amount}`
795
+ );
796
+ }
797
+ if (decimals !== USDC_DECIMALS) {
798
+ reject("transfer_mismatch", `${expectation.label} has unexpected decimals`);
799
+ }
800
+ if (ix.accounts[0] !== expectation.source) {
801
+ reject("transfer_mismatch", `${expectation.label} source mismatch`);
802
+ }
803
+ if (ix.accounts[1] !== expectation.mint) {
804
+ reject("transfer_mismatch", `${expectation.label} mint mismatch`);
805
+ }
806
+ if (ix.accounts[2] !== expectation.destination) {
807
+ reject("transfer_mismatch", `${expectation.label} destination mismatch`);
808
+ }
809
+ if (ix.accounts[3] !== expectation.authority) {
810
+ reject("transfer_mismatch", `${expectation.label} authority mismatch`);
811
+ }
812
+ }
813
+ function expectCloseAccount(ixs, expectation) {
814
+ const ix = ixs.shift();
815
+ if (ix === void 0 || ix.programAddress !== SPL_TOKEN_PROGRAM_ID || ix.data[0] !== 9) {
816
+ reject("close_mismatch", "Expected CloseAccount instruction");
817
+ }
818
+ if (ix.accounts[0] !== expectation.account) {
819
+ reject("close_mismatch", "CloseAccount target is not the temporary account");
820
+ }
821
+ if (ix.accounts[1] !== expectation.destination) {
822
+ reject("close_mismatch", "CloseAccount rent destination must be the sponsor");
823
+ }
824
+ if (ix.accounts[2] !== expectation.owner) {
825
+ reject("close_mismatch", "CloseAccount authority must be the agent wallet");
826
+ }
827
+ }
828
+ function expectMemo(ixs, memo) {
829
+ const ix = ixs.shift();
830
+ if (ix === void 0 || ix.programAddress !== MEMO_PROGRAM_ID) {
831
+ reject("memo_mismatch", "Expected Memo instruction");
832
+ }
833
+ if (Buffer.from(ix.data).toString("utf8") !== memo) {
834
+ reject("memo_mismatch", "Memo content does not match the paymentId");
835
+ }
836
+ }
837
+ function expectAtaCreateForOwner(ix, owner) {
838
+ if (ix.accounts[2] !== owner) {
839
+ reject(
840
+ "unexpected_instruction",
841
+ "Associated token account creation for a foreign owner"
842
+ );
843
+ }
844
+ }
845
+ function bytesStartWith(data, prefix) {
846
+ if (data.length < prefix.length) {
847
+ return false;
848
+ }
849
+ return prefix.every((byte, index) => data[index] === byte);
850
+ }
851
+ function readU64LE(data, offset) {
852
+ if (data.length < offset + 8) {
853
+ reject("invalid_transaction_encoding", "Instruction data too short for u64");
854
+ }
855
+ return Buffer.from(data.subarray(offset, offset + 8)).readBigUInt64LE(0);
856
+ }
857
+ function readU32LE(data, offset) {
858
+ if (data.length < offset + 4) {
859
+ reject("invalid_transaction_encoding", "Instruction data too short for u32");
860
+ }
861
+ return Buffer.from(data.subarray(offset, offset + 4)).readUInt32LE(0);
862
+ }
863
+ function readShortVec(bytes, startOffset) {
864
+ let value = 0;
865
+ let shift = 0;
866
+ let offset = startOffset;
867
+ while (offset < bytes.length) {
868
+ const byte = bytes[offset];
869
+ value |= (byte & 127) << shift;
870
+ offset += 1;
871
+ if ((byte & 128) === 0) {
872
+ return { value, nextOffset: offset };
873
+ }
874
+ shift += 7;
875
+ if (shift > 28) {
876
+ return null;
877
+ }
878
+ }
879
+ return null;
880
+ }
881
+
882
+ // ../../src/client/agent-wallet-signer.ts
883
+ var LocalKeypairAgentWalletSigner = class {
884
+ validationMode = "structured_intent_transaction";
885
+ keyPairSigner;
886
+ validationPolicy;
887
+ constructor(keyPairSigner2, validationPolicy) {
888
+ this.keyPairSigner = keyPairSigner2;
889
+ this.validationPolicy = validationPolicy;
890
+ }
891
+ get walletAddress() {
892
+ return this.keyPairSigner.address;
893
+ }
894
+ async signPayment(params) {
895
+ this.assertIntentWallet(params.intent.wallet);
896
+ validatePaymentIntentTransaction({
897
+ ...params,
898
+ ...this.validationPolicy === void 0 ? {} : { policy: this.validationPolicy }
899
+ });
900
+ return this.sign(params.serializedTransaction);
901
+ }
902
+ async signDeposit(params) {
903
+ this.assertIntentWallet(params.intent.wallet);
904
+ validateDepositIntentTransaction({
905
+ ...params,
906
+ ...this.validationPolicy === void 0 ? {} : { policy: this.validationPolicy }
907
+ });
908
+ return this.sign(params.serializedTransaction);
909
+ }
910
+ async signWithdrawal(params) {
911
+ this.assertIntentWallet(params.intent.wallet);
912
+ validateWithdrawalIntentTransaction({
913
+ ...params,
914
+ ...this.validationPolicy === void 0 ? {} : { policy: this.validationPolicy }
915
+ });
916
+ return this.sign(params.serializedTransaction);
917
+ }
918
+ assertIntentWallet(wallet) {
919
+ if (wallet !== this.keyPairSigner.address) {
920
+ throw new IntentValidationError(
921
+ "wallet_mismatch",
922
+ "Intent wallet does not match this signer's wallet"
923
+ );
924
+ }
925
+ }
926
+ async signApiMessage(message) {
927
+ const signature = await signBytes(
928
+ this.keyPairSigner.keyPair.privateKey,
929
+ message
930
+ );
931
+ return bs584.encode(signature);
932
+ }
933
+ async sign(serializedTransaction) {
934
+ const { serializedBase64, transaction } = await addSignaturesToSerializedTransaction({
935
+ serializedBase64: serializedTransaction,
936
+ signers: [this.keyPairSigner.keyPair]
937
+ });
938
+ const agentSignature = signatureBase58ForSigner(
939
+ transaction,
940
+ this.keyPairSigner.address
941
+ );
942
+ if (agentSignature === null) {
943
+ throw new IntentValidationError(
944
+ "signing_failed",
945
+ "Agent signature was not produced"
946
+ );
947
+ }
948
+ return { serializedTransaction: serializedBase64, agentSignature };
949
+ }
950
+ };
951
+
952
+ // ../../src/client/lookup-tables.ts
953
+ import { fetchAllMaybeAddressLookupTable } from "@solana-program/address-lookup-table";
954
+ import { address, getCompiledTransactionMessageDecoder as getCompiledTransactionMessageDecoder2 } from "@solana/kit";
955
+ function lookupTableAddressesForTransaction(serializedTransaction) {
956
+ const wire = Buffer.from(serializedTransaction, "base64");
957
+ let offset = 0;
958
+ let signatureCount = 0;
959
+ let shift = 0;
960
+ while (offset < wire.length) {
961
+ const byte = wire[offset];
962
+ signatureCount |= (byte & 127) << shift;
963
+ offset += 1;
964
+ if ((byte & 128) === 0) {
965
+ break;
966
+ }
967
+ shift += 7;
968
+ }
969
+ const messageBytes = wire.subarray(offset + signatureCount * 64);
970
+ const compiled = getCompiledTransactionMessageDecoder2().decode(messageBytes);
971
+ const lookups = compiled.addressTableLookups ?? [];
972
+ return lookups.map((lookup) => String(lookup.lookupTableAddress));
973
+ }
974
+ async function fetchLookupTablesForTransaction(rpc2, serializedTransaction) {
975
+ const addresses = lookupTableAddressesForTransaction(serializedTransaction);
976
+ if (addresses.length === 0) {
977
+ return {};
978
+ }
979
+ const tables = await fetchAllMaybeAddressLookupTable(
980
+ rpc2,
981
+ addresses.map((value) => address(value))
982
+ );
983
+ const result = {};
984
+ for (const table of tables) {
985
+ if (table.exists) {
986
+ result[table.address] = table.data.addresses.map(String);
987
+ }
988
+ }
989
+ return result;
990
+ }
991
+
992
+ // ../../src/api/wallet-auth.ts
993
+ import { createHash as createHash3 } from "node:crypto";
994
+ import bs585 from "bs58";
995
+ import nacl from "tweetnacl";
996
+ var WALLET_AUTH_WALLET_HEADER = "x-subly-wallet";
997
+ var WALLET_AUTH_SIGNED_AT_HEADER = "x-subly-signed-at";
998
+ var WALLET_AUTH_SIGNATURE_HEADER = "x-subly-signature";
999
+ function sha256Hex(data) {
1000
+ return createHash3("sha256").update(data, "utf8").digest("hex");
1001
+ }
1002
+ function walletAuthMessage(params) {
1003
+ return new TextEncoder().encode(
1004
+ `subly-api:${params.method.toUpperCase()}:${params.path}:${sha256Hex(
1005
+ params.rawBody
1006
+ )}:${params.signedAtMs}`
1007
+ );
1008
+ }
1009
+
1010
+ // ../../src/client/wallet-auth-headers.ts
1011
+ async function walletAuthHeaders(params) {
1012
+ const signedAtMs = String(Date.now());
1013
+ const message = walletAuthMessage({
1014
+ method: params.method,
1015
+ path: new URL(params.url).pathname,
1016
+ rawBody: params.body ?? "",
1017
+ signedAtMs
1018
+ });
1019
+ return {
1020
+ [WALLET_AUTH_WALLET_HEADER]: params.signer.walletAddress,
1021
+ [WALLET_AUTH_SIGNED_AT_HEADER]: signedAtMs,
1022
+ [WALLET_AUTH_SIGNATURE_HEADER]: await params.signer.signApiMessage(message)
1023
+ };
1024
+ }
1025
+
1026
+ // ../../src/client/onboarding.ts
1027
+ var SELF_SERVE_POLICY_ID = "self-serve";
1028
+ var OnboardingError = class extends Error {
1029
+ constructor(step, message, detail = null) {
1030
+ super(message);
1031
+ this.step = step;
1032
+ this.detail = detail;
1033
+ this.name = "OnboardingError";
1034
+ }
1035
+ step;
1036
+ detail;
1037
+ };
1038
+ async function ensureWalletOnboarded(params) {
1039
+ const fetchImpl = params.fetchImpl ?? fetch;
1040
+ const baseUrl = params.facilitatorBaseUrl.replace(/\/$/, "");
1041
+ const post = async (step, path, body) => {
1042
+ const url2 = `${baseUrl}${path}`;
1043
+ const serialized = JSON.stringify(body);
1044
+ const response = await fetchImpl(url2, {
1045
+ method: "POST",
1046
+ headers: {
1047
+ ...await walletAuthHeaders({
1048
+ signer: params.signer,
1049
+ method: "POST",
1050
+ url: url2,
1051
+ body: serialized
1052
+ }),
1053
+ "content-type": "application/json"
1054
+ },
1055
+ body: serialized
1056
+ });
1057
+ if (response.status !== 200) {
1058
+ let detail = null;
1059
+ try {
1060
+ detail = await response.json();
1061
+ } catch {
1062
+ detail = null;
1063
+ }
1064
+ throw new OnboardingError(
1065
+ step,
1066
+ `wallet onboarding ${step} failed with ${response.status}`,
1067
+ detail
1068
+ );
1069
+ }
1070
+ };
1071
+ const wallet = params.signer.walletAddress;
1072
+ await post("register", "/v1/wallets/agent", {
1073
+ wallet,
1074
+ signingPolicyId: SELF_SERVE_POLICY_ID,
1075
+ signingMode: "non_interactive",
1076
+ signerValidationMode: params.signer.validationMode,
1077
+ signerProvider: "local-keypair",
1078
+ activateForPayments: true
1079
+ });
1080
+ await post("sync", `/v1/wallets/${wallet}/sync`, { source: "chain" });
1081
+ }
1082
+
1083
+ // ../../src/x402/headers.ts
1084
+ import { z } from "zod";
1085
+ var PAYMENT_REQUIRED_HEADER = "payment-required";
1086
+ var PAYMENT_SIGNATURE_HEADER = "payment-signature";
1087
+ var PAYMENT_RESPONSE_HEADER = "payment-response";
1088
+ var X402_VERSION = 2;
1089
+ var MAX_HEADER_JSON_BYTES = 16384;
1090
+ var X402HeaderError = class extends Error {
1091
+ reason;
1092
+ constructor(reason, message) {
1093
+ super(message);
1094
+ this.name = "X402HeaderError";
1095
+ this.reason = reason;
1096
+ }
1097
+ };
1098
+ var sublyPaymentRequirementsSchema = z.object({
1099
+ scheme: z.literal(PAYMENT_SCHEME),
1100
+ network: z.string().min(1),
1101
+ asset: z.string().min(32),
1102
+ /** Exact seller amount in raw USDC; the scheme settles exactly this. */
1103
+ amountRawUsdc: z.string().regex(/^[1-9]\d*$/),
1104
+ resource: z.string().url(),
1105
+ description: z.string().optional(),
1106
+ mimeType: z.string().optional(),
1107
+ payTo: z.string().min(32),
1108
+ maxTimeoutSeconds: z.number().int().positive(),
1109
+ extra: z.object({
1110
+ sellerRequestId: z.string().min(1),
1111
+ seller: z.string().min(32),
1112
+ sellerUsdcAta: z.string().min(32),
1113
+ vault: z.string().min(32),
1114
+ shareMint: z.string().min(32)
1115
+ })
1116
+ }).loose();
1117
+ var paymentRequiredSchema = z.object({
1118
+ x402Version: z.number().int(),
1119
+ accepts: z.array(z.unknown()),
1120
+ error: z.string().optional()
1121
+ }).loose();
1122
+ var sublyPaymentPayloadSchema = z.object({
1123
+ x402Version: z.number().int(),
1124
+ scheme: z.literal(PAYMENT_SCHEME),
1125
+ network: z.string().min(1),
1126
+ payload: z.object({
1127
+ paymentId: z.string().min(1),
1128
+ requestBindingHash: z.string().min(1),
1129
+ preparedMessageHash: z.string().min(1),
1130
+ serializedTransaction: z.string().min(1).max(4096),
1131
+ agentSignature: z.string().min(1).max(128),
1132
+ temporarySettlementSignature: z.string().min(1).max(128)
1133
+ })
1134
+ }).loose();
1135
+ function encodeX402Header(value) {
1136
+ const json = JSON.stringify(value);
1137
+ if (Buffer.byteLength(json, "utf8") > MAX_HEADER_JSON_BYTES) {
1138
+ throw new X402HeaderError(
1139
+ "header_too_large",
1140
+ `x402 header JSON exceeds ${MAX_HEADER_JSON_BYTES} bytes`
1141
+ );
1142
+ }
1143
+ return Buffer.from(json, "utf8").toString("base64");
1144
+ }
1145
+ function decodeX402Header(headerValue) {
1146
+ if (headerValue.length > Math.ceil(MAX_HEADER_JSON_BYTES * 4 / 3) + 4) {
1147
+ throw new X402HeaderError(
1148
+ "header_too_large",
1149
+ `x402 header exceeds ${MAX_HEADER_JSON_BYTES} encoded bytes`
1150
+ );
1151
+ }
1152
+ const json = Buffer.from(headerValue, "base64").toString("utf8");
1153
+ try {
1154
+ return JSON.parse(json);
1155
+ } catch {
1156
+ throw new X402HeaderError(
1157
+ "invalid_header_encoding",
1158
+ "x402 header is not base64-encoded JSON"
1159
+ );
1160
+ }
1161
+ }
1162
+ function decodePaymentRequiredHeader(headerValue) {
1163
+ const parsed = paymentRequiredSchema.safeParse(decodeX402Header(headerValue));
1164
+ if (!parsed.success) {
1165
+ throw new X402HeaderError(
1166
+ "invalid_payment_required",
1167
+ "PAYMENT-REQUIRED header is not a valid x402 PaymentRequired object"
1168
+ );
1169
+ }
1170
+ const sublyRequirements = parsed.data.accepts.flatMap((candidate) => {
1171
+ const requirement = sublyPaymentRequirementsSchema.safeParse(candidate);
1172
+ return requirement.success ? [requirement.data] : [];
1173
+ });
1174
+ return { paymentRequired: parsed.data, sublyRequirements };
1175
+ }
1176
+ function requestBodyHashFor(body) {
1177
+ if (body === null || body === void 0 || body.length === 0) {
1178
+ return EMPTY_BODY_HASH;
1179
+ }
1180
+ return sha256TaggedHex(
1181
+ typeof body === "string" ? Buffer.from(body, "utf8") : Buffer.from(body)
1182
+ );
1183
+ }
1184
+
1185
+ // ../../src/client/paid-fetch.ts
1186
+ var PaidFetchError = class extends Error {
1187
+ constructor(reason, message, detail = null) {
1188
+ super(message);
1189
+ this.reason = reason;
1190
+ this.detail = detail;
1191
+ this.name = "PaidFetchError";
1192
+ }
1193
+ reason;
1194
+ detail;
1195
+ };
1196
+ var DEFAULT_PENDING_TTL_MS = 11e4;
1197
+ var DEFAULT_MAX_TRACKED_URLS = 1e3;
1198
+ var DEFAULT_MAX_BODY_CHARS = 2e4;
1199
+ function formatRawUsdcAmount(raw) {
1200
+ const value = BigInt(raw);
1201
+ const negative = value < 0n;
1202
+ const abs = negative ? -value : value;
1203
+ const whole = abs / 1000000n;
1204
+ const frac = (abs % 1000000n).toString().padStart(6, "0");
1205
+ return `${negative ? "-" : ""}${whole}.${frac}`;
1206
+ }
1207
+ var PaidFetchService = class {
1208
+ signatureBuilder;
1209
+ fetchImpl;
1210
+ fetchBudget;
1211
+ paymentStatusFor;
1212
+ defaultMaxAmountRawUsdc;
1213
+ pendingTtlMs;
1214
+ maxTrackedUrls;
1215
+ maxBodyChars;
1216
+ nowMs;
1217
+ stateStore;
1218
+ pending = /* @__PURE__ */ new Map();
1219
+ inFlight = /* @__PURE__ */ new Map();
1220
+ constructor(config) {
1221
+ this.signatureBuilder = config.signatureBuilder;
1222
+ this.fetchImpl = config.fetchImpl ?? fetch;
1223
+ this.fetchBudget = config.fetchBudget ?? (async () => null);
1224
+ this.paymentStatusFor = config.paymentStatusFor ?? (async () => "indeterminate");
1225
+ this.defaultMaxAmountRawUsdc = config.defaultMaxAmountRawUsdc;
1226
+ this.pendingTtlMs = config.pendingTtlMs ?? DEFAULT_PENDING_TTL_MS;
1227
+ this.maxTrackedUrls = config.maxTrackedUrls ?? DEFAULT_MAX_TRACKED_URLS;
1228
+ this.maxBodyChars = config.maxBodyChars ?? DEFAULT_MAX_BODY_CHARS;
1229
+ this.nowMs = config.nowMs ?? (() => Date.now());
1230
+ this.stateStore = config.stateStore ?? null;
1231
+ if (this.stateStore !== null) {
1232
+ for (const record of this.stateStore.load()) {
1233
+ const { url: url2, ...entry } = record;
1234
+ this.pending.set(url2, entry);
1235
+ }
1236
+ }
1237
+ }
1238
+ /**
1239
+ * GET the URL, paying a 402 challenge when needed. Concurrent calls for the
1240
+ * same URL share one flow and one result.
1241
+ */
1242
+ paidFetch(params) {
1243
+ const existing = this.inFlight.get(params.url);
1244
+ if (existing !== void 0) {
1245
+ return existing;
1246
+ }
1247
+ const flow = this.run(params).finally(() => {
1248
+ this.inFlight.delete(params.url);
1249
+ });
1250
+ this.inFlight.set(params.url, flow);
1251
+ return flow;
1252
+ }
1253
+ async run(params) {
1254
+ const { url: url2 } = params;
1255
+ const pending = this.pending.get(url2);
1256
+ if (pending !== void 0) {
1257
+ const expired = this.nowMs() - pending.challengeAtMs > this.pendingTtlMs;
1258
+ if (pending.unresolved || expired) {
1259
+ if (params.forceNewPayment === true) {
1260
+ this.untrack(url2);
1261
+ } else {
1262
+ const outcome = await this.paymentStatusFor(pending.paymentId);
1263
+ if (outcome === "not_settled") {
1264
+ this.untrack(url2);
1265
+ } else if (outcome === "settled") {
1266
+ throw new PaidFetchError(
1267
+ "payment_already_settled",
1268
+ `the previous payment for this URL settled (paymentId=${pending.paymentId}) but the content delivery was lost, and the signature can no longer be retried. Calling again with forceNewPayment=true will PAY A SECOND TIME for the same resource.`,
1269
+ { paymentId: pending.paymentId }
1270
+ );
1271
+ } else {
1272
+ throw new PaidFetchError(
1273
+ "payment_outcome_unknown",
1274
+ `a previously signed payment for this URL (paymentId=${pending.paymentId}) has an unknown outcome. Verify whether it settled before purchasing again; to pay again anyway, call this tool with forceNewPayment=true.`,
1275
+ { paymentId: pending.paymentId }
1276
+ );
1277
+ }
1278
+ }
1279
+ } else {
1280
+ return this.deliver(url2, pending, {
1281
+ retried: true,
1282
+ budgetBefore: null
1283
+ });
1284
+ }
1285
+ }
1286
+ const challengeAtMs = this.nowMs();
1287
+ const first = await this.fetchImpl(url2);
1288
+ const firstText = await first.text();
1289
+ if (first.status !== 402) {
1290
+ return {
1291
+ paid: false,
1292
+ status: first.status,
1293
+ body: this.truncated(firstText)
1294
+ };
1295
+ }
1296
+ const challengeHeader = first.headers.get(PAYMENT_REQUIRED_HEADER);
1297
+ if (challengeHeader === null) {
1298
+ throw new PaidFetchError(
1299
+ "invalid_challenge",
1300
+ "402 response is missing the PAYMENT-REQUIRED header"
1301
+ );
1302
+ }
1303
+ const requirement = decodePaymentRequiredHeader(challengeHeader).sublyRequirements[0];
1304
+ if (requirement === void 0) {
1305
+ throw new PaidFetchError(
1306
+ "invalid_challenge",
1307
+ "402 challenge contains no subly-yield-exact requirement"
1308
+ );
1309
+ }
1310
+ const amountRawUsdc = BigInt(requirement.amountRawUsdc);
1311
+ const maxAmountRawUsdc = params.maxAmountRawUsdc ?? this.defaultMaxAmountRawUsdc;
1312
+ if (amountRawUsdc > maxAmountRawUsdc) {
1313
+ throw new PaidFetchError(
1314
+ "amount_exceeds_client_cap",
1315
+ `the challenge demands ${formatRawUsdcAmount(amountRawUsdc)} USDC, above this tool call's cap of ${formatRawUsdcAmount(maxAmountRawUsdc)} USDC; nothing was paid. Raise maxAmountRawUsdc only if this price is expected.`,
1316
+ {
1317
+ amountRawUsdc: requirement.amountRawUsdc,
1318
+ maxAmountRawUsdc: maxAmountRawUsdc.toString(),
1319
+ payTo: requirement.payTo
1320
+ }
1321
+ );
1322
+ }
1323
+ const budgetBefore = await this.fetchBudget();
1324
+ const { headerValue, paymentId } = await this.signatureBuilder.buildPaymentSignatureHeader({
1325
+ paymentRequiredHeader: challengeHeader,
1326
+ httpMethod: "GET",
1327
+ url: url2
1328
+ });
1329
+ const entry = {
1330
+ headerValue,
1331
+ paymentId,
1332
+ amountUsdc: formatRawUsdcAmount(amountRawUsdc),
1333
+ payTo: requirement.payTo,
1334
+ challengeAtMs,
1335
+ unresolved: false
1336
+ };
1337
+ this.track(url2, entry);
1338
+ return this.deliver(url2, entry, { retried: false, budgetBefore });
1339
+ }
1340
+ /**
1341
+ * Sends the signed PAYMENT-SIGNATURE retry. The tracked entry is removed
1342
+ * only on confirmed delivery (200). A fresh 402 proves the signature can no
1343
+ * longer settle, so the entry is kept as an unresolved marker; every other
1344
+ * failure keeps it retryable so the next call reuses the same signature.
1345
+ */
1346
+ async deliver(url2, entry, params) {
1347
+ let second;
1348
+ let secondText;
1349
+ try {
1350
+ second = await this.fetchImpl(url2, {
1351
+ headers: { [PAYMENT_SIGNATURE_HEADER]: entry.headerValue }
1352
+ });
1353
+ secondText = await second.text();
1354
+ } catch (error) {
1355
+ throw new PaidFetchError(
1356
+ "delivery_failed_payment_pending",
1357
+ `delivery request failed in flight (${error instanceof Error ? error.message : String(error)}); the payment (paymentId=${entry.paymentId}) is already signed and may settle. Call this tool again with the same URL to retry delivery with the same payment signature \u2014 do NOT treat this as unpaid.`,
1358
+ { paymentId: entry.paymentId }
1359
+ );
1360
+ }
1361
+ if (second.status === 200) {
1362
+ this.untrack(url2);
1363
+ const transaction = receiptTransaction(second.headers);
1364
+ return {
1365
+ paid: true,
1366
+ status: second.status,
1367
+ body: this.truncated(secondText),
1368
+ ...params.retried ? { retriedPendingPayment: true } : {},
1369
+ payment: {
1370
+ amountUsdc: entry.amountUsdc,
1371
+ payTo: entry.payTo,
1372
+ paymentId: entry.paymentId,
1373
+ transaction,
1374
+ solscanUrl: transaction === null ? null : `https://solscan.io/tx/${transaction}`,
1375
+ budgetBefore: params.budgetBefore,
1376
+ budgetAfter: await this.fetchBudget()
1377
+ }
1378
+ };
1379
+ }
1380
+ if (second.status === 402) {
1381
+ entry.unresolved = true;
1382
+ this.persist();
1383
+ throw new PaidFetchError(
1384
+ "payment_outcome_unknown",
1385
+ `the seller no longer accepts the signed payment (paymentId=${entry.paymentId}); it may or may not have settled. Verify the payment before purchasing again; to pay again anyway, call this tool with forceNewPayment=true.`,
1386
+ { paymentId: entry.paymentId }
1387
+ );
1388
+ }
1389
+ throw new PaidFetchError(
1390
+ "delivery_failed_payment_pending",
1391
+ `paid delivery failed with ${second.status} (paymentId=${entry.paymentId}); the payment may already have settled. Call this tool again with the same URL to retry delivery with the same payment signature \u2014 do NOT treat this as unpaid.`,
1392
+ {
1393
+ paymentId: entry.paymentId,
1394
+ status: second.status,
1395
+ body: this.truncated(secondText)
1396
+ }
1397
+ );
1398
+ }
1399
+ track(url2, entry) {
1400
+ if (!this.pending.has(url2) && this.pending.size >= this.maxTrackedUrls) {
1401
+ const oldest = this.pending.keys().next();
1402
+ if (!oldest.done) {
1403
+ this.pending.delete(oldest.value);
1404
+ }
1405
+ }
1406
+ this.pending.set(url2, entry);
1407
+ this.persist();
1408
+ }
1409
+ untrack(url2) {
1410
+ this.pending.delete(url2);
1411
+ this.persist();
1412
+ }
1413
+ persist() {
1414
+ if (this.stateStore === null) {
1415
+ return;
1416
+ }
1417
+ this.stateStore.save(
1418
+ [...this.pending.entries()].map(([url2, entry]) => ({ url: url2, ...entry }))
1419
+ );
1420
+ }
1421
+ truncated(text) {
1422
+ return text.length > this.maxBodyChars ? `${text.slice(0, this.maxBodyChars)}
1423
+ ... (truncated)` : text;
1424
+ }
1425
+ };
1426
+ function receiptTransaction(headers) {
1427
+ try {
1428
+ const receiptHeader = headers.get(PAYMENT_RESPONSE_HEADER);
1429
+ if (receiptHeader === null) {
1430
+ return null;
1431
+ }
1432
+ const receipt = decodeX402Header(receiptHeader);
1433
+ return typeof receipt.transaction === "string" && receipt.transaction.length > 0 ? receipt.transaction : null;
1434
+ } catch {
1435
+ return null;
1436
+ }
1437
+ }
1438
+
1439
+ // ../../src/solana/keys.ts
1440
+ import { readFileSync } from "node:fs";
1441
+ import bs586 from "bs58";
1442
+ import {
1443
+ createKeyPairSignerFromBytes
1444
+ } from "@solana/kit";
1445
+ async function loadKeyPairSigner(params) {
1446
+ const { base58Secret, jsonFilePath, label } = params;
1447
+ if (base58Secret !== void 0 && base58Secret.length > 0) {
1448
+ const bytes = bs586.decode(base58Secret);
1449
+ if (bytes.length !== 64) {
1450
+ throw new Error(`${label} base58 secret must decode to 64 bytes`);
1451
+ }
1452
+ return createKeyPairSignerFromBytes(bytes);
1453
+ }
1454
+ if (jsonFilePath !== void 0 && jsonFilePath.length > 0) {
1455
+ const raw = JSON.parse(readFileSync(jsonFilePath, "utf8"));
1456
+ if (!Array.isArray(raw) || raw.length !== 64) {
1457
+ throw new Error(`${label} keypair file must be a 64-byte JSON array`);
1458
+ }
1459
+ return createKeyPairSignerFromBytes(Uint8Array.from(raw));
1460
+ }
1461
+ throw new Error(`${label} keypair is not configured`);
1462
+ }
1463
+
1464
+ // ../../src/solana/rpc.ts
1465
+ import { createSolanaRpc } from "@solana/kit";
1466
+ function createRpc(url2) {
1467
+ return createSolanaRpc(url2);
1468
+ }
1469
+
1470
+ // ../../src/x402/client.ts
1471
+ var X402ClientError = class extends Error {
1472
+ reason;
1473
+ detail;
1474
+ constructor(reason, message, detail) {
1475
+ super(message);
1476
+ this.name = "X402ClientError";
1477
+ this.reason = reason;
1478
+ this.detail = detail;
1479
+ }
1480
+ };
1481
+ var SublyX402Client = class {
1482
+ config;
1483
+ signer;
1484
+ lookupTablesFor;
1485
+ fetchImpl;
1486
+ constructor(config) {
1487
+ this.config = {
1488
+ facilitatorBaseUrl: config.facilitatorBaseUrl.replace(/\/$/, ""),
1489
+ network: config.network ?? SOLANA_MAINNET_NETWORK
1490
+ };
1491
+ this.signer = config.signer;
1492
+ this.lookupTablesFor = config.lookupTablesFor ?? null;
1493
+ this.fetchImpl = config.fetchImpl ?? fetch;
1494
+ }
1495
+ /**
1496
+ * Builds the PAYMENT-SIGNATURE header for a 402 challenge. The request
1497
+ * method, URL, and body must be exactly the request being retried; they are
1498
+ * bound into the payment and verified again by the seller and facilitator.
1499
+ */
1500
+ async buildPaymentSignatureHeader(input) {
1501
+ const requirement = this.selectRequirement(input.paymentRequiredHeader);
1502
+ if (requirement.resource !== input.url) {
1503
+ throw new X402ClientError(
1504
+ "resource_mismatch",
1505
+ "PAYMENT-REQUIRED resource does not match the request URL"
1506
+ );
1507
+ }
1508
+ const requestBodyHash = requestBodyHashFor(input.body);
1509
+ const prepared = await this.preparePayment({
1510
+ requirement,
1511
+ httpMethod: input.httpMethod.toUpperCase(),
1512
+ requestBodyHash
1513
+ });
1514
+ const lookupTables = this.lookupTablesFor === null ? void 0 : await this.lookupTablesFor(prepared.intentJson.serializedTransaction);
1515
+ const signed = await this.signer.signPayment({
1516
+ intent: prepared.intentJson.signingIntent,
1517
+ serializedTransaction: prepared.intentJson.serializedTransaction,
1518
+ lookupTables
1519
+ });
1520
+ const payload = {
1521
+ x402Version: X402_VERSION,
1522
+ scheme: requirement.scheme,
1523
+ network: requirement.network,
1524
+ payload: {
1525
+ paymentId: prepared.paymentId,
1526
+ requestBindingHash: prepared.requestBindingHash,
1527
+ preparedMessageHash: prepared.preparedMessageHash,
1528
+ serializedTransaction: signed.serializedTransaction,
1529
+ agentSignature: signed.agentSignature,
1530
+ temporarySettlementSignature: prepared.temporarySettlementSignature
1531
+ }
1532
+ };
1533
+ return {
1534
+ headerValue: encodeX402Header(payload),
1535
+ paymentId: prepared.paymentId
1536
+ };
1537
+ }
1538
+ /**
1539
+ * Convenience wrapper: performs the request, and on a 402 with a Subly
1540
+ * requirement pays from vault yield and retries once.
1541
+ */
1542
+ async fetchWithPayment(url2, init) {
1543
+ const first = await this.fetchImpl(url2, init);
1544
+ if (first.status !== 402) {
1545
+ return first;
1546
+ }
1547
+ const challenge = first.headers.get(PAYMENT_REQUIRED_HEADER);
1548
+ if (challenge === null) {
1549
+ return first;
1550
+ }
1551
+ const { headerValue } = await this.buildPaymentSignatureHeader({
1552
+ paymentRequiredHeader: challenge,
1553
+ httpMethod: init?.method ?? "GET",
1554
+ url: url2,
1555
+ body: init?.body ?? null
1556
+ });
1557
+ return this.fetchImpl(url2, {
1558
+ ...init,
1559
+ headers: {
1560
+ ...init?.headers,
1561
+ [PAYMENT_SIGNATURE_HEADER]: headerValue
1562
+ }
1563
+ });
1564
+ }
1565
+ selectRequirement(paymentRequiredHeader) {
1566
+ let sublyRequirements;
1567
+ try {
1568
+ sublyRequirements = decodePaymentRequiredHeader(
1569
+ paymentRequiredHeader
1570
+ ).sublyRequirements;
1571
+ } catch (error) {
1572
+ throw new X402ClientError(
1573
+ error instanceof X402HeaderError ? error.reason : "invalid_challenge",
1574
+ "Cannot decode the PAYMENT-REQUIRED header"
1575
+ );
1576
+ }
1577
+ const selected = sublyRequirements.find(
1578
+ (candidate) => candidate.network === this.config.network && candidate.extra.vault === SUBLY_VAULT.address && candidate.extra.shareMint === SUBLY_VAULT.shareMint && candidate.asset === SUBLY_VAULT.usdcMint
1579
+ ) ?? null;
1580
+ if (selected === null) {
1581
+ throw new X402ClientError(
1582
+ "no_supported_requirement",
1583
+ "The 402 challenge contains no supported subly-yield-exact requirement"
1584
+ );
1585
+ }
1586
+ return selected;
1587
+ }
1588
+ async preparePayment(input) {
1589
+ const { requirement } = input;
1590
+ const wallet = this.signer.walletAddress;
1591
+ const prepareUrl = `${this.config.facilitatorBaseUrl}/v1/payments/prepare`;
1592
+ const prepareBody = JSON.stringify({
1593
+ wallet,
1594
+ scheme: requirement.scheme,
1595
+ network: requirement.network,
1596
+ vault: requirement.extra.vault,
1597
+ shareMint: requirement.extra.shareMint,
1598
+ asset: requirement.asset,
1599
+ seller: requirement.extra.seller,
1600
+ sellerRequestId: requirement.extra.sellerRequestId,
1601
+ httpMethod: input.httpMethod,
1602
+ canonicalResourceUrl: requirement.resource,
1603
+ requestBodyHash: input.requestBodyHash,
1604
+ amountRawUsdc: requirement.amountRawUsdc,
1605
+ payTo: requirement.payTo,
1606
+ sellerUsdcAta: requirement.extra.sellerUsdcAta,
1607
+ dustRecipientUsdcAta: deriveAssociatedTokenAddress({
1608
+ owner: wallet,
1609
+ mint: SUBLY_VAULT.usdcMint
1610
+ })
1611
+ });
1612
+ const response = await this.fetchImpl(prepareUrl, {
1613
+ method: "POST",
1614
+ headers: {
1615
+ ...await walletAuthHeaders({
1616
+ signer: this.signer,
1617
+ method: "POST",
1618
+ url: prepareUrl,
1619
+ body: prepareBody
1620
+ }),
1621
+ "content-type": "application/json"
1622
+ },
1623
+ body: prepareBody
1624
+ });
1625
+ const body = await response.json();
1626
+ if (response.status !== 200) {
1627
+ const error = body.error;
1628
+ throw new X402ClientError(
1629
+ typeof error?.code === "string" ? error.code : "prepare_failed",
1630
+ "Payment preparation failed at the facilitator",
1631
+ body
1632
+ );
1633
+ }
1634
+ const prepared = body;
1635
+ if (typeof prepared.paymentId !== "string" || typeof prepared.preparedMessageHash !== "string" || typeof prepared.intentJson?.serializedTransaction !== "string" || typeof prepared.intentJson?.signingIntent !== "object") {
1636
+ throw new X402ClientError(
1637
+ "invalid_prepare_response",
1638
+ "Facilitator prepare response is missing required fields"
1639
+ );
1640
+ }
1641
+ return prepared;
1642
+ }
1643
+ };
1644
+
1645
+ // ../../demo/shared.ts
1646
+ function fail(message) {
1647
+ console.error(message);
1648
+ process.exit(1);
1649
+ }
1650
+
1651
+ // ../../demo/pay.ts
1652
+ var url = process.argv[2];
1653
+ if (url === void 0 || !/^https?:\/\//.test(url)) {
1654
+ fail("Usage: npm run demo:pay -- <url> [maxAmountRawUsdc]");
1655
+ }
1656
+ var maxAmountArg = process.argv[3];
1657
+ var facilitatorBaseUrl = process.env.SUBLY_FACILITATOR_URL ?? "https://api.demo.sublyfi.com";
1658
+ var rpcUrl = process.env.SOLANA_RPC_URL ?? "https://api.mainnet-beta.solana.com";
1659
+ var defaultMaxAmountRawUsdc = process.env.SUBLY_MCP_MAX_AMOUNT_RAW_USDC === void 0 ? 10000n : BigInt(process.env.SUBLY_MCP_MAX_AMOUNT_RAW_USDC);
1660
+ var pendingStatePath = process.env.SUBLY_MCP_STATE_PATH ?? "demo/env/mcp-pending-payments.json";
1661
+ var keyPairSigner = await loadKeyPairSigner({
1662
+ base58Secret: process.env.SUBLY_DEMO_AGENT_KEYPAIR,
1663
+ jsonFilePath: process.env.SUBLY_DEMO_AGENT_KEYPAIR_PATH,
1664
+ label: "SUBLY_DEMO_AGENT_KEYPAIR"
1665
+ });
1666
+ var signer = new LocalKeypairAgentWalletSigner(keyPairSigner);
1667
+ var rpc = createRpc(rpcUrl);
1668
+ async function fetchBudget() {
1669
+ try {
1670
+ const budgetUrl = `${facilitatorBaseUrl}/v1/wallets/${signer.walletAddress}/budget`;
1671
+ const response = await fetch(budgetUrl, {
1672
+ headers: await walletAuthHeaders({ signer, method: "GET", url: budgetUrl })
1673
+ });
1674
+ if (response.status !== 200) {
1675
+ return null;
1676
+ }
1677
+ const body = await response.json();
1678
+ return body.budget === void 0 ? null : {
1679
+ positionValueUsdc: formatRawUsdcAmount(body.budget.positionValueRawUsdc),
1680
+ spendableYieldUsdc: formatRawUsdcAmount(
1681
+ body.budget.spendableYieldRawUsdc
1682
+ )
1683
+ };
1684
+ } catch {
1685
+ return null;
1686
+ }
1687
+ }
1688
+ async function paymentStatusFor(paymentId) {
1689
+ try {
1690
+ const statusUrl = `${facilitatorBaseUrl}/v1/payments/${paymentId}`;
1691
+ const response = await fetch(statusUrl, {
1692
+ headers: await walletAuthHeaders({ signer, method: "GET", url: statusUrl })
1693
+ });
1694
+ if (response.status !== 200) {
1695
+ return "indeterminate";
1696
+ }
1697
+ const body = await response.json();
1698
+ if (body.status === "settled") {
1699
+ return "settled";
1700
+ }
1701
+ if (body.status === "expired" || body.status === "failed" || body.status === "failed_not_submitted") {
1702
+ return "not_settled";
1703
+ }
1704
+ return "indeterminate";
1705
+ } catch {
1706
+ return "indeterminate";
1707
+ }
1708
+ }
1709
+ function fileStateStore(path) {
1710
+ return {
1711
+ load() {
1712
+ try {
1713
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
1714
+ return Array.isArray(parsed) ? parsed : [];
1715
+ } catch {
1716
+ return [];
1717
+ }
1718
+ },
1719
+ save(records) {
1720
+ try {
1721
+ writeFileSync(path, JSON.stringify(records));
1722
+ } catch (error) {
1723
+ console.error(
1724
+ `[subly-pay] failed to persist pending payments: ${error instanceof Error ? error.message : String(error)}`
1725
+ );
1726
+ }
1727
+ }
1728
+ };
1729
+ }
1730
+ var service = new PaidFetchService({
1731
+ signatureBuilder: new SublyX402Client({
1732
+ facilitatorBaseUrl,
1733
+ signer,
1734
+ lookupTablesFor: (serializedTransaction) => fetchLookupTablesForTransaction(rpc, serializedTransaction)
1735
+ }),
1736
+ defaultMaxAmountRawUsdc,
1737
+ fetchBudget,
1738
+ paymentStatusFor,
1739
+ stateStore: fileStateStore(pendingStatePath)
1740
+ });
1741
+ console.error(`[subly-pay] agent ${signer.walletAddress} -> ${facilitatorBaseUrl}`);
1742
+ try {
1743
+ await ensureWalletOnboarded({ facilitatorBaseUrl, signer });
1744
+ } catch (error) {
1745
+ console.error(
1746
+ `[subly-pay] onboarding skipped: ${error instanceof Error ? error.message : String(error)}`
1747
+ );
1748
+ }
1749
+ try {
1750
+ const result = await service.paidFetch({
1751
+ url,
1752
+ ...maxAmountArg === void 0 ? {} : { maxAmountRawUsdc: BigInt(maxAmountArg) }
1753
+ });
1754
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1755
+ `);
1756
+ } catch (error) {
1757
+ if (error instanceof PaidFetchError) {
1758
+ process.stdout.write(
1759
+ `${JSON.stringify(
1760
+ { paid: false, refused: true, reason: error.reason, message: error.message, detail: error.detail },
1761
+ null,
1762
+ 2
1763
+ )}
1764
+ `
1765
+ );
1766
+ process.exit(1);
1767
+ }
1768
+ fail(`[subly-pay] ${error instanceof Error ? error.message : String(error)}`);
1769
+ }