@fibo-crypto/react-sdk 0.3.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/LICENSE +21 -0
- package/README.md +312 -0
- package/dist/chunk-FRD4NVYJ.js +109 -0
- package/dist/chunk-FRD4NVYJ.js.map +1 -0
- package/dist/client.d.ts +284 -0
- package/dist/client.js +3 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +189 -0
- package/dist/index.js +407 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fibo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
# `@fibo-crypto/react-sdk`
|
|
2
|
+
|
|
3
|
+
React SDK for [Fibo SaaS](https://docs.fibo-crypto.fr) — non-custodial crypto infrastructure for B2B platforms. Wraps the [Fibo REST API](https://docs.fibo-crypto.fr/docs/api-reference/introduction) and the underlying [Privy](https://privy.io) embedded-wallet provider so integrators get a single dependency to install.
|
|
4
|
+
|
|
5
|
+
Status: **PoC v0.3**. Provides `FiboProvider`, `useFiboApi`, `useFiboAuth`, `useFiboWallet` (EVM + Solana + Bitcoin), `useFiboBalance`, `useFiboTransactions`, `useFiboSwap` (EVM same-chain + cross-chain via Biconomy MEE). Higher-level write-flows for `useFiboTransfer` + `useFiboYield` ship in v0.4+.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
# During pre-release: install from the tarball produced by `npm run pack:tgz`
|
|
11
|
+
npm install <path-to-fibo-react-sdk-0.1.0.tgz> --legacy-peer-deps
|
|
12
|
+
|
|
13
|
+
# Once published to public npm (post-M5):
|
|
14
|
+
npm install @fibo-crypto/react-sdk --legacy-peer-deps
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
> **Note — `--legacy-peer-deps` flag**: Privy v3 declares optional peer dependencies (`@abstract-foundation/agw-client`, `@solana/kit`, `permissionless`, etc.) that npm 7+ may surface as `ERESOLVE` errors. If your install fails, retry with `--legacy-peer-deps`. A future SDK release will pin compatible versions in `overrides` so the flag is no longer needed.
|
|
18
|
+
|
|
19
|
+
Peer deps: `react ^18 || ^19`, `react-dom ^18 || ^19`. The Privy SDK comes as a transitive dependency (per [ADR 0003](https://github.com/vigimani/fibo-saas/blob/main/docs/adr/0003-privy-as-transitive-dep-in-sdk.md)) — you don't install it separately.
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import { FiboProvider } from '@fibo-crypto/react-sdk';
|
|
25
|
+
|
|
26
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
27
|
+
return (
|
|
28
|
+
<FiboProvider
|
|
29
|
+
publishableKey={process.env.NEXT_PUBLIC_FIBO_PUBLISHABLE_KEY!}
|
|
30
|
+
externalUserId={session?.user?.id}
|
|
31
|
+
loginMethods={['email', 'passkey']}
|
|
32
|
+
theme={{ accent: '#5B44F9' }}
|
|
33
|
+
>
|
|
34
|
+
{children}
|
|
35
|
+
</FiboProvider>
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`publishableKey` is your `pk_test_*` / `pk_live_*` from the Fibo dashboard (or via `fibo keys mint` from the CLI). Never embed an `sk_*` in your frontend bundle.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### `useFiboAuth()`
|
|
45
|
+
|
|
46
|
+
Privy's auth state surfaced through Fibo's interface — login/logout, ready state, current user.
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
import { useFiboAuth } from '@fibo-crypto/react-sdk';
|
|
50
|
+
|
|
51
|
+
function LoginCard() {
|
|
52
|
+
const { isReady, isAuthenticated, user, login, logout } = useFiboAuth();
|
|
53
|
+
|
|
54
|
+
if (!isReady) return null;
|
|
55
|
+
if (!isAuthenticated) return <button onClick={login}>Sign in</button>;
|
|
56
|
+
return (
|
|
57
|
+
<div>
|
|
58
|
+
<p>Hello, {user?.email}</p>
|
|
59
|
+
<button onClick={logout}>Sign out</button>
|
|
60
|
+
</div>
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### `useFiboWallet()`
|
|
66
|
+
|
|
67
|
+
Reads the user's embedded wallet addresses across **EVM + Solana + Bitcoin**. EVM and Solana are auto-provisioned by `FiboProvider` on the first login; Bitcoin requires an explicit creation step (`createBitcoinWallet()`).
|
|
68
|
+
|
|
69
|
+
```tsx
|
|
70
|
+
import { useFiboWallet } from '@fibo-crypto/react-sdk';
|
|
71
|
+
|
|
72
|
+
function WalletAddresses() {
|
|
73
|
+
const {
|
|
74
|
+
isReady,
|
|
75
|
+
addresses,
|
|
76
|
+
bitcoinWallets,
|
|
77
|
+
createBitcoinWallet,
|
|
78
|
+
} = useFiboWallet();
|
|
79
|
+
|
|
80
|
+
if (!isReady) return <p>Loading…</p>;
|
|
81
|
+
return (
|
|
82
|
+
<ul>
|
|
83
|
+
<li>EVM: {addresses.evm ?? '—'}</li>
|
|
84
|
+
<li>Solana: {addresses.solana ?? '—'}</li>
|
|
85
|
+
<li>
|
|
86
|
+
Bitcoin: {addresses.bitcoin ?? (
|
|
87
|
+
<button onClick={() => createBitcoinWallet()}>Create BTC wallet</button>
|
|
88
|
+
)}
|
|
89
|
+
</li>
|
|
90
|
+
</ul>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
For raw PSBT signing on Bitcoin (transfers / swaps), use Privy's `@privy-io/react-auth/extended-chains` `useSignRawHash` hook directly — wire it into `@scure/btc-signer` PSBT inputs. A higher-level `useFiboBitcoinSwap` hook lands in v0.4.
|
|
96
|
+
|
|
97
|
+
### `useFiboBalance(address, opts?)`
|
|
98
|
+
|
|
99
|
+
Fetches the on-chain balance for an EVM address. Pass `null` for `address` while you wait for a wallet to be ready. Optional `refreshIntervalMs` enables polling.
|
|
100
|
+
|
|
101
|
+
```tsx
|
|
102
|
+
import { useFiboWallet, useFiboBalance } from '@fibo-crypto/react-sdk';
|
|
103
|
+
|
|
104
|
+
function BalanceBadge() {
|
|
105
|
+
const { addresses } = useFiboWallet();
|
|
106
|
+
const { balance, isLoading, error, refetch } = useFiboBalance(
|
|
107
|
+
addresses.evm,
|
|
108
|
+
{ refreshIntervalMs: 10_000 }, // poll every 10s
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
if (isLoading) return <span>Loading…</span>;
|
|
112
|
+
if (error) return <span>Error: {error.message}</span>;
|
|
113
|
+
return <span>{balance?.usdc.formatted ?? '—'} USDC</span>;
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### `useFiboSwap()`
|
|
118
|
+
|
|
119
|
+
Quote → sign → submit ceremony for cross-chain (and same-chain) swaps via Biconomy MEE. The hook handles the full EIP-7702 authorization flow + MEE quote signing under the hood — Privy renders the signature UI.
|
|
120
|
+
|
|
121
|
+
```tsx
|
|
122
|
+
import { useFiboSwap, useFiboWallet } from '@fibo-crypto/react-sdk';
|
|
123
|
+
|
|
124
|
+
function SwapButton() {
|
|
125
|
+
const { addresses } = useFiboWallet();
|
|
126
|
+
const {
|
|
127
|
+
quote,
|
|
128
|
+
executeSwap,
|
|
129
|
+
currentQuote,
|
|
130
|
+
expiresInSeconds,
|
|
131
|
+
isExpired,
|
|
132
|
+
isLoading,
|
|
133
|
+
phase,
|
|
134
|
+
error,
|
|
135
|
+
result,
|
|
136
|
+
reset,
|
|
137
|
+
} = useFiboSwap();
|
|
138
|
+
|
|
139
|
+
// 1. Get a quote (user picks amount via your UI)
|
|
140
|
+
async function onQuote() {
|
|
141
|
+
await quote({
|
|
142
|
+
source: { token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', chainId: 8453, amount: '5' }, // 5 USDC
|
|
143
|
+
destination: { token: '0x0000000000000000000000000000000000000000', chainId: 8453 }, // ETH
|
|
144
|
+
// userAddress auto-resolved from useFiboWallet().addresses.evm
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 2. Execute (user clicks confirm)
|
|
149
|
+
async function onExecute() {
|
|
150
|
+
const exec = await executeSwap();
|
|
151
|
+
console.log('MEE super hash:', exec.super_hash);
|
|
152
|
+
console.log('Tracker:', exec.tracker_url);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 3. Allow re-quoting after success or error
|
|
156
|
+
const isDone = phase === 'done' || phase === 'error';
|
|
157
|
+
|
|
158
|
+
return (
|
|
159
|
+
<div>
|
|
160
|
+
<button onClick={onQuote} disabled={isLoading}>Get quote</button>
|
|
161
|
+
{currentQuote && phase !== 'done' && (
|
|
162
|
+
<>
|
|
163
|
+
<p>You receive ~{currentQuote.breakdown.destination.amount} (expires {expiresInSeconds}s)</p>
|
|
164
|
+
<button onClick={onExecute} disabled={isExpired || isLoading}>
|
|
165
|
+
{isLoading ? phase : 'Execute swap'}
|
|
166
|
+
</button>
|
|
167
|
+
</>
|
|
168
|
+
)}
|
|
169
|
+
{error && <p>Error: {error.message}</p>}
|
|
170
|
+
{result && (
|
|
171
|
+
<>
|
|
172
|
+
<p>Submitted ✓ super_hash={result.super_hash}</p>
|
|
173
|
+
<button onClick={reset}>New swap</button>
|
|
174
|
+
</>
|
|
175
|
+
)}
|
|
176
|
+
{isDone && !result && <button onClick={reset}>Try again</button>}
|
|
177
|
+
</div>
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`phase` walks through `'idle' → 'quoting' → 'preparing' → 'signing_authorization' → 'submitting' → 'signing_mee_quote' → 'executing' → 'done'`. Useful for showing fine-grained loading copy ("Awaiting signature…" vs "Submitting on-chain…"). Use `isLoading` for "is the hook currently working" boolean (true during any phase except `'idle'`, `'done'`, `'error'`).
|
|
183
|
+
|
|
184
|
+
**Multi-wallet note**: `useFiboSwap` auto-resolves the EVM address from the first Privy embedded wallet (`walletClientType === 'privy'`). If the user has multiple EVM wallets connected (e.g., external wallet + embedded), pass `userAddress` explicitly in the `quote()` params to control which wallet is used. A wallet-picker flow lands in v0.4.
|
|
185
|
+
|
|
186
|
+
**Scope v0.3**: EVM same-chain + EVM cross-chain swaps (the routes that go through Biconomy MEE). Solana and Bitcoin swaps land in v0.4 with their own ceremonies.
|
|
187
|
+
|
|
188
|
+
### `useFiboTransactions(opts?)`
|
|
189
|
+
|
|
190
|
+
Lists the tenant's recent transactions. Supports filtering by `status` + cursor pagination via `before`.
|
|
191
|
+
|
|
192
|
+
```tsx
|
|
193
|
+
import { useFiboTransactions } from '@fibo-crypto/react-sdk';
|
|
194
|
+
|
|
195
|
+
function RecentSwaps() {
|
|
196
|
+
const { transactions, isLoading, hasMore, nextBefore } = useFiboTransactions({
|
|
197
|
+
status: 'confirmed',
|
|
198
|
+
limit: 20,
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
if (isLoading) return <p>Loading…</p>;
|
|
202
|
+
return (
|
|
203
|
+
<ul>
|
|
204
|
+
{transactions.map((tx) => (
|
|
205
|
+
<li key={tx.id}>
|
|
206
|
+
{tx.kind} — {tx.source_amount} {tx.source_currency} →{' '}
|
|
207
|
+
{tx.dest_amount} {tx.dest_currency}
|
|
208
|
+
</li>
|
|
209
|
+
))}
|
|
210
|
+
{hasMore && <button onClick={() => /* pass nextBefore as `before` */}>Load more</button>}
|
|
211
|
+
</ul>
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### `useFiboApi()`
|
|
217
|
+
|
|
218
|
+
Returns the typed REST client. Use for any endpoint not covered by a higher-level hook.
|
|
219
|
+
|
|
220
|
+
```tsx
|
|
221
|
+
import { useFiboApi } from '@fibo-crypto/react-sdk';
|
|
222
|
+
|
|
223
|
+
function CustomCall() {
|
|
224
|
+
const api = useFiboApi();
|
|
225
|
+
useEffect(() => {
|
|
226
|
+
api.listTransactions({ status: 'failed', limit: 5 }).then((r) => console.log(r.data));
|
|
227
|
+
}, [api]);
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Non-React contexts
|
|
233
|
+
|
|
234
|
+
The HTTP client is exported standalone via the `/client` sub-export — no React dependency, usable from a Node.js script or Bun:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { createFiboClient } from '@fibo-crypto/react-sdk/client';
|
|
238
|
+
|
|
239
|
+
const fibo = createFiboClient({
|
|
240
|
+
baseUrl: 'https://api.fibo-crypto.fr',
|
|
241
|
+
apiKey: process.env.FIBO_API_KEY!,
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
const balance = await fibo.getEvmBalance('0xabc...');
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
## Configuration
|
|
248
|
+
|
|
249
|
+
| Prop | Default | Description |
|
|
250
|
+
|---|---|---|
|
|
251
|
+
| `publishableKey` | (required) | Your Fibo `pk_*` key |
|
|
252
|
+
| `baseUrl` | `https://api.fibo-crypto.fr` | Override for sandbox / local dev (`http://localhost:3001`) |
|
|
253
|
+
| `externalUserId` | `undefined` | Your own user id, echoed in webhook payloads |
|
|
254
|
+
| `loginMethods` | `['email', 'google', 'apple']` | Privy login providers shown in the modal |
|
|
255
|
+
| `theme.accent` | `#5B44F9` | Accent color for Privy modals |
|
|
256
|
+
| `theme.fontFamily` | `undefined` | Font family for Privy modals |
|
|
257
|
+
| `privyAppIdOverride` | (Fibo's shared app) | Rarely used — only when a custom contractual Privy app is provisioned |
|
|
258
|
+
|
|
259
|
+
## Errors
|
|
260
|
+
|
|
261
|
+
Every API call throws `FiboApiError` on a non-2xx response — fields `status`, `code`, `message`, `details`, `request_id`.
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { FiboApiError } from '@fibo-crypto/react-sdk';
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
await api.prepareTx({ quote_id, user_address });
|
|
268
|
+
} catch (err) {
|
|
269
|
+
if (err instanceof FiboApiError) {
|
|
270
|
+
console.error(`Fibo error ${err.code} (${err.status})`, err.message);
|
|
271
|
+
if (err.request_id) console.error('request_id:', err.request_id);
|
|
272
|
+
} else {
|
|
273
|
+
throw err;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
`request_id` is the canonical trace id for the request — include it when reporting issues to Fibo support.
|
|
279
|
+
|
|
280
|
+
## Build & publish
|
|
281
|
+
|
|
282
|
+
```bash
|
|
283
|
+
npm install # one-time
|
|
284
|
+
npm run typecheck # tsc --noEmit, strict + noUncheckedIndexedAccess
|
|
285
|
+
npm run build # tsup -> dist/ (ESM + d.ts)
|
|
286
|
+
npm run pack:tgz # produces fibo-react-sdk-0.3.0.tgz
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The tarball can be referenced directly in an integrator's `package.json` (`"@fibo-crypto/react-sdk": "https://cdn.fibo-crypto.fr/sdk/react-sdk-0.3.0.tgz"`) ahead of the public npm publication.
|
|
290
|
+
|
|
291
|
+
## Roadmap
|
|
292
|
+
|
|
293
|
+
**Shipped in v0.3** (current):
|
|
294
|
+
- Privy v3 — bitcoin-taproot in extended-chains
|
|
295
|
+
- `useFiboWallet` — EVM + Solana + Bitcoin address readout + BTC creation
|
|
296
|
+
- `useFiboSwap` — EVM quote → sign → submit ceremony via Biconomy MEE
|
|
297
|
+
|
|
298
|
+
**Shipped in v0.2**:
|
|
299
|
+
- `useFiboBalance` — EVM balance with optional polling
|
|
300
|
+
- `useFiboTransactions` — paginated history
|
|
301
|
+
|
|
302
|
+
**Next (v0.4+)**:
|
|
303
|
+
- `useFiboSwap` extended to Solana + Bitcoin routes
|
|
304
|
+
- `useFiboTransfer` — cross-chain transfer
|
|
305
|
+
- `useFiboYield` — Aave + Beefy supply/withdraw
|
|
306
|
+
- Sub-export `@fibo-crypto/react-sdk/monerium` — drop-in SEPA on-ramp connector
|
|
307
|
+
- Sub-export `@fibo-crypto/react-sdk/transak` — drop-in card on-ramp connector
|
|
308
|
+
- React Native package `@fibo/native-sdk` — same hooks, Privy Expo runtime
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
UNLICENSED — internal use only during PoC. Public license decision lands at first paid integrator.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
var DEFAULT_BASE_URL = "https://api.fibo-crypto.fr";
|
|
3
|
+
var FiboApiError = class extends Error {
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
details;
|
|
7
|
+
request_id;
|
|
8
|
+
constructor(info) {
|
|
9
|
+
super(`[${info.status} ${info.code}] ${info.message}`);
|
|
10
|
+
this.name = "FiboApiError";
|
|
11
|
+
this.status = info.status;
|
|
12
|
+
this.code = info.code;
|
|
13
|
+
this.details = info.details;
|
|
14
|
+
this.request_id = info.request_id;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
async function parseError(res) {
|
|
18
|
+
const text = await res.text();
|
|
19
|
+
try {
|
|
20
|
+
const j = JSON.parse(text);
|
|
21
|
+
return {
|
|
22
|
+
status: res.status,
|
|
23
|
+
code: j.error?.code ?? `http_${res.status}`,
|
|
24
|
+
message: j.error?.message ?? res.statusText,
|
|
25
|
+
details: j.error?.details,
|
|
26
|
+
request_id: j.error?.request_id
|
|
27
|
+
};
|
|
28
|
+
} catch {
|
|
29
|
+
return {
|
|
30
|
+
status: res.status,
|
|
31
|
+
code: `http_${res.status}`,
|
|
32
|
+
message: res.statusText
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function createFiboClient(config) {
|
|
37
|
+
if (!config.allowSecretKey && config.apiKey.startsWith("sk_")) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
"FiboProvider / createFiboClient requires a publishable key (pk_test_* / pk_live_*). Secret keys (sk_*) must never be embedded in browser code. For trusted server-side contexts, pass `allowSecretKey: true` explicitly."
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
43
|
+
async function request(args) {
|
|
44
|
+
const headers = {
|
|
45
|
+
Accept: "application/json",
|
|
46
|
+
Authorization: `Bearer ${config.apiKey}`
|
|
47
|
+
};
|
|
48
|
+
if (args.body !== void 0) headers["Content-Type"] = "application/json";
|
|
49
|
+
const res = await fetch(`${baseUrl}${args.path}`, {
|
|
50
|
+
method: args.method,
|
|
51
|
+
headers,
|
|
52
|
+
body: args.body !== void 0 ? JSON.stringify(args.body) : void 0,
|
|
53
|
+
signal: args.signal
|
|
54
|
+
});
|
|
55
|
+
if (res.status === 204) return void 0;
|
|
56
|
+
if (!res.ok) throw new FiboApiError(await parseError(res));
|
|
57
|
+
const text = await res.text();
|
|
58
|
+
if (!text) return void 0;
|
|
59
|
+
return JSON.parse(text);
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
request,
|
|
63
|
+
health: () => request({ method: "GET", path: "/health" }),
|
|
64
|
+
quoteSwap: (params) => request({
|
|
65
|
+
method: "POST",
|
|
66
|
+
path: "/v1/quote",
|
|
67
|
+
body: { product: "swap", ...params }
|
|
68
|
+
}),
|
|
69
|
+
quoteBuyEure: (params) => request({
|
|
70
|
+
method: "POST",
|
|
71
|
+
path: "/v1/quote",
|
|
72
|
+
body: { product: "buy_eure", ...params }
|
|
73
|
+
}),
|
|
74
|
+
prepareTx: (params) => request({ method: "POST", path: "/v1/prepare-tx", body: params }),
|
|
75
|
+
submit: (params) => request({ method: "POST", path: "/v1/submit", body: params }),
|
|
76
|
+
executeSignedQuote: (params) => request({
|
|
77
|
+
method: "POST",
|
|
78
|
+
path: "/v1/execute-signed-quote",
|
|
79
|
+
body: params
|
|
80
|
+
}),
|
|
81
|
+
getTransaction: (id, opts) => request({
|
|
82
|
+
method: "GET",
|
|
83
|
+
path: `/v1/transactions/${id}`,
|
|
84
|
+
signal: opts?.signal
|
|
85
|
+
}),
|
|
86
|
+
listTransactions: (params, opts) => {
|
|
87
|
+
const qs = new URLSearchParams();
|
|
88
|
+
if (params?.limit !== void 0) qs.set("limit", String(params.limit));
|
|
89
|
+
if (params?.status) qs.set("status", params.status);
|
|
90
|
+
if (params?.before) qs.set("before", params.before);
|
|
91
|
+
const query = qs.toString();
|
|
92
|
+
return request({
|
|
93
|
+
method: "GET",
|
|
94
|
+
path: `/v1/transactions${query ? `?${query}` : ""}`,
|
|
95
|
+
signal: opts?.signal
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
moneriumCreateOrder: (params) => request({ method: "POST", path: "/v1/monerium/orders", body: params }),
|
|
99
|
+
getEvmBalance: (address, opts) => request({
|
|
100
|
+
method: "GET",
|
|
101
|
+
path: `/v1/balance/evm/${address}`,
|
|
102
|
+
signal: opts?.signal
|
|
103
|
+
})
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { DEFAULT_BASE_URL, FiboApiError, createFiboClient };
|
|
108
|
+
//# sourceMappingURL=chunk-FRD4NVYJ.js.map
|
|
109
|
+
//# sourceMappingURL=chunk-FRD4NVYJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";AAqBO,IAAM,gBAAA,GAAmB;AA+BzB,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACtB,MAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EAEhB,YAAY,IAAA,EAAwB;AAClC,IAAA,KAAA,CAAM,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA,CAAA,EAAI,KAAK,IAAI,CAAA,EAAA,EAAK,IAAA,CAAK,OAAO,CAAA,CAAE,CAAA;AACrD,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AACpB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AAAA,EACzB;AACF;AAEA,eAAe,WAAW,GAAA,EAA0C;AAClE,EAAA,MAAM,IAAA,GAAO,MAAM,GAAA,CAAI,IAAA,EAAK;AAC5B,EAAA,IAAI;AACF,IAAA,MAAM,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAQzB,IAAA,OAAO;AAAA,MACL,QAAQ,GAAA,CAAI,MAAA;AAAA,MACZ,MAAM,CAAA,CAAE,KAAA,EA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,CAAC,OAAA,EAAS,IAAA,KACvB,OAAA,CAAQ;AAAA,MACN,MAAA,EAAQ,KAAA;AAAA,MACR,IAAA,EAAM,mBAAmB,OAAO,CAAA,CAAA;AAAA,MAChC,QAAQ,IAAA,EAAM;AAAA,KACf;AAAA,GACL;AACF","file":"chunk-FRD4NVYJ.js","sourcesContent":["// HTTP client for the Fibo backend.\n//\n// `createFiboClient({ baseUrl, apiKey })` returns a typed wrapper around\n// every endpoint the SDK consumes. No React dependency — usable from\n// any Node.js or browser context. The React-aware FiboProvider in\n// ./FiboProvider.tsx wires this client into a context for the hooks.\n\nimport type {\n EvmBalanceResponse,\n Eip7702Signature,\n ExecuteResponse,\n MoneriumOrderResponse,\n PrepareTxResponse,\n QuoteResponse,\n SubmitResponse,\n TransactionState,\n TransactionListParams,\n TransactionListResponse,\n} from './types.js';\n\n/** Default API base URL — exported so callers and FiboProvider stay in sync. */\nexport const DEFAULT_BASE_URL = 'https://api.fibo-crypto.fr';\n\nexport interface FiboClientConfig {\n /** API base URL — defaults to https://api.fibo-crypto.fr if omitted. */\n baseUrl?: string;\n /**\n * Bearer token used on every request. MUST be a publishable key\n * (`pk_test_*` / `pk_live_*`) when used from browser contexts —\n * secret keys (`sk_*`) are rejected to prevent accidentally embedding\n * them in client bundles where any visitor could extract them.\n *\n * For trusted server-side contexts (Node scripts, CLI tools, backend-\n * to-backend integrations) where an `sk_*` is intentional, set\n * `allowSecretKey: true` to bypass the guard.\n */\n apiKey: string;\n /**\n * Opt-out of the `pk_*`-only check. Use only in trusted server-side\n * contexts. Defaults to false. The `@fibo-crypto/cli` admin tool passes true.\n */\n allowSecretKey?: boolean;\n}\n\nexport interface FiboApiErrorInfo {\n status: number;\n code: string;\n message: string;\n details?: unknown;\n request_id?: string;\n}\n\nexport class FiboApiError extends Error {\n public readonly status: number;\n public readonly code: string;\n public readonly details?: unknown;\n public readonly request_id?: string;\n\n constructor(info: FiboApiErrorInfo) {\n super(`[${info.status} ${info.code}] ${info.message}`);\n this.name = 'FiboApiError';\n this.status = info.status;\n this.code = info.code;\n this.details = info.details;\n this.request_id = info.request_id;\n }\n}\n\nasync function parseError(res: Response): Promise<FiboApiErrorInfo> {\n const text = await res.text();\n try {\n const j = JSON.parse(text) as {\n error?: {\n code?: string;\n message?: string;\n details?: unknown;\n request_id?: string;\n };\n };\n return {\n status: res.status,\n code: j.error?.code ?? `http_${res.status}`,\n message: j.error?.message ?? res.statusText,\n details: j.error?.details,\n request_id: j.error?.request_id,\n };\n } catch {\n return {\n status: res.status,\n code: `http_${res.status}`,\n message: res.statusText,\n };\n }\n}\n\ninterface RequestArgs {\n method: 'GET' | 'POST' | 'DELETE' | 'PUT';\n path: string;\n body?: unknown;\n /** Pass to cancel the fetch — e.g., on component unmount or address change. */\n signal?: AbortSignal;\n}\n\nexport interface FiboClient {\n request<T>(args: RequestArgs): Promise<T>;\n health(): Promise<{ ok: boolean; ts: number }>;\n quoteSwap(params: {\n source: { token: string; chain_id: number; amount: string };\n destination: { token: string; chain_id: number };\n user_address: string;\n }): Promise<Extract<QuoteResponse, { kind: 'swap' }>>;\n quoteBuyEure(params: {\n fiat_amount: string;\n user_address: string;\n }): Promise<Extract<QuoteResponse, { kind: 'buy_eure' }>>;\n prepareTx(params: {\n quote_id: string;\n user_address: string;\n }): Promise<PrepareTxResponse>;\n submit(params: {\n quote_id: string;\n transaction_id: string;\n signatures: { step_index: number; signature: Eip7702Signature }[];\n }): Promise<SubmitResponse>;\n executeSignedQuote(params: {\n transaction_id: string;\n quote_signature: `0x${string}`;\n }): Promise<ExecuteResponse>;\n getTransaction(id: string, opts?: { signal?: AbortSignal }): Promise<TransactionState>;\n listTransactions(\n params?: TransactionListParams,\n opts?: { signal?: AbortSignal },\n ): Promise<TransactionListResponse>;\n moneriumCreateOrder(params: {\n user_address: string;\n amount: string;\n chain?: string;\n }): Promise<MoneriumOrderResponse>;\n getEvmBalance(\n address: string,\n opts?: { signal?: AbortSignal },\n ): Promise<EvmBalanceResponse>;\n}\n\nexport function createFiboClient(config: FiboClientConfig): FiboClient {\n // Browser-safety guard: reject secret keys unless the caller explicitly\n // opts out. Even though the backend accepts both pk_ and sk_ on data-plane\n // routes (Stripe-style — sk_ has all pk_ permissions plus more), embedding\n // an sk_ in a browser bundle leaks it to every visitor. Fail fast at SDK\n // construction time rather than waiting for the integrator to notice.\n if (!config.allowSecretKey && config.apiKey.startsWith('sk_')) {\n throw new Error(\n 'FiboProvider / createFiboClient requires a publishable key (pk_test_* / pk_live_*). ' +\n 'Secret keys (sk_*) must never be embedded in browser code. ' +\n 'For trusted server-side contexts, pass `allowSecretKey: true` explicitly.',\n );\n }\n\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n\n async function request<T>(args: RequestArgs): Promise<T> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (args.body !== undefined) headers['Content-Type'] = 'application/json';\n\n const res = await fetch(`${baseUrl}${args.path}`, {\n method: args.method,\n headers,\n body: args.body !== undefined ? JSON.stringify(args.body) : undefined,\n signal: args.signal,\n });\n\n if (res.status === 204) return undefined as T;\n if (!res.ok) throw new FiboApiError(await parseError(res));\n\n const text = await res.text();\n if (!text) return undefined as T;\n return JSON.parse(text) as T;\n }\n\n return {\n request,\n health: () => request({ method: 'GET', path: '/health' }),\n quoteSwap: (params) =>\n request({\n method: 'POST',\n path: '/v1/quote',\n body: { product: 'swap', ...params },\n }),\n quoteBuyEure: (params) =>\n request({\n method: 'POST',\n path: '/v1/quote',\n body: { product: 'buy_eure', ...params },\n }),\n prepareTx: (params) =>\n request({ method: 'POST', path: '/v1/prepare-tx', body: params }),\n submit: (params) =>\n request({ method: 'POST', path: '/v1/submit', body: params }),\n executeSignedQuote: (params) =>\n request({\n method: 'POST',\n path: '/v1/execute-signed-quote',\n body: params,\n }),\n getTransaction: (id, opts) =>\n request({\n method: 'GET',\n path: `/v1/transactions/${id}`,\n signal: opts?.signal,\n }),\n listTransactions: (params, opts) => {\n const qs = new URLSearchParams();\n if (params?.limit !== undefined) qs.set('limit', String(params.limit));\n if (params?.status) qs.set('status', params.status);\n if (params?.before) qs.set('before', params.before);\n const query = qs.toString();\n return request({\n method: 'GET',\n path: `/v1/transactions${query ? `?${query}` : ''}`,\n signal: opts?.signal,\n });\n },\n moneriumCreateOrder: (params) =>\n request({ method: 'POST', path: '/v1/monerium/orders', body: params }),\n getEvmBalance: (address, opts) =>\n request({\n method: 'GET',\n path: `/v1/balance/evm/${address}`,\n signal: opts?.signal,\n }),\n };\n}\n\n// Re-export types so a consumer importing from '@fibo-crypto/react-sdk/client' gets\n// the type definitions without a separate import.\nexport type * from './types.js';\n"]}
|