@cloak.dev/sdk 0.2.5-staging.4b3a899 → 0.2.6-staging.6c85601

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/README.md CHANGED
@@ -5,13 +5,13 @@ per-mint pool, send privately inside the pool, withdraw to any address, or swap
5
5
  USDC/USDT with the output landing in a public token account. Groth16 proofs are generated
6
6
  client-side (snarkjs) and verified on-chain by the Cloak program.
7
7
 
8
- Version 0.2.5 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
8
+ Version 0.2.6 targets the mainnet program deployed on 2026-08-24 and the ceremony-frozen
9
9
  `cloak-transaction-0.2.0` circuit bundle. See [Version and compatibility](#version-and-compatibility).
10
10
 
11
11
  ## Installation
12
12
 
13
13
  ```bash
14
- npm install @cloak.dev/sdk@^0.2.5
14
+ npm install @cloak.dev/sdk@^0.2.6
15
15
  ```
16
16
 
17
17
  The SDK is built on [`@solana/kit`](https://github.com/anza-xyz/kit) and re-exports the pieces an
@@ -647,7 +647,7 @@ relay endpoint and the localhost-RPC check.
647
647
 
648
648
  ## Version and compatibility
649
649
 
650
- - SDK 0.2.5 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
650
+ - SDK 0.2.6 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
651
651
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
652
652
  since 0.2.0; only the SDK package version has moved. All flows in this README were exercised on
653
653
  mainnet on 2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to
@@ -658,6 +658,11 @@ relay endpoint and the localhost-RPC check.
658
658
  the relay protocol and every hash the SDK computes are unchanged; what changes is the shape of
659
659
  the Solana values at the API boundary, listed under
660
660
  [Migrating from @solana/web3.js](#migrating-from-solanaweb3js).
661
+ - 0.2.6 adds one optional field, `affiliate_code`, to the relay request schema, used only by
662
+ Cloak's own apps. It is signed only when present, so a request without it is byte-identical to
663
+ 0.2.5 and every public flow and option is unchanged. Requests that carry it require a relay
664
+ version that accepts `affiliate_code` in the signed request view (the relay's affiliate-program
665
+ release, REL-010/REL-011); an older relay answers them with 401.
661
666
  - Proofs generated with the 0.1.x circuits are rejected by the mainnet program. SDK 0.1.x builds
662
667
  (which ship the 0.1.0 bundle) are not usable against it; upgrade to 0.2.x.
663
668
  - The note-based `CloakSDK` class is removed in 0.2.0. It targeted the pre-0.2.0 instruction layout
package/dist/index.cjs CHANGED
@@ -1670,9 +1670,47 @@ function assertAllowedRelayOrigin(value) {
1670
1670
  }
1671
1671
  return trimmed.replace(/\/$/, "");
1672
1672
  }
1673
- async function relayFetch(url, init) {
1673
+ async function relayFetch(url, init, options) {
1674
1674
  assertAllowedRelayOrigin(url);
1675
- return fetch(url, init);
1675
+ const extra = sanitizeExtraHeaders(options?.extraHeaders);
1676
+ if (!extra) return fetch(url, init);
1677
+ return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
1678
+ }
1679
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1680
+ var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
1681
+ function sanitizeExtraHeaders(extra) {
1682
+ if (!extra || typeof extra !== "object") return void 0;
1683
+ const out = {};
1684
+ let any = false;
1685
+ for (const [name, value] of Object.entries(extra)) {
1686
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
1687
+ if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
1688
+ out[name] = value;
1689
+ any = true;
1690
+ }
1691
+ return any ? out : void 0;
1692
+ }
1693
+ function mergeRelayHeaders(base, extraHeaders) {
1694
+ const extra = sanitizeExtraHeaders(extraHeaders);
1695
+ if (!extra) return base;
1696
+ const merged = {};
1697
+ const taken = /* @__PURE__ */ new Set();
1698
+ const put = (name, value) => {
1699
+ merged[name] = value;
1700
+ taken.add(name.toLowerCase());
1701
+ };
1702
+ if (typeof Headers !== "undefined" && base instanceof Headers) {
1703
+ base.forEach((value, name) => put(name, value));
1704
+ } else if (Array.isArray(base)) {
1705
+ for (const [name, value] of base) put(name, value);
1706
+ } else if (base) {
1707
+ for (const [name, value] of Object.entries(base)) put(name, value);
1708
+ }
1709
+ for (const [name, value] of Object.entries(extra)) {
1710
+ if (taken.has(name.toLowerCase())) continue;
1711
+ put(name, value);
1712
+ }
1713
+ return merged;
1676
1714
  }
1677
1715
  function assertAllowedRpcEndpoint(endpoint) {
1678
1716
  if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
@@ -2022,6 +2060,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
2022
2060
  "slippage_bps",
2023
2061
  "swap_max_retries"
2024
2062
  ];
2063
+ var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
2025
2064
  var UTF8 = new TextEncoder();
2026
2065
  function compareKeysBytewise(a, b) {
2027
2066
  if (a === b) return 0;
@@ -2085,6 +2124,11 @@ function buildAuthRequest(body, sender, fields) {
2085
2124
  }
2086
2125
  out[k] = value;
2087
2126
  }
2127
+ for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
2128
+ const value = body[k];
2129
+ if (value === void 0 || value === null) continue;
2130
+ out[k] = value;
2131
+ }
2088
2132
  return out;
2089
2133
  }
2090
2134
  function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
@@ -6742,6 +6786,9 @@ function assertInputMints(inputUtxos, expectedMint) {
6742
6786
  );
6743
6787
  }
