@ab-org/predicate-market-sdk 1.0.0 → 2.0.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.
Files changed (91) hide show
  1. package/dist/index.d.ts +706 -22
  2. package/dist/index.js +43009 -23
  3. package/package.json +11 -5
  4. package/dist/auth/autoReconnect.d.ts +0 -11
  5. package/dist/auth/autoReconnect.js +0 -36
  6. package/dist/auth/bundledConfig.d.ts +0 -2
  7. package/dist/auth/bundledConfig.js +0 -19
  8. package/dist/auth/config.d.ts +0 -29
  9. package/dist/auth/config.js +0 -53
  10. package/dist/auth/google.d.ts +0 -43
  11. package/dist/auth/google.js +0 -147
  12. package/dist/auth/oidcRelay.d.ts +0 -11
  13. package/dist/auth/oidcRelay.js +0 -107
  14. package/dist/auth/twitter.d.ts +0 -7
  15. package/dist/auth/twitter.js +0 -94
  16. package/dist/auth/walletAccount.d.ts +0 -20
  17. package/dist/auth/walletAccount.js +0 -267
  18. package/dist/constants/chains.d.ts +0 -2
  19. package/dist/constants/chains.js +0 -3
  20. package/dist/modules/api.d.ts +0 -149
  21. package/dist/modules/api.js +0 -95
  22. package/dist/modules/balanceQuery.d.ts +0 -27
  23. package/dist/modules/balanceQuery.js +0 -60
  24. package/dist/modules/deposit.d.ts +0 -31
  25. package/dist/modules/deposit.js +0 -58
  26. package/dist/modules/marketData.d.ts +0 -8
  27. package/dist/modules/marketData.js +0 -107
  28. package/dist/modules/withdraw.d.ts +0 -31
  29. package/dist/modules/withdraw.js +0 -61
  30. package/dist/modules/withdrawDirect.d.ts +0 -14
  31. package/dist/modules/withdrawDirect.js +0 -33
  32. package/dist/modules/withdrawExecutor.d.ts +0 -56
  33. package/dist/modules/withdrawExecutor.js +0 -210
  34. package/dist/policyAdapter.d.ts +0 -11
  35. package/dist/policyAdapter.js +0 -38
  36. package/dist/types.d.ts +0 -62
  37. package/dist/types.js +0 -1
  38. package/dist/ui/DepositModal.d.ts +0 -36
  39. package/dist/ui/DepositModal.js +0 -354
  40. package/dist/ui/SignInModal.d.ts +0 -22
  41. package/dist/ui/SignInModal.js +0 -77
  42. package/dist/ui/SignInModal.sections.d.ts +0 -33
  43. package/dist/ui/SignInModal.sections.js +0 -45
  44. package/dist/ui/SignInModal.shared.d.ts +0 -15
  45. package/dist/ui/SignInModal.shared.js +0 -126
  46. package/dist/ui/WalletSelectionModal.d.ts +0 -14
  47. package/dist/ui/WalletSelectionModal.js +0 -54
  48. package/dist/ui/WithdrawModal.d.ts +0 -57
  49. package/dist/ui/WithdrawModal.js +0 -574
  50. package/dist/ui/components/CloseButton.d.ts +0 -4
  51. package/dist/ui/components/CloseButton.js +0 -15
  52. package/dist/ui/components/Countdown.d.ts +0 -16
  53. package/dist/ui/components/Countdown.js +0 -42
  54. package/dist/ui/components/DepositDetailsPanel.d.ts +0 -8
  55. package/dist/ui/components/DepositDetailsPanel.js +0 -143
  56. package/dist/ui/components/DropdownField.d.ts +0 -19
  57. package/dist/ui/components/DropdownField.js +0 -81
  58. package/dist/ui/components/Field.d.ts +0 -10
  59. package/dist/ui/components/Field.js +0 -21
  60. package/dist/ui/components/LoginRequiredOverlay.d.ts +0 -6
  61. package/dist/ui/components/LoginRequiredOverlay.js +0 -31
  62. package/dist/ui/components/ModalCard.d.ts +0 -9
  63. package/dist/ui/components/ModalCard.js +0 -14
  64. package/dist/ui/components/ModalFrame.d.ts +0 -9
  65. package/dist/ui/components/ModalFrame.js +0 -18
  66. package/dist/ui/components/PrimaryButton.d.ts +0 -2
  67. package/dist/ui/components/PrimaryButton.js +0 -14
  68. package/dist/ui/components/QRCodePanel.d.ts +0 -4
  69. package/dist/ui/components/QRCodePanel.js +0 -43
  70. package/dist/ui/components/Select.d.ts +0 -12
  71. package/dist/ui/components/Select.js +0 -29
  72. package/dist/ui/components/StepIndicator.d.ts +0 -7
  73. package/dist/ui/components/StepIndicator.js +0 -35
  74. package/dist/ui/components/Success.d.ts +0 -1
  75. package/dist/ui/components/Success.js +0 -4
  76. package/dist/ui/components/Toast.d.ts +0 -8
  77. package/dist/ui/components/Toast.js +0 -51
  78. package/dist/ui/hooks/useSession.d.ts +0 -2
  79. package/dist/ui/hooks/useSession.js +0 -10
  80. package/dist/ui/signInTypes.d.ts +0 -28
  81. package/dist/ui/signInTypes.js +0 -1
  82. package/dist/ui/theme.d.ts +0 -31
  83. package/dist/ui/theme.js +0 -31
  84. package/dist/ui/useSignInModalController.d.ts +0 -25
  85. package/dist/ui/useSignInModalController.js +0 -119
  86. package/dist/utils/env.d.ts +0 -1
  87. package/dist/utils/env.js +0 -63
  88. package/dist/utils/explorer.d.ts +0 -3
  89. package/dist/utils/explorer.js +0 -47
  90. package/dist/walletUtils.d.ts +0 -3
  91. package/dist/walletUtils.js +0 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ab-org/predicate-market-sdk",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist/**/*",
