@paxosglobal/sdk 0.0.0-stage → 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.
Files changed (212) hide show
  1. package/AGENTS.md +268 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +191 -0
  4. package/README.md +445 -2
  5. package/dist/auth.d.ts +60 -0
  6. package/dist/auth.js +248 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +353 -0
  9. package/dist/client.js +967 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/constants.d.ts +16 -0
  12. package/dist/constants.js +17 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/decimal-fields.d.ts +16 -0
  15. package/dist/decimal-fields.js +570 -0
  16. package/dist/decimal-fields.js.map +1 -0
  17. package/dist/decimal.d.ts +25 -0
  18. package/dist/decimal.js +93 -0
  19. package/dist/decimal.js.map +1 -0
  20. package/dist/decode.d.ts +34 -0
  21. package/dist/decode.js +118 -0
  22. package/dist/decode.js.map +1 -0
  23. package/dist/enums.d.ts +1080 -0
  24. package/dist/enums.js +1031 -0
  25. package/dist/enums.js.map +1 -0
  26. package/dist/errors.d.ts +142 -0
  27. package/dist/errors.js +261 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/generated-types.d.ts +13629 -0
  30. package/dist/generated-types.js +3 -0
  31. package/dist/generated-types.js.map +1 -0
  32. package/dist/index.d.ts +32 -0
  33. package/dist/index.js +31 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/models.d.ts +299 -0
  36. package/dist/models.js +3 -0
  37. package/dist/models.js.map +1 -0
  38. package/dist/paxos-client.d.ts +107 -0
  39. package/dist/paxos-client.js +157 -0
  40. package/dist/paxos-client.js.map +1 -0
  41. package/dist/query-keys.d.ts +1 -0
  42. package/dist/query-keys.js +31 -0
  43. package/dist/query-keys.js.map +1 -0
  44. package/dist/response-defaults.d.ts +2 -0
  45. package/dist/response-defaults.js +109 -0
  46. package/dist/response-defaults.js.map +1 -0
  47. package/dist/services/account-members.d.ts +32 -0
  48. package/dist/services/account-members.js +46 -0
  49. package/dist/services/account-members.js.map +1 -0
  50. package/dist/services/accounts.d.ts +74 -0
  51. package/dist/services/accounts.js +71 -0
  52. package/dist/services/accounts.js.map +1 -0
  53. package/dist/services/address-verification.d.ts +72 -0
  54. package/dist/services/address-verification.js +64 -0
  55. package/dist/services/address-verification.js.map +1 -0
  56. package/dist/services/api-credentials.d.ts +44 -0
  57. package/dist/services/api-credentials.js +42 -0
  58. package/dist/services/api-credentials.js.map +1 -0
  59. package/dist/services/claims.d.ts +68 -0
  60. package/dist/services/claims.js +67 -0
  61. package/dist/services/claims.js.map +1 -0
  62. package/dist/services/cross-chain-transfer.d.ts +71 -0
  63. package/dist/services/cross-chain-transfer.js +68 -0
  64. package/dist/services/cross-chain-transfer.js.map +1 -0
  65. package/dist/services/crypto-deposits.d.ts +30 -0
  66. package/dist/services/crypto-deposits.js +39 -0
  67. package/dist/services/crypto-deposits.js.map +1 -0
  68. package/dist/services/crypto-withdrawals.d.ts +60 -0
  69. package/dist/services/crypto-withdrawals.js +42 -0
  70. package/dist/services/crypto-withdrawals.js.map +1 -0
  71. package/dist/services/deposit-addresses.d.ts +54 -0
  72. package/dist/services/deposit-addresses.js +36 -0
  73. package/dist/services/deposit-addresses.js.map +1 -0
  74. package/dist/services/events.d.ts +53 -0
  75. package/dist/services/events.js +39 -0
  76. package/dist/services/events.js.map +1 -0
  77. package/dist/services/exchange.d.ts +52 -0
  78. package/dist/services/exchange.js +30 -0
  79. package/dist/services/exchange.js.map +1 -0
  80. package/dist/services/fees.d.ts +15 -0
  81. package/dist/services/fees.js +24 -0
  82. package/dist/services/fees.js.map +1 -0
  83. package/dist/services/fiat-transfers.d.ts +133 -0
  84. package/dist/services/fiat-transfers.js +127 -0
  85. package/dist/services/fiat-transfers.js.map +1 -0
  86. package/dist/services/identity-controls.d.ts +43 -0
  87. package/dist/services/identity-controls.js +42 -0
  88. package/dist/services/identity-controls.js.map +1 -0
  89. package/dist/services/identity-documents.d.ts +45 -0
  90. package/dist/services/identity-documents.js +50 -0
  91. package/dist/services/identity-documents.js.map +1 -0
  92. package/dist/services/identity.d.ts +122 -0
  93. package/dist/services/identity.js +66 -0
  94. package/dist/services/identity.js.map +1 -0
  95. package/dist/services/index.d.ts +89 -0
  96. package/dist/services/index.js +55 -0
  97. package/dist/services/index.js.map +1 -0
  98. package/dist/services/institution-members.d.ts +30 -0
  99. package/dist/services/institution-members.js +44 -0
  100. package/dist/services/institution-members.js.map +1 -0
  101. package/dist/services/internal-transfers.d.ts +15 -0
  102. package/dist/services/internal-transfers.js +26 -0
  103. package/dist/services/internal-transfers.js.map +1 -0
  104. package/dist/services/issuer-quotes.d.ts +72 -0
  105. package/dist/services/issuer-quotes.js +66 -0
  106. package/dist/services/issuer-quotes.js.map +1 -0
  107. package/dist/services/limits.d.ts +20 -0
  108. package/dist/services/limits.js +23 -0
  109. package/dist/services/limits.js.map +1 -0
  110. package/dist/services/market-data.d.ts +15 -0
  111. package/dist/services/market-data.js +23 -0
  112. package/dist/services/market-data.js.map +1 -0
  113. package/dist/services/monitoring-addresses.d.ts +64 -0
  114. package/dist/services/monitoring-addresses.js +68 -0
  115. package/dist/services/monitoring-addresses.js.map +1 -0
  116. package/dist/services/orchestration-rules.d.ts +53 -0
  117. package/dist/services/orchestration-rules.js +47 -0
  118. package/dist/services/orchestration-rules.js.map +1 -0
  119. package/dist/services/orchestrations.d.ts +70 -0
  120. package/dist/services/orchestrations.js +45 -0
  121. package/dist/services/orchestrations.js.map +1 -0
  122. package/dist/services/orders.d.ts +86 -0
  123. package/dist/services/orders.js +67 -0
  124. package/dist/services/orders.js.map +1 -0
  125. package/dist/services/paxos-transfers.d.ts +24 -0
  126. package/dist/services/paxos-transfers.js +35 -0
  127. package/dist/services/paxos-transfers.js.map +1 -0
  128. package/dist/services/payments.d.ts +46 -0
  129. package/dist/services/payments.js +35 -0
  130. package/dist/services/payments.js.map +1 -0
  131. package/dist/services/payout-groups.d.ts +59 -0
  132. package/dist/services/payout-groups.js +59 -0
  133. package/dist/services/payout-groups.js.map +1 -0
  134. package/dist/services/pricing.d.ts +67 -0
  135. package/dist/services/pricing.js +42 -0
  136. package/dist/services/pricing.js.map +1 -0
  137. package/dist/services/profiles.d.ts +106 -0
  138. package/dist/services/profiles.js +84 -0
  139. package/dist/services/profiles.js.map +1 -0
  140. package/dist/services/quote-executions.d.ts +51 -0
  141. package/dist/services/quote-executions.js +41 -0
  142. package/dist/services/quote-executions.js.map +1 -0
  143. package/dist/services/quotes.d.ts +44 -0
  144. package/dist/services/quotes.js +48 -0
  145. package/dist/services/quotes.js.map +1 -0
  146. package/dist/services/reward-addresses.d.ts +80 -0
  147. package/dist/services/reward-addresses.js +79 -0
  148. package/dist/services/reward-addresses.js.map +1 -0
  149. package/dist/services/rewards-statements.d.ts +35 -0
  150. package/dist/services/rewards-statements.js +32 -0
  151. package/dist/services/rewards-statements.js.map +1 -0
  152. package/dist/services/rewards.d.ts +34 -0
  153. package/dist/services/rewards.js +37 -0
  154. package/dist/services/rewards.js.map +1 -0
  155. package/dist/services/sandbox-deposits.d.ts +15 -0
  156. package/dist/services/sandbox-deposits.js +22 -0
  157. package/dist/services/sandbox-deposits.js.map +1 -0
  158. package/dist/services/sandbox-fiat-transfers.d.ts +15 -0
  159. package/dist/services/sandbox-fiat-transfers.js +24 -0
  160. package/dist/services/sandbox-fiat-transfers.js.map +1 -0
  161. package/dist/services/sandbox-identity.d.ts +39 -0
  162. package/dist/services/sandbox-identity.js +60 -0
  163. package/dist/services/sandbox-identity.js.map +1 -0
  164. package/dist/services/settlement.d.ts +76 -0
  165. package/dist/services/settlement.js +79 -0
  166. package/dist/services/settlement.js.map +1 -0
  167. package/dist/services/stablecoin-conversion.d.ts +70 -0
  168. package/dist/services/stablecoin-conversion.js +65 -0
  169. package/dist/services/stablecoin-conversion.js.map +1 -0
  170. package/dist/services/statements.d.ts +44 -0
  171. package/dist/services/statements.js +35 -0
  172. package/dist/services/statements.js.map +1 -0
  173. package/dist/services/tax-documentation.d.ts +21 -0
  174. package/dist/services/tax-documentation.js +33 -0
  175. package/dist/services/tax-documentation.js.map +1 -0
  176. package/dist/services/tax-forms.d.ts +45 -0
  177. package/dist/services/tax-forms.js +38 -0
  178. package/dist/services/tax-forms.js.map +1 -0
  179. package/dist/services/transfers.d.ts +96 -0
  180. package/dist/services/transfers.js +37 -0
  181. package/dist/services/transfers.js.map +1 -0
  182. package/dist/services/travel-rule.d.ts +32 -0
  183. package/dist/services/travel-rule.js +30 -0
  184. package/dist/services/travel-rule.js.map +1 -0
  185. package/dist/services/user-audit-logs.d.ts +45 -0
  186. package/dist/services/user-audit-logs.js +27 -0
  187. package/dist/services/user-audit-logs.js.map +1 -0
  188. package/dist/services/webhooks.d.ts +58 -0
  189. package/dist/services/webhooks.js +42 -0
  190. package/dist/services/webhooks.js.map +1 -0
  191. package/dist/signing.d.ts +33 -0
  192. package/dist/signing.js +186 -0
  193. package/dist/signing.js.map +1 -0
  194. package/dist/testing/fixtures.d.ts +40 -0
  195. package/dist/testing/fixtures.js +131 -0
  196. package/dist/testing/fixtures.js.map +1 -0
  197. package/dist/testing/index.d.ts +28 -0
  198. package/dist/testing/index.js +28 -0
  199. package/dist/testing/index.js.map +1 -0
  200. package/dist/testing/mock-server.d.ts +121 -0
  201. package/dist/testing/mock-server.js +276 -0
  202. package/dist/testing/mock-server.js.map +1 -0
  203. package/dist/timeouts.d.ts +13 -0
  204. package/dist/timeouts.js +71 -0
  205. package/dist/timeouts.js.map +1 -0
  206. package/dist/types.d.ts +6 -0
  207. package/dist/types.js +7 -0
  208. package/dist/types.js.map +1 -0
  209. package/dist/version.d.ts +1 -0
  210. package/dist/version.js +2 -0
  211. package/dist/version.js.map +1 -0
  212. package/package.json +67 -4