6744
6788
  }
6789
+ function affiliateCodeOrUndefined(code) {
6790
+ return typeof code === "string" && code.length > 0 ? code : void 0;
6791
+ }
6745
6792
  function parseNkInput(input) {
6746
6793
  if (typeof input !== "string") {
6747
6794
  if (input.length !== 32) {
@@ -8085,6 +8132,39 @@ function buildTransactRequestBody(params) {
8085
8132
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
8086
8133
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
8087
8134
  }
8135
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8136
+ if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
8137
+ body.affiliate_code = affiliateCode;
8138
+ }
8139
+ return body;
8140
+ }
8141
+ function buildTransactSwapRequestBody(params) {
8142
+ const body = {
8143
+ proof_bytes: params.proofB64,
8144
+ public_inputs: params.publicInputsB64,
8145
+ output_mint: params.outputMint,
8146
+ recipient_ata: params.recipientAta,
8147
+ recipient: params.recipientWallet,
8148
+ // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
8149
+ // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
8150
+ min_output_amount: params.minOutputAmount.toString(),
8151
+ // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
8152
+ max_fee: params.maxFee.toString(),
8153
+ slippage_bps: params.slippageBps,
8154
+ dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
8155
+ exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
8156
+ route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
8157
+ swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
8158
+ encrypted_notes: params.encryptedNotes,
8159
+ risk_quote: params.riskQuote,
8160
+ // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
8161
+ // bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
8162
+ // params; the program builds the amount-bound R_fb from them at close.
8163
+ refund_pubkey: params.refundPubkeyB64,
8164
+ refund_blinding: params.refundBlindingB64
8165
+ };
8166
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
8167
+ if (affiliateCode) body.affiliate_code = affiliateCode;
8088
8168
  return body;
8089
8169
  }
8090
8170
  function resolveUserWallet(options) {
@@ -8220,7 +8300,7 @@ async function submitTransactToRelay(args) {
8220
8300
  try {
8221
8301
  response = await doFetch(`${relayUrl}/transact`, {
8222
8302
  method: "POST",
8223
- headers: { "Content-Type": "application/json" },
8303
+ headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
8224
8304
  body: requestPayload,
8225
8305
  signal: controller.signal
8226
8306
  });
@@ -9243,7 +9323,10 @@ async function transact(params, options) {
9243
9323
  // For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
9244
9324
  sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
9245
9325
  externalAmount,
9246
- recipientDeliveryNotes
9326
+ recipientDeliveryNotes,
9327
+ // SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
9328
+ // for deposits and shield-to-shield sends.
9329
+ affiliateCode: options.affiliateCode
9247
9330
  });
9248
9331
  void metadataBundle;
9249
9332
  const relaySubmission = await submitTransactToRelay({
@@ -9264,7 +9347,8 @@ async function transact(params, options) {
9264
9347
  inputNullifiers
9265
9348
  },
9266
9349
  canRetryStaleRoot: submissionAttempts < maxRootRetries,
9267
- onProgress
9350
+ onProgress,
9351
+ extraHeaders: options.relayHeaders
9268
9352
  });
9269
9353
  if (relaySubmission.kind === "stale-root") {
9270
9354
  lastError = relaySubmission.error;
@@ -10311,30 +10395,27 @@ async function swapUtxo(params, options) {
10311
10395
  const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
10312
10396
  await options.onSwapStatePredicted(ssp);
10313
10397
  }
10314
- const requestBody = {
10315
- proof_bytes: proofB64,
10316
- public_inputs: publicInputsB64,
10317
- output_mint: outputMint,
10318
- recipient_ata: recipientAta,
10319
- recipient: recipientWallet,
10320
- // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
10321
- // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
10322
- min_output_amount: minOutputAmount.toString(),
10323
- // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
10324
- max_fee: swapMaxFee.toString(),
10325
- slippage_bps: swapSlippageBps,
10326
- dexes: swapDexes && swapDexes.length > 0 ? swapDexes : void 0,
10327
- exclude_dexes: swapExcludeDexes && swapExcludeDexes.length > 0 ? swapExcludeDexes : void 0,
10328
- route_retry_attempts: options.swapRouteRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(options.swapRouteRetryAttempts))) : void 0,
10329
- swap_max_retries: options.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(options.swapMaxRetries))) : void 0,
10330
- encrypted_notes: encryptedNotes,
10331
- risk_quote: riskQuoteData,
10332
- // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
10333
- // bound into the proof's ext_data_hash above. The relay forwards both verbatim into the swap
10334
- // params; the program builds the amount-bound R_fb from them at close.
10335
- refund_pubkey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10336
- refund_blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64")
10337
- };
10398
+ const requestBody = buildTransactSwapRequestBody({
10399
+ proofB64,
10400
+ publicInputsB64,
10401
+ outputMint,
10402
+ recipientAta,
10403
+ recipientWallet,
10404
+ minOutputAmount,
10405
+ maxFee: swapMaxFee,
10406
+ slippageBps: swapSlippageBps,
10407
+ dexes: swapDexes,
10408
+ excludeDexes: swapExcludeDexes,
10409
+ routeRetryAttempts: options.swapRouteRetryAttempts,
10410
+ swapMaxRetries: options.swapMaxRetries,
10411
+ encryptedNotes,
10412
+ riskQuote: riskQuoteData,
10413
+ refundPubkeyB64: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("base64"),
10414
+ refundBlindingB64: Buffer.from(bigintToBytes323(refundBlinding)).toString("base64"),
10415
+ // SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
10416
+ // a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
10417
+ affiliateCode: options.affiliateCode
10418
+ });
10338
10419
  try {
10339
10420
  if (relayAuthPlan.kind === "wallet") {
10340
10421
  walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
@@ -10353,11 +10434,16 @@ async function swapUtxo(params, options) {
10353
10434
  TRANSACT_SWAP_AUTH_FIELDS
10354
10435
  );
10355
10436
  if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
10356
- const response = await relayFetch(`${relayUrl}/transact_swap`, {
10357
- method: "POST",
10358
- headers: { "Content-Type": "application/json" },
10359
- body: JSON.stringify(requestBody)
10360
- });
10437
+ const response = await relayFetch(
10438
+ `${relayUrl}/transact_swap`,
10439
+ {
10440
+ method: "POST",
10441
+ headers: { "Content-Type": "application/json" },
10442
+ body: JSON.stringify(requestBody)
10443
+ },
10444
+ // SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
10445
+ { extraHeaders: options.relayHeaders }
10446
+ );
10361
10447
  const responseText = await response.text();
10362
10448
  if (!response.ok) {
10363
10449
  if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
@@ -13332,7 +13418,7 @@ async function withShieldRetries(attempt, hooks = {}) {
13332
13418
  }
13333
13419
 
13334
13420
  // src/index.ts
13335
- var VERSION = "0.2.5";
13421
+ var VERSION = "0.2.6";
13336
13422
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13337
13423
  // Annotate the CommonJS export names for ESM import in node:
13338
13424
  0 && (module.exports = {
package/dist/index.d.cts CHANGED
@@ -3558,6 +3558,29 @@ interface TransactOptions {
3558
3558
  * relay does not authenticate this way.
3559
3559
  */
3560
3560
  relayAuthBatch?: RelayBatchAuthItemHandle;
3561
+ /**
3562
+ * Referral code attached to fee-bearing relay requests (SDK-001).
3563
+ *
3564
+ * Sent as `affiliate_code`, and signed inside the relay request, only when it is a non-empty
3565
+ * string AND the request is fee-bearing: a withdrawal / send to a public address
3566
+ * (`externalAmount < 0` with a recipient) or a swap intake. Deposits and shield-to-shield sends
3567
+ * never carry it, whatever is passed here. Omitted, every request is byte-identical to one built
3568
+ * without this option (INV-007). Requires a relay that accepts `affiliate_code`.
3569
+ *
3570
+ * @internal For Cloak's own web and mobile apps. Not part of the public API, not documented, and
3571
+ * may change without notice.
3572
+ */
3573
+ affiliateCode?: string;
3574
+ /**
3575
+ * Extra HTTP headers sent with this flow's relay submissions (`POST /transact` and
3576
+ * `POST /transact_swap`), e.g. `{ "X-Cloak-Client": "cloak-mobile/ios/1.4.0" }` (SDK-004).
3577
+ * They never replace a header the SDK sets itself; malformed entries are dropped. Omitted, the
3578
+ * requests are exactly what they were.
3579
+ *
3580
+ * @internal For Cloak's own mobile app. Not part of the public API, and a browser caller should
3581
+ * not set it: a non-safelisted header makes every submission a CORS preflight.
3582
+ */
3583
+ relayHeaders?: Record<string, string>;
3561
3584
  }
3562
3585
  /**
3563
3586
  * Switchboard-style response: a pre-built instruction.
@@ -3611,6 +3634,13 @@ interface TransactRequestBodyParams {
3611
3634
  externalAmount: bigint;
3612
3635
  /** Base64 CLKD1 envelopes, from `buildRecipientDeliveryNotes`. Omitted when the rail is off. */
3613
3636
  recipientDeliveryNotes?: string[];
3637
+ /**
3638
+ * `TransactOptions.affiliateCode`. Only a withdrawal (`externalAmount < 0` with a recipient)
3639
+ * carries it; for any other shape it is ignored.
3640
+ *
3641
+ * @internal
3642
+ */
3643
+ affiliateCode?: string;
3614
3644
  }
3615
3645
  /**
3616
3646
  * Assemble the `/transact` body.
@@ -3676,6 +3706,13 @@ interface SubmitTransactToRelayArgs {
3676
3706
  requestTimeoutMs?: number;
3677
3707
  /** Injection seam for tests; defaults to global fetch. */
3678
3708
  fetchImpl?: typeof fetch;
3709
+ /**
3710
+ * Extra headers for the `/transact` POST, e.g. the mobile app's `X-Cloak-Client` (SDK-004).
3711
+ * Never replace `Content-Type`; omitted, the request headers are exactly what they were.
3712
+ *
3713
+ * @internal
3714
+ */
3715
+ extraHeaders?: Record<string, string>;
3679
3716
  onProgress?: (status: string) => void;
3680
3717
  /** Total window allowed for the on-chain settlement check after a reported success. */
3681
3718
  settlementTimeoutMs?: number;
@@ -5748,7 +5785,7 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
5748
5785
  * @packageDocumentation
5749
5786
  */
5750
5787
 
5751
- declare const VERSION = "0.2.5";
5788
+ declare const VERSION = "0.2.6";
5752
5789
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
5753
5790
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
5754
5791
 
package/dist/index.d.ts CHANGED
@@ -3558,6 +3558,29 @@ interface TransactOptions {
3558
3558
  * relay does not authenticate this way.
3559
3559
  */
3560
3560
  relayAuthBatch?: RelayBatchAuthItemHandle;
3561
+ /**
3562
+ * Referral code attached to fee-bearing relay requests (SDK-001).
3563
+ *
3564
+ * Sent as `affiliate_code`, and signed inside the relay request, only when it is a non-empty
3565
+ * string AND the request is fee-bearing: a withdrawal / send to a public address
3566
+ * (`externalAmount < 0` with a recipient) or a swap intake. Deposits and shield-to-shield sends
3567
+ * never carry it, whatever is passed here. Omitted, every request is byte-identical to one built
3568
+ * without this option (INV-007). Requires a relay that accepts `affiliate_code`.
3569
+ *
3570
+ * @internal For Cloak's own web and mobile apps. Not part of the public API, not documented, and
3571
+ * may change without notice.
3572
+ */
3573
+ affiliateCode?: string;
3574
+ /**
3575
+ * Extra HTTP headers sent with this flow's relay submissions (`POST /transact` and
3576
+ * `POST /transact_swap`), e.g. `{ "X-Cloak-Client": "cloak-mobile/ios/1.4.0" }` (SDK-004).
3577
+ * They never replace a header the SDK sets itself; malformed entries are dropped. Omitted, the
3578
+ * requests are exactly what they were.
3579
+ *
3580
+ * @internal For Cloak's own mobile app. Not part of the public API, and a browser caller should
3581
+ * not set it: a non-safelisted header makes every submission a CORS preflight.
3582
+ */
3583
+ relayHeaders?: Record<string, string>;
3561
3584
  }
3562
3585
  /**
3563
3586
  * Switchboard-style response: a pre-built instruction.
@@ -3611,6 +3634,13 @@ interface TransactRequestBodyParams {
3611
3634
  externalAmount: bigint;
3612
3635
  /** Base64 CLKD1 envelopes, from `buildRecipientDeliveryNotes`. Omitted when the rail is off. */
3613
3636
  recipientDeliveryNotes?: string[];
3637
+ /**
3638
+ * `TransactOptions.affiliateCode`. Only a withdrawal (`externalAmount < 0` with a recipient)
3639
+ * carries it; for any other shape it is ignored.
3640
+ *
3641
+ * @internal
3642
+ */
3643
+ affiliateCode?: string;
3614
3644
  }
3615
3645
  /**
3616
3646
  * Assemble the `/transact` body.
@@ -3676,6 +3706,13 @@ interface SubmitTransactToRelayArgs {
3676
3706
  requestTimeoutMs?: number;
3677
3707
  /** Injection seam for tests; defaults to global fetch. */
3678
3708
  fetchImpl?: typeof fetch;
3709
+ /**
3710
+ * Extra headers for the `/transact` POST, e.g. the mobile app's `X-Cloak-Client` (SDK-004).
3711
+ * Never replace `Content-Type`; omitted, the request headers are exactly what they were.
3712
+ *
3713
+ * @internal
3714
+ */
3715
+ extraHeaders?: Record<string, string>;
3679
3716
  onProgress?: (status: string) => void;
3680
3717
  /** Total window allowed for the on-chain settlement check after a reported success. */
3681
3718
  settlementTimeoutMs?: number;
@@ -5748,7 +5785,7 @@ declare function withShieldRetries<T>(attempt: (attemptNo: number) => Promise<T>
5748
5785
  * @packageDocumentation
5749
5786
  */
5750
5787
 
5751
- declare const VERSION = "0.2.5";
5788
+ declare const VERSION = "0.2.6";
5752
5789
  /** True when scanner supports TransactSwap (tag 1). Check this to verify the correct SDK bundle is loaded. */
5753
5790
  declare const SCANNER_SUPPORTS_TRANSACT_SWAP = true;
5754
5791
 
package/dist/index.js CHANGED
@@ -801,9 +801,47 @@ function assertAllowedRelayOrigin(value) {
801
801
  }
802
802
  return trimmed.replace(/\/$/, "");
803
803
  }
804
- async function relayFetch(url, init) {
804
+ async function relayFetch(url, init, options) {
805
805
  assertAllowedRelayOrigin(url);
806
- return fetch(url, init);
806
+ const extra = sanitizeExtraHeaders(options?.extraHeaders);
807
+ if (!extra) return fetch(url, init);
808
+ return fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) });
809
+ }
810
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
811
+ var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
812
+ function sanitizeExtraHeaders(extra) {
813
+ if (!extra || typeof extra !== "object") return void 0;
814
+ const out = {};
815
+ let any = false;
816
+ for (const [name, value] of Object.entries(extra)) {
817
+ if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
818
+ if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
819
+ out[name] = value;
820
+ any = true;
821
+ }
822
+ return any ? out : void 0;
823
+ }
824
+ function mergeRelayHeaders(base, extraHeaders) {
825
+ const extra = sanitizeExtraHeaders(extraHeaders);
826
+ if (!extra) return base;
827
+ const merged = {};
828
+ const taken = /* @__PURE__ */ new Set();
829
+ const put = (name, value) => {
830
+ merged[name] = value;
831
+ taken.add(name.toLowerCase());
832
+ };
833
+ if (typeof Headers !== "undefined" && base instanceof Headers) {
834
+ base.forEach((value, name) => put(name, value));
835
+ } else if (Array.isArray(base)) {
836
+ for (const [name, value] of base) put(name, value);
837
+ } else if (base) {
838
+ for (const [name, value] of Object.entries(base)) put(name, value);
839
+ }
840
+ for (const [name, value] of Object.entries(extra)) {
841
+ if (taken.has(name.toLowerCase())) continue;
842
+ put(name, value);
843
+ }
844
+ return merged;
807
845
  }
808
846
  function assertAllowedRpcEndpoint(endpoint) {
809
847
  if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
@@ -1176,6 +1214,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
1176
1214
  "slippage_bps",
1177
1215
  "swap_max_retries"
1178
1216
  ];
1217
+ var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
1179
1218
  var UTF8 = new TextEncoder();
1180
1219
  function compareKeysBytewise(a, b) {
1181
1220
  if (a === b) return 0;
@@ -1239,6 +1278,11 @@ function buildAuthRequest(body, sender, fields) {
1239
1278
  }
1240
1279
  out[k] = value;
1241
1280
  }
1281
+ for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
1282
+ const value = body[k];
1283
+ if (value === void 0 || value === null) continue;
1284
+ out[k] = value;
1285
+ }
1242
1286
  return out;