@@ -23,8 +23,7 @@
23
23
  "@cubist-labs/cubesigner-sdk": "^0.4.219",
24
24
  "axios": "^1.13.6",
25
25
  "qrcode-generator": "^2.0.4",
26
- "@ab-org/wallet-utils": "0.0.7",
27
- "@ab-org/sdk-core": "0.1.0"
26
+ "@ab-org/sdk-core": "0.1.1"
28
27
  },
29
28
  "peerDependencies": {
30
29
  "react": ">=18",
@@ -33,10 +32,17 @@
33
32
  "devDependencies": {
34
33
  "@types/react": "^18.2.66",
35
34
  "typescript": "^5.5.4",
36
- "viem": "2.21.54"
35
+ "viem": "2.21.54",
36
+ "tsup": "^8.5.1",
37
+ "@ab-org/chains-service": "0.0.8",
38
+ "@ab-org/cubist-wallet-sdk": "0.0.9",
39
+ "@ab-org/sign-in-sdk": "0.1.0",
40
+ "@ab-org/social-account-sdk": "0.0.10",
41
+ "@ab-org/wallet-utils": "0.0.7",
42
+ "@ab-org/oidc-auth": "0.0.16"
37
43
  },
38
44
  "scripts": {
39
- "build": "tsc -p tsconfig.json",
45
+ "build": "tsup",
40
46
  "lint": "eslint 'src/**/*.{ts,tsx}'",
41
47
  "test": "vitest run --passWithNoTests"
42
48
  }
@@ -1,11 +0,0 @@
1
- import { type WalletSession } from "@ab-org/sdk-core";
2
- /**
3
- * Attempt to silently reconnect a wallet whose session was restored
4
- * from localStorage cache. Creates a temporary `WalletConnector` with
5
- * the default adapter registry (injected wallets + Cubist if configured)
6
- * and delegates to `WalletConnector.tryAutoReconnect()`.
7
- *
8
- * Safe to call multiple times — concurrent calls share the same promise.
9
- * Returns the fresh session on success, or `null` if reconnection failed.
10
- */
11
- export declare function tryAutoReconnect(): Promise<WalletSession | null>;
@@ -1,36 +0,0 @@
1
- import { sessionStore, WalletConnector, createDefaultInjectedWalletRegistry, CubistSocialProvider, } from "@ab-org/sdk-core";
2
- import { getSDKConfig } from "./config.js";
3
- let pending = null;
4
- /**
5
- * Attempt to silently reconnect a wallet whose session was restored
6
- * from localStorage cache. Creates a temporary `WalletConnector` with
7
- * the default adapter registry (injected wallets + Cubist if configured)
8
- * and delegates to `WalletConnector.tryAutoReconnect()`.
9
- *
10
- * Safe to call multiple times — concurrent calls share the same promise.
11
- * Returns the fresh session on success, or `null` if reconnection failed.
12
- */
13
- export function tryAutoReconnect() {
14
- const session = sessionStore.getState().session;
15
- if (!session)
16
- return Promise.resolve(null);
17
- if (pending)
18
- return pending;
19
- pending = doAutoReconnect().finally(() => {
20
- pending = null;
21
- });
22
- return pending;
23
- }
24
- async function doAutoReconnect() {
25
- const config = getSDKConfig();
26
- const registry = createDefaultInjectedWalletRegistry();
27
- const adapters = [...registry.map((r) => r.provider)];
28
- if (config.cubeSigner) {
29
- adapters.push(new CubistSocialProvider({
30
- ...config.cubeSigner,
31
- defaultSessionPolicy: config.signIn?.sessionPolicy ?? config.cubeSigner.defaultSessionPolicy,
32
- }));
33
- }
34
- const connector = new WalletConnector(adapters);
35
- return connector.tryAutoReconnect();
36
- }
@@ -1,2 +0,0 @@
1
- import type { SDKConfig } from "./config.js";
2
- export declare const BUNDLED_AUTH_CONFIG: Partial<SDKConfig>;
@@ -1,19 +0,0 @@
1
- import { getEnv } from "../utils/env.js";
2
- function readOptionalEnv(key) {
3
- const value = getEnv(key);
4
- return value === "" ? undefined : value;
5
- }
6
- const relayOrigin = readOptionalEnv("RELAY_ORIGIN");
7
- const cubeEnv = readOptionalEnv("CUBE_SIGNER_ENV");
8
- const cubeOrgId = readOptionalEnv("CUBE_SIGNER_ORG_ID");
9
- export const BUNDLED_AUTH_CONFIG = {
10
- googleClientId: readOptionalEnv("GOOGLE_CLIENT_ID"),
11
- twitterClientId: readOptionalEnv("X_CLIENT_ID"),
12
- twitterRedirectUri: relayOrigin ? `${relayOrigin}/auth/twitter-callback` : undefined,
13
- cubeSigner: cubeEnv && cubeOrgId
14
- ? {
15
- env: cubeEnv,
16
- orgId: cubeOrgId,
17
- }
18
- : undefined,
19
- };
@@ -1,29 +0,0 @@
1
- import type { CubeSignerConfig } from "@ab-org/sdk-core";
2
- import type { SignInUiConfig } from "../ui/signInTypes.js";
3
- export interface SDKConfig {
4
- googleClientId?: string;
5
- twitterClientId?: string;
6
- twitterRedirectUri?: string;
7
- cubeSigner?: CubeSignerConfig;
8
- signIn?: SignInUiConfig;
9
- }
10
- /**
11
- * Fixed auth config: built-in bundled defaults (see bundledConfig.ts) with optional
12
- * overrides from environment (server / `NEXT_PUBLIC_*` client). Used as defaults in initSDK.
13
- */
14
- export declare function getFixedAuthConfig(): Partial<SDKConfig>;
15
- /**
16
- * Config for initializing the predicate SDK. Defaults come from bundled config
17
- * (and env overrides); you may override any of them here. Optional top-level
18
- * `registerUser` is merged into `cubeSigner.oidcLoginHooks` when cubeSigner is present.
19
- */
20
- export interface PredicateSDKConfig extends Partial<SDKConfig> {
21
- /**
22
- * Optional hook to register the user on your backend when CubeSigner proof
23
- * indicates the user is not initialized. Used when cubeSigner is available
24
- * (from env or override).
25
- */
26
- registerUser?: (oidcToken: string) => Promise<void>;
27
- }
28
- export declare function initSDK(config?: PredicateSDKConfig): void;
29
- export declare function getSDKConfig(): Readonly<SDKConfig>;
@@ -1,53 +0,0 @@
1
- import { getEnv } from "../utils/env.js";
2
- import { BUNDLED_AUTH_CONFIG } from "./bundledConfig.js";
3
- import { tryAutoReconnect } from "./autoReconnect.js";
4
- let sdkConfig = {};
5
- function readOptionalEnv(key) {
6
- const value = getEnv(key);
7
- return value === "" ? undefined : value;
8
- }
9
- /**
10
- * Fixed auth config: built-in bundled defaults (see bundledConfig.ts) with optional
11
- * overrides from environment (server / `NEXT_PUBLIC_*` client). Used as defaults in initSDK.
12
- */
13
- export function getFixedAuthConfig() {
14
- const envGoogle = readOptionalEnv("GOOGLE_CLIENT_ID");
15
- const envTwitter = readOptionalEnv("X_CLIENT_ID");
16
- const relayOrigin = readOptionalEnv("RELAY_ORIGIN");
17
- const envRedirect = relayOrigin ? `${relayOrigin}/auth/twitter-callback` : undefined;
18
- const cubeEnv = readOptionalEnv("CUBE_SIGNER_ENV");
19
- const cubeOrgId = readOptionalEnv("CUBE_SIGNER_ORG_ID");
20
- const cubeSignerFromEnv = cubeEnv && cubeOrgId
21
- ? { env: cubeEnv, orgId: cubeOrgId }
22
- : undefined;
23
- return {
24
- googleClientId: envGoogle || BUNDLED_AUTH_CONFIG.googleClientId,
25
- twitterClientId: envTwitter || BUNDLED_AUTH_CONFIG.twitterClientId,
26
- twitterRedirectUri: envRedirect || BUNDLED_AUTH_CONFIG.twitterRedirectUri,
27
- cubeSigner: cubeSignerFromEnv ?? BUNDLED_AUTH_CONFIG.cubeSigner,
28
- };
29
- }
30
- export function initSDK(config = {}) {
31
- const { registerUser, ...rest } = config;
32
- const fixed = getFixedAuthConfig();
33
- const merged = {
34
- ...sdkConfig,
35
- ...fixed,
36
- ...rest,
37
- cubeSigner: rest.cubeSigner ?? fixed.cubeSigner,
38
- };
39
- if (registerUser != null && merged.cubeSigner) {
40
- merged.cubeSigner = {
41
- ...merged.cubeSigner,
42
- oidcLoginHooks: {
43
- ...merged.cubeSigner.oidcLoginHooks,
44
- registerUser,
45
- },
46
- };
47
- }
48
- sdkConfig = merged;
49
- tryAutoReconnect().catch(() => { });
50
- }
51
- export function getSDKConfig() {
52
- return sdkConfig;
53
- }
@@ -1,43 +0,0 @@
1
- declare global {
2
- interface Window {
3
- google?: {
4
- accounts: {
5
- id: {
6
- initialize(config: GISInitConfig): void;
7
- prompt(momentListener?: (notification: GISPromptMoment) => void): void;
8
- renderButton(parent: HTMLElement, options: GISButtonConfig): void;
9
- revoke(hint: string, callback?: () => void): void;
10
- };
11
- };
12
- };
13
- }
14
- }
15
- interface GISInitConfig {
16
- client_id: string;
17
- callback: (response: GISCredentialResponse) => void;
18
- auto_select?: boolean;
19
- cancel_on_tap_outside?: boolean;
20
- use_fedcm_for_prompt?: boolean;
21
- }
22
- interface GISCredentialResponse {
23
- credential: string;
24
- }
25
- interface GISPromptMoment {
26
- isSkippedMoment(): boolean;
27
- isDismissedMoment(): boolean;
28
- isNotDisplayed(): boolean;
29
- getDismissedReason(): string;
30
- }
31
- interface GISButtonConfig {
32
- type?: "standard" | "icon";
33
- size?: "large" | "medium" | "small";
34
- }
35
- export interface GoogleCredential {
36
- idToken: string;
37
- email?: string;
38
- name?: string;
39
- picture?: string;
40
- }
41
- export declare function isFedCMSupported(): boolean;
42
- export declare function signInWithGoogle(clientId: string): Promise<GoogleCredential>;
43
- export {};
@@ -1,147 +0,0 @@
1
- const GIS_URL = "https://accounts.google.com/gsi/client";
2
- let loadPromise = null;
3
- let currentCredentialHandler = null;
4
- let initializedKey = null;
5
- function loadGIS() {
6
- if (loadPromise)
7
- return loadPromise;
8
- if (window.google?.accounts?.id) {
9
- loadPromise = Promise.resolve();
10
- return loadPromise;
11
- }
12
- loadPromise = new Promise((resolve, reject) => {
13
- const script = document.createElement("script");
14
- script.src = GIS_URL;
15
- script.async = true;
16
- script.defer = true;
17
- script.onload = () => resolve();
18
- script.onerror = () => reject(new Error("Failed to load Google Identity Services"));
19
- document.head.appendChild(script);
20
- });
21
- return loadPromise;
22
- }
23
- function decodeJwtPayload(token) {
24
- const parts = token.split(".");
25
- if (parts.length !== 3)
26
- throw new Error("Invalid JWT");
27
- const payload = parts[1];
28
- if (!payload)
29
- throw new Error("Invalid JWT payload");
30
- let padded = payload.replace(/-/g, "+").replace(/_/g, "/");
31
- while (padded.length % 4 !== 0)
32
- padded += "=";
33
- return JSON.parse(atob(padded));
34
- }
35
- export function isFedCMSupported() {
36
- if (typeof window === "undefined" || typeof navigator === "undefined")
37
- return false;
38
- if (!window.isSecureContext)
39
- return false;
40
- return typeof navigator.credentials?.get === "function";
41
- }
42
- export async function signInWithGoogle(clientId) {
43
- await loadGIS();
44
- const gid = window.google?.accounts?.id;
45
- if (!gid)
46
- throw new Error("Google Identity Services not available");
47
- const SIGN_IN_TIMEOUT_MS = 90000;
48
- return new Promise((resolve, reject) => {
49
- let settled = false;
50
- let fallbackContainer = null;
51
- const cleanupFallback = () => {
52
- if (!fallbackContainer)
53
- return;
54
- fallbackContainer.remove();
55
- fallbackContainer = null;
56
- };
57
- const finish = (fn) => {
58
- if (settled)
59
- return;
60
- settled = true;
61
- clearTimeout(timeoutId);
62
- cleanupFallback();
63
- fn();
64
- };
65
- const timeoutId = setTimeout(() => {
66
- finish(() => reject(new Error("Google sign-in timed out")));
67
- }, SIGN_IN_TIMEOUT_MS);
68
- const handleCredential = (response) => {
69
- finish(() => {
70
- try {
71
- const payload = decodeJwtPayload(response.credential);
72
- resolve({
73
- idToken: response.credential,
74
- email: payload.email,
75
- name: payload.name,
76
- picture: payload.picture,
77
- });
78
- }
79
- catch {
80
- resolve({ idToken: response.credential });
81
- }
82
- });
83
- };
84
- const useFedcmForPrompt = isFedCMSupported();
85
- const initKey = `${clientId}\0${useFedcmForPrompt ? "1" : "0"}`;
86
- currentCredentialHandler = handleCredential;
87
- if (initializedKey !== initKey) {
88
- initializedKey = initKey;
89
- gid.initialize({
90
- client_id: clientId,
91
- callback: (response) => currentCredentialHandler?.(response),
92
- auto_select: false,
93
- cancel_on_tap_outside: true,
94
- use_fedcm_for_prompt: useFedcmForPrompt,
95
- });
96
- }
97
- const triggerFallback = () => {
98
- if (settled)
99
- return;
100
- fallbackContainer = document.createElement("div");
101
- Object.assign(fallbackContainer.style, {
102
- position: "fixed",
103
- top: "-9999px",
104
- left: "-9999px",
105
- opacity: "0",
106
- pointerEvents: "none",
107
- });
108
- document.body.appendChild(fallbackContainer);
109
- gid.renderButton(fallbackContainer, { type: "standard", size: "large" });
110
- const tryClickButton = (attemptsLeft) => {
111
- requestAnimationFrame(() => {
112
- const btn = fallbackContainer?.querySelector('[role="button"]') ??
113
- fallbackContainer?.querySelector("div[style]");
114
- if (btn) {
115
- Object.assign(fallbackContainer.style, { pointerEvents: "auto" });
116
- btn.click();
117
- return;
118
- }
119
- if (attemptsLeft > 0) {
120
- tryClickButton(attemptsLeft - 1);
121
- return;
122
- }
123
- finish(() => reject(new Error("Google sign-in unavailable")));
124
- });
125
- };
126
- tryClickButton(8);
127
- };
128
- gid.prompt((moment) => {
129
- if (settled)
130
- return;
131
- if (moment.isDismissedMoment()) {
132
- const reason = moment.getDismissedReason();
133
- if (reason === "credential_returned")
134
- return;
135
- finish(() => reject(new Error(`Google sign-in dismissed: ${reason}`)));
136
- return;
137
- }
138
- if (moment.isSkippedMoment()) {
139
- triggerFallback();
140
- return;
141
- }
142
- if (moment.isNotDisplayed()) {
143
- triggerFallback();
144
- }
145
- });
146
- });
147
- }
@@ -1,11 +0,0 @@
1
- export type OidcRelayStage = "dev" | "prod";
2
- interface CreateOidcRelayAuthOptions {
3
- stage: OidcRelayStage;
4
- googleClientId: string;
5
- xClientId: string;
6
- }
7
- export declare function createOidcRelayAuth({ stage, googleClientId, xClientId, }: CreateOidcRelayAuthOptions): {
8
- loginByGoogle(): Promise<string>;
9
- loginByX(): Promise<string>;
10
- };
11
- export {};
@@ -1,107 +0,0 @@
1
- import { getEnv } from "../utils/env.js";
2
- function getRelayOrigin() {
3
- if (typeof window === "undefined") {
4
- throw new Error("OIDC relay requires a browser environment");
5
- }
6
- if (window.location.hostname === "localhost") {
7
- return window.location.origin;
8
- }
9
- const relayOrigin = getEnv("RELAY_ORIGIN");
10
- if (!relayOrigin) {
11
- throw new Error("RELAY_ORIGIN is not configured");
12
- }
13
- return relayOrigin;
14
- }
15
- function openRelayWindow(url, name) {
16
- const width = 420;
17
- const height = 640;
18
- const top = (window.innerHeight - height) / 2 + window.screenY;
19
- const left = (window.innerWidth - width) / 2 + window.screenX;
20
- return window.open(url, name, `dialog=yes,top=${top}px,left=${left}px,width=${width}px,height=${height}px`);
21
- }
22
- function waitForOidcToken(popup, relayOrigin, timeoutMs = 120000) {
23
- return new Promise((resolve, reject) => {
24
- if (!popup) {
25
- reject(new Error("Failed to open login popup"));
26
- return;
27
- }
28
- let settled = false;
29
- const cleanup = () => {
30
- clearTimeout(timeout);
31
- clearInterval(closedCheck);
32
- window.removeEventListener("message", onMessage);
33
- };
34
- const finish = (fn) => {
35
- if (settled)
36
- return;
37
- settled = true;
38
- cleanup();
39
- fn();
40
- };
41
- const timeout = window.setTimeout(() => {
42
- try {
43
- popup.close();
44
- }
45
- catch {
46
- // Ignore popup close errors on timeout.
47
- }
48
- finish(() => reject(new Error("Login timeout")));
49
- }, timeoutMs);
50
- const onMessage = (event) => {
51
- if (event.origin !== relayOrigin)
52
- return;
53
- if (event.data?.action !== "login")
54
- return;
55
- const payload = (event.data?.data ?? {});
56
- if (payload.error) {
57
- try {
58
- popup.close();
59
- }
60
- catch {
61
- // Ignore popup close errors after relay failure.
62
- }
63
- finish(() => reject(new Error(String(payload.error))));
64
- return;
65
- }
66
- if (payload.oidcToken) {
67
- try {
68
- popup.close();
69
- }
70
- catch {
71
- // Ignore popup close errors after success.
72
- }
73
- finish(() => resolve(payload.oidcToken));
74
- }
75
- };
76
- const closedCheck = window.setInterval(() => {
77
- if (popup.closed) {
78
- finish(() => reject(new Error("Login cancelled by user")));
79
- }
80
- }, 400);
81
- window.addEventListener("message", onMessage);
82
- });
83
- }
84
- export function createOidcRelayAuth({ stage, googleClientId, xClientId, }) {
85
- const relayOrigin = getRelayOrigin();
86
- const buildUrl = (provider, clientId) => {
87
- const target = window.location.origin;
88
- const params = new URLSearchParams({
89
- target,
90
- stage,
91
- eventId: Date.now().toString(),
92
- action: "login",
93
- clientId,
94
- });
95
- return `${relayOrigin}/relay/${provider}?${params.toString()}`;
96
- };
97
- return {
98
- async loginByGoogle() {
99
- const popup = openRelayWindow(buildUrl("google", googleClientId), "Google login");
100
- return waitForOidcToken(popup, relayOrigin);
101
- },
102
- async loginByX() {
103
- const popup = openRelayWindow(buildUrl("x", xClientId), "X login");
104
- return waitForOidcToken(popup, relayOrigin);
105
- },
106
- };
107
- }
@@ -1,7 +0,0 @@
1
- export interface TwitterAuthResult {
2
- code: string;
3
- codeVerifier: string;
4
- state: string;
5
- }
6
- export declare function notifyTwitterCallback(): void;
7
- export declare function signInWithTwitter(clientId: string, redirectUri: string): Promise<TwitterAuthResult>;
@@ -1,94 +0,0 @@
1
- function generateRandom(length) {
2
- const array = new Uint8Array(length);
3
- crypto.getRandomValues(array);
4
- return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
5
- }
6
- function base64url(buffer) {
7
- const bytes = new Uint8Array(buffer);
8
- let binary = "";
9
- for (const b of bytes)
10
- binary += String.fromCharCode(b);
11
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
- }
13
- async function createCodeChallenge(verifier) {
14
- const encoder = new TextEncoder();
15
- const data = encoder.encode(verifier);
16
- const digest = await crypto.subtle.digest("SHA-256", data);
17
- return base64url(digest);
18
- }
19
- const POPUP_WIDTH = 600;
20
- const POPUP_HEIGHT = 700;
21
- const MESSAGE_TYPE = "twitter-oauth-callback";
22
- const TWITTER_AUTH_URL = "https://twitter.com/i/oauth2/authorize";
23
- export function notifyTwitterCallback() {
24
- const params = new URLSearchParams(window.location.search);
25
- const code = params.get("code");
26
- const state = params.get("state");
27
- const error = params.get("error");
28
- if (window.opener) {
29
- window.opener.postMessage({ type: MESSAGE_TYPE, code, state, error }, window.location.origin);
30
- window.close();
31
- }
32
- }
33
- export async function signInWithTwitter(clientId, redirectUri) {
34
- const codeVerifier = generateRandom(64);
35
- const codeChallenge = await createCodeChallenge(codeVerifier);
36
- const state = generateRandom(16);
37
- const authUrl = new URL(TWITTER_AUTH_URL);
38
- authUrl.searchParams.set("response_type", "code");
39
- authUrl.searchParams.set("client_id", clientId);
40
- authUrl.searchParams.set("redirect_uri", redirectUri);
41
- authUrl.searchParams.set("scope", "tweet.read users.read offline.access");
42
- authUrl.searchParams.set("state", state);
43
- authUrl.searchParams.set("code_challenge", codeChallenge);
44
- authUrl.searchParams.set("code_challenge_method", "S256");
45
- const left = Math.round(screen.width / 2 - POPUP_WIDTH / 2);
46
- const top = Math.round(screen.height / 2 - POPUP_HEIGHT / 2);
47
- const popup = window.open(authUrl.toString(), "twitter-auth", `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},toolbar=no,menubar=no`);
48
- if (!popup) {
49
- throw new Error("Failed to open Twitter login popup. Check your popup blocker.");
50
- }
51
- return new Promise((resolve, reject) => {
52
- let settled = false;
53
- const cleanup = () => {
54
- window.removeEventListener("message", onMessage);
55
- clearInterval(pollTimer);
56
- };
57
- const onMessage = (event) => {
58
- if (event.origin !== window.location.origin)
59
- return;
60
- const data = event.data;
61
- if (!data || data.type !== MESSAGE_TYPE)
62
- return;
63
- if (settled)
64
- return;
65
- settled = true;
66
- cleanup();
67
- if (data.error) {
68
- reject(new Error(`Twitter auth error: ${data.error}`));
69
- return;
70
- }
71
- if (!data.code) {
72
- reject(new Error("No authorization code received from Twitter"));
73
- return;
74
- }
75
- if (data.state !== state) {
76
- reject(new Error("State mismatch - possible CSRF attack"));
77
- return;
78
- }
79
- resolve({
80
- code: data.code,
81
- codeVerifier,
82
- state,
83
- });
84
- };
85
- const pollTimer = setInterval(() => {
86
- if (popup.closed && !settled) {
87
- settled = true;
88
- cleanup();
89
- reject(new Error("Twitter login popup was closed"));
90
- }
91
- }, 500);
92
- window.addEventListener("message", onMessage);
93
- });
94
- }
@@ -1,20 +0,0 @@
1
- import { type CubeSignerConfig, type CubeSignerSession, type WalletAuthSource, type WalletProvider, type WalletProviderRequest, type WalletSession } from "@ab-org/sdk-core";
2
- export declare class EmbeddedWalletAccountProvider implements WalletProvider {
3
- private readonly provider;
4
- constructor(provider: WalletProvider);
5
- request<T = unknown>(payload: WalletProviderRequest): Promise<T>;
6
- disconnect(): Promise<void>;
7
- eth_accounts(): Promise<string[]>;
8
- eth_chainId(): Promise<string>;
9
- }
10
- export default class WalletAccount {
11
- private static instance;
12
- private static instanceToken;
13
- private static walletSession;
14
- private static cubeSignerSession;
15
- static clearInstance(): void;
16
- static getWalletSession(): WalletSession | null;
17
- static getCubeSignerSession(): CubeSignerSession | null;
18
- static getInstance(oidcToken: string, authSource: WalletAuthSource, cubeSignerConfig: CubeSignerConfig): Promise<EmbeddedWalletAccountProvider>;
19
- }
20
- export declare function clearSocialAccountInstance(): void;