package/README.md CHANGED
@@ -1,3 +1,446 @@
1
- # Temporary Holding Version
1
+ # Paxos TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Beta: we aim to avoid breaking changes, but they may occur before 1.0. Support is provided through standard Paxos support channels; please do not open GitHub issues.
4
+
5
+ Official TypeScript SDK for the [Paxos API](https://docs.paxos.com). Fully async with typed parameters and responses.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @paxosglobal/sdk
11
+ ```
12
+
13
+ The package is ESM-only: use `import`. On Node 22.12 and later `require()` also works through require(esm); Node 22.12 prints an `ExperimentalWarning` for it (newer releases no longer do).
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { PaxosClient, Scope } from "@paxosglobal/sdk";
19
+
20
+ const client = new PaxosClient({
21
+ clientId: process.env.PAXOS_CLIENT_ID!,
22
+ clientSecret: process.env.PAXOS_CLIENT_SECRET!,
23
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
24
+ sandbox: true,
25
+ });
26
+
27
+ const transfer = await client.transfers.getTransfer("txn_123");
28
+ console.log(transfer.id, transfer.status);
29
+ ```
30
+
31
+ ## Sandbox
32
+
33
+ Use `sandbox: true` to target the Paxos sandbox environment for testing:
34
+
35
+ ```typescript
36
+ import { Decimal, PaxosClient, Scope } from "@paxosglobal/sdk";
37
+
38
+ const client = new PaxosClient({
39
+ clientId: process.env.PAXOS_SANDBOX_CLIENT_ID!,
40
+ clientSecret: process.env.PAXOS_SANDBOX_CLIENT_SECRET!,
41
+ scopes: [Scope.FUNDING_READ_PROFILE],
42
+ sandbox: true,
43
+ });
44
+
45
+ // Sandbox-only operations
46
+ await client.sandboxDeposits.createSandboxDeposit("p_123", {
47
+ asset: "ETH",
48
+ amount: new Decimal("10.0"),
49
+ crypto_network: "ETHEREUM",
50
+ });
51
+ ```
52
+
53
+ ## Custom Base URL
54
+
55
+ `baseUrl` must include the API version prefix (for example `https://api.paxos.com/v2`); one trailing slash is ignored. Set `baseUrl` and `tokenUrl` together (for a local or staging server), or neither; setting only one throws (an empty string counts as unset).
56
+
57
+ ## Custom HTTP Stack
58
+
59
+ Pass `fetch` to customize the HTTP stack for both API and OAuth token requests, for example to
60
+ route through a corporate proxy with undici (`npm install undici`):
61
+
62
+ ```typescript
63
+ import { PaxosClient, Scope } from "@paxosglobal/sdk";
64
+ import { ProxyAgent, fetch as undiciFetch } from "undici";
65
+
66
+ const dispatcher = new ProxyAgent(process.env.HTTPS_PROXY!);
67
+
68
+ const proxyFetch: typeof fetch = (input, init) =>
69
+ undiciFetch(
70
+ input as Parameters<typeof undiciFetch>[0],
71
+ { ...init, dispatcher } as Parameters<typeof undiciFetch>[1],
72
+ ) as unknown as Promise<Response>;
73
+
74
+ const client = new PaxosClient({
75
+ clientId: process.env.PAXOS_CLIENT_ID!,
76
+ clientSecret: process.env.PAXOS_CLIENT_SECRET!,
77
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
78
+ fetch: proxyFetch,
79
+ });
80
+ ```
81
+
82
+ ## Authentication
83
+
84
+ The SDK uses OAuth2 client credentials. Token acquisition, caching, and refresh are handled automatically. Pass at least one `Scope` constant (required; the constructor throws otherwise); methods that need a scope state it in their JSDoc (for example `Requires scope: transfer:read_transfer`); a few public endpoints need none:
85
+
86
+ ```typescript
87
+ const client = new PaxosClient({
88
+ clientId: "your_client_id",
89
+ clientSecret: "your_client_secret",
90
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
91
+ });
92
+ ```
93
+
94
+ ## Error Handling
95
+
96
+ Every SDK error extends `PaxosError`. HTTP error responses are `PaxosApiError` subclasses (RFC 7807, with `status` and `requestId`); network and timeout errors are siblings with no status. Use type guard functions for specific handling:
97
+
98
+ ```typescript
99
+ import { isNotFoundError, isRateLimitError, isApiError } from "@paxosglobal/sdk";
100
+
101
+ try {
102
+ const transfer = await client.transfers.getTransfer("txn_123");
103
+ } catch (err) {
104
+ if (isNotFoundError(err)) {
105
+ console.log("Transfer not found:", err.detail);
106
+ } else if (isRateLimitError(err)) {
107
+ console.log("Rate limited after SDK retries; this call has finished");
108
+ } else if (isApiError(err)) {
109
+ // Always log requestId -- it is needed for Paxos support
110
+ console.log("API error:", err.status, err.title, err.requestId);
111
+ }
112
+ }
113
+ ```
114
+
115
+ Type guards: `isPaxosError` (any SDK error), `isApiError`, `isNotFoundError`, `isRateLimitError`, `isUnauthorizedError`, `isAuthenticationError`, `isForbiddenError`, `isValidationError`, `isConflictError`, `isUnprocessableError`, `isServerError`, `isNetworkError`, `isTimeoutError`.
116
+
117
+ Every `PaxosError` also exposes `status`, `title`, `detail` and `requestId`, `undefined` when absent, as are `type`, `instance` and `PaxosAuthenticationError.code` on the errors that carry them, and `ResponseMetadata.requestId` when no ID is known (`status` is always a `number` on `PaxosApiError`), so a mapper can read them without narrowing first.
118
+
119
+ Transport failures (DNS, connection refused, TLS, reset) throw `PaxosNetworkError` (no status, `cause` preserved), not `PaxosServerError`. Timeouts throw `PaxosTimeoutError`. Neither is a `PaxosApiError`, so guard `err.status` with `isApiError`. Both expose `requestId`, the `Paxos-Request-Id` of the most recent attempt built (undefined if none); the request may still have reached Paxos, so quote it to support.
120
+
121
+ OAuth and token-endpoint failures are API errors (`PaxosAuthenticationError`, a `PaxosApiError`) carrying the real HTTP status.
122
+
123
+ The SDK automatically retries on 429 (rate limit) and 500, 502, 503 and 504 (server errors) with exponential backoff, up to 3 retries.
124
+
125
+ HTTP 500, 502, 503 and 504 responses are retried for GET, HEAD, OPTIONS and DELETE, and for POST, PUT and PATCH requests on operations whose ref_id the SDK manages (create operations with a ref_id). Other POST, PUT and PATCH requests, including UpdateIdentity and UpdateAccount, are returned to the caller without a retry because the request may already have taken effect; check the resource's state before retrying such a call yourself.
126
+
127
+ ## Pagination
128
+
129
+ List methods return async iterators that automatically handle pagination. Parameters use typed interfaces with IDE autocompletion:
130
+
131
+ ```typescript
132
+ for await (const transfer of client.transfers.listTransfers({
133
+ profile_ids: ["p_123"],
134
+ limit: 50,
135
+ order: "DESC",
136
+ })) {
137
+ console.log(transfer.id, transfer.status);
138
+ }
139
+
140
+ // No params required for unfiltered lists
141
+ for await (const profile of client.profiles.listProfiles()) {
142
+ console.log(profile.id);
143
+ }
144
+ ```
145
+
146
+ Cursor management is automatic, and iteration always terminates — even if the server
147
+ returns a non-advancing cursor, or an empty page alongside a cursor.
148
+
149
+ `limit` controls page size, not the total number of results — it's re-sent unchanged on
150
+ every page. To bound a whole iteration instead, pass `maxItems` and/or `maxDuration` in the
151
+ options argument:
152
+
153
+ ```typescript
154
+ for await (const transfer of client.transfers.listTransfers(
155
+ { limit: 100, profile_ids: ["p_123"] }, // 100 items per page (server-side max varies by endpoint)
156
+ { maxItems: 250, maxDuration: 10_000 }, // stop after 250 items total (~3 pages) or 10s, whichever comes first
157
+ )) {
158
+ console.log(transfer.id);
159
+ }
160
+ ```
161
+
162
+ A `maxDuration` that elapses throws `PaxosTimeoutError` rather than silently returning a
163
+ partial result — catch it explicitly if partial data is acceptable for your use case.
164
+
165
+ ## Pages
166
+
167
+ Every list method also exposes whole pages through `pages()`. Each page carries its own
168
+ items, `nextCursor` and `metadata` (request ID, status code, raw body), so the raw body of
169
+ every page is available, not just the last:
170
+
171
+ ```typescript
172
+ for await (const page of client.transfers.listTransfers({ limit: 100 }).pages()) {
173
+ console.log(page.items.length, page.nextCursor, page.metadata.requestId);
174
+ await archive(page.metadata.rawBody);
175
+ }
176
+ ```
177
+
178
+ Pages are fetched lazily and share the termination rules and `maxItems` / `maxDuration` /
179
+ `signal` options of item iteration; `maxItems` trims the final page. To resume later, break
180
+ after the pages you want and keep the last `nextCursor`; do not rely on `maxItems` for that,
181
+ because a page trimmed by it has no `nextCursor` (compare the item count with the cap to tell
182
+ "capped" from "end of data"). Item iteration and `pages()` cannot be mixed on one iterator and
183
+ throw a `RangeError` while the iterator is live; a failed or closed iterator ends in either view with no
184
+ further request. An invalid `maxItems` or `maxDuration` fails the first pull once and then ends both
185
+ views. Calling `pages()` again continues from the next unfetched page.
186
+
187
+ Consumers without `@types/node` and with `skipLibCheck: false` may see TS2550 on
188
+ `Symbol.asyncDispose` in the emitted `.d.ts`; the member is kept for `AsyncGenerator`
189
+ compatibility with `lib` `esnext`.
190
+
191
+ ## Raw JSON
192
+
193
+ Every decoded top-level response object (each list item and each non-list call result) has a
194
+ non-enumerable, lazily parsed `rawJson` property holding that object's JSON as the server sent
195
+ it, typed through `WithRaw<T>`:
196
+
197
+ ```typescript
198
+ const transfer = await client.transfers.getTransfer("txn_123");
199
+ forward(transfer.rawJson);
200
+ for await (const t of client.transfers.listTransfers()) forward(t.rawJson);
201
+ ```
202
+
203
+ `rawJson` differs from the typed object: decimal fields are the original strings, unknown fields are
204
+ kept, and omitted zero values (required fields, empty arrays and maps) are not filled in. It is not an own enumerable key, so
205
+ `Object.keys`, spreading, `Object.assign`, `JSON.stringify` and equality checks leave it out; copy
206
+ it explicitly if it must travel with a copy. Nested objects have no `rawJson`, and it is `undefined` on
207
+ objects you build yourself. The generator rejects any schema property named `rawJson`; at runtime an unknown response field of
208
+ that name is kept and `rawJson` is not attached.
209
+
210
+ `rawJson` is a mutable cached object, so edits persist on later reads of the same object and are safe
211
+ to make before forwarding; items on a page share one parse but each has its own subtree. Each item
212
+ keeps its page body alive and, after the first `rawJson` read, the whole parsed page, so holding one
213
+ item from a large page pins the page.
214
+
215
+ ## Decimal Handling
216
+
217
+ All monetary amounts are strings on the wire. **Do not use JavaScript `number` for financial arithmetic** -- it uses IEEE 754 floats which cannot represent decimal values exactly.
218
+
219
+ Request and response monetary fields use `Decimal`, exported by the SDK. Pass
220
+ Decimal objects directly; the SDK serializes them to strings on the wire. Response decimals
221
+ always serialize (`toString()`, `JSON.stringify`) as plain fixed-point strings, never exponent
222
+ notation. Import `Decimal` from the SDK for arithmetic that keeps this formatting; it carries
223
+ 1000 significant digits, so `plus`, `minus` and `times` are exact for realistic amounts (`div` rounds at 1000). The API omits zero values, so a required decimal, string, number, boolean or list field it left out is returned as that zero value (`Decimal(0)`, `""`, `0`, `false`, `[]`); required timestamps (including string fields such as `Transfer.created_at`), enums, nested objects and nullable fields are not filled and stay `undefined` when absent; `rawJson` keeps the wire payload:
224
+
225
+ ```typescript
226
+ import { Decimal } from "@paxosglobal/sdk";
227
+
228
+ // Create a withdrawal with exact decimal amount
229
+ const withdrawal = await client.cryptoWithdrawals.createCryptoWithdrawal({
230
+ profile_id: "p_123",
231
+ asset: "BTC",
232
+ amount: new Decimal("0.5"),
233
+ destination_address: "bc1qxyz...",
234
+ crypto_network: "BITCOIN",
235
+ ref_id: "saved-withdrawal-001", // persist before submission; reuse on recovery
236
+ });
237
+
238
+ // Safe comparison and arithmetic
239
+ if (withdrawal.amount?.greaterThan("0")) {
240
+ console.log(withdrawal.amount.plus(new Decimal("0.001")).toString());
241
+ }
242
+ ```
243
+
244
+ `Decimal` normalises scale, so `"0.10"` becomes `"0.1"`. Request bodies serialise `-0.00` as `"0"`; only a direct `JSON.stringify` of the `Decimal` gives `"-0"`. `rawJson` keeps the original wire strings.
245
+
246
+ ## Timestamps
247
+
248
+ Timestamps are RFC 3339 strings, passed through unchanged. The API can return microsecond
249
+ precision, which `Date` cannot hold, so pass response values back as filters as-is:
250
+
251
+ ```typescript
252
+ for await (const t of client.transfers.listTransfers({ created_at_gt: lastTransfer.created_at })) {
253
+ console.log(new Date(t.created_at!));
254
+ }
255
+ ```
256
+
257
+ ## Per-Request Options
258
+
259
+ Override timeout or add extra headers per request. Timeouts are in milliseconds
260
+ (default: 30,000), with one budget across authentication, HTTP attempts, response
261
+ body reads, and retry backoff. Pagination `maxDuration` adds a budget across page
262
+ fetches; the tighter budget wins. Network deadline expiry throws `PaxosTimeoutError`.
263
+ An `AbortSignal` can cancel individual requests, including token waits and backoff;
264
+ cancellation preserves the signal's reason (`AbortError` by default):
265
+
266
+ ```typescript
267
+ // Custom timeout and extra headers
268
+ const transfer = await client.transfers.getTransfer("txn_123", {
269
+ callTimeout: 60_000,
270
+ extraHeaders: { "X-Trace-Id": "trace-abc" },
271
+ });
272
+
273
+ // AbortSignal for cancellation
274
+ const controller = new AbortController();
275
+ setTimeout(() => controller.abort(), 5000);
276
+
277
+ const result = await client.transfers.getTransfer("txn_123", {
278
+ signal: controller.signal,
279
+ });
280
+ ```
281
+
282
+ ## Call and attempt timeouts
283
+
284
+ All durations are milliseconds. `callTimeout` defaults to `30_000` and includes
285
+ OAuth, waiting for a shared token, retries, backoff, and the complete response
286
+ body. `callAttemptTimeout` is an optional cap for each HTTP exchange (OAuth and API
287
+ requests). Every attempt is also bounded by the remaining call/pagination budget.
288
+
289
+ ```typescript
290
+ const client = new PaxosClient({
291
+ clientId: "...",
292
+ clientSecret: "...",
293
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
294
+ callTimeout: 30_000,
295
+ callAttemptTimeout: 5_000,
296
+ });
297
+ await client.transfers.getTransfer("txn_123", {
298
+ callTimeout: 60_000, // overrides client settings, even when larger
299
+ callAttemptTimeout: null, // remove the separate attempt cap
300
+ signal: controller.signal,
301
+ });
302
+ ```
303
+
304
+ Omitted/`undefined` options inherit; `null` explicitly disables that budget.
305
+ Disabling one does not disable other budgets or cancellation. Values must be
306
+ positive, finite and at most `2_147_483_647`. `undefined` inherits the configured
307
+ budget; `null` explicitly disables it. Attempt timeouts
308
+ and network failures retry GET/HEAD/OPTIONS with backoff; ambiguous failures never
309
+ replay POST/PUT/PATCH/DELETE. The existing HTTP status retry policy still applies.
310
+ OAuth failures are surfaced without an additional retry loop.
311
+
312
+ Pagination's optional `maxDuration` begins with the first iterator consumption.
313
+ Pauses count, including pauses between buffered items; expiry throws
314
+ `PaxosTimeoutError`. Each page has its own call budget inside that iterator budget.
315
+ Caller abort preserves its reason. Hooks should cooperate with cancellation;
316
+ timing out cannot forcibly interrupt arbitrary user code.
317
+
318
+ ## Request/Response Hooks
319
+
320
+ Register hooks for logging, tracing, or metrics:
321
+
322
+ ```typescript
323
+ const client = new PaxosClient({
324
+ clientId,
325
+ clientSecret,
326
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
327
+ beforeRequest: ({ method, url, headers }) => {
328
+ headers.set("X-Trace-Id", crypto.randomUUID());
329
+ console.log(`-> ${method} ${url}`);
330
+ },
331
+ afterResponse: (req, res) => {
332
+ console.log(`<- ${res.status} ${req.url} (${res.body.length} bytes)`);
333
+ },
334
+ });
335
+ ```
336
+
337
+ - Both hooks can be synchronous or return a `Promise`, and each client has one hook of each kind.
338
+ - `beforeRequest` runs once per HTTP attempt (including retries and the 401 refresh retry), before signing, and not for the OAuth token request. It may add headers and override `Paxos-Request-Id`, and may replace `req.headers` with a new `Headers` object, but must not change `method`, `url` or `body`, nor change, remove or add SDK-owned headers (`Authorization`, `Content-Type`, `Accept`, `Paxos-SDK-Language`, `Paxos-SDK-Version`, `Paxos-Signature`); doing so fails the call and nothing is sent.
339
+ - `afterResponse` runs once per attempt that received a response, before status and retry handling, with the buffered response body; the SDK still decodes the response normally.
340
+ - Throwing from either hook fails the call with that error and is not retried.
341
+
342
+ ## Concurrency
343
+
344
+ The client is safe to use across concurrent requests (e.g., `Promise.all`). All methods are async-native.
345
+
346
+ ## Request Signing
347
+
348
+ Request signing is configured per OAuth client. Setup follows the guide (https://docs.paxos.com/guides/developer/request-signing), which says request signing "must be activated by Paxos" and to contact Support (https://support.paxos.com). Credentials with the crypto-withdrawal scope also need Paxos Support to register the public key before signing works.
349
+
350
+ 1. Generate a private key with OpenSSL 3 or later (check with `openssl version`; the macOS system `openssl` is LibreSSL and does not support Ed25519). For Ed25519 (EdDSA): `openssl genpkey -algorithm ed25519 -out private.pem`. For P-256 (ES256): `openssl ecparam -name prime256v1 -genkey -noout -out private.pem`
351
+ 2. Derive the public key. For Ed25519: `openssl pkey -in private.pem -pubout -out public.pem`. For P-256: `openssl ec -in private.pem -pubout -out public.pem`
352
+ 3. In the Dashboard, go to Developer > API, open the credential and choose Edit. Click "Add Public Key", enter a nickname, select the algorithm that matches your key (EdDSA or ES256), paste the contents of `public.pem`, click "Save Key", then save the credential with "Save API Credential".
353
+ 4. Copy the Key ID (a UUID) shown on the saved public key.
354
+ 5. Activate signing. For credentials without the crypto-withdrawal scope, turn on "Enable Request Signing" (available once the credential has a public key), save the credential, then contact Support to complete activation. For credentials with the crypto-withdrawal scope, contact Support to register the key with the signing stack, and turn on "Enable Request Signing" only after they confirm.
355
+ 6. Configure the SDK with the private key and the Key ID:
356
+
357
+ ```typescript
358
+ import { readFileSync } from "node:fs";
359
+
360
+ const client = new PaxosClient({
361
+ clientId: process.env.PAXOS_CLIENT_ID!,
362
+ clientSecret: process.env.PAXOS_CLIENT_SECRET!,
363
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
364
+ signingKey: readFileSync("private.pem", "utf8"),
365
+ keyId: process.env.PAXOS_KEY_ID!,
366
+ });
367
+ ```
368
+
369
+ The options are `signingKey` and `keyId`; pass both together. The private key can be the PEM file contents as written by step 1 (an unencrypted PKCS#8 `-----BEGIN PRIVATE KEY-----` block for either key type, or an unencrypted SEC1 `-----BEGIN EC PRIVATE KEY-----` block for P-256) or, for Ed25519 only, 128 hex characters (the 32-byte seed followed by the matching 32-byte public key). Pass the PEM exactly as openssl writes it (multi-line, with the BEGIN and END lines); reformatted PEM, such as a single line with spaces, may be rejected. Load it from a file or a secret store (keep its newlines if it comes from an environment variable); do not put key literals in source. Encrypted PEM is rejected: decrypt it first. Whatever the format, an invalid key makes the constructor throw.
370
+
371
+ The SDK supports Ed25519 (EdDSA) and P-256 (ES256) keys and picks the algorithm from the key; other key types and curves are rejected.
372
+
373
+ Only API requests are signed; OAuth token requests are not. Each signed request carries a JWS in the `Paxos-Signature` header covering the method, the full transmitted path (including the `/v2` prefix), the exact serialized query string and the body bytes. Signing runs after `beforeRequest`, so it covers the final request.
374
+
375
+ Once signing is enforced for the credential, unsigned or mis-signed requests are rejected with HTTP 401, surfaced as `PaxosUnauthorizedError` (`isUnauthorizedError(err)`) with `requestId`. Quote the request ID when contacting Support.
376
+
377
+ ## Debug Logging
378
+
379
+ Enable debug output with the `PAXOS_LOG_LEVEL` environment variable:
380
+
381
+ ```bash
382
+ PAXOS_LOG_LEVEL=debug node app.js
383
+ ```
384
+
385
+ Or provide a custom logger callback:
386
+
387
+ ```typescript
388
+ const client = new PaxosClient({
389
+ clientId: "your_client_id",
390
+ clientSecret: "your_client_secret",
391
+ scopes: [Scope.TRANSFER_READ_TRANSFER],
392
+ logger: (level, message, data) => {
393
+ console.log(`[${level}] ${message}`, data);
394
+ },
395
+ });
396
+ ```
397
+
398
+ The explicit logger takes precedence over `PAXOS_LOG_LEVEL`.
399
+
400
+ Debug logging never writes request or response bodies. It logs the method, path (no query string), status, request ID, elapsed time and retry attempt.
401
+
402
+ ## Response Metadata
403
+
404
+ Capture metadata from a typed service call with `onResponseMetadata`. It runs for
405
+ the terminal HTTP response (including API errors), or once per pagination page (so an auto-paginated call invokes it once per page; a hook also sees every page).
406
+ It does not run when the call ends without a terminal HTTP response.
407
+
408
+ ```typescript
409
+ await client.transfers.getTransfer("txn_123", {
410
+ onResponseMetadata: ({ requestId, statusCode }) => {
411
+ console.log({ requestId, statusCode });
412
+ },
413
+ });
414
+ ```
415
+
416
+ For a passthrough or BFF, forward the unmodified JSON of a call from
417
+ `rawBody` (`string`, set for every received response, `""` for an empty body) instead of re-serializing the typed model:
418
+
419
+ ```typescript
420
+ let body = "";
421
+ await client.transfers.getTransfer("txn_123", {
422
+ onResponseMetadata: ({ rawBody }) => {
423
+ body = rawBody;
424
+ },
425
+ });
426
+ ```
427
+
428
+ Callbacks should not throw: their exceptions terminate the call. See the
429
+ [developer guide](https://docs.paxos.com/sdks) for recovery and client lifetime.
430
+
431
+ ## Request Bodies
432
+
433
+ Empty lists and empty map fields are omitted from request bodies; empty objects for nested model fields are sent as given.
434
+
435
+ ## Reference IDs
436
+
437
+ For operations that take a `ref_id`, the SDK fills an omitted `ref_id` with a UUID once per method call and reuses it across internal retries. Set it yourself to persist it before submission.
438
+
439
+ ## Requirements
440
+
441
+ - Node.js 22.12 or later
442
+ - ES2022
443
+
444
+ ## License
445
+
446
+ [Apache 2.0](LICENSE)
package/dist/auth.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * OAuth2 client credentials token manager.
3
+ *
4
+ * Tokens are cached and refreshed 60 seconds before expiry.
5
+ * Concurrent calls share a single in-flight refresh request to avoid
6
+ * stampeding the token endpoint.
7
+ */
8
+ import { type Timeout } from "./timeouts.js";
9
+ /**
10
+ * TokenManager handles automatic OAuth2 token acquisition and caching.
11
+ *
12
+ * Users of the SDK never need to call this directly — the PaxosClient
13
+ * injects the Bearer token on every request.
14
+ */
15
+ export declare class TokenManager {
16
+ #private;
17
+ private readonly clientId;
18
+ private readonly tokenUrl;
19
+ private readonly scopes;
20
+ private readonly timeoutMs;
21
+ private readonly fetchFn;
22
+ private refreshController;
23
+ private expiresAt;
24
+ private refreshGeneration;
25
+ constructor(clientId: string, clientSecret: string, tokenUrl: string, scopes?: readonly string[], timeoutMs?: Timeout, fetchFn?: typeof fetch);
26
+ /**
27
+ * Return a valid access token, fetching a new one if the cached token
28
+ * has expired or is about to expire within the 60-second buffer.
29
+ *
30
+ * `timeoutMs`, if given, bounds the token request only if a refresh is
31
+ * actually triggered — used internally by pagination to keep a
32
+ * mid-iteration refresh inside the remaining `maxDuration` budget rather
33
+ * than this manager's own default timeout.
34
+ *
35
+ * If a refresh is already in-flight from another caller, this call joins
36
+ * it (concurrent refreshes share a single fetch) rather than starting a
37
+ * duplicate one — but `timeoutMs`, if given, bounds *this* caller's own
38
+ * wait for that shared refresh, not the original caller's timeout, so a
39
+ * short remaining budget here can't be blocked past it by someone else's
40
+ * slower refresh.
41
+ */
42
+ getToken(timeoutMs?: Timeout, signal?: AbortSignal): Promise<string>;
43
+ /**
44
+ * Return the current cached token without triggering a refresh.
45
+ */
46
+ peekToken(): string | null;
47
+ /**
48
+ * Invalidate the cached token so the next call to getToken() forces a refresh.
49
+ *
50
+ * Called automatically on 401 responses to handle server-side token revocation.
51
+ */
52
+ invalidate(rejectedToken?: string): void;
53
+ /**
54
+ * Fetch a fresh token from the OAuth2 endpoint.
55
+ *
56
+ * Multiple concurrent callers share a single in-flight fetch (singleflight pattern).
57
+ */
58
+ private refresh;
59
+ private fetchToken;
60
+ }