uniport-sdk 0.0.11 → 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/README.md CHANGED
@@ -19,18 +19,22 @@ npm install uniport-sdk
19
19
  import { UniportButton } from 'uniport-sdk'
20
20
 
21
21
  <UniportButton
22
+ appId="app_..."
22
23
  recipient="0x..."
23
24
  destinationToken="arbitrumUSDC"
24
- onSuccess={(result) => console.log('Paid', result.txHash)}
25
+ onSuccess={(result) => console.log('Paid', result.depositAddress)}
25
26
  />
26
27
  ```
27
28
 
28
- The SDK uses Uniport's hosted backend. No API key or backend URL is required for standard integration.
29
+ Get your `appId` at [uniport.dev/dashboard](https://uniport.dev/dashboard): create an app and add the websites it runs on. The App ID is public, so it is safe in browser code; what it controls is which sites may use it. On `localhost` the SDK works without one, which is enough to try it out. Deployed sites need one.
30
+
31
+ The SDK uses Uniport's hosted backend. No secret key or backend of your own is needed.
29
32
 
30
33
  ## UniportButton Props
31
34
 
32
35
  | Prop | Type | Required | Description |
33
36
  |------|------|----------|-------------|
37
+ | `appId` | `string` | On deployed sites | Your public App ID from the dashboard. Optional on `localhost`. Can also be set once with `configureUniport({ appId })` |
34
38
  | `recipient` | `string` | Yes | Recipient wallet address on the destination chain |
35
39
  | `destinationToken` | `string` | Yes | Destination token name from the supported token table |
36
40
  | `amount` | `string` | No | Exact destination amount. If omitted, the payer enters an input amount in the modal |
@@ -40,13 +44,36 @@ The SDK uses Uniport's hosted backend. No API key or backend URL is required for
40
44
  | `disabled` | `boolean` | No | Disable the button |
41
45
  | `className` | `string` | No | Custom CSS class |
42
46
  | `theme` | `'light' \| 'dark'` | No | Modal theme |
43
- | `onSuccess` | `(result) => void` | No | Called when payment completes |
47
+ | `onSuccess` | `(result) => void` | No | Called when payment completes, with `{ txHash, amount, depositAddress, depositMemo, correlationId }` |
44
48
  | `onError` | `(error) => void` | No | Called when payment fails |
45
49
  | `onOpenChange` | `(open) => void` | No | Called when modal opens or closes |
46
50
 
47
51
  If `refundAddress` is omitted, the payer can enter it inside the modal. The refund address is on the source chain the payer sends from.
48
52
 
49
- When `amount` is set, the payer can't change it in the modal. `onSuccess` runs in the payer's browser, so before granting goods or access, confirm on your server that the recipient received the amount.
53
+ When `amount` is set, the payer can't change it in the modal.
54
+
55
+ ## Confirming a payment
56
+
57
+ `onSuccess` receives `{ txHash, amount, depositAddress, depositMemo, correlationId }`. It runs in the payer's browser, so do not grant goods or access on its word alone. Send `depositAddress` to your server and have it check the payment:
58
+
59
+ ```ts
60
+ const res = await fetch(
61
+ `https://api.uniport.dev/v1/payments/${encodeURIComponent(depositAddress)}`
62
+ )
63
+ if (!res.ok) throw new Error('Try again shortly')
64
+ const payment = await res.json()
65
+
66
+ const paid =
67
+ payment.status === 'SUCCESS' &&
68
+ payment.amountOut !== null &&
69
+ payment.appId === process.env.UNIPORT_APP_ID &&
70
+ // EVM (0x) addresses only. On other chains, such as Solana, compare exactly.
71
+ payment.recipient.toLowerCase() === MY_WALLET.toLowerCase() &&
72
+ payment.destinationAsset === EXPECTED_ASSET_ID &&
73
+ BigInt(payment.amountOut) >= EXPECTED_AMOUNT
74
+ ```
75
+
76
+ `amountOut` is `null` until the payment is delivered. If `record` is `unavailable`, Uniport could not read its record just now, so `appId` is `null`: ask again shortly. Also record each payment you accept, so it cannot be used for two orders: store `payment.depositAddress` and `payment.depositMemo` from the response, not the values the browser sent, because the same address can be written in more than one way. Add `?memo=` with `depositMemo` on chains that use a memo. No secret is needed for this call.
50
77
 
51
78
  When `amount` is supplied, the modal requests that exact destination amount and rounds the quoted input upward only when the increase is at most 0.25%. Rounded surplus and failed-swap refunds are credited to Uniport's configured Intents account. When `amount` is omitted, the payer enters an exact input amount and receives the quoted output.
52
79
 
@@ -198,6 +225,7 @@ The package exports:
198
225
  - `UniportButton`
199
226
  - `UniportModal`
200
227
  - `useUniportPayment`
228
+ - `configureUniport` — set `appId` once for the core functions
201
229
  - `getQuote`
202
230
  - `submitDepositTx`
203
231
  - `getExecutionStatus`
@@ -213,6 +241,17 @@ The package exports:
213
241
 
214
242
  Backend request failures are surfaced as typed `UniportError` instances from the core module. Timeouts, quote failures, deposit submission failures, and status failures are normalized by the SDK before they reach your UI.
215
243
 
244
+ Four codes mean the app's setup needs fixing. The payer sees a neutral message, and the reason is logged to the browser console:
245
+
246
+ | Code | Meaning | Fix |
247
+ |------|---------|-----|
248
+ | `APP_ID_REQUIRED` | The site is not `localhost` and no `appId` was passed | Create an app in the dashboard and pass its ID |
249
+ | `APP_NOT_FOUND` | The App ID is unknown, mistyped or disabled | Copy it again from the dashboard |
250
+ | `ORIGIN_NOT_ALLOWED` | The App ID is being used on a site that is not on its list | Add the site to the app's allowed origins |
251
+ | `RECIPIENT_NOT_ALLOWED` | The app only accepts payments to listed addresses, and `recipient` is not one | Use a listed address, or change the list |
252
+
253
+ `RATE_LIMITED` means too many requests in a short time; the payer is asked to wait a minute.
254
+
216
255
  ## License
217
256
 
218
257
  MIT
@@ -534,16 +534,37 @@ function getSupportedChains() {
534
534
  }
535
535
 
536
536
  // src/core/config.ts
537
- var DEFAULT_HOSTED_BACKEND_URL = "https://uniport-backend-production.up.railway.app";
537
+ var DEFAULT_HOSTED_BACKEND_URL = "https://api.uniport.dev";
538
538
  var DEFAULT_REQUEST_TIMEOUT_MS = 2e4;
539
+ var APP_ID_FORMAT = /^app_[0-9A-Za-z]{22}$/;
540
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("uniport-sdk.config");
541
+ var globalStore = globalThis;
542
+ var store = globalStore[STORE_KEY] ?? (globalStore[STORE_KEY] = { warnedAppIds: /* @__PURE__ */ new Set() });
543
+ function checkAppId(appId) {
544
+ const value = appId?.trim();
545
+ if (!value) return void 0;
546
+ if (value.startsWith("sk_") || value.startsWith("whsec_")) {
547
+ throw new Error(
548
+ "Uniport: a secret key was passed as appId. Secret keys must stay on your server; use the public App ID (app_...) from https://uniport.dev/dashboard."
549
+ );
550
+ }
551
+ if (!APP_ID_FORMAT.test(value) && !store.warnedAppIds.has(value)) {
552
+ store.warnedAppIds.add(value);
553
+ console.warn(
554
+ `Uniport: "${value}" does not look like an App ID (app_ followed by 22 characters). Copy it from https://uniport.dev/dashboard.`
555
+ );
556
+ }
557
+ return value;
558
+ }
539
559
  function normalizeBackendUrl(url) {
540
560
  return url.replace(/\/+$/, "");
541
561
  }