1243
1287
  }
1244
1288
  function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
@@ -5874,6 +5918,9 @@ function assertInputMints(inputUtxos, expectedMint) {
5874
5918
  );
5875
5919
  }
5876
5920
  }
5921
+ function affiliateCodeOrUndefined(code) {
5922
+ return typeof code === "string" && code.length > 0 ? code : void 0;
5923
+ }
5877
5924
  function parseNkInput(input) {
5878
5925
  if (typeof input !== "string") {
5879
5926
  if (input.length !== 32) {
@@ -7217,6 +7264,39 @@ function buildTransactRequestBody(params) {
7217
7264
  if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
7218
7265
  body.recipient_delivery_notes = params.recipientDeliveryNotes;
7219
7266
  }
7267
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
7268
+ if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
7269
+ body.affiliate_code = affiliateCode;
7270
+ }
7271
+ return body;
7272
+ }
7273
+ function buildTransactSwapRequestBody(params) {
7274
+ const body = {
7275
+ proof_bytes: params.proofB64,
7276
+ public_inputs: params.publicInputsB64,
7277
+ output_mint: params.outputMint,
7278
+ recipient_ata: params.recipientAta,
7279
+ recipient: params.recipientWallet,
7280
+ // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
7281
+ // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
7282
+ min_output_amount: params.minOutputAmount.toString(),
7283
+ // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
7284
+ max_fee: params.maxFee.toString(),
7285
+ slippage_bps: params.slippageBps,
7286
+ dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
7287
+ exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
7288
+ route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
7289
+ swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
7290
+ encrypted_notes: params.encryptedNotes,
7291
+ risk_quote: params.riskQuote,
7292
+ // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
7293
+ // bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
7294
+ // params; the program builds the amount-bound R_fb from them at close.
7295
+ refund_pubkey: params.refundPubkeyB64,
7296
+ refund_blinding: params.refundBlindingB64
7297
+ };
7298
+ const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
7299
+ if (affiliateCode) body.affiliate_code = affiliateCode;
7220
7300
  return body;
7221
7301
  }
7222
7302
  function resolveUserWallet(options) {
@@ -7352,7 +7432,7 @@ async function submitTransactToRelay(args) {
7352
7432
  try {
7353
7433
  response = await doFetch(`${relayUrl}/transact`, {
7354
7434
  method: "POST",
7355
- headers: { "Content-Type": "application/json" },
7435
+ headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
7356
7436
  body: requestPayload,
7357
7437
  signal: controller.signal
7358
7438
  });
@@ -8375,7 +8455,10 @@ async function transact(params, options) {
8375
8455
  // For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
8376
8456
  sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
8377
8457
  externalAmount,
8378
- recipientDeliveryNotes
8458
+ recipientDeliveryNotes,
8459
+ // SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
8460
+ // for deposits and shield-to-shield sends.
8461
+ affiliateCode: options.affiliateCode
8379
8462
  });
8380
8463
  void metadataBundle;
8381
8464
  const relaySubmission = await submitTransactToRelay({
@@ -8396,7 +8479,8 @@ async function transact(params, options) {
8396
8479
  inputNullifiers
8397
8480
  },
8398
8481
  canRetryStaleRoot: submissionAttempts < maxRootRetries,
8399
- onProgress
8482
+ onProgress,
8483
+ extraHeaders: options.relayHeaders
8400
8484
  });
8401
8485
  if (relaySubmission.kind === "stale-root") {
8402
8486
  lastError = relaySubmission.error;
@@ -9443,30 +9527,27 @@ async function swapUtxo(params, options) {
9443
9527
  const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
9444
9528
  await options.onSwapStatePredicted(ssp);
9445
9529
  }
9446
- const requestBody = {
9447
- proof_bytes: proofB64,
9448
- public_inputs: publicInputsB64,
9449
- output_mint: outputMint,
9450
- recipient_ata: recipientAta,
9451
- recipient: recipientWallet,
9452
- // The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
9453
- // expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
9454
- min_output_amount: minOutputAmount.toString(),
9455
- // Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
9456
- max_fee: swapMaxFee.toString(),
9457
- slippage_bps: swapSlippageBps,
9458
- dexes: swapDexes && swapDexes.length > 0 ? swapDexes : void 0,
9459
- exclude_dexes: swapExcludeDexes && swapExcludeDexes.length > 0 ? swapExcludeDexes : void 0,
9460
- route_retry_attempts: options.swapRouteRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(options.swapRouteRetryAttempts))) : void 0,
9461
- swap_max_retries: options.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(options.swapMaxRetries))) : void 0,
9462
- encrypted_notes: encryptedNotes,
9463
- risk_quote: riskQuoteData,
9464
- // V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
9465
- // bound into the proof's ext_data_hash above. The relay forwards both verbatim into the swap
9466
- // params; the program builds the amount-bound R_fb from them at close.
9467
- refund_pubkey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
9468
- refund_blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64")
9469
- };
9530
+ const requestBody = buildTransactSwapRequestBody({
9531
+ proofB64,
9532
+ publicInputsB64,
9533
+ outputMint,
9534
+ recipientAta,
9535
+ recipientWallet,
9536
+ minOutputAmount,
9537
+ maxFee: swapMaxFee,
9538
+ slippageBps: swapSlippageBps,
9539
+ dexes: swapDexes,
9540
+ excludeDexes: swapExcludeDexes,
9541
+ routeRetryAttempts: options.swapRouteRetryAttempts,
9542
+ swapMaxRetries: options.swapMaxRetries,
9543
+ encryptedNotes,
9544
+ riskQuote: riskQuoteData,
9545
+ refundPubkeyB64: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
9546
+ refundBlindingB64: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64"),
9547
+ // SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
9548
+ // a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
9549
+ affiliateCode: options.affiliateCode
9550
+ });
9470
9551
  try {
9471
9552
  if (relayAuthPlan.kind === "wallet") {
9472
9553
  walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
@@ -9485,11 +9566,16 @@ async function swapUtxo(params, options) {
9485
9566
  TRANSACT_SWAP_AUTH_FIELDS
9486
9567
  );
9487
9568
  if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
9488
- const response = await relayFetch(`${relayUrl}/transact_swap`, {
9489
- method: "POST",
9490
- headers: { "Content-Type": "application/json" },
9491
- body: JSON.stringify(requestBody)
9492
- });
9569
+ const response = await relayFetch(
9570
+ `${relayUrl}/transact_swap`,
9571
+ {
9572
+ method: "POST",
9573
+ headers: { "Content-Type": "application/json" },
9574
+ body: JSON.stringify(requestBody)
9575
+ },
9576
+ // SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
9577
+ { extraHeaders: options.relayHeaders }
9578
+ );
9493
9579
  const responseText = await response.text();
9494
9580
  if (!response.ok) {
9495
9581
  if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
@@ -12461,7 +12547,7 @@ async function withShieldRetries(attempt, hooks = {}) {
12461
12547
  }
12462
12548
 
12463
12549
  // src/index.ts
12464
- var VERSION = "0.2.5";
12550
+ var VERSION = "0.2.6";
12465
12551
  var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
12466
12552
  export {
12467
12553
  AccountRole,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloak.dev/sdk",
3
3
  "description": "Shield, send, and swap on Solana privately — TypeScript SDK with UTXO-based zero-knowledge transactions",
4
- "version": "0.2.5-staging.4b3a899",
4
+ "version": "0.2.6-staging.6c85601",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",