@circle-fin/daa-react-native-sdk 0.0.0-stage → 0.5.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 (337) hide show
  1. package/DaaReactNativeSdk.podspec +69 -0
  2. package/LICENSE +176 -0
  3. package/README.md +691 -2
  4. package/android/build.gradle +102 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
  7. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +104 -0
  8. package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
  9. package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
  10. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +107 -0
  11. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +318 -0
  12. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +122 -0
  13. package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
  14. package/build/DaaClient.d.ts +237 -0
  15. package/build/DaaClient.js +442 -0
  16. package/build/api/AccountLimitsClient.d.ts +79 -0
  17. package/build/api/AccountLimitsClient.js +142 -0
  18. package/build/api/AccountsClient.d.ts +98 -0
  19. package/build/api/AccountsClient.js +279 -0
  20. package/build/api/AchFiatAccountsClient.d.ts +92 -0
  21. package/build/api/AchFiatAccountsClient.js +142 -0
  22. package/build/api/AuthClient.d.ts +95 -0
  23. package/build/api/AuthClient.js +221 -0
  24. package/build/api/ContractExecutionsClient.d.ts +114 -0
  25. package/build/api/ContractExecutionsClient.js +462 -0
  26. package/build/api/DaaUserClient.d.ts +187 -0
  27. package/build/api/DaaUserClient.js +312 -0
  28. package/build/api/DepositAddressesClient.d.ts +112 -0
  29. package/build/api/DepositAddressesClient.js +222 -0
  30. package/build/api/DepositsClient.d.ts +106 -0
  31. package/build/api/DepositsClient.js +183 -0
  32. package/build/api/FiatAccountsClient.d.ts +43 -0
  33. package/build/api/FiatAccountsClient.js +46 -0
  34. package/build/api/TransactionsClient.d.ts +64 -0
  35. package/build/api/TransactionsClient.js +121 -0
  36. package/build/api/TransfersClient.d.ts +107 -0
  37. package/build/api/TransfersClient.js +324 -0
  38. package/build/api/WireFiatAccountsClient.d.ts +99 -0
  39. package/build/api/WireFiatAccountsClient.js +156 -0
  40. package/build/api/WithdrawalsClient.d.ts +97 -0
  41. package/build/api/WithdrawalsClient.js +308 -0
  42. package/build/api/deviceApproval.d.ts +48 -0
  43. package/build/api/deviceApproval.js +247 -0
  44. package/build/api/deviceStatus.d.ts +61 -0
  45. package/build/api/deviceStatus.js +216 -0
  46. package/build/api/loginFailure.d.ts +51 -0
  47. package/build/api/loginFailure.js +95 -0
  48. package/build/api/pagination.d.ts +29 -0
  49. package/build/api/pagination.js +50 -0
  50. package/build/api/queryParameters.d.ts +23 -0
  51. package/build/api/queryParameters.js +77 -0
  52. package/build/api/resourceRequest.d.ts +60 -0
  53. package/build/api/resourceRequest.js +79 -0
  54. package/build/api/signedResource.d.ts +124 -0
  55. package/build/api/signedResource.js +267 -0
  56. package/build/auth/RegistrationFlowKey.d.ts +93 -0
  57. package/build/auth/RegistrationFlowKey.js +203 -0
  58. package/build/auth/daaRegistrationNative.d.ts +58 -0
  59. package/build/auth/daaRegistrationNative.js +158 -0
  60. package/build/auth/deviceAuthorization.d.ts +87 -0
  61. package/build/auth/deviceAuthorization.js +295 -0
  62. package/build/auth/ownerGrant.d.ts +29 -0
  63. package/build/auth/ownerGrant.js +90 -0
  64. package/build/auth/registrationAuthorization.d.ts +48 -0
  65. package/build/auth/registrationAuthorization.js +246 -0
  66. package/build/auth/registrationCodeVerifier.d.ts +31 -0
  67. package/build/auth/registrationCodeVerifier.js +75 -0
  68. package/build/config.d.ts +106 -0
  69. package/build/config.js +131 -0
  70. package/build/crypto/base64url.d.ts +26 -0
  71. package/build/crypto/base64url.js +87 -0
  72. package/build/crypto/bytes.d.ts +27 -0
  73. package/build/crypto/bytes.js +32 -0
  74. package/build/crypto/jwkThumbprint.d.ts +32 -0
  75. package/build/crypto/jwkThumbprint.js +49 -0
  76. package/build/crypto/matchingCode.d.ts +47 -0
  77. package/build/crypto/matchingCode.js +93 -0
  78. package/build/crypto/random.d.ts +35 -0
  79. package/build/crypto/random.js +106 -0
  80. package/build/crypto/serialization.d.ts +26 -0
  81. package/build/crypto/serialization.js +43 -0
  82. package/build/crypto/sha256.d.ts +18 -0
  83. package/build/crypto/sha256.js +100 -0
  84. package/build/errors.d.ts +307 -0
  85. package/build/errors.js +413 -0
  86. package/build/index.d.ts +69 -0
  87. package/build/index.js +67 -0
  88. package/build/models/Account.d.ts +201 -0
  89. package/build/models/Account.js +147 -0
  90. package/build/models/AccountLimitsUsage.d.ts +169 -0
  91. package/build/models/AccountLimitsUsage.js +86 -0
  92. package/build/models/Ach.d.ts +135 -0
  93. package/build/models/Ach.js +184 -0
  94. package/build/models/AddressObject.d.ts +128 -0
  95. package/build/models/AddressObject.js +141 -0
  96. package/build/models/BusinessPii.d.ts +84 -0
  97. package/build/models/BusinessPii.js +142 -0
  98. package/build/models/ContractExecution.d.ts +197 -0
  99. package/build/models/ContractExecution.js +130 -0
  100. package/build/models/CreateAccountRequest.d.ts +74 -0
  101. package/build/models/CreateAccountRequest.js +19 -0
  102. package/build/models/CreateContractExecutionRequest.d.ts +81 -0
  103. package/build/models/CreateContractExecutionRequest.js +19 -0
  104. package/build/models/CreateTransferRequest.d.ts +91 -0
  105. package/build/models/CreateTransferRequest.js +19 -0
  106. package/build/models/CreateWithdrawalRequest.d.ts +99 -0
  107. package/build/models/CreateWithdrawalRequest.js +19 -0
  108. package/build/models/DaaUserContext.d.ts +146 -0
  109. package/build/models/DaaUserContext.js +164 -0
  110. package/build/models/Deposit.d.ts +241 -0
  111. package/build/models/Deposit.js +149 -0
  112. package/build/models/DepositSummary.d.ts +91 -0
  113. package/build/models/DepositSummary.js +114 -0
  114. package/build/models/DeviceStatus.d.ts +69 -0
  115. package/build/models/DeviceStatus.js +19 -0
  116. package/build/models/FiatAccount.d.ts +99 -0
  117. package/build/models/FiatAccount.js +151 -0
  118. package/build/models/GenerateAddressRequest.d.ts +67 -0
  119. package/build/models/GenerateAddressRequest.js +68 -0
  120. package/build/models/Money.d.ts +76 -0
  121. package/build/models/Money.js +99 -0
  122. package/build/models/Page.d.ts +33 -0
  123. package/build/models/Page.js +57 -0
  124. package/build/models/PendingDeviceApproval.d.ts +121 -0
  125. package/build/models/PendingDeviceApproval.js +208 -0
  126. package/build/models/PendingDeviceRegistration.d.ts +229 -0
  127. package/build/models/PendingDeviceRegistration.js +636 -0
  128. package/build/models/PreparedContractExecution.d.ts +70 -0
  129. package/build/models/PreparedContractExecution.js +77 -0
  130. package/build/models/PreparedSocialLogin.d.ts +148 -0
  131. package/build/models/PreparedSocialLogin.js +252 -0
  132. package/build/models/Transaction.d.ts +233 -0
  133. package/build/models/Transaction.js +182 -0
  134. package/build/models/Transfer.d.ts +335 -0
  135. package/build/models/Transfer.js +240 -0
  136. package/build/models/Wire.d.ts +213 -0
  137. package/build/models/Wire.js +264 -0
  138. package/build/models/Withdrawal.d.ts +201 -0
  139. package/build/models/Withdrawal.js +156 -0
  140. package/build/models/codeSecrets.d.ts +100 -0
  141. package/build/models/codeSecrets.js +321 -0
  142. package/build/models/redaction.d.ts +18 -0
  143. package/build/models/redaction.js +23 -0
  144. package/build/sca/ScaClient.d.ts +105 -0
  145. package/build/sca/ScaClient.js +193 -0
  146. package/build/securekey/InMemorySecureKey.d.ts +25 -0
  147. package/build/securekey/InMemorySecureKey.js +168 -0
  148. package/build/securekey/NativeSecureKey.d.ts +26 -0
  149. package/build/securekey/NativeSecureKey.js +355 -0
  150. package/build/securekey/NativeSecureKeyBridge.d.ts +151 -0
  151. package/build/securekey/NativeSecureKeyBridge.js +19 -0
  152. package/build/securekey/SecureKey.d.ts +257 -0
  153. package/build/securekey/SecureKey.js +19 -0
  154. package/build/securekey/alias.d.ts +97 -0
  155. package/build/securekey/alias.js +184 -0
  156. package/build/securekey/ownerAuthKeyResolver.d.ts +73 -0
  157. package/build/securekey/ownerAuthKeyResolver.js +78 -0
  158. package/build/securekey/registration.d.ts +19 -0
  159. package/build/securekey/registration.js +38 -0
  160. package/build/securekey/resolveNativeBridge.d.ts +33 -0
  161. package/build/securekey/resolveNativeBridge.js +201 -0
  162. package/build/testing.d.ts +18 -0
  163. package/build/testing.js +34 -0
  164. package/build/transport/DaaTransport.d.ts +35 -0
  165. package/build/transport/DaaTransport.js +19 -0
  166. package/build/transport/headers.d.ts +41 -0
  167. package/build/transport/headers.js +81 -0
  168. package/build/validation/requestBody.d.ts +27 -0
  169. package/build/validation/requestBody.js +56 -0
  170. package/build/validation/uuid.d.ts +25 -0
  171. package/build/validation/uuid.js +33 -0
  172. package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
  173. package/build/wire/accountLimitsUsagePayload.js +130 -0
  174. package/build/wire/accountPayload.d.ts +36 -0
  175. package/build/wire/accountPayload.js +100 -0
  176. package/build/wire/achPayload.d.ts +24 -0
  177. package/build/wire/achPayload.js +82 -0
  178. package/build/wire/addressObjectPayload.d.ts +44 -0
  179. package/build/wire/addressObjectPayload.js +64 -0
  180. package/build/wire/contractExecutionPayload.d.ts +24 -0
  181. package/build/wire/contractExecutionPayload.js +130 -0
  182. package/build/wire/daaStatusCodes.d.ts +81 -0
  183. package/build/wire/daaStatusCodes.js +86 -0
  184. package/build/wire/dataEnvelope.d.ts +40 -0
  185. package/build/wire/dataEnvelope.js +79 -0
  186. package/build/wire/depositPayload.d.ts +42 -0
  187. package/build/wire/depositPayload.js +159 -0
  188. package/build/wire/deviceContextPayload.d.ts +35 -0
  189. package/build/wire/deviceContextPayload.js +59 -0
  190. package/build/wire/deviceRegistrationResultPayload.d.ts +77 -0
  191. package/build/wire/deviceRegistrationResultPayload.js +162 -0
  192. package/build/wire/deviceStatusPayload.d.ts +20 -0
  193. package/build/wire/deviceStatusPayload.js +66 -0
  194. package/build/wire/errorEnvelope.d.ts +43 -0
  195. package/build/wire/errorEnvelope.js +85 -0
  196. package/build/wire/fiatAccountPayload.d.ts +37 -0
  197. package/build/wire/fiatAccountPayload.js +93 -0
  198. package/build/wire/instant.d.ts +27 -0
  199. package/build/wire/instant.js +94 -0
  200. package/build/wire/jsonNumber.d.ts +30 -0
  201. package/build/wire/jsonNumber.js +34 -0
  202. package/build/wire/moneyPayload.d.ts +30 -0
  203. package/build/wire/moneyPayload.js +56 -0
  204. package/build/wire/paginationLinks.d.ts +28 -0
  205. package/build/wire/paginationLinks.js +167 -0
  206. package/build/wire/payload.d.ts +60 -0
  207. package/build/wire/payload.js +121 -0
  208. package/build/wire/pendingRegistrationPayload.d.ts +48 -0
  209. package/build/wire/pendingRegistrationPayload.js +72 -0
  210. package/build/wire/socialLoginRequestPayload.d.ts +26 -0
  211. package/build/wire/socialLoginRequestPayload.js +55 -0
  212. package/build/wire/transactionPayload.d.ts +31 -0
  213. package/build/wire/transactionPayload.js +149 -0
  214. package/build/wire/transferPayload.d.ts +43 -0
  215. package/build/wire/transferPayload.js +218 -0
  216. package/build/wire/wireEnums.d.ts +22 -0
  217. package/build/wire/wireEnums.js +69 -0
  218. package/build/wire/wirePayload.d.ts +29 -0
  219. package/build/wire/wirePayload.js +138 -0
  220. package/build/wire/withdrawalPayload.d.ts +27 -0
  221. package/build/wire/withdrawalPayload.js +179 -0
  222. package/expo-module.config.json +14 -0
  223. package/ios/DaaRegistrationExceptions.swift +58 -0
  224. package/ios/DaaRegistrationModule.swift +125 -0
  225. package/ios/DaaScaExceptions.swift +96 -0
  226. package/ios/DaaScaModule.swift +125 -0
  227. package/ios/DaaSecureKeyExceptions.swift +125 -0
  228. package/ios/DaaSecureKeyModule.swift +306 -0
  229. package/ios/InstallationIdentityStore.swift +162 -0
  230. package/ios/UnpaddedBase64URL.swift +42 -0
  231. package/package.json +114 -4
  232. package/src/DaaClient.ts +509 -0
  233. package/src/api/AccountLimitsClient.ts +146 -0
  234. package/src/api/AccountsClient.ts +308 -0
  235. package/src/api/AchFiatAccountsClient.ts +147 -0
  236. package/src/api/AuthClient.ts +266 -0
  237. package/src/api/ContractExecutionsClient.ts +527 -0
  238. package/src/api/DaaUserClient.ts +345 -0
  239. package/src/api/DepositAddressesClient.ts +239 -0
  240. package/src/api/DepositsClient.ts +208 -0
  241. package/src/api/FiatAccountsClient.ts +50 -0
  242. package/src/api/TransactionsClient.ts +138 -0
  243. package/src/api/TransfersClient.ts +364 -0
  244. package/src/api/WireFiatAccountsClient.ts +172 -0
  245. package/src/api/WithdrawalsClient.ts +342 -0
  246. package/src/api/deviceApproval.ts +306 -0
  247. package/src/api/deviceStatus.ts +238 -0
  248. package/src/api/loginFailure.ts +112 -0
  249. package/src/api/pagination.ts +63 -0
  250. package/src/api/queryParameters.ts +82 -0
  251. package/src/api/resourceRequest.ts +135 -0
  252. package/src/api/signedResource.ts +427 -0
  253. package/src/auth/RegistrationFlowKey.ts +274 -0
  254. package/src/auth/daaRegistrationNative.ts +191 -0
  255. package/src/auth/deviceAuthorization.ts +365 -0
  256. package/src/auth/ownerGrant.ts +102 -0
  257. package/src/auth/registrationAuthorization.ts +309 -0
  258. package/src/auth/registrationCodeVerifier.ts +76 -0
  259. package/src/config.ts +192 -0
  260. package/src/crypto/base64url.ts +88 -0
  261. package/src/crypto/bytes.ts +30 -0
  262. package/src/crypto/jwkThumbprint.ts +65 -0
  263. package/src/crypto/matchingCode.ts +100 -0
  264. package/src/crypto/random.ts +113 -0
  265. package/src/crypto/serialization.ts +42 -0
  266. package/src/crypto/sha256.ts +105 -0
  267. package/src/errors.ts +576 -0
  268. package/src/index.ts +258 -0
  269. package/src/models/Account.ts +264 -0
  270. package/src/models/AccountLimitsUsage.ts +192 -0
  271. package/src/models/Ach.ts +269 -0
  272. package/src/models/AddressObject.ts +169 -0
  273. package/src/models/BusinessPii.ts +154 -0
  274. package/src/models/ContractExecution.ts +250 -0
  275. package/src/models/CreateAccountRequest.ts +109 -0
  276. package/src/models/CreateContractExecutionRequest.ts +100 -0
  277. package/src/models/CreateTransferRequest.ts +114 -0
  278. package/src/models/CreateWithdrawalRequest.ts +120 -0
  279. package/src/models/DaaUserContext.ts +228 -0
  280. package/src/models/Deposit.ts +307 -0
  281. package/src/models/DepositSummary.ts +142 -0
  282. package/src/models/DeviceStatus.ts +50 -0
  283. package/src/models/FiatAccount.ts +195 -0
  284. package/src/models/GenerateAddressRequest.ts +101 -0
  285. package/src/models/Money.ts +91 -0
  286. package/src/models/Page.ts +48 -0
  287. package/src/models/PendingDeviceApproval.ts +229 -0
  288. package/src/models/PendingDeviceRegistration.ts +791 -0
  289. package/src/models/PreparedContractExecution.ts +128 -0
  290. package/src/models/PreparedSocialLogin.ts +297 -0
  291. package/src/models/Transaction.ts +322 -0
  292. package/src/models/Transfer.ts +459 -0
  293. package/src/models/Wire.ts +405 -0
  294. package/src/models/Withdrawal.ts +283 -0
  295. package/src/models/codeSecrets.ts +360 -0
  296. package/src/models/redaction.ts +22 -0
  297. package/src/sca/ScaClient.ts +289 -0
  298. package/src/securekey/InMemorySecureKey.ts +192 -0
  299. package/src/securekey/NativeSecureKey.ts +388 -0
  300. package/src/securekey/NativeSecureKeyBridge.ts +189 -0
  301. package/src/securekey/SecureKey.ts +279 -0
  302. package/src/securekey/alias.ts +212 -0
  303. package/src/securekey/ownerAuthKeyResolver.ts +135 -0
  304. package/src/securekey/registration.ts +40 -0
  305. package/src/securekey/resolveNativeBridge.ts +343 -0
  306. package/src/testing.ts +32 -0
  307. package/src/transport/DaaTransport.ts +42 -0
  308. package/src/transport/headers.ts +93 -0
  309. package/src/validation/requestBody.ts +60 -0
  310. package/src/validation/uuid.ts +31 -0
  311. package/src/wire/accountLimitsUsagePayload.ts +182 -0
  312. package/src/wire/accountPayload.ts +108 -0
  313. package/src/wire/achPayload.ts +98 -0
  314. package/src/wire/addressObjectPayload.ts +64 -0
  315. package/src/wire/contractExecutionPayload.ts +152 -0
  316. package/src/wire/daaStatusCodes.ts +86 -0
  317. package/src/wire/dataEnvelope.ts +80 -0
  318. package/src/wire/depositPayload.ts +186 -0
  319. package/src/wire/deviceContextPayload.ts +60 -0
  320. package/src/wire/deviceRegistrationResultPayload.ts +211 -0
  321. package/src/wire/deviceStatusPayload.ts +68 -0
  322. package/src/wire/errorEnvelope.ts +87 -0
  323. package/src/wire/fiatAccountPayload.ts +112 -0
  324. package/src/wire/instant.ts +96 -0
  325. package/src/wire/jsonNumber.ts +33 -0
  326. package/src/wire/moneyPayload.ts +55 -0
  327. package/src/wire/paginationLinks.ts +204 -0
  328. package/src/wire/payload.ts +146 -0
  329. package/src/wire/pendingRegistrationPayload.ts +118 -0
  330. package/src/wire/socialLoginRequestPayload.ts +66 -0
  331. package/src/wire/transactionPayload.ts +181 -0
  332. package/src/wire/transferPayload.ts +249 -0
  333. package/src/wire/wireEnums.ts +74 -0
  334. package/src/wire/wirePayload.ts +160 -0
  335. package/src/wire/withdrawalPayload.ts +219 -0
  336. package/testing.d.ts +19 -0
  337. package/testing.js +25 -0
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import {
20
+ DaaUserContext,
21
+ DECODER_TOKEN,
22
+ type DeviceRegistrationResult,
23
+ } from '../models/DaaUserContext'
24
+ import { canonicalBytes32 } from '../crypto/matchingCode'
25
+ import { isUuid } from '../validation/uuid'
26
+ import { toDeviceContext } from './deviceContextPayload'
27
+ import { requiredDateTime } from './instant'
28
+ import { asObject, MalformedPayloadError, optionalString, requiredString } from './payload'
29
+
30
+ /** The only `type` a device key registration may echo. */
31
+ const DEVICE_KEY_TYPE = 'deviceKey'
32
+
33
+ /**
34
+ * The `KeyCredential` members that `DeviceContext` names differently, by their
35
+ * `DeviceContext` name. A decoder error names the `KeyCredential` member.
36
+ */
37
+ const KEY_CREDENTIAL_NAMES: Readonly<Record<string, string>> = Object.freeze({
38
+ deviceCredentialStatus: 'credentialStatus',
39
+ authKeyId: 'credentialId',
40
+ })
41
+
42
+ /**
43
+ * A `pending_approval` registration as DAA sends it. `PendingDeviceRegistration`
44
+ * adds the local code secret and AuthKey thumbprint to make the public
45
+ * `PendingDeviceApproval`.
46
+ */
47
+ export type PendingApprovalPayload = Readonly<{
48
+ status: 'PENDING_APPROVAL'
49
+ requestId: string
50
+ authKeyId: string
51
+ expiresAt: string
52
+ codeNonce: string
53
+ /** The request's stored seal, or `null` from a DAA that doesn't send it. */
54
+ codeSeal: string | null
55
+ }>
56
+
57
+ /**
58
+ * A `pending_activation` registration as DAA sends it: a device approved from
59
+ * another device, signing in again during the account's cool-down.
60
+ * `PendingDeviceRegistration` acknowledges the key with `ownerBindingId`,
61
+ * which the public result leaves out.
62
+ */
63
+ export type PendingActivationPayload = Readonly<{
64
+ status: 'PENDING_ACTIVATION'
65
+ authKeyId: string
66
+ ownerBindingId: string
67
+ readyAt: string
68
+ }>
69
+
70
+ /**
71
+ * Complete's decoded payload, before the pending variants get their local state.
72
+ * `/v1/accounts/auth/keys` never returns `RECOVERY_PENDING`, so this decoder
73
+ * never produces it, although the public `DeviceRegistrationResult` keeps it.
74
+ */
75
+ export type DecodedDeviceRegistration =
76
+ | Extract<DeviceRegistrationResult, { status: 'ACTIVE' }>
77
+ | PendingApprovalPayload
78
+ | PendingActivationPayload
79
+
80
+ /**
81
+ * Map Complete's `data` payload: the `KeyCredential` that
82
+ * `POST /v1/accounts/auth/keys` returns for `"type": "deviceKey"`.
83
+ *
84
+ * DAA builds a `KeyCredential` from the same `DeviceContext` that
85
+ * `get_device_context` returns, with names that fit both key types. For a
86
+ * device key, `credentialStatus` is the `deviceCredentialStatus` and
87
+ * `credentialId` is the `authKeyId` (the `kid` that later
88
+ * `X-Device-Authorization` requests sign with). Every other member keeps its
89
+ * name. So the payload is checked for `type: "deviceKey"`, those two members
90
+ * are renamed, and the result is decoded as a `DeviceContext`:
91
+ *
92
+ * - `active` is `ACTIVE` (`toDeviceContext`), a first device or a key the
93
+ * account already holds;
94
+ * - `pending_approval` is a new device on an account that already has one (see
95
+ * `toPendingApproval`);
96
+ * - `pending_activation` is an approved device signing in again during its
97
+ * cool-down (see `toPendingActivation`);
98
+ * - any other status, or a missing one, fails closed, as does a malformed
99
+ * UUID or timestamp.
100
+ *
101
+ * Any other `type` is refused. Extra members are otherwise ignored.
102
+ * `clientEntityId` comes from Social Session, not this payload.
103
+ */
104
+ export function toDeviceRegistrationResult(
105
+ value: unknown,
106
+ sessionClientEntityId: string,
107
+ ): DecodedDeviceRegistration {
108
+ const payload = deviceContextFromKeyCredential(asObject(value, 'payload'))
109
+ try {
110
+ const credentialStatus = optionalString(payload, 'deviceCredentialStatus')
111
+ if (credentialStatus === 'pending_approval') {
112
+ return toPendingApproval(payload)
113
+ }
114
+ if (credentialStatus === 'pending_activation') {
115
+ return toPendingActivation(payload)
116
+ }
117
+ const result: DecodedDeviceRegistration = Object.freeze({
118
+ status: 'ACTIVE',
119
+ context: new DaaUserContext(DECODER_TOKEN, {
120
+ clientEntityId: sessionClientEntityId,
121
+ deviceContext: toDeviceContext(payload),
122
+ }),
123
+ })
124
+ return result
125
+ } catch (error) {
126
+ if (error instanceof MalformedPayloadError) {
127
+ throw new MalformedPayloadError(KEY_CREDENTIAL_NAMES[error.fieldName] ?? error.fieldName)
128
+ }
129
+ throw error
130
+ }
131
+ }
132
+
133
+ /**
134
+ * The `KeyCredential` as a flat `DeviceContext`: `credentialStatus` becomes
135
+ * `deviceCredentialStatus` and `credentialId` becomes `authKeyId`; every other
136
+ * member is kept as it is.
137
+ */
138
+ function deviceContextFromKeyCredential(payload: Record<string, unknown>): Record<string, unknown> {
139
+ if (requiredString(payload, 'type') !== DEVICE_KEY_TYPE) {
140
+ throw new MalformedPayloadError('type')
141
+ }
142
+ const deviceContext: Record<string, unknown> = { ...payload }
143
+ delete deviceContext.type
144
+ delete deviceContext.credentialStatus
145
+ delete deviceContext.credentialId
146
+ deviceContext.deviceCredentialStatus = payload.credentialStatus
147
+ deviceContext.authKeyId = payload.credentialId
148
+ return deviceContext
149
+ }
150
+
151
+ /**
152
+ * The `DeviceContext` DAA returns for a new device on an account that
153
+ * already has one: `deviceCredentialStatus: "pending_approval"` with the
154
+ * request's `requestId`, `expiresAt` and the enclave's `codeNonce` (32 bytes,
155
+ * canonical unpadded Base64URL, so `PendingDeviceApproval` can decode it).
156
+ * `codeSeal`, when present, is the seal the request was created with (32
157
+ * bytes, the same encoding): for a key that was already waiting it is the one
158
+ * from its first registration, not this body's. A DAA that doesn't send it
159
+ * yet decodes as `null`. `ownerBindingId` and `resolvedAt` are not read:
160
+ * nothing here signs until the request is approved.
161
+ */
162
+ function toPendingApproval(payload: Record<string, unknown>): PendingApprovalPayload {
163
+ const codeNonce = requiredString(payload, 'codeNonce')
164
+ if (canonicalBytes32(codeNonce) === null) {
165
+ throw new MalformedPayloadError('codeNonce')
166
+ }
167
+ const codeSeal = optionalString(payload, 'codeSeal')
168
+ if (codeSeal !== null && canonicalBytes32(codeSeal) === null) {
169
+ throw new MalformedPayloadError('codeSeal')
170
+ }
171
+ return Object.freeze({
172
+ status: 'PENDING_APPROVAL',
173
+ requestId: requiredUuid(payload, 'requestId'),
174
+ authKeyId: requiredUuid(payload, 'authKeyId'),
175
+ expiresAt: requiredDateTime(payload, 'expiresAt'),
176
+ codeNonce,
177
+ codeSeal,
178
+ })
179
+ }
180
+
181
+ /**
182
+ * The `DeviceContext` DAA returns for a device an existing device already
183
+ * approved, signing in again before the account's cool-down ends:
184
+ * `deviceCredentialStatus: "pending_activation"` with `readyAt`, when the key
185
+ * may sign. The key is the account's, so `ownerBindingId` and `authKeyId` are
186
+ * final. The `pending_approval` fields (`requestId`, `expiresAt`, `codeNonce`,
187
+ * `codeSeal`) make the payload ambiguous, so a payload carrying any of them is
188
+ * refused. `resolvedAt` is not read.
189
+ */
190
+ function toPendingActivation(payload: Record<string, unknown>): PendingActivationPayload {
191
+ for (const name of ['requestId', 'expiresAt', 'codeNonce', 'codeSeal']) {
192
+ const value = payload[name]
193
+ if (value !== undefined && value !== null) {
194
+ throw new MalformedPayloadError(name)
195
+ }
196
+ }
197
+ return Object.freeze({
198
+ status: 'PENDING_ACTIVATION',
199
+ authKeyId: requiredUuid(payload, 'authKeyId'),
200
+ ownerBindingId: requiredUuid(payload, 'ownerBindingId'),
201
+ readyAt: requiredDateTime(payload, 'readyAt'),
202
+ })
203
+ }
204
+
205
+ function requiredUuid(payload: Record<string, unknown>, name: string): string {
206
+ const value = requiredString(payload, name)
207
+ if (!isUuid(value)) {
208
+ throw new MalformedPayloadError(name)
209
+ }
210
+ return value
211
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import type { DeviceStatus } from '../models/DeviceStatus'
20
+ import { isUuid } from '../validation/uuid'
21
+ import { requiredDateTime } from './instant'
22
+ import { asObject, MalformedPayloadError, optionalString, requiredString } from './payload'
23
+
24
+ /** Decode the status route's `data`. An unknown `status` is kept as `unrecognized`. */
25
+ export function toDeviceStatus(value: unknown): DeviceStatus {
26
+ const payload = asObject(value, 'payload')
27
+ const authKeyId = requiredUuid(payload, 'authKeyId')
28
+ const status = requiredString(payload, 'status')
29
+ switch (status) {
30
+ case 'pending_approval':
31
+ case 'expired':
32
+ return Object.freeze({
33
+ status,
34
+ authKeyId,
35
+ requestId: requiredUuid(payload, 'requestId'),
36
+ expiresAt: requiredDateTime(payload, 'expiresAt'),
37
+ })
38
+ case 'denied':
39
+ case 'cancelled':
40
+ return Object.freeze({ status, authKeyId, requestId: requiredUuid(payload, 'requestId') })
41
+ case 'pending_activation':
42
+ return Object.freeze({
43
+ status,
44
+ authKeyId,
45
+ ...optionalRequestId(payload),
46
+ readyAt: requiredDateTime(payload, 'readyAt'),
47
+ })
48
+ case 'active':
49
+ return Object.freeze({ status, authKeyId, ...optionalRequestId(payload) })
50
+ default:
51
+ // Preserved, not refused: DAA may add a status before this SDK knows it.
52
+ return Object.freeze({ status: 'unrecognized', authKeyId, rawValue: status })
53
+ }
54
+ }
55
+
56
+ function optionalRequestId(payload: Record<string, unknown>): { requestId?: string } {
57
+ return optionalString(payload, 'requestId') === null
58
+ ? {}
59
+ : { requestId: requiredUuid(payload, 'requestId') }
60
+ }
61
+
62
+ function requiredUuid(payload: Record<string, unknown>, name: string): string {
63
+ const value = requiredString(payload, name)
64
+ if (!isUuid(value)) {
65
+ throw new MalformedPayloadError(name)
66
+ }
67
+ return value
68
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import { JSON_NUMBER } from './jsonNumber'
20
+
21
+ /**
22
+ * The DAA status code from an error body, when the body carries a readable one.
23
+ *
24
+ * Best-effort by design: a failed call must still surface its HTTP status and
25
+ * correlation id when the provider returned an empty body, a proxy's HTML error
26
+ * page, or a shape the contract does not describe. Losing the whole error because
27
+ * its detail did not parse would be worse than losing the detail, so every failure
28
+ * here is `null`.
29
+ *
30
+ * Only the code is lifted. The envelope's `message` and `externalMessage` are
31
+ * provider-authored text from a response the SDK cannot vouch for, and the SDK
32
+ * error model has nowhere to put them that is not a log line.
33
+ *
34
+ * DAA sends the flat platform error body, with the code at the **root**:
35
+ * `{"code":420034,"message":"…","externalMessage":"…"}`. The SDK also
36
+ * accepts the code at `status.code`, but only when the root `code` is absent.
37
+ * A root `code` that is present decides alone, even when it is unreadable or
38
+ * unknown and `status.code` is a known code. Present means the key exists with
39
+ * a value other than `null`. Neither is under `data`: the `data` success
40
+ * wrapper is never applied to an error response.
41
+ *
42
+ * A decimal-string code comes back as the number. Any other string comes back
43
+ * unchanged so that an `api` error can still show it, but it classifies
44
+ * nothing: `isDaaStatus` matches numbers only.
45
+ */
46
+ export function readDaaStatusCode(bytes: Uint8Array | null): string | number | null {
47
+ if (bytes === null || bytes.length === 0) {
48
+ return null
49
+ }
50
+
51
+ let root: unknown
52
+ try {
53
+ root = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown
54
+ } catch {
55
+ return null
56
+ }
57
+
58
+ if (!isObject(root)) {
59
+ return null
60
+ }
61
+ const flat = root['code']
62
+ if (flat !== undefined && flat !== null) {
63
+ return codeValue(flat)
64
+ }
65
+ const status = root['status']
66
+ return isObject(status) ? codeValue(status['code']) : null
67
+ }
68
+
69
+ function isObject(value: unknown): value is Record<string, unknown> {
70
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
71
+ }
72
+
73
+ function codeValue(code: unknown): string | number | null {
74
+ // A numeric code arrives as a number from `JSON.parse`. A status code is
75
+ // small enough that no rounding question arises, so it is handed back as it
76
+ // came.
77
+ if (typeof code === 'number') {
78
+ return Number.isFinite(code) ? code : null
79
+ }
80
+ if (typeof code !== 'string' || code.length === 0) {
81
+ return null
82
+ }
83
+ // A code the service quoted is handed back as a number when it is one, so a
84
+ // consumer can compare it without knowing which shape arrived. A string that
85
+ // is not a number is kept only for diagnostics on the `api` error.
86
+ return JSON_NUMBER.test(code) ? Number(code) : code
87
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import type { FiatAccountStatus } from '../models/FiatAccount'
20
+ import { BankAddress, BillingDetails } from '../models/FiatAccount'
21
+ import {
22
+ MalformedPayloadError,
23
+ asObject,
24
+ optionalObject,
25
+ optionalString,
26
+ requiredString,
27
+ unrecognized,
28
+ } from './payload'
29
+
30
+ /** Decoders shared by the wire and ACH fiat-account payloads (`wirePayload.ts`, `achPayload.ts`). */
31
+
32
+ const STATUSES = new Map<string, FiatAccountStatus>([
33
+ ['pending', Object.freeze({ kind: 'pending' as const })],
34
+ ['complete', Object.freeze({ kind: 'complete' as const })],
35
+ ['failed', Object.freeze({ kind: 'failed' as const })],
36
+ ])
37
+
38
+ export function toFiatAccountStatus(raw: string): FiatAccountStatus {
39
+ return STATUSES.get(raw) ?? unrecognized(raw)
40
+ }
41
+
42
+ export function optionalBoolean(
43
+ payload: Record<string, unknown>,
44
+ name: string,
45
+ label = name,
46
+ ): boolean | null {
47
+ const value = payload[name]
48
+ if (value === undefined || value === null) {
49
+ return null
50
+ }
51
+ if (typeof value !== 'boolean') {
52
+ throw new MalformedPayloadError(label)
53
+ }
54
+ return value
55
+ }
56
+
57
+ /**
58
+ * Decode the guaranteed `BillingDetails` shape.
59
+ *
60
+ * The service requires `name`, `city`, `country`, `line1`, and `postalCode` on
61
+ * every wire/ACH fiat account, unlike `Account`'s optional `BusinessPii`
62
+ * enrichment — so a fiat account missing one of these is a broken contract,
63
+ * not a partially-enriched record.
64
+ */
65
+ export function toBillingDetails(value: unknown, label: string): BillingDetails {
66
+ const payload = asObject(value, label)
67
+ return new BillingDetails({
68
+ name: requiredString(payload, 'name', `${label}.name`),
69
+ city: requiredString(payload, 'city', `${label}.city`),
70
+ country: requiredString(payload, 'country', `${label}.country`),
71
+ line1: requiredString(payload, 'line1', `${label}.line1`),
72
+ line2: optionalString(payload, 'line2', `${label}.line2`),
73
+ district: optionalString(payload, 'district', `${label}.district`),
74
+ postalCode: requiredString(payload, 'postalCode', `${label}.postalCode`),
75
+ valid: optionalBoolean(payload, 'valid', `${label}.valid`),
76
+ })
77
+ }
78
+
79
+ export function requiredBillingDetails(
80
+ payload: Record<string, unknown>,
81
+ name: string,
82
+ ): BillingDetails {
83
+ const value = payload[name]
84
+ if (value === undefined || value === null) {
85
+ throw new MalformedPayloadError(name)
86
+ }
87
+ return toBillingDetails(value, name)
88
+ }
89
+
90
+ /**
91
+ * Decode the optional `BankAddress` shape. Only `country` is guaranteed when
92
+ * the object is present at all.
93
+ */
94
+ export function toBankAddress(value: unknown, label: string): BankAddress {
95
+ const payload = asObject(value, label)
96
+ return new BankAddress({
97
+ bankName: optionalString(payload, 'bankName', `${label}.bankName`),
98
+ city: optionalString(payload, 'city', `${label}.city`),
99
+ country: requiredString(payload, 'country', `${label}.country`),
100
+ line1: optionalString(payload, 'line1', `${label}.line1`),
101
+ line2: optionalString(payload, 'line2', `${label}.line2`),
102
+ district: optionalString(payload, 'district', `${label}.district`),
103
+ })
104
+ }
105
+
106
+ export function optionalBankAddress(
107
+ payload: Record<string, unknown>,
108
+ name: string,
109
+ ): BankAddress | null {
110
+ const value = optionalObject(payload, name)
111
+ return value === null ? null : toBankAddress(value, name)
112
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import { MalformedPayloadError, requiredString } from './payload'
20
+
21
+ // The two wire forms a login-flow timestamp arrives in, and the single form
22
+ // the login decoders hand on.
23
+ //
24
+ // By default the service serialises a timestamp as a JSON number: an integral
25
+ // count of epoch milliseconds, not fractional seconds. Most timestamps opt out
26
+ // and are sent as ISO-8601 strings: every response carrying a `createDate` /
27
+ // `updateDate` does. Exactly three responses do not — Prepare
28
+ // (`PreparedSocialLogin`), Session and the device context — and those three are
29
+ // the login flow's three responses. The number form is therefore not a
30
+ // service-wide habit but a property of precisely the fields these decoders
31
+ // read, which is why this lives on its own rather than in `payload.ts` beside
32
+ // `requiredString`: a resource `createDate` arriving as a number would be a real
33
+ // contract violation, and `deposit`/`transfer`/`withdrawal` must keep rejecting
34
+ // it.
35
+ //
36
+ // The three fields are `PreparedSocialLogin.expiresAt`,
37
+ // `SocialSession.expiresAt` and `DeviceContext.resolvedAt`. They are the same
38
+ // kind of field, serialised the same way, so all three accept both forms. The
39
+ // device context's other timestamps (`expiresAt` on `pending_approval`,
40
+ // `readyAt` on `pending_activation`) come in the same response and accept both
41
+ // forms too.
42
+
43
+ /**
44
+ * The ISO-8601 form the contract declares for an `Instant`, with a `T`
45
+ * separator. The service does not always send this form — see `requiredDateTime`
46
+ * — but it is the single form these decoders hand on.
47
+ */
48
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
49
+
50
+ /**
51
+ * Render epoch milliseconds as the same ISO-8601 text the string form carries.
52
+ *
53
+ * Three checks, no coercions. A fractional, non-finite, or beyond-safe-integer
54
+ * value is not a count of milliseconds, and zero or below is a field that
55
+ * arrived as a number without being a timestamp. What survives that can still be
56
+ * outside the range `Date` represents, so the instant is checked before it is
57
+ * rendered. The rendered text then has to satisfy `DATE_TIME` exactly as the
58
+ * string form does — which is what bounds the year, rather than an invented
59
+ * constant: an epoch rendering `'+275760-09-13T00:00:00.000Z'` is rejected here
60
+ * for the same reason that string would be.
61
+ */
62
+ function fromEpochMillis(value: number, name: string): string {
63
+ if (!Number.isSafeInteger(value) || value <= 0) {
64
+ throw new MalformedPayloadError(name)
65
+ }
66
+ const instant = new Date(value)
67
+ if (Number.isNaN(instant.getTime())) {
68
+ throw new MalformedPayloadError(name)
69
+ }
70
+ const text = instant.toISOString()
71
+ if (!DATE_TIME.test(text)) {
72
+ throw new MalformedPayloadError(name)
73
+ }
74
+ return text
75
+ }
76
+
77
+ /**
78
+ * A login-flow timestamp the service guarantees, in either form it sends.
79
+ *
80
+ * The contract OpenAPI declares an ISO-8601 string and the running service
81
+ * sends a JSON number of epoch milliseconds, so the SDK accepts both. A number
82
+ * is normalised to the string form at this boundary, so every public timestamp
83
+ * stays one stable type no matter which form arrived. Anything that is neither
84
+ * form still fails closed.
85
+ */
86
+ export function requiredDateTime(payload: Record<string, unknown>, name: string): string {
87
+ const raw = payload[name]
88
+ if (typeof raw === 'number') {
89
+ return fromEpochMillis(raw, name)
90
+ }
91
+ const value = requiredString(payload, name)
92
+ if (!DATE_TIME.test(value)) {
93
+ throw new MalformedPayloadError(name)
94
+ }
95
+ return value
96
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // The JSON number grammar, applied to values that arrive as text.
20
+
21
+ /**
22
+ * RFC 8259's number grammar.
23
+ *
24
+ * The service sends `Money.amount` as a plain decimal JSON **string**, not a
25
+ * number. So the exact decimal survives
26
+ * `JSON.parse` untouched, and nothing on the way in checks that the text is a
27
+ * number at all — the OpenAPI's `type: number` describes the schema, not the
28
+ * wire.
29
+ *
30
+ * That makes this the **only** check on an amount rather than a second one, which
31
+ * is why it lives on its own rather than beside a decoder.
32
+ */
33
+ export const JSON_NUMBER = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import { Money } from '../models/Money'
20
+ import { JSON_NUMBER } from './jsonNumber'
21
+ import { asObject, MalformedPayloadError, requiredString } from './payload'
22
+
23
+ /**
24
+ * Decode the shared `Money` wire shape without coercing its decimal.
25
+ *
26
+ * The service serializes `amount` as a plain decimal JSON string. Accepting a JSON number would lose precision in
27
+ * `JSON.parse` before this decoder could inspect it, so only an RFC 8259
28
+ * number-shaped string is accepted. `Money` owns redaction of the amount.
29
+ */
30
+ export function toMoney(value: unknown, label: string): Money {
31
+ const payload = asObject(value, label)
32
+ const amount = requiredString(payload, 'amount', `${label}.amount`)
33
+ if (!JSON_NUMBER.test(amount)) {
34
+ throw new MalformedPayloadError(`${label}.amount`)
35
+ }
36
+ return new Money(amount, requiredString(payload, 'currency', `${label}.currency`))
37
+ }
38
+
39
+ /** Decode a guaranteed money field. */
40
+ export function requiredMoney(payload: Record<string, unknown>, name: string): Money {
41
+ const value = payload[name]
42
+ if (value === undefined || value === null) {
43
+ throw new MalformedPayloadError(name)
44
+ }
45
+ return toMoney(value, name)
46
+ }
47
+
48
+ /** Decode a money field the service may omit. JSON `null` is absence. */
49
+ export function optionalMoney(payload: Record<string, unknown>, name: string): Money | null {
50
+ const value = payload[name]
51
+ if (value === undefined || value === null) {
52
+ return null
53
+ }
54
+ return toMoney(value, name)
55
+ }