542
562
  function getUniportConfig() {
543
- const backendUrl = DEFAULT_HOSTED_BACKEND_URL;
563
+ const backendUrl = store.backendUrl || DEFAULT_HOSTED_BACKEND_URL;
544
564
  return {
565
+ appId: store.appId,
545
566
  backendUrl: normalizeBackendUrl(backendUrl),
546
- requestTimeoutMs: DEFAULT_REQUEST_TIMEOUT_MS
567
+ requestTimeoutMs: store.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
547
568
  };
548
569
  }
549
570
 
@@ -576,7 +597,40 @@ function extractDetailMessage(details) {
576
597
  }
577
598
  return void 0;
578
599
  }
600
+ var APP_SETUP_CODES = /* @__PURE__ */ new Set([
601
+ "APP_ID_REQUIRED",
602
+ "APP_NOT_FOUND",
603
+ "ORIGIN_NOT_ALLOWED",
604
+ "RECIPIENT_NOT_ALLOWED"
605
+ ]);
606
+ function isAppSetupError(error) {
607
+ return APP_SETUP_CODES.has(errorCode(error) ?? "");
608
+ }
609
+ function isRateLimitError(error) {
610
+ return errorCode(error) === "RATE_LIMITED";
611
+ }
612
+ function errorCode(error) {
613
+ if (typeof error !== "object" || error === null) return void 0;
614
+ const code = error.code;
615
+ return typeof code === "string" ? code : void 0;
616
+ }
579
617
  function toUniportError(body, fallback) {
618
+ if (body.code && APP_SETUP_CODES.has(body.code)) {
619
+ console.error(`Uniport [${body.code}]: ${body.message ?? "The app is not set up correctly."}`);
620
+ return new UniportError({
621
+ code: body.code,
622
+ message: "Payments are not available on this site right now. Please contact the site owner.",
623
+ details: body.message,
624
+ status: fallback.status
625
+ });
626
+ }
627
+ if (fallback.status === 429) {
628
+ return new UniportError({
629
+ code: "RATE_LIMITED",
630
+ message: "Too many requests. Please wait a minute and try again.",
631
+ status: 429
632
+ });
633
+ }
580
634
  const detailMessage = extractDetailMessage(body.details);
581
635
  return new UniportError({
582
636
  code: body.code || fallback.code,
@@ -648,6 +702,22 @@ function formatDisplayAmount(amount, significantDigits = 6) {
648
702
  useGrouping: false
649
703
  }).format(num);
650
704
  }
705
+ function postHeaders(appId) {
706
+ const headers = { "Content-Type": "application/json" };
707
+ if (appId) headers["X-Uniport-App-Id"] = appId;
708
+ return headers;
709
+ }
710
+ var warnedAboutMissingAppId = false;
711
+ function warnIfAppIdMissing(appId) {
712
+ if (appId || warnedAboutMissingAppId || typeof window === "undefined") return;
713
+ const host = window.location?.hostname ?? "";
714
+ const local = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost");
715
+ if (local) return;
716
+ warnedAboutMissingAppId = true;
717
+ console.warn(
718
+ "Uniport: no appId is set. Without one the SDK only works on localhost. Create an App ID at https://uniport.dev/dashboard and pass it as the appId prop."
719
+ );
720
+ }
651
721
  async function getQuote(options) {
652
722
  const {
653
723
  originToken,
@@ -660,14 +730,15 @@ async function getQuote(options) {
660
730
  swapType = "EXACT_INPUT",
661
731
  deadline,
662
732
  dry = false,
663
- referral = "uniport",
664
733
  signal
665
734
  } = options;
666
735
  const amountInSmallestUnits = toSmallestUnits(
667
736
  amount,
668
737
  swapType === "EXACT_OUTPUT" ? destinationToken.decimals : originToken.decimals
669
738
  );
670
- const { backendUrl, requestTimeoutMs } = getUniportConfig();
739
+ const { backendUrl, requestTimeoutMs, appId: configuredAppId } = getUniportConfig();
740
+ const appId = checkAppId(options.appId) ?? configuredAppId;
741
+ warnIfAppIdMissing(appId);
671
742
  const { signal: requestSignal, cleanup, didTimeout } = createTimeoutSignal(
672
743
  requestTimeoutMs,
673
744
  signal
@@ -676,7 +747,7 @@ async function getQuote(options) {
676
747
  try {
677
748
  response = await fetch(`${backendUrl}/api/quote`, {
678
749
  method: "POST",
679
- headers: { "Content-Type": "application/json" },
750
+ headers: postHeaders(appId),
680
751
  signal: requestSignal,
681
752
  body: JSON.stringify({
682
753
  dry,
@@ -688,8 +759,7 @@ async function getQuote(options) {
688
759
  amount: amountInSmallestUnits,
689
760
  refundTo,
690
761
  recipient,
691
- deadline: deadline?.toISOString() || generateDeadline(1),
692
- referral
762
+ deadline: deadline?.toISOString() || generateDeadline(1)
693
763
  })
694
764
  });
695
765
  } catch (error) {
@@ -826,6 +896,7 @@ function normalizeError(error, fallback) {
826
896
  }
827
897
  function useUniportPayment(options) {
828
898
  const {
899
+ appId,
829
900
  recipient,
830
901
  refundAddress: initialRefundAddress,
831
902
  destinationToken,
@@ -834,6 +905,7 @@ function useUniportPayment(options) {
834
905
  onError
835
906
  } = options;
836
907
  const swapType = initialAmount === void 0 ? "EXACT_INPUT" : "EXACT_OUTPUT";
908
+ checkAppId(appId);
837
909
  const destToken = getToken(destinationToken);
838
910
  if (!destToken) {
839
911
  throw new Error(
@@ -868,6 +940,12 @@ function useUniportPayment(options) {
868
940
  }, []);
869
941
  const effectiveRefundAddress = swapType === "EXACT_OUTPUT" ? "" : refundAddress.trim() || (selectedChain && usesEvmAddress(selectedChain.id) ? evmDefaultRefundAddress : "");
870
942
  const pollingRef = react.useRef(null);
943
+ const callbacksRef = react.useRef({ onSuccess, onError });
944
+ react.useEffect(() => {
945
+ callbacksRef.current = { onSuccess, onError };
946
+ });
947
+ const pollPausedUntilRef = react.useRef(0);
948
+ const pollGenerationRef = react.useRef(0);
871
949
  const lastStatusRef = react.useRef(null);
872
950
  const previewDebounceRef = react.useRef(null);
873
951
  const previewAbortRef = react.useRef(null);
@@ -901,6 +979,7 @@ function useUniportPayment(options) {
901
979
  refundTo: nextRefundAddress,
902
980
  swapType,
903
981
  dry: true,
982
+ appId,
904
983
  signal: controller.signal
905
984
  });
906
985
  setPreviewQuote(result);
@@ -922,7 +1001,7 @@ function useUniportPayment(options) {
922
1001
  }
923
1002
  }, 250);
924
1003
  },
925
- [destToken, recipient, swapType]
1004
+ [appId, destToken, recipient, swapType]
926
1005
  );
927
1006
  const setAmount = react.useCallback(
928
1007
  (newAmount) => {
@@ -968,7 +1047,8 @@ function useUniportPayment(options) {
968
1047
  recipient,
969
1048
  refundTo: effectiveRefundAddress,
970
1049
  swapType,
971
- dry: false
1050
+ dry: false,
1051
+ appId
972
1052
  });
973
1053
  setQuote(result);
974
1054
  setPaymentState("awaiting_deposit");
@@ -985,9 +1065,11 @@ function useUniportPayment(options) {
985
1065
  recipient,
986
1066
  destToken,
987
1067
  swapType,
1068
+ appId,
988
1069
  onError
989
1070
  ]);
990
1071
  const stopPolling = react.useCallback(() => {
1072
+ pollGenerationRef.current += 1;
991
1073
  if (pollingRef.current) {
992
1074
  clearInterval(pollingRef.current);
993
1075
  pollingRef.current = null;
@@ -995,11 +1077,14 @@ function useUniportPayment(options) {
995
1077
  }, []);
996
1078
  const pollStatus = react.useCallback(async () => {
997
1079
  if (!quote?.depositAddress) return;
1080
+ if (Date.now() < pollPausedUntilRef.current) return;
1081
+ const generation = pollGenerationRef.current;
998
1082
  try {
999
1083
  const result = await getExecutionStatus(
1000
1084
  quote.depositAddress,
1001
1085
  quote.memo
1002
1086
  );
1087
+ if (generation !== pollGenerationRef.current) return;
1003
1088
  setStatus(result);
1004
1089
  if (result.status !== lastStatusRef.current) {
1005
1090
  lastStatusRef.current = result.status;
@@ -1008,9 +1093,12 @@ function useUniportPayment(options) {
1008
1093
  } else if (result.isSuccess) {
1009
1094
  setPaymentState("success");
1010
1095
  stopPolling();
1011
- onSuccess?.({
1096
+ callbacksRef.current.onSuccess?.({
1012
1097
  txHash: result.destinationTxHashes?.[0] || "",
1013
- amount: quote.amountOut
1098
+ amount: quote.amountOut,
1099
+ depositAddress: quote.depositAddress,
1100
+ depositMemo: quote.memo,
1101
+ correlationId: quote.correlationId
1014
1102
  });
1015
1103
  } else if (result.isComplete) {
1016
1104
  setPaymentState("error");
@@ -1019,13 +1107,15 @@ function useUniportPayment(options) {
1019
1107
  result.status === "REFUNDED" ? "Payment was refunded" : "Payment failed"
1020
1108
  );
1021
1109
  setError(err);
1022
- onError?.(err);
1110
+ callbacksRef.current.onError?.(err);
1023
1111
  }
1024
1112
  }
1025
1113
  } catch (err) {
1114
+ if (generation !== pollGenerationRef.current) return;
1115
+ if (isRateLimitError(err)) pollPausedUntilRef.current = Date.now() + 3e4;
1026
1116
  console.error("Status poll error:", err);
1027
1117
  }
1028
- }, [quote, onSuccess, onError, stopPolling]);
1118
+ }, [quote, stopPolling]);
1029
1119
  const startPolling = react.useCallback(() => {
1030
1120
  if (pollingRef.current) return;
1031
1121
  pollStatus();
@@ -1294,6 +1384,9 @@ function WarningTriangle({ color }) {
1294
1384
  ] });
1295
1385
  }
1296
1386
  function formatPreviewError(error) {
1387
+ if (isAppSetupError(error) || isRateLimitError(error)) {
1388
+ return error.message;
1389
+ }
1297
1390
  if (error.name === "AbortError") {
1298
1391
  return "Estimate request was cancelled. Try again.";
1299
1392
  }
@@ -1319,6 +1412,7 @@ function formatChainLabel(chainId) {
1319
1412
  return CHAINS[chainId]?.name ?? chainId.toUpperCase();
1320
1413
  }
1321
1414
  function UniportModal({
1415
+ appId,
1322
1416
  open,
1323
1417
  onClose,
1324
1418
  recipient,
@@ -1331,6 +1425,7 @@ function UniportModal({
1331
1425
  }) {
1332
1426
  const t = getTheme(themeMode);
1333
1427
  const payment = useUniportPayment({
1428
+ appId,
1334
1429
  recipient,
1335
1430
  refundAddress,
1336
1431
  destinationToken,
@@ -2253,6 +2348,7 @@ function getButtonStyle(variant, theme, disabled) {
2253
2348
  };
2254
2349
  }
2255
2350
  function UniportButton({
2351
+ appId,
2256
2352
  recipient,
2257
2353
  refundAddress,
2258
2354
  destinationToken,
@@ -2296,6 +2392,7 @@ function UniportButton({
2296
2392
  /* @__PURE__ */ jsxRuntime.jsx(
2297
2393
  UniportModal,
2298
2394
  {
2395
+ appId,
2299
2396
  open: isOpen,
2300
2397
  onClose: handleClose,
2301
2398
  recipient,